<commit_before>/**
 * Created by YS on 2017-04-14.
 */

var credentials = require('../credentials');
var mysqlSetting = require('../models/mysqlSetting');
var VersionModel = require('../models/versionModel');
var CrashModel = require('../models/crashModel');

/**
 *
 * @type {{
 *  upload: module.exports.upload
 * }}
 */
module.exports = {

    getCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            activity_name : req.params.activityName,
            limit : Number(req.query.limit) || 10,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return VersionModel.getVersionId(context, data);
            })
            .then(function(context) {
                return VersionModel.getActivityIdByVersionWithName(context, data);
            })
            .then(function(context) {
                return CrashModel.getCrashList(context, data)
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json({
                    crash: data
                });
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getTopCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            limit : Number(req.query.limit) || 10,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashNameWithCount(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json({
                    error_rank: data
                });
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getCrashUsage : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashUsage(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json({
                    crash: data
                });
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getVersionsByCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            crash_id : req.params.crashId,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashInfo(context, data);
            })
            .then(function(context) {
                return VersionModel.getVersionsByCrash(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = {
                        crash_info : data.crashInfo,
                        crash_version : data.crash_version_list
                    }
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json(data);
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getCrashEventPath : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            crash_id : req.params.crashId,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                console.log('EVENT PATH START');
                return CrashModel.getEventPath(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    console.log('EVENT PATH END');
                    context.result = data.eventpath
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json(data);
            })
            .catch(function(err) {
                return next(err);
            });
    }
};<commit_msg>*chg crash usage data type to array<commit_after>/**
 * Created by YS on 2017-04-14.
 */

var credentials = require('../credentials');
var mysqlSetting = require('../models/mysqlSetting');
var VersionModel = require('../models/versionModel');
var CrashModel = require('../models/crashModel');

/**
 *
 * @type {{
 *  upload: module.exports.upload
 * }}
 */
module.exports = {

    getCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            activity_name : req.params.activityName,
            limit : Number(req.query.limit) || 10,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return VersionModel.getVersionId(context, data);
            })
            .then(function(context) {
                return VersionModel.getActivityIdByVersionWithName(context, data);
            })
            .then(function(context) {
                return CrashModel.getCrashList(context, data)
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json({
                    crash: data
                });
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getTopCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            limit : Number(req.query.limit) || 10,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashNameWithCount(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json({
                    error_rank: data
                });
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getCrashUsage : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashUsage(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = data.crashList;
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json(data);
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getVersionsByCrash : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            crash_id : req.params.crashId,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                return CrashModel.getCrashInfo(context, data);
            })
            .then(function(context) {
                return VersionModel.getVersionsByCrash(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    context.result = {
                        crash_info : data.crashInfo,
                        crash_version : data.crash_version_list
                    }
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json(data);
            })
            .catch(function(err) {
                return next(err);
            });
    },

    getCrashEventPath : function (req, res, next) {
        var data = {
            access_token: req.header('access-token'),
            package_name : req.params.packageName,
            crash_id : req.params.crashId,
            filter : require('./filter').setFilter(req.query)
        };

        mysqlSetting.getPool()
            .then(mysqlSetting.getConnection)
            .then(mysqlSetting.connBeginTransaction)
            .then(function(context) {
                console.log('EVENT PATH START');
                return CrashModel.getEventPath(context, data);
            })
            .then(function(context) {
                return new Promise(function(resolved) {
                    console.log('EVENT PATH END');
                    context.result = data.eventpath
                    return resolved(context);
                });
            })
            .then(mysqlSetting.commitTransaction)
            .then(function(data) {
                res.statusCode = 200;
                return res.json(data);
            })
            .catch(function(err) {
                return next(err);
            });
    }
};<|endoftext|>


<commit_before>var stream = require('stream')
var events = require('events')
var exit = require('./exit')

var Program = require('./program')

var slice = [].slice

// Use given stream or create pseudo-stream.
function createStream (s) { return s || new stream.PassThrough }

module.exports = function () {
    // Variadic arguments.
    var vargs = slice.call(arguments)

    // First argument is always the module.
    var module = vargs.shift()

    // Usage source can be specified explicitly, or else it is sought in the
    // comments of the main module.
    var usage = typeof vargs[0] == 'string'
              ? vargs.shift()
              : module.filename

    // Check for default values for named parameters when argument parser is
    // invoked as a main module.
    var defaults = typeof vargs[0] == 'object' ? vargs.shift() : {}

    // Ensure we have defaults.
    defaults.argv || (defaults.argv = [])
    defaults.properties || (defaults.properties = [])

    // Main body of argument parser or program is final argument.
    var main = vargs.shift()

    var invoke = module.exports = function (argv, options, callback) {
        var vargs = slice.call(arguments, arguments.length >= 3 ? 2 : 1)
        var parameters = []
        if (Array.isArray(argv)) {
            argv = [ argv ]
        } else {
            var object = {}
            for (var key in argv) {
                object[key] = argv[key]
            }
            argv = [ object ]
            if (Array.isArray(object.argv)) {
                argv.push(object.argv)
                delete object.argv
            }
        }
        if (typeof options == 'function') {
            callback = options
            options = {}
        }
        argv.unshift(defaults.argv)
        argv = argv.slice()
        while (argv.length != 0) {
            var argument = argv.shift()
            switch (typeof argument) {
            case 'object':
                if (Array.isArray(argument)) {
                    argv.unshift.apply(argv, argument)
                } else {
                    if (('name' in argument) &&
                        ('value' in argument) &&
                        Object.keys(argument).length == 2
                    ) {
                        parameters.push(argument)
                    } else {
                        for (var name in argument) {
                            parameters.push({ name: name, value: argument[name] })
                        }
                    }
                }
                break
            default:
                parameters.push(argument)
                break
            }
        }
        // What we're shooting for here is this:
        //
        //   Create a signature that would be a reasonable signature for a
        //   generic function that is not an Arguable argument parser.
        //
        //   Or put another way, tell the user to create an argument parser that
        //   accepts an arguments array and a pseudo-process, the program, and a
        //   callback, so that you can tell them to either use Arguable, or else
        //   implement an argument parser that accepts reasonable arguments as
        //   opposed to accepting convoluted named parameters.
        //
        // If options is really an `EventEmitter`, then our argument parser is
        // being called as a universal submodule. This is an interface that
        // allows a library module author to document that a submodule accepts
        // an arguments array and a signal handler. The library module author
        // can document as many `Program` features as they would like, or they
        // could simply say that it is only for events, or they can say that it
        // is mean to be ignored by the submodule author.
        //
        // Now the submodule author can use Arguable for their argument parser
        // and program will be correctly configured, or they can create a
        // function that takes the argument array and use the argument parser
        // module of their choice. Additional properties are arguments to the
        // argument parser, not properties on this mystery event emitter.

        // Note that all the other options are debugging options.
        if (options instanceof events.EventEmitter) {
            options = { events: options }
            options.stdin = options.events.stdin
            options.stdout = options.events.stdout
            options.stderr = options.events.stderr
        }
        // TODO Okay, now we have space for additional arguments that follow the
        // event emitter or the options. These can be passed in as variadic
        // arguments to be interpreted by the caller. This can be experimental.
        //
        var send = options.send || options.events && options.events.send && function () {
            options.events.send.apply(options.events, slice.call(arguments))
        }
        var ee = options.events
        if (ee == null) {
            ee = new events.EventEmitter
            ee.mainModule = process.mainModule
            ee.connected = ('connected' in options) ? options.connected : true
            ee.disconnect = function () { this.connected = false }
        }
        var isMainModule = ('isMainModule' in options)
                         ? options.isMainModule
                         : process.mainModule === module
        var program = new Program(usage, parameters, {
            module: module,
            stdout: createStream(options.stdout),
            stdin: createStream(options.stdin),
            stderr: createStream(options.stderr),
            isMainModule: isMainModule,
            events: ee,
            properties: [ defaults.properties, options.properties || {} ],
            send: send || null,
            env: options.env || {}
        })
        main.apply(null, [ program ].concat(vargs))
        return program
    }
    if (module === process.mainModule) {
        invoke(process.argv.slice(2), {
// No. Stop! There is no `process.stdio`. Do not add one! (Again.)
            env: process.env,
            stdout: process.stdout,
            stdin: process.stdin,
            stderr: process.stderr,
            events: process
        }, exit(process))
    }
}
<commit_msg>Add ability to add properties at the end.<commit_after>var stream = require('stream')
var events = require('events')
var exit = require('./exit')

var Program = require('./program')

var slice = [].slice

// Use given stream or create pseudo-stream.
function createStream (s) { return s || new stream.PassThrough }

module.exports = function () {
    // Variadic arguments.
    var vargs = slice.call(arguments)

    // First argument is always the module.
    var module = vargs.shift()

    // Usage source can be specified explicitly, or else it is sought in the
    // comments of the main module.
    var usage = typeof vargs[0] == 'string'
              ? vargs.shift()
              : module.filename

    // Check for default values for named parameters when argument parser is
    // invoked as a main module.
    var defaults = typeof vargs[0] == 'object' ? vargs.shift() : {}

    // Ensure we have defaults.
    defaults.argv || (defaults.argv = [])
    defaults.properties || (defaults.properties = [])

    // Main body of argument parser or program is final argument.
    var main = vargs.shift()

    var properties = vargs.shift() || {}

    var invoke = module.exports = function (argv, options, callback) {
        var vargs = slice.call(arguments, arguments.length >= 3 ? 2 : 1)
        var parameters = []
        if (Array.isArray(argv)) {
            argv = [ argv ]
        } else {
            var object = {}
            for (var key in argv) {
                object[key] = argv[key]
            }
            argv = [ object ]
            if (Array.isArray(object.argv)) {
                argv.push(object.argv)
                delete object.argv
            }
        }
        if (typeof options == 'function') {
            callback = options
            options = {}
        }
        argv.unshift(defaults.argv)
        argv = argv.slice()
        while (argv.length != 0) {
            var argument = argv.shift()
            switch (typeof argument) {
            case 'object':
                if (Array.isArray(argument)) {
                    argv.unshift.apply(argv, argument)
                } else {
                    if (('name' in argument) &&
                        ('value' in argument) &&
                        Object.keys(argument).length == 2
                    ) {
                        parameters.push(argument)
                    } else {
                        for (var name in argument) {
                            parameters.push({ name: name, value: argument[name] })
                        }
                    }
                }
                break
            default:
                parameters.push(argument)
                break
            }
        }
        // What we're shooting for here is this:
        //
        //   Create a signature that would be a reasonable signature for a
        //   generic function that is not an Arguable argument parser.
        //
        //   Or put another way, tell the user to create an argument parser that
        //   accepts an arguments array and a pseudo-process, the program, and a
        //   callback, so that you can tell them to either use Arguable, or else
        //   implement an argument parser that accepts reasonable arguments as
        //   opposed to accepting convoluted named parameters.
        //
        // If options is really an `EventEmitter`, then our argument parser is
        // being called as a universal submodule. This is an interface that
        // allows a library module author to document that a submodule accepts
        // an arguments array and a signal handler. The library module author
        // can document as many `Program` features as they would like, or they
        // could simply say that it is only for events, or they can say that it
        // is mean to be ignored by the submodule author.
        //
        // Now the submodule author can use Arguable for their argument parser
        // and program will be correctly configured, or they can create a
        // function that takes the argument array and use the argument parser
        // module of their choice. Additional properties are arguments to the
        // argument parser, not properties on this mystery event emitter.

        // Note that all the other options are debugging options.
        if (options instanceof events.EventEmitter) {
            options = { events: options }
            options.stdin = options.events.stdin
            options.stdout = options.events.stdout
            options.stderr = options.events.stderr
        }
        // TODO Okay, now we have space for additional arguments that follow the
        // event emitter or the options. These can be passed in as variadic
        // arguments to be interpreted by the caller. This can be experimental.
        //
        var send = options.send || options.events && options.events.send && function () {
            options.events.send.apply(options.events, slice.call(arguments))
        }
        var ee = options.events
        if (ee == null) {
            ee = new events.EventEmitter
            ee.mainModule = process.mainModule
            ee.connected = ('connected' in options) ? options.connected : true
            ee.disconnect = function () { this.connected = false }
        }
        var isMainModule = ('isMainModule' in options)
                         ? options.isMainModule
                         : process.mainModule === module
        var program = new Program(usage, parameters, {
            module: module,
            stdout: createStream(options.stdout),
            stdin: createStream(options.stdin),
            stderr: createStream(options.stderr),
            isMainModule: isMainModule,
            events: ee,
            properties: [ defaults.properties, properties, options.properties || {} ],
            send: send || null,
            env: options.env || {}
        })
        main.apply(null, [ program ].concat(vargs))
        return program
    }
    if (module === process.mainModule) {
        invoke(process.argv.slice(2), {
// No. Stop! There is no `process.stdio`. Do not add one! (Again.)
            env: process.env,
            stdout: process.stdout,
            stdin: process.stdin,
            stderr: process.stderr,
            events: process
        }, exit(process))
    }
}
<|endoftext|>


<commit_before>module.exports = {

  index: function(req, res, next){
    res.render('index');
  }

};
<commit_msg>Send user email if logged in<commit_after>module.exports = {

  index: function(req, res, next){
    res.render('index', {user: req.user ? req.user.email : null});
  }

};
<|endoftext|>


<commit_before>/*! @license MIT ©2014–2016 Ruben Verborgh, Ghent University – imec */
// jQuery widget for Triple Pattern Fragments query execution

(function ($) {
  // Query UI main entry point, which mimics the jQuery UI widget interface:
  // - $(element).queryui(options) initializes the widget
  // - $(element).queryui('option', [key], [value]) gets or sets one or all options
  $.fn.queryui = function (operation, option, value) {
    // Shift parameters if no operation given
    if (typeof operation !== 'string')
      value = option, option = operation, operation = 'init';

    // Apply the operation to all elements;
    // if one element yields a value, stop and return it
    var result = this;
    for (var i = 0; i < this.length && result === this; i++) {
      var $element = $(this[i]), queryui = $element.data('queryui');
      switch (operation) {
      // initialize the element as a Query UI
      case 'init':
        if (!queryui) {
          $element.data('queryui', queryui = new LdfQueryUI($element, option));
          queryui._create();
        }
        break;
      // set an option of a Query UI
      case 'option':
        if (!queryui) throw new Error('Query UI not activated on this element');
        // retrieve all options
        if (option === undefined)     result = queryui.options;
        // retrieve a specific option
        else if (value === undefined) result = queryui.options[value];
        // set a specific option
        else queryui._setOption(option, value);
        break;
      }
    }
    return result;
  };

  // Creates a new Query UI interface for the given element
  function LdfQueryUI($element, options) {
    this.element = $element;
    this.options = $.extend({}, this.options, options);

    // Create the query execution Web Worker
    var self = this;
    this._queryWorker = new Worker('scripts/ldf-client-worker.js');
    this._queryWorker.onmessage = function (message) {
      var data = message.data;
      switch (data.type) {
      case 'queryInfo': return self._initResults(data.queryType);
      case 'result':    return self._addResult(data.result);
      case 'end':       return self._endResults();
      case 'log':       return self._logAppender(data.log);
      case 'error':     return this.onerror(data.error);
      }
    };
    this._queryWorker.onerror = function (error) {
      self._stopExecution(error);
    };
  }

  LdfQueryUI.prototype = {
    // Default widget options
    options: {
      datasources: [],
      queries: [],
      prefixes: [],
    },

    // Initializes the widget
    _create: function () {
      var self = this,
          options = this.options,
          $element = this.element,
          $stop = this.$stop = $('.stop', $element),
          $start = this.$start = $('.start', $element),
          $query = this.$query = $('.queryText', $element),
          $queries = this.$queries = $('.query', $element),
          $log = $('.log', $element),
          $results = $('.results', $element),
          $resultsText = $('
', { class: 'text' }),
          $datasources = this.$datasources = $('.datasources', $element),
          $datetime = this.$datetime = $('.datetime', $element),
          $details = this.$details = $('.details', $element),
          $showDetails = this.$showDetails = $('.details-toggle', $element);

      // Replace non-existing elements by an empty text box
      if (!$datasources.length) $datasources = this.$datasources = $('<select>');
      if (!$results.length) $results = $('
');
      if (!$log.length) $log = $('
');

      // When a datasource is selected, load the corresponding query set
      $datasources.chosen({
        create_option: true, persistent_create_option: true,
        skip_no_results: true, search_contains: true, display_selected_options: false,
        placeholder_text: ' ', create_option_text: 'Add datasource',
      });
      $datasources.change(function () {
        self._setOption('selectedDatasources', $datasources.val());
      });

      // When a query is selected, load it into the editor
      $query.edited = $query.val() !== '';
      $query.change(function () {
        options.query = $query.val();
        $query.edited = true;
      });
      $queries.chosen({ skip_no_results: true, placeholder_text: ' ' });
      $queries.change(function (query) {
        if (query = $queries.val())
          $query.val(options.query = query).edited = false;
      });

      // Update datetime on change
      $datetime.change(function () { self._setOption('datetime', $datetime.val()); });

      // Set up starting and stopping
      $start.click(this._startExecution.bind(this));
      $stop.click(this._stopExecution.bind(this));

      // Set up details toggling
      $showDetails.click(function () {
        $details.is(':visible') ? self._hideDetails() : self._showDetails();
      });

      // Set up results
      $results.append($resultsText);
      this._resultsScroller = new FastScroller($results, renderResult);
      this._resultAppender = appenderFor($resultsText);
      this._logAppender = appenderFor($log);
      this.$timing = $('.timing', $element);

      // Apply all options
      for (var key in options)
        this._setOption(key, options[key], true);
    },

    // Sets a specific widget option
    _setOption: function (key, value, initialize) {
      var options = this.options;
      if (!initialize && options[key] === value) return;
      options[key] = value;

      // Apply the chosen option
      var self = this, $datasources = this.$datasources, $queries = this.$queries;
      switch (key) {
      // Set the datasources available for querying
      case 'datasources':
        // Create options for each datasource
        $datasources.empty().append((value || []).map(function (datasource, index) {
          return $('<option>', { text: datasource.name, value: datasource.url });
        }));
        // Restore selected datasources
        this._setOption('selectedDatasources', options.selectedDatasources, true);
        break;
      // Set the datasources to query
      case 'selectedDatasources':
        // Choose the first available datasource if none was chosen
        var $options = $datasources.children();
        if (initialize && !(value && value.length) && $options.length)
          options[key] = value = [$options.val()];
        // Select chosen datasources that were already in the list
        var selected = toHash(value);
        $options.each(function (index) {
          var $option = $(this), url = $(this).val();
          $option.attr('selected', url in selected);
          selected[url] = true;
        });
        // Add and select chosen datasources that were not in the list yet
        $datasources.append($.map(selected, function (exists, url) {
          return exists ? null :
                 $('<option>', { text: url, value: url, selected: true });
        })).trigger('chosen:updated');
        // Update the query set
        this._loadQueries(value);
        break;
      // Set the query
      case 'query':
        this.$query.val(value).change();
        break;
      // Set the list of all possible queries
      case 'queries':
        this._loadQueries(options.selectedDatasources);
        break;
      case 'datetime':
        if (value)
          this._showDetails();
        this.$datetime.val(value).change();
        break;
      // Set the list of selectable queries
      case 'relevantQueries':
        value = value || [];
        // If the current query was not edited and not in the list,
        // load the first selectable query
        if (!this.$query.edited &&
            !value.some(function (v) { return v.sparql === options.query; }))
          value[0] && this._setOption('query', value[0].sparql);
        // Update the selectable query list
        $queries.empty().append($('<option>'), value.map(function (query) {
          return $('<option>', { text: query.name, value: query.sparql,
                                 selected: options.query === query.sparql });
        })).trigger('chosen:updated').change();
        break;
      // Load settings from a JSON resource
      case 'settings':
        $.getJSON(value, function (settings) {
          for (var key in settings)
            self._setOption(key, settings[key]);
        });
        break;
      }
    },

    // Load queries relevant for the given datasources
    _loadQueries: function (datasources) {
      datasources = toHash(datasources);
      var queries = (this.options.queries || []).filter(function (query, index) {
        query.id = index;
        // Include the query if it indicates no datasources,
        // or if it is relevant for at least one datasource
        return !query.datasources || !query.datasources.length ||
               query.datasources.some(function (d) { return d in datasources; });
      });

      // Load the set of queries if it is different from the current set
      var querySetId = queries.map(function (q) { return q.id; }).join();
      if (this._querySetId !== querySetId) {
        this._querySetId = querySetId;
        this._setOption('relevantQueries', queries);
        this.element.trigger('changeQuerySet');
      }
    },

    // Starts query execution
    _startExecution: function () {
      var datasources = this.$datasources.val();
      if (!datasources || !datasources.length)
        return alert('Please choose a datasource to execute the query.');

      // Clear results and log
      this.$stop.show();
      this.$start.hide();
      this._resultsScroller.removeAll();
      this._resultAppender.clear();
      this._logAppender.clear();

      // Scroll page to the results
      $('html,body').animate({ scrollTop: this.$start.offset().top });

      // Start the timer
      this._resultCount = 0;
      this._startTimer();

      // Let the worker execute the query
      this._queryWorker.postMessage({
        type: 'query',
        query: this.$query.val(),
        datasources: datasources,
        prefixes: this.options.prefixes,
        datetime: parseDate(this.options.datetime),
      });
    },

    // Stops query execution
    _stopExecution: function (error) {
      // Stop the worker and the timer
      this._queryWorker.postMessage({ type: 'stop' });
      this._stopTimer();

      // Reset the UI
      this.$stop.hide();
      this.$start.show();
      if (error && error.message)
        this._resultAppender(error.message);
      this._resultAppender.flush();
      this._logAppender.flush();
      this._writeResult = this._writeEnd = null;
    },

    // Initializes the result display, depending on the query type
    _initResults: function (queryType) {
      var resultAppender = this._resultAppender;
      switch (queryType) {
      // For SELECT queries, add the rows to the result
      case 'SELECT':
        this._writeResult = function (row) {
          this._resultsScroller.addContent([row]);
        };
        this._writeEnd = function () {
          if (!this._resultCount)
            resultAppender('This query has no results.');
        };
        break;
      // For CONSTRUCT and DESCRIBE queries,
      // write a Turtle representation of the triples
      case 'CONSTRUCT':
      case 'DESCRIBE':
        var writer = new N3.Writer({
          write: function (chunk, encoding, done) {
            resultAppender(chunk), done && done();
          },
        }, this.options);
        this._writeResult = function (triple) { writer.addTriple(triple); };
        this._writeEnd = function () { writer.end(); };
        break;
      // For ASK queries, write whether an answer exists
      case 'ASK':
        this._writeResult = function (exists) { resultAppender(exists); };
        this._writeEnd = $.noop;
        break;
      // Other queries cannot be displayed
      default:
        resultAppender(queryType + ' queries are unsupported.');
      }
    },

    // Adds a result to the display
    _addResult: function (result) {
      if (this._writeResult) {
        this._resultCount++;
        this._writeResult(result);
      }
    },

    // Finalizes the display after all results have been added
    _endResults: function () {
      if (this._writeEnd) {
        this._writeEnd();
        this._stopExecution();
      }
    },

    // Starts the results timer
    _startTimer: function () {
      this._startTime = new Date();
      this._stopTimer();
      this._updateTimer();
      this._updateTimerHandle = setInterval(this._updateTimer.bind(this), 100);
    },

    // Updates the result timer
    _updateTimer: function () {
      this.$timing.text(this._resultCount.toLocaleString() + ' result' +
                        (this._resultCount === 1 ? '' : 's') + ' in ' +
                        ((new Date() - this._startTime) / 1000).toFixed(1) + 's');
    },

    // Stops the result timer
    _stopTimer: function () {
      if (this._updateTimerHandle) {
        this._updateTimer();
        clearInterval(this._updateTimerHandle);
        this._updateTimerHandle = 0;
      }
    },

    // Shows the details panel
    _showDetails: function () {
      this.$details.slideDown(150);
      this.$showDetails.addClass('enabled');
    },

    // Hides the details panel
    _hideDetails: function () {
      this._setOption('datetime', '');
      this.$details.slideUp(150);
      this.$showDetails.removeClass('enabled');
    },
  };

  // Creates a function that appends text to the given element in a throttled way
  function appenderFor($element) {
    var buffer, allowedAppends, timeout, delay = 1000;
    // Resets the element
    function clear() {
      buffer = '';
      $element.empty();
      allowedAppends = 50;
      clearTimeout(timeout);
    }
    clear();
    // Appends the text to the element, or queues it for appending
    function append(text) {
      // Append directly if still allowed
      if (allowedAppends > 0) {
        $element.append(escape(text));
        // When no longer allowed, re-enable appending after a delay
        if (--allowedAppends === 0)
          timeout = setTimeout(flush, delay);
      }
      // Otherwise, queue for appending
      else
        buffer += text;
    }
    // Writes buffered text and re-enables appending
    function flush() {
      // Clear timeout in case flush was explicitly triggered
      clearTimeout(timeout);
      timeout = null;
      // Re-enable appending right away if no text was queued
      if (!buffer)
        allowedAppends = 1;
      // Otherwise, append queued text and wait to re-enable
      else {
        $element.append(escape(buffer));
        buffer = '';
        timeout = setTimeout(flush, delay);
      }
    }
    // Export the append function
    append.clear = clear;
    append.flush = flush;
    return append;
  }

  // Escapes special HTML characters and convert URLs into links
  function escape(text) {
    return (text + '').replace(/(<)|(>)|(&)|http(s?:\/\/[^\s<>]+)/g, escapeMatch);
  }
  function escapeMatch(match, lt, gt, amp, url) {
    return lt && '<' || gt && '>' || amp && '&' ||
           (url = 'http' + escape(url)) &&
           '' + url + '';
  }

  // Converts the array to a hash with the elements as keys
  function toHash(array) {
    var hash = {}, length = array ? array.length : 0;
    for (var i = 0; i < length; i++)
      hash[array[i]] = false;
    return hash;
  }

  // Parses a yyyy-mm-dd date string into a Date
  function parseDate(date) {
    if (date) {
      try { return new Date(Date.parse(date)); }
      catch (e) { /* ignore invalid dates */ }
    }
  }

  // Transforms a result row into an HTML element
  function renderResult(row, container) {
    container = container || $('
', { class: 'result' }).append($('
'))[0];
    $(container.firstChild).empty().append($.map(row, function (value, variable) {
      return [$('
', { text: variable }), $('
', { html: escape(value) })];
    }));
    return container;
  }
})(jQuery);
<commit_msg>Query datasource specifications can use wildcards.<commit_after>/*! @license MIT ©2014–2016 Ruben Verborgh, Ghent University – imec */
// jQuery widget for Triple Pattern Fragments query execution

(function ($) {
  // Query UI main entry point, which mimics the jQuery UI widget interface:
  // - $(element).queryui(options) initializes the widget
  // - $(element).queryui('option', [key], [value]) gets or sets one or all options
  $.fn.queryui = function (operation, option, value) {
    // Shift parameters if no operation given
    if (typeof operation !== 'string')
      value = option, option = operation, operation = 'init';

    // Apply the operation to all elements;
    // if one element yields a value, stop and return it
    var result = this;
    for (var i = 0; i < this.length && result === this; i++) {
      var $element = $(this[i]), queryui = $element.data('queryui');
      switch (operation) {
      // initialize the element as a Query UI
      case 'init':
        if (!queryui) {
          $element.data('queryui', queryui = new LdfQueryUI($element, option));
          queryui._create();
        }
        break;
      // set an option of a Query UI
      case 'option':
        if (!queryui) throw new Error('Query UI not activated on this element');
        // retrieve all options
        if (option === undefined)     result = queryui.options;
        // retrieve a specific option
        else if (value === undefined) result = queryui.options[value];
        // set a specific option
        else queryui._setOption(option, value);
        break;
      }
    }
    return result;
  };

  // Creates a new Query UI interface for the given element
  function LdfQueryUI($element, options) {
    this.element = $element;
    this.options = $.extend({}, this.options, options);

    // Create the query execution Web Worker
    var self = this;
    this._queryWorker = new Worker('scripts/ldf-client-worker.js');
    this._queryWorker.onmessage = function (message) {
      var data = message.data;
      switch (data.type) {
      case 'queryInfo': return self._initResults(data.queryType);
      case 'result':    return self._addResult(data.result);
      case 'end':       return self._endResults();
      case 'log':       return self._logAppender(data.log);
      case 'error':     return this.onerror(data.error);
      }
    };
    this._queryWorker.onerror = function (error) {
      self._stopExecution(error);
    };
  }

  LdfQueryUI.prototype = {
    // Default widget options
    options: {
      datasources: [],
      queries: [],
      prefixes: [],
    },

    // Initializes the widget
    _create: function () {
      var self = this,
          options = this.options,
          $element = this.element,
          $stop = this.$stop = $('.stop', $element),
          $start = this.$start = $('.start', $element),
          $query = this.$query = $('.queryText', $element),
          $queries = this.$queries = $('.query', $element),
          $log = $('.log', $element),
          $results = $('.results', $element),
          $resultsText = $('
', { class: 'text' }),
          $datasources = this.$datasources = $('.datasources', $element),
          $datetime = this.$datetime = $('.datetime', $element),
          $details = this.$details = $('.details', $element),
          $showDetails = this.$showDetails = $('.details-toggle', $element);

      // Replace non-existing elements by an empty text box
      if (!$datasources.length) $datasources = this.$datasources = $('<select>');
      if (!$results.length) $results = $('
');
      if (!$log.length) $log = $('
');

      // When a datasource is selected, load the corresponding query set
      $datasources.chosen({
        create_option: true, persistent_create_option: true,
        skip_no_results: true, search_contains: true, display_selected_options: false,
        placeholder_text: ' ', create_option_text: 'Add datasource',
      });
      $datasources.change(function () {
        self._setOption('selectedDatasources', $datasources.val());
      });

      // When a query is selected, load it into the editor
      $query.edited = $query.val() !== '';
      $query.change(function () {
        options.query = $query.val();
        $query.edited = true;
      });
      $queries.chosen({ skip_no_results: true, placeholder_text: ' ' });
      $queries.change(function (query) {
        if (query = $queries.val())
          $query.val(options.query = query).edited = false;
      });

      // Update datetime on change
      $datetime.change(function () { self._setOption('datetime', $datetime.val()); });

      // Set up starting and stopping
      $start.click(this._startExecution.bind(this));
      $stop.click(this._stopExecution.bind(this));

      // Set up details toggling
      $showDetails.click(function () {
        $details.is(':visible') ? self._hideDetails() : self._showDetails();
      });

      // Set up results
      $results.append($resultsText);
      this._resultsScroller = new FastScroller($results, renderResult);
      this._resultAppender = appenderFor($resultsText);
      this._logAppender = appenderFor($log);
      this.$timing = $('.timing', $element);

      // Apply all options
      for (var key in options)
        this._setOption(key, options[key], true);
    },

    // Sets a specific widget option
    _setOption: function (key, value, initialize) {
      var options = this.options;
      if (!initialize && options[key] === value) return;
      options[key] = value;

      // Apply the chosen option
      var self = this, $datasources = this.$datasources, $queries = this.$queries;
      switch (key) {
      // Set the datasources available for querying
      case 'datasources':
        // Create options for each datasource
        $datasources.empty().append((value || []).map(function (datasource, index) {
          return $('<option>', { text: datasource.name, value: datasource.url });
        }));
        // Restore selected datasources
        this._setOption('selectedDatasources', options.selectedDatasources, true);
        break;
      // Set the datasources to query
      case 'selectedDatasources':
        // Choose the first available datasource if none was chosen
        var $options = $datasources.children();
        if (initialize && !(value && value.length) && $options.length)
          options[key] = value = [$options.val()];
        // Select chosen datasources that were already in the list
        var selected = toHash(value);
        $options.each(function (index) {
          var $option = $(this), url = $(this).val();
          $option.attr('selected', url in selected);
          selected[url] = true;
        });
        // Add and select chosen datasources that were not in the list yet
        $datasources.append($.map(selected, function (exists, url) {
          return exists ? null :
                 $('<option>', { text: url, value: url, selected: true });
        })).trigger('chosen:updated');
        // Update the query set
        this._loadQueries(value);
        break;
      // Set the query
      case 'query':
        this.$query.val(value).change();
        break;
      // Set the list of all possible queries
      case 'queries':
        value.forEach(function (query) {
          // Create a regex that only matches relevant datasources for this query
          query.datasourceMatcher =
            new RegExp('^(?:' + (
              // Datasource specifications can use '*' to indicate a wildcard,
              // and specifying no datasources means all datasources match
              query.datasources.map(toRegExp).join('|').replace(/\\\*|^$/g, '.*')
            ) + ')$');
        });
        this._loadQueries(options.selectedDatasources);
        break;
      case 'datetime':
        if (value)
          this._showDetails();
        this.$datetime.val(value).change();
        break;
      // Set the list of selectable queries
      case 'relevantQueries':
        value = value || [];
        // If the current query was not edited and not in the list,
        // load the first selectable query
        if (!this.$query.edited &&
            !value.some(function (v) { return v.sparql === options.query; }))
          value[0] && this._setOption('query', value[0].sparql);
        // Update the selectable query list
        $queries.empty().append($('<option>'), value.map(function (query) {
          return $('<option>', { text: query.name, value: query.sparql,
                                 selected: options.query === query.sparql });
        })).trigger('chosen:updated').change();
        break;
      // Load settings from a JSON resource
      case 'settings':
        $.getJSON(value, function (settings) {
          for (var key in settings)
            self._setOption(key, settings[key]);
        });
        break;
      }
    },

    // Load queries relevant for the given datasources
    _loadQueries: function (datasources) {
      var queries = (this.options.queries || []).filter(function (query, index) {
        query.id = index;
        // Include the query if it is relevant for at least one datasource
        return !datasources ||
               datasources.some(function (d) { return query.datasourceMatcher.test(d); });
      });

      // Load the set of queries if it is different from the current set
      var querySetId = queries.map(function (q) { return q.id; }).join();
      if (this._querySetId !== querySetId) {
        this._querySetId = querySetId;
        this._setOption('relevantQueries', queries);
        this.element.trigger('changeQuerySet');
      }
    },

    // Starts query execution
    _startExecution: function () {
      var datasources = this.$datasources.val();
      if (!datasources || !datasources.length)
        return alert('Please choose a datasource to execute the query.');

      // Clear results and log
      this.$stop.show();
      this.$start.hide();
      this._resultsScroller.removeAll();
      this._resultAppender.clear();
      this._logAppender.clear();

      // Scroll page to the results
      $('html,body').animate({ scrollTop: this.$start.offset().top });

      // Start the timer
      this._resultCount = 0;
      this._startTimer();

      // Let the worker execute the query
      this._queryWorker.postMessage({
        type: 'query',
        query: this.$query.val(),
        datasources: datasources,
        prefixes: this.options.prefixes,
        datetime: parseDate(this.options.datetime),
      });
    },

    // Stops query execution
    _stopExecution: function (error) {
      // Stop the worker and the timer
      this._queryWorker.postMessage({ type: 'stop' });
      this._stopTimer();

      // Reset the UI
      this.$stop.hide();
      this.$start.show();
      if (error && error.message)
        this._resultAppender(error.message);
      this._resultAppender.flush();
      this._logAppender.flush();
      this._writeResult = this._writeEnd = null;
    },

    // Initializes the result display, depending on the query type
    _initResults: function (queryType) {
      var resultAppender = this._resultAppender;
      switch (queryType) {
      // For SELECT queries, add the rows to the result
      case 'SELECT':
        this._writeResult = function (row) {
          this._resultsScroller.addContent([row]);
        };
        this._writeEnd = function () {
          if (!this._resultCount)
            resultAppender('This query has no results.');
        };
        break;
      // For CONSTRUCT and DESCRIBE queries,
      // write a Turtle representation of the triples
      case 'CONSTRUCT':
      case 'DESCRIBE':
        var writer = new N3.Writer({
          write: function (chunk, encoding, done) {
            resultAppender(chunk), done && done();
          },
        }, this.options);
        this._writeResult = function (triple) { writer.addTriple(triple); };
        this._writeEnd = function () { writer.end(); };
        break;
      // For ASK queries, write whether an answer exists
      case 'ASK':
        this._writeResult = function (exists) { resultAppender(exists); };
        this._writeEnd = $.noop;
        break;
      // Other queries cannot be displayed
      default:
        resultAppender(queryType + ' queries are unsupported.');
      }
    },

    // Adds a result to the display
    _addResult: function (result) {
      if (this._writeResult) {
        this._resultCount++;
        this._writeResult(result);
      }
    },

    // Finalizes the display after all results have been added
    _endResults: function () {
      if (this._writeEnd) {
        this._writeEnd();
        this._stopExecution();
      }
    },

    // Starts the results timer
    _startTimer: function () {
      this._startTime = new Date();
      this._stopTimer();
      this._updateTimer();
      this._updateTimerHandle = setInterval(this._updateTimer.bind(this), 100);
    },

    // Updates the result timer
    _updateTimer: function () {
      this.$timing.text(this._resultCount.toLocaleString() + ' result' +
                        (this._resultCount === 1 ? '' : 's') + ' in ' +
                        ((new Date() - this._startTime) / 1000).toFixed(1) + 's');
    },

    // Stops the result timer
    _stopTimer: function () {
      if (this._updateTimerHandle) {
        this._updateTimer();
        clearInterval(this._updateTimerHandle);
        this._updateTimerHandle = 0;
      }
    },

    // Shows the details panel
    _showDetails: function () {
      this.$details.slideDown(150);
      this.$showDetails.addClass('enabled');
    },

    // Hides the details panel
    _hideDetails: function () {
      this._setOption('datetime', '');
      this.$details.slideUp(150);
      this.$showDetails.removeClass('enabled');
    },
  };

  // Creates a function that appends text to the given element in a throttled way
  function appenderFor($element) {
    var buffer, allowedAppends, timeout, delay = 1000;
    // Resets the element
    function clear() {
      buffer = '';
      $element.empty();
      allowedAppends = 50;
      clearTimeout(timeout);
    }
    clear();
    // Appends the text to the element, or queues it for appending
    function append(text) {
      // Append directly if still allowed
      if (allowedAppends > 0) {
        $element.append(escape(text));
        // When no longer allowed, re-enable appending after a delay
        if (--allowedAppends === 0)
          timeout = setTimeout(flush, delay);
      }
      // Otherwise, queue for appending
      else
        buffer += text;
    }
    // Writes buffered text and re-enables appending
    function flush() {
      // Clear timeout in case flush was explicitly triggered
      clearTimeout(timeout);
      timeout = null;
      // Re-enable appending right away if no text was queued
      if (!buffer)
        allowedAppends = 1;
      // Otherwise, append queued text and wait to re-enable
      else {
        $element.append(escape(buffer));
        buffer = '';
        timeout = setTimeout(flush, delay);
      }
    }
    // Export the append function
    append.clear = clear;
    append.flush = flush;
    return append;
  }

  // Escapes special HTML characters and convert URLs into links
  function escape(text) {
    return (text + '').replace(/(<)|(>)|(&)|http(s?:\/\/[^\s<>]+)/g, escapeMatch);
  }
  function escapeMatch(match, lt, gt, amp, url) {
    return lt && '<' || gt && '>' || amp && '&' ||
           (url = 'http' + escape(url)) &&
           '' + url + '';
  }

  // Escapes the string for usage as a regular expression
  function toRegExp(string) {
    return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  }

  // Converts the array to a hash with the elements as keys
  function toHash(array) {
    var hash = {}, length = array ? array.length : 0;
    for (var i = 0; i < length; i++)
      hash[array[i]] = false;
    return hash;
  }

  // Parses a yyyy-mm-dd date string into a Date
  function parseDate(date) {
    if (date) {
      try { return new Date(Date.parse(date)); }
      catch (e) { /* ignore invalid dates */ }
    }
  }

  // Transforms a result row into an HTML element
  function renderResult(row, container) {
    container = container || $('
', { class: 'result' }).append($('
'))[0];
    $(container.firstChild).empty().append($.map(row, function (value, variable) {
      return [$('
', { text: variable }), $('
', { html: escape(value) })];
    }));
    return container;
  }
})(jQuery);
<|endoftext|>


<commit_before>var async = require('async');
var _ = require('underscore');
var graph = require('fbgraph');

/**
 * GET /new_transaction
 * Contact form page.
 */

exports.getNewTransaction = function(req, res) {
  var token = _.findWhere(req.user.tokens, { kind: 'facebook' });
  graph.setAccessToken(token.accessToken);
  async.parallel({
     getMyFriends: function(done) {
        graph.get(req.user.facebook + '/friends', function(err, friends) {
          done(err, friends.data);
	});
     }
  },
  function(err, results) {
    if (err) return next(err);
    var friends = results.getMyFriends;
    var friendsLength = Object.keys(friends).length;
    var friendsJson = [];
    for (var i = 0; i < friendsLength; i++) {
	friendsJson.push("{name:'"+friends[i].name+"'}");
    }
    res.render('new_transaction', {
      title: 'New Transaction',
      friends: "["+friendsJson+"]"
    });
  });
};

/**
 * POST /new_transaction
 * Send a contact form via Nodemailer.
 * @param name
 * @param amount
 * @param comment
 */

exports.postNewTransaction = function(req, res) {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('comment', 'Comment cannot be blank').notEmpty();

  var errors = req.validationErrors();
  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/new_transaction');
  }
};
<commit_msg>Include missing next param.<commit_after>var async = require('async');
var _ = require('underscore');
var graph = require('fbgraph');

/**
 * GET /new_transaction
 * Contact form page.
 */

exports.getNewTransaction = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'facebook' });
  graph.setAccessToken(token.accessToken);
  async.parallel({
     getMyFriends: function(done) {
        graph.get(req.user.facebook + '/friends', function(err, friends) {
          done(err, friends.data);
	});
     }
  },
  function(err, results) {
    if (err) return next(err);
    var friends = results.getMyFriends;
    var friendsLength = Object.keys(friends).length;
    var friendsJson = [];
    for (var i = 0; i < friendsLength; i++) {
	friendsJson.push("{name:'"+friends[i].name+"'}");
    }
    res.render('new_transaction', {
      title: 'New Transaction',
      friends: "["+friendsJson+"]"
    });
  });
};

/**
 * POST /new_transaction
 * Send a contact form via Nodemailer.
 * @param name
 * @param amount
 * @param comment
 */

exports.postNewTransaction = function(req, res) {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('comment', 'Comment cannot be blank').notEmpty();

  var errors = req.validationErrors();
  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/new_transaction');
  }
};
<|endoftext|>


<commit_before>var testControllers = angular.module('testController', []);

/*Filter for displaying time format  -- Liz*/
app.filter('formatTime', function () {
    return function (sec) {
        return new Date(1970, 0, 1).setSeconds(sec);
    }
});

testControllers.controller('testCtrl', ['$scope', '$interval', 'loadTestFactory', function ($scope, $interval, loadTestFactory) {
    $scope.testStatus = "pending";
    $scope.quizId = null;
    $scope.testTitle = "";
    $scope.activequiz = [];
    $scope.qTitle = "";
    var counter = 0;
    $scope.options = [];
    $scope.qLength = 0;
    $scope.userAns = {answer: 0};
    $scope.allQuesitons = [];
    $scope.timeFormat = 'HH:mm:ss';

    /*Timer * -- Liz*/
    var decrCountdown = function () {
        $scope.countdown -= 1;
        if ($scope.countdown < 1) {
            endQuiz(); // calling endquiz method if countdown ends
            console.log('calling endquiz from timer');
        }
    };
    /* timer */
    var startCountdown = function () {
        $interval(decrCountdown, 1000, $scope.countdown);
    };

    /*start quiz*/
    $scope.startQuiz = function () {
        $scope.testStatus = "inProgress";
        $scope.activequiz = loadTestFactory.getQuiz(0);
        $scope.testTitle = $scope.activequiz.title;
        $scope.questions = $scope.activequiz.questions;
        $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
        $scope.options = $scope.activequiz.questions[ counter ].options;
        $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;
        $scope.qLength = $scope.activequiz.questions.length;
        $scope.countdown = $scope.activequiz.limitMinutes * 60; // minutes into seconds
        for (var i = 0; i < $scope.qLength; i++){

        $scope.saveToObject($scope.questions[i].questionTitle, $scope.questions[i].options, $scope.questions[i].correctAns , $scope.userAns.answer);
        }
        console.log("filling test data");
        startCountdown();
    };

    $scope.nextQuestion = function (checkedValue) {
        console.log(counter);
        counter++;
        if (counter < $scope.qLength) {
            $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
            $scope.options = $scope.activequiz.questions[ counter ].options;
            $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;

        } else if (counter >= $scope.qLength) {
            counter = $scope.qLength;
            //  kalla funktion som visar test översikt i slut
            $scope.endQuiz();
            console.log('endquiz called from nextquestion function');
        }
    };

    $scope.prevQuestion = function () {
        counter--;
        if (counter > 0) {
            $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
            $scope.options = $scope.activequiz.questions[ counter ].options;
            $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;
        }else{
            counter = 0;
        }
    };

    $scope.saveToObject = function (title, options, correctAns , answer) {
        var object = {
            questionTitle: title,
            options: options,
            correctAns: correctAns,
            userAns : answer
        }

        $scope.allQuesitons.push(object);
    }

    /*Add answer to answers array*/
    $scope.addAns = function () {

    };

    $scope.getResult = function () {
    };

    $scope.endQuiz = function () {
        $scope.testStatus = "inactive";
    };

}]);<commit_msg>fixed so that questions are saved...again<commit_after>var testControllers = angular.module('testController', []);

/*Filter for displaying time format  -- Liz*/
app.filter('formatTime', function () {
    return function (sec) {
        return new Date(1970, 0, 1).setSeconds(sec);
    }
});

testControllers.controller('testCtrl', ['$scope', '$interval', 'loadTestFactory', function ($scope, $interval, loadTestFactory) {
    $scope.testStatus = "pending";
    $scope.quizId = null;
    $scope.testTitle = "";
    $scope.activequiz = [];
    $scope.qTitle = "";
    var counter = 0;
    $scope.options = [];
    $scope.qLength = 0;
    $scope.userAns = {answer: 0};
    $scope.allQuesitons = [];
    $scope.timeFormat = 'HH:mm:ss';

    /*Timer * -- Liz*/
    var decrCountdown = function () {
        $scope.countdown -= 1;
        if ($scope.countdown < 1) {
            endQuiz(); // calling endquiz method if countdown ends
            console.log('calling endquiz from timer');
        }
    };
    /* timer */
    var startCountdown = function () {
        $interval(decrCountdown, 1000, $scope.countdown);
    };

    /*start quiz*/
    $scope.startQuiz = function () {
        $scope.testStatus = "inProgress";
        $scope.activequiz = loadTestFactory.getQuiz(0);
        $scope.testTitle = $scope.activequiz.title;
        $scope.questions = $scope.activequiz.questions;
        $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
        $scope.options = $scope.activequiz.questions[ counter ].options;
        $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;
        $scope.qLength = $scope.activequiz.questions.length;
        $scope.countdown = $scope.activequiz.limitMinutes * 60; // minutes into seconds
        for (var i = 0; i < $scope.qLength; i++){

        $scope.saveToObject($scope.questions[i].questionTitle, $scope.questions[i].options, $scope.questions[i].correctAns , $scope.userAns.answer);
        }
        console.log("filling test data");
        startCountdown();
    };

    $scope.nextQuestion = function (checkedValue) {
        console.log(counter);
        counter++;
        if (counter < $scope.qLength) {
            $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
            $scope.options = $scope.activequiz.questions[ counter ].options;
            $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;

        } else if (counter >= $scope.qLength) {
            counter = $scope.qLength;
            //  kalla funktion som visar test översikt i slut
            $scope.endQuiz();
            console.log('endquiz called from nextquestion function');
        }
    };

    $scope.prevQuestion = function () {
        counter--;
        if (counter >= 0) {
            $scope.qTitle = $scope.activequiz.questions[ counter ].questionTitle;
            $scope.options = $scope.activequiz.questions[ counter ].options;
            $scope.corrAns = $scope.activequiz.questions[ counter ].correctAns;
        }else{
            counter = 0;
        }
    };

    $scope.saveToObject = function (title, options, correctAns , answer) {
        var object = {
            questionTitle: title,
            options: options,
            correctAns: correctAns,
            userAns : answer
        }

        $scope.allQuesitons.push(object);
    }

    /*updates answers to object array allQuestions */
    $scope.addAns = function () {
        $scope.allQuesitons[counter].userAns = $scope.userAns.answer;
        console.table($scope.allQuesitons);
    };

    $scope.endQuiz = function () {
        $scope.testStatus = "inactive";
    };

}]);<|endoftext|>


<commit_before>/**!
 * byte - benchmark/put.js
 *
 * Copyright(c) fengmk2 and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
 *   dead-horse <dead_horse@qq.com> (https://github.com/dead-horse)
 */

"use strict";

/**
 * Module dependencies.
 */

var Benchmark = require('benchmark');
var benchmarks = require('beautify-benchmark');
var ByteBuffer = require('../');

var suite = new Benchmark.Suite();

var putBytes = ByteBuffer.allocate(1);
var putCharBytes = ByteBuffer.allocate(1);
var putCharNumBytes = ByteBuffer.allocate(1);
var putShortBytes = ByteBuffer.allocate(2);
var putIntBytes = ByteBuffer.allocate(4);
var putFloatBytes = ByteBuffer.allocate(4);
var putDoubleBytes = ByteBuffer.allocate(8);
var putLongBytes = ByteBuffer.allocate(8);
var putBigLongBytes = ByteBuffer.allocate(8);
var putStringBytes = ByteBuffer.allocate(100);
var putBufStringBytes = ByteBuffer.allocate(100);
var putRawStringBytes = ByteBuffer.allocate(100);

var bytes = ByteBuffer.allocate(1024 * 1024);

var string = '';
while(string.length < 100) {
  string += 'fffff';
}
var bufString = new Buffer(100);

var buf = new Buffer(10);
var src = new Buffer([0x61, 0x62, 0x63]);

suite
.add('buf[0] = 97', function () {
  buf[0] = 97;
})
.add('put(0, 97)', function () {
  putBytes.put(0, 97);
})
.add('copy[0] = 97', function () {
  src.copy(buf, 0, 0, 1);
})
.add('putBuffer(0, <Buffer 61>)', function () {
  putBytes.putBuffer(0, src, 0, 1);
})
.add('putChar(0, "a")', function () {
  putCharBytes.putChar(0, 'a');
})
.add('putChar(0, 97)', function () {
  putCharNumBytes.putChar(0, 97);
})
.add('putChar("a")', function () {
  putCharBytes.putChar('a');
})
.add('putChar(97)', function () {
  putCharNumBytes.putChar(97);
})
.add('putShort(0, 1)', function () {
  putShortBytes.putShort(0, 1);
})
.add('putInt(0, 1)', function () {
  putIntBytes.putInt(0, 1);
})
.add('putFloat(0, 1)', function () {
  putFloatBytes.putFloat(0, 1);
})
.add('putDouble(0, 1)', function () {
  putDoubleBytes.putDouble(0, 1);
})
.add('putLong(0, 100000)', function () {
  putLongBytes.putLong(0, 100000);
})
.add('putSmallSLong(0, "10000") ', function () {
  putLongBytes.putLong(0, '10000');
})
.add('putBigNumLong(0, 34359738368) ', function () {
  putLongBytes.putLong(0, 34359738368);
})
.add('putSafeStrLong(0, "34359738368")', function () {
  putLongBytes.putLong(0, "34359738368");
})
.add('putStrLong(0, "9223372036854775808")', function () {
  putLongBytes.putLong(0, '9223372036854775808');
})
.add('ByteBuffer.allocate(100).putString(0, str)', function () {
  ByteBuffer.allocate(100).putString(0, string);
})
.add('putString(0, str)', function () {
  putStringBytes.putString(0, string);
})
.add('bytes.putString(str)', function () {
  bytes.reset();
  bytes.putString(string);
})
.add('putString(0, buf)', function () {
  putBufStringBytes.putString(0, bufString);
})
.add('bytes.putString(buf)', function () {
  bytes.reset();
  bytes.putString(bufString);
})
.add('putRawString(0, str)', function () {
  putRawStringBytes.putRawString(0, string);
})
.add('bytes.putRawString(str)', function () {
  bytes.reset();
  bytes.putRawString(string);
})
.add('bytes.putRawString(str).array()', function () {
  bytes.reset();
  bytes.putRawString(string).array();
})
.add('bytes.putRawString(str).array(0, 100)', function () {
  bytes.reset();
  bytes.putRawString(string).array(0, 100);
})

.on('cycle', function(event) {
  benchmarks.add(event.target);
})
.on('start', function(event) {
  console.log('\n  node version: %s, date: %s\n  Starting...', process.version, Date());
})
.on('complete', function done() {
  benchmarks.log();
})
.run({ 'async': false });

  // node version: v0.11.13, date: Mon Aug 25 2014 20:53:00 GMT+0800 (CST)
  // Starting...
  // 26 tests completed.

  // buf[0] = 97                                x 84,635,292 ops/sec ±2.52% (92 runs sampled)
  // put(0, 97)                                 x 79,838,465 ops/sec ±1.68% (96 runs sampled)
  // copy[0] = 97                               x 11,999,602 ops/sec ±1.07% (93 runs sampled)
  // putBuffer(0, <Buffer 61>)                  x 11,057,277 ops/sec ±0.64% (96 runs sampled)
  // putChar(0, "a")                            x 79,879,315 ops/sec ±1.41% (95 runs sampled)
  // putChar(0, 97)                             x 70,565,032 ops/sec ±1.81% (93 runs sampled)
  // putChar("a")                               x 19,361,166 ops/sec ±11.06% (86 runs sampled)
  // putChar(97)                                x 15,251,731 ops/sec ±1.32% (48 runs sampled)
  // putShort(0, 1)                             x 20,484,781 ops/sec ±1.03% (93 runs sampled)
  // putInt(0, 1)                               x  7,993,369 ops/sec ±8.83% (92 runs sampled)
  // putFloat(0, 1)                             x  9,646,213 ops/sec ±0.74% (99 runs sampled)
  // putDouble(0, 1)                            x  9,685,708 ops/sec ±0.51% (99 runs sampled)
  // putLong(0, 100000)                         x 26,825,432 ops/sec ±0.78% (99 runs sampled)
  // putSmallSLong(0, "10000")                  x 16,357,843 ops/sec ±0.79% (97 runs sampled)
  // putBigNumLong(0, 34359738368)              x  9,969,444 ops/sec ±0.77% (94 runs sampled)
  // putSafeStrLong(0, "34359738368")           x  4,633,738 ops/sec ±0.72% (98 runs sampled)
  // putStrLong(0, "9223372036854775808")       x    970,579 ops/sec ±0.82% (99 runs sampled)
  // ByteBuffer.allocate(100).putString(0, str) x    151,029 ops/sec ±1.55% (88 runs sampled)
  // putString(0, str)                          x    756,345 ops/sec ±0.77% (97 runs sampled)
  // bytes.putString(str)                       x    760,108 ops/sec ±0.60% (98 runs sampled)
  // putString(0, buf)                          x  3,308,635 ops/sec ±5.37% (96 runs sampled)
  // bytes.putString(buf)                       x  2,203,119 ops/sec ±0.91% (97 runs sampled)
  // putRawString(0, str)                       x  2,354,233 ops/sec ±0.79% (96 runs sampled)
  // bytes.putRawString(str)                    x  1,389,442 ops/sec ±0.86% (96 runs sampled)
  // bytes.putRawString(str).array()            x    294,978 ops/sec ±1.87% (87 runs sampled)
  // bytes.putRawString(str).array(0, 100)      x    320,174 ops/sec ±1.71% (87 runs sampled)
<commit_msg>fix benchmark<commit_after>/**!
 * byte - benchmark/put.js
 *
 * Copyright(c) fengmk2 and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
 *   dead-horse <dead_horse@qq.com> (https://github.com/dead-horse)
 */

"use strict";

/**
 * Module dependencies.
 */

var Benchmark = require('benchmark');
var benchmarks = require('beautify-benchmark');
var ByteBuffer = require('../');

var suite = new Benchmark.Suite();

var putBytes = ByteBuffer.allocate(1);
var putCharBytes = ByteBuffer.allocate(1);
var putCharNumBytes = ByteBuffer.allocate(1);
var putShortBytes = ByteBuffer.allocate(2);
var putIntBytes = ByteBuffer.allocate(4);
var putFloatBytes = ByteBuffer.allocate(4);
var putDoubleBytes = ByteBuffer.allocate(8);
var putLongBytes = ByteBuffer.allocate(8);
var putBigLongBytes = ByteBuffer.allocate(8);
var putStringBytes = ByteBuffer.allocate(100);
var putBufStringBytes = ByteBuffer.allocate(100);
var putRawStringBytes = ByteBuffer.allocate(100);

var bytes = ByteBuffer.allocate(1024 * 1024);

var string = '';
while(string.length < 100) {
  string += 'fffff';
}
var bufString = new Buffer(100);

var buf = new Buffer(10);
var src = new Buffer([0x61, 0x62, 0x63]);

suite
.add('buf[0] = 97', function () {
  buf[0] = 97;
})
.add('put(0, 97)', function () {
  putBytes.put(0, 97);
})
.add('copy[0] = 97', function () {
  src.copy(buf, 0, 0, 1);
})
.add('put(<Buffer 61>)', function () {
  putBytes.put(src, 0, 1);
})
.add('putChar(0, "a")', function () {
  putCharBytes.putChar(0, 'a');
})
.add('putChar(0, 97)', function () {
  putCharNumBytes.putChar(0, 97);
})
.add('putChar("a")', function () {
  putCharBytes.position(0);
  putCharBytes.putChar('a');
})
.add('putChar(97)', function () {
  putCharNumBytes.position(0);
  putCharNumBytes.putChar(97);
})
// .add('putShort(0, 1)', function () {
//   putShortBytes.putShort(0, 1);
// })
// .add('putInt(0, 1)', function () {
//   putIntBytes.putInt(0, 1);
// })
// .add('putFloat(0, 1)', function () {
//   putFloatBytes.putFloat(0, 1);
// })
// .add('putDouble(0, 1)', function () {
//   putDoubleBytes.putDouble(0, 1);
// })
// .add('putLong(0, 100000)', function () {
//   putLongBytes.putLong(0, 100000);
// })
// .add('putSmallSLong(0, "10000") ', function () {
//   putLongBytes.putLong(0, '10000');
// })
// .add('putBigNumLong(0, 34359738368) ', function () {
//   putLongBytes.putLong(0, 34359738368);
// })
// .add('putSafeStrLong(0, "34359738368")', function () {
//   putLongBytes.putLong(0, "34359738368");
// })
// .add('putStrLong(0, "9223372036854775808")', function () {
//   putLongBytes.putLong(0, '9223372036854775808');
// })
// .add('ByteBuffer.allocate(100).putString(0, str)', function () {
//   ByteBuffer.allocate(100).putString(0, string);
// })
// .add('putString(0, str)', function () {
//   putStringBytes.putString(0, string);
// })
// .add('bytes.putString(str)', function () {
//   bytes.reset();
//   bytes.putString(string);
// })
// .add('putString(0, buf)', function () {
//   putBufStringBytes.putString(0, bufString);
// })
// .add('bytes.putString(buf)', function () {
//   bytes.reset();
//   bytes.putString(bufString);
// })
// .add('putRawString(0, str)', function () {
//   putRawStringBytes.putRawString(0, string);
// })
// .add('bytes.putRawString(str)', function () {
//   bytes.reset();
//   bytes.putRawString(string);
// })
// .add('bytes.putRawString(str).array()', function () {
//   bytes.reset();
//   bytes.putRawString(string).array();
// })
// .add('bytes.putRawString(str).array(0, 100)', function () {
//   bytes.reset();
//   bytes.putRawString(string).array(0, 100);
// })

.on('cycle', function(event) {
  benchmarks.add(event.target);
})
.on('start', function(event) {
  console.log('\n  node version: %s, date: %s\n  Starting...', process.version, Date());
})
.on('complete', function done() {
  benchmarks.log();
})
.run({ 'async': false });

  // node version: v0.11.13, date: Mon Aug 25 2014 20:53:00 GMT+0800 (CST)

  // buf[0] = 97                                x 88,742,069 ops/sec ±2.47% (97 runs sampled)
  // put(0, 97)                                 x 82,112,998 ops/sec ±1.53% (100 runs sampled)
  // copy[0] = 97                               x 12,676,454 ops/sec ±0.82% (96 runs sampled)
  // put(<Buffer 61>)                           x 11,351,102 ops/sec ±1.55% (93 runs sampled)
  // putChar(0, "a")                            x 81,818,815 ops/sec ±1.51% (96 runs sampled)
  // putChar(0, 97)                             x 76,162,783 ops/sec ±2.49% (96 runs sampled)
  // putChar("a")                               x 66,728,369 ops/sec ±0.99% (97 runs sampled)
  // putChar(97)                                x 47,502,811 ops/sec ±1.97% (94 runs sampled)
  // putShort(0, 1)                             x 19,918,200 ops/sec ±1.03% (95 runs sampled)
  // putInt(0, 1)                               x  7,027,621 ops/sec ±6.70% (91 runs sampled)
  // putFloat(0, 1)                             x 10,104,306 ops/sec ±1.04% (91 runs sampled)
  // putDouble(0, 1)                            x 10,157,512 ops/sec ±1.10% (95 runs sampled)
  // putLong(0, 100000)                         x 26,364,254 ops/sec ±0.94% (93 runs sampled)
  // putSmallSLong(0, "10000")                  x 13,080,481 ops/sec ±1.18% (91 runs sampled)
  // putBigNumLong(0, 34359738368)              x  7,608,611 ops/sec ±1.17% (90 runs sampled)
  // putSafeStrLong(0, "34359738368")           x  4,070,055 ops/sec ±0.88% (93 runs sampled)
  // putStrLong(0, "9223372036854775808")       x    985,469 ops/sec ±0.89% (95 runs sampled)
  // ByteBuffer.allocate(100).putString(0, str) x    149,300 ops/sec ±1.60% (86 runs sampled)
  // putString(0, str)                          x    914,022 ops/sec ±3.70% (90 runs sampled)
  // bytes.putString(str)                       x    973,302 ops/sec ±0.72% (97 runs sampled)
  // putString(0, buf)                          x  2,535,609 ops/sec ±0.93% (94 runs sampled)
  // bytes.putString(buf)                       x  2,570,024 ops/sec ±3.20% (97 runs sampled)
  // putRawString(0, str)                       x  2,514,063 ops/sec ±0.74% (98 runs sampled)
  // bytes.putRawString(str)                    x  1,479,018 ops/sec ±0.76% (96 runs sampled)
  // bytes.putRawString(str).array()            x    325,139 ops/sec ±1.71% (83 runs sampled)
  // bytes.putRawString(str).array(0, 100)      x    333,073 ops/sec ±1.72% (85 runs sampled)

  // node version: v0.10.31, date: Mon Aug 25 2014 22:11:41 GMT+0800 (CST)
  // Starting...

  // buf[0] = 97      x 79,267,829 ops/sec ±2.42% (88 runs sampled)
  // put(0, 97)       x 38,461,819 ops/sec ±1.13% (87 runs sampled)
  // copy[0] = 97     x  7,619,200 ops/sec ±0.85% (96 runs sampled)
  // put(<Buffer 61>) x  6,753,096 ops/sec ±1.06% (92 runs sampled)
  // putChar(0, "a")  x 44,172,729 ops/sec ±0.60% (97 runs sampled)
  // putChar(0, 97)   x 52,013,919 ops/sec ±1.86% (89 runs sampled)
  // putChar("a")     x 29,461,362 ops/sec ±0.56% (100 runs sampled)
  // putChar(97)      x 33,144,916 ops/sec ±0.89% (93 runs sampled)
<|endoftext|>


<commit_before>var passport = require('passport');

var User = require('../models/User');

// Get the new user form
var newUser = function(req, res, next) {
  res.render('auth/register');
};

//Post the new user form
var create = function(req, res) {
  User.register(new User({username: req.body.username, name: req.body.name}), req.body.password, function(err, user) {
    if (err) return res.render('auth/register', {user: user});
    passport.authenticate('local')(req, res, function () {
      req.session.save(function (err) {
        if (err) {
          return next(err);
        }
        res.redirect('/users/:id');
      });
    });
  });
};

var show = function(req, res, next) {
  var id = req.params.id;
  User.findById({_id: id}, function(error, user) {
    if(error) res.json({message: 'Could not find User because: ' + error});
        res.render(
          'user/:id',
          {
            user: req.user
        }
        );
        //api time!
        //rs.json (user: user});
      });
};

//NEED TO WRITE CODE TO EDIT USER PROFILE

//NEED TO WRITE CODE TO DELETE USER PROFILE

module.exports = {
  newUser:  newUser,
  create:   create,
  show:     show
};
<commit_msg>User show page should receive info about user<commit_after>var passport = require('passport');

var User = require('../models/User');

// Get the new user form
var newUser = function(req, res, next) {
  res.render('auth/register');
};

//Post the new user form
var create = function(req, res) {
  User.register(new User({username: req.body.username, name: req.body.name}), req.body.password, function(err, user) {
    if (err) return res.render('auth/register', {user: user});
    passport.authenticate('local')(req, res, function () {
      req.session.save(function (err) {
        if (err) {
          return next(err);
        }
        res.redirect('/users/:id');
      });
    });
  });
};

var show = function(req, res, next) {
  var id = req.params.id;
  User.findById({_id: id}, function(error, user) {
    if(error) res.json({message: 'Could not find User because: ' + error});
        res.render('users/show', {user: user});
        //api time!
        //rs.json (user: user});
      });
};

//NEED TO WRITE CODE TO EDIT USER PROFILE

//NEED TO WRITE CODE TO DELETE USER PROFILE

module.exports = {
  newUser:  newUser,
  create:   create,
  show:     show
};
<|endoftext|>


<commit_before>var async = require('async');
var postgres = require('../postgres');

function prepareQueryValues(resultSet) {
  //
  // Prepare parametrized query
  //

  var params = '';
  var values = [];
  var count = 1;

  // Construct params string
  params = '$'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::int8, $'+(count++)+
           '::int8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::int4, $'+(count++)+
           '::int4, $'+(count++)+
           "::timestamp AT TIME ZONE 'UTC', $"+(count++)+
           '::float8, $'+(count++)+
           '::float8';

  // Get current time
  var now = new Date();

  values.push(resultSet.metrics.bidMean,
              resultSet.metrics.bidWeightedAverage,
              resultSet.metrics.bidMedian,
              resultSet.metrics.askWeightedAverage,
              resultSet.metrics.askMean,
              resultSet.metrics.askMedian,
              resultSet.metrics.bidPricesVolume,
              resultSet.metrics.askPricesVolume,
              resultSet.metrics.bidPercentile95,
              resultSet.metrics.askPercentile95,
              resultSet.regionID,
              resultSet.typeID,
              now.toUTCString(),
              resultSet.metrics.bidStdDev,
              resultSet.metrics.askStdDev,
              resultSet.metrics.regionID,
              resultSet.metrics.typeID);

  return {
      params: params,
      values: values
  };
}

function isPresentRegionStat(resultSet, callback) {
  // Get connection from pool
  postgres(function(err, pgClient, done) {
    if (err) {
      // Return connection to pool
      done();

      err.module = 'pgConnect';

      // Handle errors
      callback(err, null);
    } else {
      pgClient.query('SELECT 1 FROM market_data_itemregionstat '+
                             'WHERE mapregion_id = $1 '+
                               'AND invtype_id = $2', [resultSet.regionID, resultSet.typeID], function(err, result) {
                                                                             done(); // Return connection to pool

                                                                             if(err) {
                                                                              err.module = 'orderRegionStats#isPresentRegionStat';
                                                                             }

                                                                             resultSet.result = result;
                                                                             callback(err, resultSet); // Run callback of waterfall
                                                                          });
    }
  });
}

function upsertRegionStats(resultSet, callback) {

  var queryValues = prepareQueryValues(resultSet);

  // Get connection from pool
  postgres(function(err, pgClient, done) {
    if (err) {
      // Return connection to pool
      done();

      err.module = 'pgConnect';

      // Handle errors
      callback(err, null);
    } else {

      if (resultSet.result.rowCount === 0) {

        // Insert new row
        pgClient.query('INSERT INTO market_data_itemregionstat (buymean, ' +
                                                               'buyavg, ' +
                                                               'buymedian, ' +
                                                               'sellmean, ' +
                                                               'sellavg, ' +
                                                               'sellmedian, ' +
                                                               'buyvolume, ' +
                                                               'sellvolume, ' +
                                                               'buy_95_percentile, ' +
                                                               'sell_95_percentile, ' +
                                                               'mapregion_id, ' +
                                                               'invtype_id, ' +
                                                               'lastupdate, ' +
                                                               'buy_std_dev, ' +
                                                               'sell_std_dev) VALUES (' + queryValues.params + ')', queryValues.values.slice(0, 15), function(err, result) {
          done(); // Return connection to pool

          if(err) {
            err.module = 'orderRegionStats#insertRegionStats';
          }

          resultSet.result = result;
          callback(err, resultSet); // Run callback of waterfall
        });
      } else {
        // Update row
        pgClient.query('UPDATE market_data_itemregionstat SET buymean=$1, ' +
                                                             'buyavg=$2, ' +
                                                             'buymedian=$3, ' +
                                                             'sellmean=$4, ' +
                                                             'sellavg=$5, ' +
                                                             'sellmedian=$6, ' +
                                                             'buyvolume=$7, ' +
                                                             'sellvolume=$8, ' +
                                                             'buy_95_percentile=$9, ' +
                                                             'sell_95_percentile=$10, ' +
                                                             'mapregion_id=$11, ' +
                                                             'invtype_id=$12, ' +
                                                             'lastupdate=$13, ' +
                                                             'buy_std_dev=$14, ' +
                                                             'sell_std_dev=$15 WHERE mapregion_id=$16 AND invtype_id=$17', queryValues.values, function(err, result) {
          done(); // Return connection to pool

          if(err) {
            err.module = 'orderRegionStats#updateRegionStats';
          }

          resultSet.result = result;
          callback(err, resultSet); // Run callback of waterfall
        });
      }
    }
  });
}

exports = module.exports = function(resultSet, callback) {
  //
  // Stores order statistics in itemRegionStats table
  //

  if(resultSet.objects.length === 0) {

    // SKIP EMPTY MESSAGES
    return callback(null, resultSet);

  } else {

    async.waterfall([
      function (callback) {
        isPresentRegionStat(resultSet, callback); // Check if region/type pair already exists in DB
      },
      upsertRegionStats                           // Update / insert line
    ], function (error, result) {
      // Error handling
      callback(error, result);
    });
  }

};<commit_msg>Fixed itemRegionStat generation<commit_after>var async = require('async');
var postgres = require('../postgres');

function prepareQueryValues(resultSet) {
  //
  // Prepare parametrized query
  //

  var params = '';
  var values = [];
  var count = 1;

  // Construct params string
  params = '$'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::int8, $'+(count++)+
           '::int8, $'+(count++)+
           '::float8, $'+(count++)+
           '::float8, $'+(count++)+
           '::int4, $'+(count++)+
           '::int4, $'+(count++)+
           "::timestamp AT TIME ZONE 'UTC', $"+(count++)+
           '::float8, $'+(count++)+
           '::float8';

  // Get current time
  var now = new Date();

  values.push(resultSet.metrics.bidMean,
              resultSet.metrics.bidWeightedAverage,
              resultSet.metrics.bidMedian,
              resultSet.metrics.askWeightedAverage,
              resultSet.metrics.askMean,
              resultSet.metrics.askMedian,
              resultSet.metrics.bidPricesVolume,
              resultSet.metrics.askPricesVolume,
              resultSet.metrics.bidPercentile95,
              resultSet.metrics.askPercentile95,
              resultSet.regionID,
              resultSet.typeID,
              now.toUTCString(),
              resultSet.metrics.bidStdDev,
              resultSet.metrics.askStdDev,
              resultSet.regionID,
              resultSet.typeID);

  return {
      params: params,
      values: values
  };
}

function isPresentRegionStat(resultSet, callback) {
  // Get connection from pool
  postgres(function(err, pgClient, done) {
    if (err) {
      // Return connection to pool
      done();

      err.module = 'pgConnect';

      // Handle errors
      callback(err, null);
    } else {
      pgClient.query('SELECT 1 FROM market_data_itemregionstat '+
                             'WHERE mapregion_id = $1 '+
                               'AND invtype_id = $2', [resultSet.regionID, resultSet.typeID], function(err, result) {
                                                                             done(); // Return connection to pool

                                                                             if(err) {
                                                                              err.module = 'orderRegionStats#isPresentRegionStat';
                                                                             }

                                                                             resultSet.result = result;
                                                                             callback(err, resultSet); // Run callback of waterfall
                                                                          });
    }
  });
}

function upsertRegionStats(resultSet, callback) {

  var queryValues = prepareQueryValues(resultSet);

  // Get connection from pool
  postgres(function(err, pgClient, done) {
    if (err) {
      // Return connection to pool
      done();

      err.module = 'pgConnect';

      // Handle errors
      callback(err, null);
    } else {

      if (resultSet.result.rowCount === 0) {

        // Insert new row
        pgClient.query('INSERT INTO market_data_itemregionstat (buymean, ' +
                                                               'buyavg, ' +
                                                               'buymedian, ' +
                                                               'sellmean, ' +
                                                               'sellavg, ' +
                                                               'sellmedian, ' +
                                                               'buyvolume, ' +
                                                               'sellvolume, ' +
                                                               'buy_95_percentile, ' +
                                                               'sell_95_percentile, ' +
                                                               'mapregion_id, ' +
                                                               'invtype_id, ' +
                                                               'lastupdate, ' +
                                                               'buy_std_dev, ' +
                                                               'sell_std_dev) VALUES (' + queryValues.params + ')', queryValues.values.slice(0, 15), function(err, result) {
          done(); // Return connection to pool

          if(err) {
            err.module = 'orderRegionStats#insertRegionStats';
          }

          resultSet.result = result;
          callback(err, resultSet); // Run callback of waterfall
        });
      } else {
        // Update row
        pgClient.query('UPDATE market_data_itemregionstat SET buymean=$1, ' +
                                                             'buyavg=$2, ' +
                                                             'buymedian=$3, ' +
                                                             'sellmean=$4, ' +
                                                             'sellavg=$5, ' +
                                                             'sellmedian=$6, ' +
                                                             'buyvolume=$7, ' +
                                                             'sellvolume=$8, ' +
                                                             'buy_95_percentile=$9, ' +
                                                             'sell_95_percentile=$10, ' +
                                                             'mapregion_id=$11, ' +
                                                             'invtype_id=$12, ' +
                                                             'lastupdate=$13, ' +
                                                             'buy_std_dev=$14, ' +
                                                             'sell_std_dev=$15 WHERE mapregion_id=$16 AND invtype_id=$17', queryValues.values, function(err, result) {
          done(); // Return connection to pool

          if(err) {
            err.module = 'orderRegionStats#updateRegionStats';
          }

          resultSet.result = result;
          callback(err, resultSet); // Run callback of waterfall
        });
      }
    }
  });
}

exports = module.exports = function(resultSet, callback) {
  //
  // Stores order statistics in itemRegionStats table
  //

  if(resultSet.objects.length === 0) {

    // SKIP EMPTY MESSAGES
    return callback(null, resultSet);

  } else {

    async.waterfall([
      function (callback) {
        isPresentRegionStat(resultSet, callback); // Check if region/type pair already exists in DB
      },
      upsertRegionStats                           // Update / insert line
    ], function (error, result) {
      // Error handling
      callback(error, result);
    });
  }

};
<|endoftext|>