<commit_before>var argv = require('minimist')(process.argv.slice(2));
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var compression = require('compression')
var bodyParser = require('body-parser');
var cors = require("cors");
// Logging packages
var rollbar = require('rollbar');
var winston = require('winston');
require('winston-rollbar').Rollbar;
require('./console-winston');

// Set the valid environments
var validEnvironments = ['production', 'demo', 'staging', 'staging-trigger', 'development', 'testing'];

// Get the runtime environment from the node app argument; default to development
var environment = argv.env || 'development';

// Ensure the environment argument is valid
if(validEnvironments.indexOf(environment) === -1) {
    console.error('Invalid environment type');
    return;
}

var settings, envSettings;

//if settings.js doesn't exist, let the user know and exit
try {
    settings = require('./settings/settings.js');

    // Environment specific configuration settings
    envSettings = require("./settings/environment-settings.js")[environment];
} catch (e) {
    console.log("Missing a settings file.\n", e);
    return;
}

// Copy the Environment specific to the settings module, then they will be available wherever settings module is required.
for (var i in envSettings) {

    if(settings.hasOwnProperty(i)){
        throw Error("Environment settings cannot overwrite runtime settings.")
    }

    settings[i] = envSettings[i];
}
settings.pg = envSettings.pg;

var DataTransformer = require('cadasta-data-transformer');
var ingestion_engine = DataTransformer(settings);

//Register the CSV Provider
require("cadasta-provider-csv").register(ingestion_engine);

//Register the GeoJSON Provider
require("cadasta-provider-geojson").register(ingestion_engine);

//Register the ONA-data Provider
require("cadasta-provider-ona").register(ingestion_engine, settings);

// Create the express instance
var app = express();

// Set app env
app.set('env', environment);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

// compress all requests: gzip/deflate
app.use(compression());

// CORS
app.use(cors());

// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Static directory
app.use(express.static(path.join(__dirname, 'public')));

// Endpoint configuration
var index = require('./routes/index');
var custom = require('./routes/custom');
var parcels = require('./routes/parcels');
var relationships = require('./routes/relationships');
var resources = require('./routes/resources');
var projects = require('./routes/projects');
var parties = require('./routes/parties');
var organizations = require('./routes/organizations');
var field_data = require('./routes/field_data');

app.use('/', index);
app.use('/', custom);
app.use('/parcels', parcels);
app.use('/providers', ingestion_engine.router);
app.use('/projects', projects,resources,relationships, parties);
app.use('/organizations', organizations);
app.use('/field_data', field_data);

// Environment-specific configuration
if (app.get('env') === 'development') {

    // Use the morgan logger and print stack trace
    app.use(logger('dev'));
    printStackTrace(app);

} else if (app.get('env') === 'testing') {

    // print stack trace
    printStackTrace(app);

} else if (app.get('env') === 'staging' || app.get('env') === 'demo') {

    // print stack trace and log warnings and errors to Rollbar logging dashboard
    printStackTrace(app);
    addLogging(app, settings);

} else if (app.get('env') === 'production') {

    // hide stack trace and log warnings and errors to Rollbar logging dashboard
    hideStackTrace(app);
    addLogging(app, settings);
}

// START THE SERVER
// =============================================================================
app.listen(envSettings.apiPort, function(){

    console.log('API listening on port ' + envSettings.apiPort);

});

module.exports = app;

function printStackTrace(app){
    // will print stacktrace
    app.use(function(err, req, res, next) {

        //Bad Db column request
        if(err.code === "42703") {
            err.status = 400;
            err.message = "Bad request: " + err.message;

        }

        console.error(err, err.stack);
        res.status(err.status || 500).json({
            message: err.message,
            error: err
        });
    });
}

function hideStackTrace(app){
    // will print stacktrace
    app.use(function(err, req, res, next) {
        console.error(err);
        res.status(err.status || 500).json({
            message: err.message,
            error: {}
        });
    });
}

function addLogging(app,settings){

    if(settings.useRollbar) {
        app.use(rollbar.errorHandler(settings.rollbarKey));
        winston.add(winston.transports.Rollbar, { rollbarAccessToken: settings.rollbarKey, level:'debug' });
        rollbar.handleUncaughtExceptions(settings.rollbarKey, { exitOnUncaughtException: true });
    }
}
<commit_msg>Go back to warn level logging.<commit_after>var argv = require('minimist')(process.argv.slice(2));
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var compression = require('compression')
var bodyParser = require('body-parser');
var cors = require("cors");
// Logging packages
var rollbar = require('rollbar');
var winston = require('winston');
require('winston-rollbar').Rollbar;
require('./console-winston');

// Set the valid environments
var validEnvironments = ['production', 'demo', 'staging', 'staging-trigger', 'development', 'testing'];

// Get the runtime environment from the node app argument; default to development
var environment = argv.env || 'development';

// Ensure the environment argument is valid
if(validEnvironments.indexOf(environment) === -1) {
    console.error('Invalid environment type');
    return;
}

var settings, envSettings;

//if settings.js doesn't exist, let the user know and exit
try {
    settings = require('./settings/settings.js');

    // Environment specific configuration settings
    envSettings = require("./settings/environment-settings.js")[environment];
} catch (e) {
    console.log("Missing a settings file.\n", e);
    return;
}

// Copy the Environment specific to the settings module, then they will be available wherever settings module is required.
for (var i in envSettings) {

    if(settings.hasOwnProperty(i)){
        throw Error("Environment settings cannot overwrite runtime settings.")
    }

    settings[i] = envSettings[i];
}
settings.pg = envSettings.pg;

var DataTransformer = require('cadasta-data-transformer');
var ingestion_engine = DataTransformer(settings);

//Register the CSV Provider
require("cadasta-provider-csv").register(ingestion_engine);

//Register the GeoJSON Provider
require("cadasta-provider-geojson").register(ingestion_engine);

//Register the ONA-data Provider
require("cadasta-provider-ona").register(ingestion_engine, settings);

// Create the express instance
var app = express();

// Set app env
app.set('env', environment);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

// compress all requests: gzip/deflate
app.use(compression());

// CORS
app.use(cors());

// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Static directory
app.use(express.static(path.join(__dirname, 'public')));

// Endpoint configuration
var index = require('./routes/index');
var custom = require('./routes/custom');
var parcels = require('./routes/parcels');
var relationships = require('./routes/relationships');
var resources = require('./routes/resources');
var projects = require('./routes/projects');
var parties = require('./routes/parties');
var organizations = require('./routes/organizations');
var field_data = require('./routes/field_data');

app.use('/', index);
app.use('/', custom);
app.use('/parcels', parcels);
app.use('/providers', ingestion_engine.router);
app.use('/projects', projects,resources,relationships, parties);
app.use('/organizations', organizations);
app.use('/field_data', field_data);

// Environment-specific configuration
if (app.get('env') === 'development') {

    // Use the morgan logger and print stack trace
    app.use(logger('dev'));
    printStackTrace(app);

} else if (app.get('env') === 'testing') {

    // print stack trace
    printStackTrace(app);

} else if (app.get('env') === 'staging' || app.get('env') === 'demo') {

    // print stack trace and log warnings and errors to Rollbar logging dashboard
    printStackTrace(app);
    addLogging(app, settings);

} else if (app.get('env') === 'production') {

    // hide stack trace and log warnings and errors to Rollbar logging dashboard
    hideStackTrace(app);
    addLogging(app, settings);
}

// START THE SERVER
// =============================================================================
app.listen(envSettings.apiPort, function(){

    console.log('API listening on port ' + envSettings.apiPort);

});

module.exports = app;

function printStackTrace(app){
    // will print stacktrace
    app.use(function(err, req, res, next) {

        //Bad Db column request
        if(err.code === "42703") {
            err.status = 400;
            err.message = "Bad request: " + err.message;

        }

        console.error(err, err.stack);
        res.status(err.status || 500).json({
            message: err.message,
            error: err
        });
    });
}

function hideStackTrace(app){
    // will print stacktrace
    app.use(function(err, req, res, next) {
        console.error(err);
        res.status(err.status || 500).json({
            message: err.message,
            error: {}
        });
    });
}

function addLogging(app,settings){

    if(settings.useRollbar) {
        app.use(rollbar.errorHandler(settings.rollbarKey));
        winston.add(winston.transports.Rollbar, { rollbarAccessToken: settings.rollbarKey, level:'warn' });
        rollbar.handleUncaughtExceptions(settings.rollbarKey, { exitOnUncaughtException: true });
    }
}
<|endoftext|>


<commit_before>K2.Knob = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Knob, K2.UIElement);

K2.Knob.prototype.getready = function(args) {

    if (args === undefined) {
        throw new Error('Error: specArgs is undefined!');
    }

    // Call the constructor from the superclass.
    K2.Knob.superclass.getready.call(this, args);

    //now that all required properties have been inherited
    //from the parent class, define extra ones from this class

    //Default value is 0
    this.values = {'knobvalue' : 0};
    this.defaultSlot = 'knobvalue';

    this.sensitivity = args.sensitivity || 2000;
    this.imagesArray = args.imagesArray || null;

    if (this.imagesArray.length < 1) {
        throw new Error('Invalid images array length, ' + this.imagesArray.length);
    }

    var width = 0,
        height = 0;

    // Calculate maximum width and height.
    for (var i = 0, len = this.imagesArray.length; i < len; i += 1) {
        if (this.imagesArray[i].width > width) {
            width = this.imagesArray[i].width;
        }
        if (this.imagesArray[i].height > height) {
            height = this.imagesArray[i].height;
        }
    }

    // Set them.
    this.setWidth(width);
    this.setHeight(height);

};

// This method returns an image index given the knob value.
K2.Knob.prototype.getImageNum = function() {
    if ((this.values.knobvalue < 0) || (this.values.knobvalue > 1)) {
        // Do nothing
        return undefined;
    }
    var ret = Math.round(this.values.knobvalue * (this.imagesArray.length - 1));
    return ret;
};

K2.Knob.prototype.getImage = function() {

    var ret = this.getImageNum();
    return this.imagesArray[ret];
};

// This method returns true if the point given belongs to this knob.
K2.Knob.prototype.isInROI = function(x, y) {
    if ((x > this.ROILeft) && (y > this.ROITop)) {
        if ((x < (this.ROILeft + this.ROIWidth)) && (y < (this.ROITop + this.ROIHeight))) {
            return true;
        }
    }
    return false;
};

K2.Knob.prototype.dragstart = K2.Knob.prototype.mousedown = function(x, y) {

    var inROI = this.isInROI(x, y);
    // Save the starting point if event happened in our ROI.
    if (inROI) {
        this.start_x = x;
        this.start_y = y;
    }

    // No value has been changed.
    return undefined;
};

K2.Knob.prototype.dragend = K2.Knob.prototype.mouseup = function(x, y) {

    // Reset the starting point.
    this.start_x = undefined;
    this.start_y = undefined;

    // No value has been changed
    return undefined;

};

K2.Knob.prototype.drag = K2.Knob.prototype.mousemove = function(curr_x, curr_y) {

    if ((this.start_x !== undefined) && (this.start_y !== undefined)) {

        // This means that the mouse is currently down.
        var deltaY = 0,
            temp_value,
            to_set,
            ret;

        deltaY = curr_y - this.start_y;

        temp_value = this.values.knobvalue;

        // Todo set sensitivity.
        to_set = temp_value - deltaY / this.sensitivity;

        if (to_set > 1) {
            to_set = 1;
        }
        if (to_set < 0) {
            to_set = 0;
        }

        ret = {'slot' : 'knobvalue', 'value' : to_set};

        return ret;
    }

    // The mouse is currently up; ignore the event notify.
    return undefined;

};

// Setters
K2.Knob.prototype.setValue = function(slot, value) {
    var temp_value = value;

    if ((temp_value < 0) || (temp_value > 1)) {
        // Out of range; do not set
        return;
    }

    // Call the superclass
    K2.Knob.superclass.setValue.call(this, slot, value);

};

K2.Knob.prototype.refresh_CANVAS2D = function(engine) {

    // Draw if visible.
    if (this.isVisible === true) {
        // Get the image to draw
        var imageNum = this.getImageNum();
        // Draw the image on the canvas
        engine.context.drawImage(this.imagesArray[imageNum], this.xOrigin, this.yOrigin);
    }

};<commit_msg>Implemented atan2 touch / drag in Knob element<commit_after>K2.Knob = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Knob, K2.UIElement);

K2.Knob.prototype.getready = function(args) {

    if (args === undefined) {
        throw new Error('Error: specArgs is undefined!');
    }

    // Call the constructor from the superclass.
    K2.Knob.superclass.getready.call(this, args);

    //now that all required properties have been inherited
    //from the parent class, define extra ones from this class

    //Default value is 0
    this.values = {'knobvalue' : 0};
    this.defaultSlot = 'knobvalue';

    this.sensitivity = args.sensitivity || 2000;
    this.imagesArray = args.imagesArray || null;

    // Can be 'atan' or 'updown'
    this.knobMethod = args.knobMethod || 'atan';

    if (this.imagesArray.length < 1) {
        throw new Error('Invalid images array length, ' + this.imagesArray.length);
    }

    var width = 0,
        height = 0;

    // Calculate maximum width and height.
    for (var i = 0, len = this.imagesArray.length; i < len; i += 1) {
        if (this.imagesArray[i].width > width) {
            width = this.imagesArray[i].width;
        }
        if (this.imagesArray[i].height > height) {
            height = this.imagesArray[i].height;
        }
    }

    // Set them.
    this.setWidth(width);
    this.setHeight(height);

};

// This method returns an image index given the knob value.
K2.Knob.prototype.getImageNum = function() {
    if ((this.values.knobvalue < 0) || (this.values.knobvalue > 1)) {
        // Do nothing
        return undefined;
    }
    var ret = Math.round(this.values.knobvalue * (this.imagesArray.length - 1));
    return ret;
};

K2.Knob.prototype.getImage = function() {

    var ret = this.getImageNum();
    return this.imagesArray[ret];
};

K2.Knob.prototype.calculateAngle = function (x,y) {

	var centerX = this.xOrigin + this.width / 2;
	var centerY = this.yOrigin + this.height / 2;

	console.log ("Point is: ", x, y, "Center is: ", centerX, centerY);

	var radtan = Math.atan2 (x - centerX, y - centerY);
	console.log('radiant atan ', radtan);

	var degreetan = radtan * (180 / Math.PI);
	degreetan = 180 - degreetan;
	console.log('degree atan ', degreetan);

	var range_val = K2.MathUtils.linearRange(0, 360, 0, 1, Math.floor(degreetan));
	return range_val;

};

// This method returns true if the point given belongs to this knob.
K2.Knob.prototype.isInROI = function(x, y) {
    if ((x > this.ROILeft) && (y > this.ROITop)) {
        if ((x < (this.ROILeft + this.ROIWidth)) && (y < (this.ROITop + this.ROIHeight))) {
            return true;
        }
    }
    return false;
};

K2.Knob.prototype.dragstart = K2.Knob.prototype.mousedown = K2.Knob.prototype.touchstart = function(x, y) {

    var inROI = this.isInROI(x, y);
    // Save the starting point if event happened in our ROI.
    if (inROI) {
        this.start_x = x;
        this.start_y = y;
    }

    if (this.knobMethod === 'atan') {
		var range_val = this.calculateAngle (x,y);
		var ret = {'slot' : 'knobvalue', 'value' : range_val};
		return ret;
    }

    // No value has been changed.
    return undefined;
};

K2.Knob.prototype.dragend = K2.Knob.prototype.mouseup = function(x, y) {

    // Reset the starting point.
    this.start_x = undefined;
    this.start_y = undefined;

    // No value has been changed
    return undefined;

};

K2.Knob.prototype.drag = K2.Knob.prototype.mousemove = function(curr_x, curr_y) {

	var ret;

	if (this.knobMethod === 'updown') {
		// TODO null or typeof
	    if ((this.start_x !== undefined) && (this.start_y !== undefined)) {

	        // This means that the mouse is currently down.
	        var deltaY = 0,
	            temp_value,
	            to_set;

	        deltaY = curr_y - this.start_y;

	        temp_value = this.values.knobvalue;

	        // Todo set sensitivity.
	        to_set = temp_value - deltaY / this.sensitivity;

	        if (to_set > 1) {
	            to_set = 1;
	        }
	        if (to_set < 0) {
	            to_set = 0;
	        }

	        ret = {'slot' : 'knobvalue', 'value' : to_set};

	        return ret;
	    }
	}

	else if (this.knobMethod === 'atan') {
		if ((this.start_x !== undefined) && (this.start_y !== undefined)) {
			var range_val = this.calculateAngle (curr_x, curr_y);
			ret = {'slot' : 'knobvalue', 'value' : range_val};
			return ret;
		}
	}

    // The mouse is currently up; ignore the event notify.
    return undefined;

};

// Setters
K2.Knob.prototype.setValue = function(slot, value) {
    var temp_value = value;

    if ((temp_value < 0) || (temp_value > 1)) {
        // Out of range; do not set
        return;
    }

    // Call the superclass
    K2.Knob.superclass.setValue.call(this, slot, value);

};

K2.Knob.prototype.refresh_CANVAS2D = function(engine) {

    // Draw if visible.
    if (this.isVisible === true) {
        // Get the image to draw
        var imageNum = this.getImageNum();
        // Draw the image on the canvas
        engine.context.drawImage(this.imagesArray[imageNum], this.xOrigin, this.yOrigin);
    }

};<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.home',
  'myApp.course',
  'myApp.myaccount',
  'myApp.login',
  'myApp.comment',
  //'myApp.module',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/home'});
//}]).constant('apidomain', 'http://162.243.153.161/');
}]).constant('apidomain', 'http://127.0.0.1:1234/');
<commit_msg>fixing: it was pointing to localhost<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.home',
  'myApp.course',
  'myApp.myaccount',
  'myApp.login',
  'myApp.comment',
  //'myApp.module',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/home'});
}]).constant('apidomain', 'http://162.243.153.161/');
//}]).constant('apidomain', 'http://127.0.0.1:1234/');
<|endoftext|>


<commit_before>(function (clique, $, _, Backbone, tangelo) {
    "use strict";

    tangelo.getPlugin("mongo").Mongo = function (cfg) {
        var findNodesService = "plugin/mongo/findNodes",
            mutators = {},
            mongoStore = {
                host: cfg.host || "localhost",
                db: cfg.database,
                coll: cfg.collection
            },
            addMutator,
            translateSpec;

        clique.util.require(cfg.database, "database");
        clique.util.require(cfg.collection, "collection");

        translateSpec = function (spec) {
            var result = {},
                value;

            if (_.has(spec, "queryOp")) {
                // If this is a "leaf node", translate it to a direct comparison
                // query and return.
                switch (spec.queryOp) {
                case "==": {
                    value = spec.value;
                    break;
                }

                case "!=":
                case ">":
                case ">=":
                case "<":
                case "<=":
                case "~~":
                case "|~":
                case "~|": {
                    throw new Error("unimplemented");
                    break;
                }

                default: {
                    throw new Error("illegal value for queryOp: " + spec.queryOp);
                    break;
                }
                }

                if (spec.field === "key") {
                    result["_id"] = {
                        $oid: value
                    };
                } else {
                    result["data." + spec.field] = value;
                }
            } else if (_.has(spec, "logicOp")) {
                // Otherwise, create a logic operator node and recurse down the
                // operands.
                result["$" + spec.logicOp] = [translateSpec(spec.left), translateSpec(spec.right)];
            }

            return result;
        };

        addMutator = function (mongoRec) {
            var target,
                mutator,
                key,
                type,
                source,
                targetNode;

            key = mongoRec._id.$oid;
            type = mongoRec.type;

            if (!_.has(mutators, key)) {
                target = {
                    key: key,
                    data: mongoRec.data || {}
                };

                if (type === "link") {
                    source = mongoRec.source;
                    if (_.isObject(source)) {
                        source = source.$oid;
                    }

                    target.source = source;

                    targetNode = mongoRec.target;
                    if (_.isObject(targetNode)) {
                        targetNode = targetNode.$oid;
                    }

                    target.target = targetNode;
                }

                mutator = new clique.util.Mutator(target);

                this.listenTo(mutator, "changed", function (mutator, prop, value) {
                    $.getJSON("plugin/mongo/update", _.extend({
                        key: mutator.key(),
                        prop: prop,
                        value: JSON.stringify(value)
                    }, mongoStore));
                });

                this.listenTo(mutator, "cleared", function (mutator, prop) {
                    $.getJSON("plugin/mongo/clear", _.extend({
                        key: mutator.key(),
                        prop: prop
                    }, mongoStore)).then(_.bind(function () {
                        this.trigger("cleared:" + mutator.key(), mutator, prop);
                    }, this));
                });

                mutators[key] = mutator;
            }

            return mutators[key];
        };

        return _.extend({
            findNodes: function (spec) {
                var targets,
                    data;

                data = _.extend({
                    spec: JSON.stringify(translateSpec(spec))
                }, mongoStore);

                return $.getJSON(findNodesService, data)
                    .then(_.partial(_.map, _, _.bind(function (r) {
                        return _.bind(addMutator, this)(r);
                    }, this)));
            },

            findNode: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(translateSpec(spec)),
                    singleton: JSON.stringify(true)
                }, mongoStore);

                return $.getJSON(findNodesService, data)
                    .then(_.bind(function (result) {
                        var def = new $.Deferred(),
                            target;

                        if (result) {
                            result = _.bind(addMutator, this)(result);
                        }

                        def.resolve(result);
                        return def;
                    }, this));
            },

            findNodeByKey: function (key) {
                return this.findNode({
                    queryOp: "==",
                    field: "key",
                    value: key
                });
            },

            findLinks: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(spec),
                    singleton: JSON.stringify(false)
                }, mongoStore);

                return $.getJSON("plugin/mongo/findLinks", data)
                    .then(_.partial(_.map, _, addMutator, this));
            },

            findLink: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(spec),
                    singleton: JSON.stringify(true)
                }, mongoStore);

                return $.getJSON("plugin/mongo/findLinks", data)
                    .then(_.bind(function (result) {
                        var def = new $.Deferred();

                        if (result) {
                            result = _.bind(addMutator, this)(result);
                        }

                        def.resolve(result);
                        return def;
                    }, this));
            },

            newNode: function (metadata) {
                var data = _.extend({
                    data: metadata ? JSON.stringify(metadata) : "{}"
                }, mongoStore);
                return $.getJSON("plugin/mongo/newNode", data)
                    .then(_.bind(addMutator, this));
            },

            newLink: function (source, target, metadata) {
                var data = _.extend({
                    source: source,
                    target: target,
                    data: metadata ? JSON.stringify(metadata) : "{}"
                }, mongoStore);

                return $.getJSON("plugin/mongo/newLink", data)
                    .then(_.bind(addMutator, this));
            },

            destroyNode: function (key) {
                var data = _.extend({
                    key: key
                }, mongoStore);
                return $.get("plugin/mongo/destroyNode", data);
            },

            destroyLink: function (key) {
                var data = _.extend({
                    key: key
                }, mongoStore);
                return $.get("plugin/mongo/destroyLink", data);
            },

            neighborhood: function (options) {
                clique.util.require(options.center, "center");
                clique.util.require(options.radius, "radius");

                options = _.clone(options);
                options.center = options.center.key();
                options = _.extend(options, mongoStore);

                return $.getJSON("plugin/mongo/neighborhood", options)
                    .then(_.bind(function (results) {
                        _.each(results.nodes, addMutator, this);
                        _.each(results.links, addMutator, this);

                        return results;
                    }, this))
                    .then(_.bind(function (results) {
                       var def = new $.Deferred();

                       _.each(results.nodes, _.bind(function (node, i) {
                            var mut = this.getMutator(node._id.$oid);

                            if (mut.key() === options.center) {
                                mut.setTransient("root", true);
                            }

                            results.nodes[i] = mut.getTarget();
                        }, this));

                       _.each(results.links, _.bind(function (link, i) {
                           var mut = this.getMutator(link._id.$oid);
                           results.links[i] = mut.getTarget();
                       }, this));

                       def.resolve(results);
                       return def;
                   }, this));
            },

            sync: function () {
                var def = new $.Deferred();
                def.resolve();
                return def;
            },

            getMutator: _.propertyOf(mutators)
        }, Backbone.Events);
    };
}(window.clique, window.jQuery, window._, window.Backbone, window.tangelo));
<commit_msg>Type checking argument to translateSpec()<commit_after>(function (clique, $, _, Backbone, tangelo) {
    "use strict";

    tangelo.getPlugin("mongo").Mongo = function (cfg) {
        var findNodesService = "plugin/mongo/findNodes",
            mutators = {},
            mongoStore = {
                host: cfg.host || "localhost",
                db: cfg.database,
                coll: cfg.collection
            },
            addMutator,
            translateSpec;

        clique.util.require(cfg.database, "database");
        clique.util.require(cfg.collection, "collection");

        translateSpec = function (spec) {
            var result = {},
                value;

            if (_.isString(spec) || _.isFunction(spec) || _.isNumber(spec)) {
                throw new Error("Type error: 'spec' must be an object");
            }

            if (_.has(spec, "queryOp")) {
                // If this is a "leaf node", translate it to a direct comparison
                // query and return.
                switch (spec.queryOp) {
                case "==": {
                    value = spec.value;
                    break;
                }

                case "!=":
                case ">":
                case ">=":
                case "<":
                case "<=":
                case "~~":
                case "|~":
                case "~|": {
                    throw new Error("unimplemented");
                    break;
                }

                default: {
                    throw new Error("illegal value for queryOp: " + spec.queryOp);
                    break;
                }
                }

                if (spec.field === "key") {
                    result["_id"] = {
                        $oid: value
                    };
                } else {
                    result["data." + spec.field] = value;
                }
            } else if (_.has(spec, "logicOp")) {
                // Otherwise, create a logic operator node and recurse down the
                // operands.
                result["$" + spec.logicOp] = [translateSpec(spec.left), translateSpec(spec.right)];
            } else {
                throw new Error("Type error: 'spec' does not have the right structure");
            }

            return result;
        };

        addMutator = function (mongoRec) {
            var target,
                mutator,
                key,
                type,
                source,
                targetNode;

            key = mongoRec._id.$oid;
            type = mongoRec.type;

            if (!_.has(mutators, key)) {
                target = {
                    key: key,
                    data: mongoRec.data || {}
                };

                if (type === "link") {
                    source = mongoRec.source;
                    if (_.isObject(source)) {
                        source = source.$oid;
                    }

                    target.source = source;

                    targetNode = mongoRec.target;
                    if (_.isObject(targetNode)) {
                        targetNode = targetNode.$oid;
                    }

                    target.target = targetNode;
                }

                mutator = new clique.util.Mutator(target);

                this.listenTo(mutator, "changed", function (mutator, prop, value) {
                    $.getJSON("plugin/mongo/update", _.extend({
                        key: mutator.key(),
                        prop: prop,
                        value: JSON.stringify(value)
                    }, mongoStore));
                });

                this.listenTo(mutator, "cleared", function (mutator, prop) {
                    $.getJSON("plugin/mongo/clear", _.extend({
                        key: mutator.key(),
                        prop: prop
                    }, mongoStore)).then(_.bind(function () {
                        this.trigger("cleared:" + mutator.key(), mutator, prop);
                    }, this));
                });

                mutators[key] = mutator;
            }

            return mutators[key];
        };

        return _.extend({
            findNodes: function (spec) {
                var targets,
                    data;

                data = _.extend({
                    spec: JSON.stringify(translateSpec(spec))
                }, mongoStore);

                return $.getJSON(findNodesService, data)
                    .then(_.partial(_.map, _, _.bind(function (r) {
                        return _.bind(addMutator, this)(r);
                    }, this)));
            },

            findNode: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(translateSpec(spec)),
                    singleton: JSON.stringify(true)
                }, mongoStore);

                return $.getJSON(findNodesService, data)
                    .then(_.bind(function (result) {
                        var def = new $.Deferred(),
                            target;

                        if (result) {
                            result = _.bind(addMutator, this)(result);
                        }

                        def.resolve(result);
                        return def;
                    }, this));
            },

            findNodeByKey: function (key) {
                return this.findNode({
                    queryOp: "==",
                    field: "key",
                    value: key
                });
            },

            findLinks: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(spec),
                    singleton: JSON.stringify(false)
                }, mongoStore);

                return $.getJSON("plugin/mongo/findLinks", data)
                    .then(_.partial(_.map, _, addMutator, this));
            },

            findLink: function (spec) {
                var data = _.extend({
                    spec: JSON.stringify(spec),
                    singleton: JSON.stringify(true)
                }, mongoStore);

                return $.getJSON("plugin/mongo/findLinks", data)
                    .then(_.bind(function (result) {
                        var def = new $.Deferred();

                        if (result) {
                            result = _.bind(addMutator, this)(result);
                        }

                        def.resolve(result);
                        return def;
                    }, this));
            },

            newNode: function (metadata) {
                var data = _.extend({
                    data: metadata ? JSON.stringify(metadata) : "{}"
                }, mongoStore);
                return $.getJSON("plugin/mongo/newNode", data)
                    .then(_.bind(addMutator, this));
            },

            newLink: function (source, target, metadata) {
                var data = _.extend({
                    source: source,
                    target: target,
                    data: metadata ? JSON.stringify(metadata) : "{}"
                }, mongoStore);

                return $.getJSON("plugin/mongo/newLink", data)
                    .then(_.bind(addMutator, this));
            },

            destroyNode: function (key) {
                var data = _.extend({
                    key: key
                }, mongoStore);
                return $.get("plugin/mongo/destroyNode", data);
            },

            destroyLink: function (key) {
                var data = _.extend({
                    key: key
                }, mongoStore);
                return $.get("plugin/mongo/destroyLink", data);
            },

            neighborhood: function (options) {
                clique.util.require(options.center, "center");
                clique.util.require(options.radius, "radius");

                options = _.clone(options);
                options.center = options.center.key();
                options = _.extend(options, mongoStore);

                return $.getJSON("plugin/mongo/neighborhood", options)
                    .then(_.bind(function (results) {
                        _.each(results.nodes, addMutator, this);
                        _.each(results.links, addMutator, this);

                        return results;
                    }, this))
                    .then(_.bind(function (results) {
                       var def = new $.Deferred();

                       _.each(results.nodes, _.bind(function (node, i) {
                            var mut = this.getMutator(node._id.$oid);

                            if (mut.key() === options.center) {
                                mut.setTransient("root", true);
                            }

                            results.nodes[i] = mut.getTarget();
                        }, this));

                       _.each(results.links, _.bind(function (link, i) {
                           var mut = this.getMutator(link._id.$oid);
                           results.links[i] = mut.getTarget();
                       }, this));

                       def.resolve(results);
                       return def;
                   }, this));
            },

            sync: function () {
                var def = new $.Deferred();
                def.resolve();
                return def;
            },

            getMutator: _.propertyOf(mutators)
        }, Backbone.Events);
    };
}(window.clique, window.jQuery, window._, window.Backbone, window.tangelo));
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.heatmap',
  'myApp.zoomHeatmap',
  'myApp.persistView',
  'myApp.bar',
  'myApp.energyProfile',
  'myApp.timeSeries',
  'calHeatmap',
  'angularDc',
  'colorpicker.module',
  'myApp.calendar',
  'ui.bootstrap'
]).

config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/bar', {
		templateUrl: 'views/bar.html',
		controller: 'barCtrl'
	}).
	when('/timeSeries', {
		templateUrl: 'views/timeSeries.html',
		controller: 'timeSeriesCtrl'
	}).
	when('/energyProfile', {
		templateUrl: 'views/energyProfile.html',
		controller: 'energyProfileCtrl'
	}).
	when('/calendar',{
		templateUrl: 'views/calendar.html',
		controller: 'DatepickerDemoCtrl'
	}).
	otherwise({redirectTo: '/heatmap'});
}]);
<commit_msg>removed the reference to the /calendar page<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.heatmap',
  'myApp.zoomHeatmap',
  'myApp.persistView',
  'myApp.bar',
  'myApp.energyProfile',
  'myApp.timeSeries',
  'calHeatmap',
  'angularDc',
  'colorpicker.module',
  'myApp.calendar',
  'ui.bootstrap'
]).

config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/bar', {
		templateUrl: 'views/bar.html',
		controller: 'barCtrl'
	}).
	when('/timeSeries', {
		templateUrl: 'views/timeSeries.html',
		controller: 'timeSeriesCtrl'
	}).
	when('/energyProfile', {
		templateUrl: 'views/energyProfile.html',
		controller: 'energyProfileCtrl'
	}).
	otherwise({redirectTo: '/heatmap'});
}]);
<|endoftext|>


<commit_before>/**
 * @class {CircularBuffer}
 */
class CircularBuffer {
    /**
     * @constructor
     *
     * @param {Number} maxSize
     *
     * @example
     *
     * const circularBuffer = require('estructura/circular-buffer')
     */
    constructor(maxSize) {
        if (isNaN(maxSize) === true) throw new Error(`${maxSize} is NaN.`)

        /**
         * @private
         *
         * @type {Array.<*>} _sCollection
         */
        this._sCollection = []

        /**
         * @private
         *
         * @type {Number}
         */
        this._headOffset = 0

        /**
         * @type {Number}
         */
        this.size = 0

        /**
         * The maximum length of our internal Array.
         *
         * @type {Number}
         */
        this.maxSize = maxSize

        /**
         * @see #.peek
         *
         * @type {Function}
         */
        this.peekFront = this.peek
    }

    /**
     * Append an item to the Circular Buffer.
     *
     * `O(1)`
     *
     * @param {*} aValue
     *
     * @return {Number} The new size of the Circular Buffer.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     *
     * circularBuffer.push('Add a new value to the end of the Circular Buffer.')
     * >>> 1
     */
    push(aValue) {
        if (this.size === this.maxSize) {
            /**
             * Replace the oldest item within the Buffer with a new
             * value.
             *
             * @type {*}
             */
            this._sCollection[this._headOffset] = aValue

            /**
             * Increase the `_headOffset` to account for the replacement
             * of the oldest value.
             *
             * @type {Number}
             */
            this._headOffset = (this._headOffset + 1) % this.maxSize
        }
        else {
            /**
             * @type {*}
             */
            this._sCollection[(this._headOffset + this.size) % this.maxSize] = aValue

            /**
             * @type {Number}
             */
            this.size++
        }

        return this.size
    }

    /**
     * Return the last item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return `undefined` when the `#.size` is equal to 0.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello John Doe!')
     *
     * circularBuffer.pop()
     * >>> Hello John Doe!
     */
    pop() {
        if (this.size === 0) return undefined

        /**
         * @type {Number}
         */
        this.size--

        /**
         * @type {Number}
         */
        const idxNr = (this._headOffset + this.size) % this.maxSize

        /**
         * @type {*}
         */
        const aValue = this._sCollection[idxNr]

        this._sCollection[idxNr] = null

        return aValue
    }

    /**
     * Return the first item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return `undefined` when the `#.size` is equal to zero.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     *
     * circularBuffer.shift()
     * >>> Hello Jane Doe!
     */
    shift() {
        if (this.size === 0) return undefined

        /**
         * @type {*}
         */
        const aValue = this._sCollection[this._headOffset]

        this._sCollection[this._headOffset] = null

        /**
         * We've shifted the first item within the Buffer. Move the `#._headOffset`
         * to the next item.
         *
         * @type {Number}
         */
        this._headOffset = (this._headOffset + 1) % this.maxSize

        /**
         * @type {Number}
         */
        this.size--

        return aValue
    }

    /**
     * Take a look at the first item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return the first item within the Circular Buffer without
     *             removing the item or `undefined` if the Buffer is empty.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     *
     * circularBuffer.peek()
     * >>> Hello Jane Doe!
     *
     * @alias peekFront
     */
    peek() {
        if (this.size === 0) return undefined

        return this._sCollection[this._headOffset]
    }

    /**
     * Take a peek at the last value within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Will return `undefined` if the Buffer is empty or
     *             the last item within the Circular Buffer.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello A.')
     * circularBuffer.push('Hello B.')
     *
     * circularBuffer.peekBack()
     * >>> Hello B.
     *
     * @example
     *
     * <caption>
     * The `#.peekBack` method will become an alias for the `#.peek` method if only
     * 1 item is present within the Circular Buffer.
     * </caption>
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello A.')
     *
     * circularBuffer.peekBack()
     * >>> Hello A.
     */
    peekBack() {
        if (this.size === 0) return undefined

        return this._sCollection[(this._headOffset + this.size - 1) % this.maxSize]
    }

    /**
     * @return {Array.<*>}
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     * circularBuffer.push('Hello John Doe!')
     *
     * circularBuffer.toArray()
     * >>> [ "Hello Jane Doe!", "Hello John Doe!" ]
     */
    toArray() {
        /**
         * @type {Number}
         */
        const sliceEnd = this._headOffset + this.size

        /**
         * @type {Array.<*>}
         */
        const toArray = this._sCollection.slice(
            this._headOffset, Math.min(sliceEnd, this.maxSize)
        )

        if (sliceEnd < this.maxSize) return toArray

        return toArray.concat(
            this._sCollection.slice(
                0, Math.max(0, sliceEnd % this.maxSize)
            )
        )
    }

    /**
     * Create a Circular Buffer from an Iterable.
     *
     * @param {Iterable} iterateOver
     *
     * @return {CircularBuffer}
     *
     * @example
     *
     * const circularBuffer = CircularBuffer.from(["John Doe", "Jane Doe"])
     */
    static from(iterateOver) {
        const circularBuffer = new CircularBuffer(Infinity)

        for (const aValue of iterateOver) circularBuffer.push(aValue)

        /**
         * Replace `Infinity` with an actual value.
         *
         * @type {Number}
         */
        circularBuffer.maxSize = circularBuffer.size

        return circularBuffer
    }
}

module.exports = CircularBuffer<commit_msg>Convention<commit_after>/**
 * @class {CircularBuffer}
 */
class CircularBuffer {
    /**
     * @constructor
     *
     * @param {Number} maxSize
     *
     * @example
     *
     * const circularBuffer = require('estructura/circular-buffer')
     */
    constructor(maxSize) {
        if (isNaN(maxSize) === true) throw new Error(`${maxSize} is NaN.`)

        this.circularBuffer_ = []

        this.headOffset_ = 0

        this.size = 0
        this.maxSize = maxSize

        this.peekFront = this.peek
    }

    /**
     * Append an item to the Circular Buffer.
     *
     * `O(1)`
     *
     * @param {*} aValue
     *
     * @return {Number} The new size of the Circular Buffer.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     *
     * circularBuffer.push('Add a new value to the end of the Circular Buffer.')
     * >>> 1
     */
    push(aValue) {
        if (this.size === this.maxSize) {
            this.circularBuffer_[this.headOffset_] = aValue

            this.headOffset_ = (this.headOffset_ + 1) % this.maxSize
        }
        else {
            this.circularBuffer_[(this.headOffset_ + this.size) % this.maxSize] = aValue

            this.size++
        }

        return this.size
    }

    /**
     * Return the last item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return `undefined` when the `#.size` is equal to 0.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello John Doe!')
     *
     * circularBuffer.pop()
     * >>> Hello John Doe!
     */
    pop() {
        if (this.size === 0) return undefined

        this.size--

        const idxNr = (this.headOffset_ + this.size) % this.maxSize, aValue = this.circularBuffer_[idxNr]

        this.circularBuffer_[idxNr] = null

        return aValue
    }

    /**
     * Return the first item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return `undefined` when the `#.size` is equal to zero.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     *
     * circularBuffer.shift()
     * >>> Hello Jane Doe!
     */
    shift() {
        if (this.size === 0) return undefined

        const aValue = this.circularBuffer_[this.headOffset_]

        this.circularBuffer_[this.headOffset_] = null

        this.headOffset_ = (this.headOffset_ + 1) % this.maxSize

        this.size--

        return aValue
    }

    /**
     * Take a look at the first item within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Return the first item within the Circular Buffer without
     *             removing the item or `undefined` if the Buffer is empty.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     *
     * circularBuffer.peek()
     * >>> Hello Jane Doe!
     *
     * @alias peekFront
     */
    peek() {
        if (this.size === 0) return undefined

        return this.circularBuffer_[this.headOffset_]
    }

    /**
     * Take a peek at the last value within the Circular Buffer.
     *
     * `O(1)`
     *
     * @return {*} Will return `undefined` if the Buffer is empty or
     *             the last item within the Circular Buffer.
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello A.')
     * circularBuffer.push('Hello B.')
     *
     * circularBuffer.peekBack()
     * >>> Hello B.
     *
     * @example
     *
     * <caption>
     * The `#.peekBack` method will become an alias for the `#.peek` method if only
     * 1 item is present within the Circular Buffer.
     * </caption>
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello A.')
     *
     * circularBuffer.peekBack()
     * >>> Hello A.
     */
    peekBack() {
        if (this.size === 0) return undefined

        return this.circularBuffer_[(this.headOffset_ + this.size - 1) % this.maxSize]
    }

    /**
     * @return {Array.<*>}
     *
     * @example
     *
     * const circularBuffer = new CircularBuffer()
     * circularBuffer.push('Hello Jane Doe!')
     * circularBuffer.push('Hello John Doe!')
     *
     * circularBuffer.toArray()
     * >>> [ "Hello Jane Doe!", "Hello John Doe!" ]
     */
    toArray() {
        const ePos = this.headOffset_ + this.size

        const toArray = this.circularBuffer_.slice(
            this.headOffset_, Math.min(ePos, this.maxSize)
        )

        if (ePos < this.maxSize) return toArray

        return toArray.concat(
            this.circularBuffer_.slice(
                0, Math.max(0, ePos % this.maxSize)
            )
        )
    }

    /**
     * Create a Circular Buffer from an Iterable.
     *
     * @param {Iterable} iterateOver
     *
     * @return {CircularBuffer}
     *
     * @example
     *
     * const circularBuffer = CircularBuffer.from(["John Doe", "Jane Doe"])
     */
    static from(iterateOver) {
        const circularBuffer = new CircularBuffer(Infinity)

        for (const aValue of iterateOver) circularBuffer.push(aValue)

        circularBuffer.maxSize = circularBuffer.size

        return circularBuffer
    }
}

module.exports = CircularBuffer<|endoftext|>


<commit_before>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');
var kv = require('beepboop-persist')();

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        archive_push(obj);
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(obj){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = obj.channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(obj);
    else {
      createPage(obj);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
    	if (!err) {
        var taggedUsers = obj.text.match(/([<][@][U][A-Za-z0-9]+[>])/g);
        if(taggedUsers){
          var taggedUsersIds = taggedUsers.slice();
          for(var i=0;i<taggedUsersIds.length;i++){
            taggedUsersIds[i].replace(/(<|@|>)/g,'');
          }
          var ps = [];
          for(var i=0;i<taggedUsersIds.length;i++){
            ps.push(getUserInfoPromise(taggedUsersIds[i]));
          }
          Promise.all(ps).then(function(results){
            for(var i=0;i<taggedUsers.length;i++){
              obj.text.replace(taggedUsers[i],results[i]);
            }
          });
        }
        var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
        var content = Buffer.from(fileBody, 'ascii');
        var b64content = content.toString('base64');
        var shaStr = res.sha;
    		github.get().repos.updateFile({
    			owner:"NeuroTechX",
    			repo:"ntx_slack_archive",
    			path:obj.channel+'.md',
    			message:"Edubot Push",
    			content:b64content,
    			sha: shaStr
    		}, function(err, res) {
        });
    	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
      });
}
function getUserInfoPromise(uid){
  return new Promise(function(resolve, reject) {
    kv.get("bot_token",function(err,bToken){
      if(err)
        _("error while loading bot token");
      else if(!err && result){
        slapp.client.users.info({token:bToken,user:uid}, (err, data) => {
          if(err)
            reject(err);
          else
            resolve(data.user.name);
        });
      }
    });
  });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<commit_msg>bToken<commit_after>const slapp = require('./slapp.js').get();
const HashMap = require('hashmap');
const request = require('request');
const fs = require('fs');
var kv = require('beepboop-persist')();

var github = require('./github.js')
function _(obj){
  var str = JSON.stringify(obj, null, 4);
  console.log(str);
}
var buffer =[];
// Archiving feature state
var isArchiving = false;

/**
 * This function that handles the module behaviour when the server is about to restart
 */
function handle_restart(){
  keys = msgMap.keys();
  keys.forEach(function(key){
    var array = msgMap.get(key);
    if(array.length)
      archive_push(key);
  })
}
/**
 * This function receives a message and store it in a hashmap that will be pushed to the github archive
 * @param {object} msg the message sent by slapp that is meant to be archived
 */
function receive(msg){
  if(isArchiving){
    slapp.client.channels.info({token:msg.meta.bot_token,channel:msg.body.event.channel}, (err, resultChannel) => {
      slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.event.user}, (uerr, resultUser) => {
        var timeStamp = new Date(msg.body.event.ts * 1000)
        var obj = {user:resultUser.user.name,
                    ts:timeStamp,
                    text:msg.body.event.text,
                    channel:resultChannel.channel.name};
        archive_push(obj);
      });
    });
  }
}
// Sets the handler for the slash command
slapp.command('/archivetogit','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      if(!text)
        msg.respond("Options for /archivetogit: \n" +
                    "\`start\` starts the archiving to git. (Github token must be initialized first using /github)\n" +
                    "\`stop \` stops the archiving to git.\n" );
      else if(text == 'start')
        archive_start(msg);
      else if(text == 'stop')
        archive_stop(msg);
      else {
        msg.respond("Please use /archivetogit to print the available options.");
      }
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})

function start(){
  isArchiving=true;
}
/**
 * This function starts the message archiving if a github token is specified
 * @param {object} msg the message received from slapp following the user command
 */
function archive_start(msg){
  if(github.getToken()!=''){
    if(!isArchiving){
  		isArchiving=true;
  	msg.respond("Archiving started.");
  	}
  	else {
  		msg.respond("Archiving is already in progress.");
  	}
  }else{
    msg.respond("Please set the github token first.");
  }
}
/**
 * This function stops the message archiving
 * @param {object} msg the message received from slapp following the user command
 */
function archive_stop(msg){
  if(isArchiving){
		isArchiving=false;
		msg.respond("Archiving stopped.");
	}
	else {
		msg.respond("Archiving is already stoped.");
	}
}
/**
 * This function pushes the message from the buffer to github
 */
function archive_push(obj){
  _('ARCHIVE PUSH buffer:');
  _(buffer);
  var channelPageName = obj.channel + '.md';
  github.get().repos.getContent({
   owner:'NeuroTechX',
   repo:'ntx_slack_archive',
   path:''},function(err,result){
    var found = false;
    for (var i = 0; i < result.length && !found; i++) {
      if (result[i].name === channelPageName) {
        found = true;
      }
    }
    if(found)
      editPage(obj);
    else {
      createPage(obj);
    }
  });
}
/**
 * This function edits the github page specified by pageName adding values to it
 * @param {string} obj the data to push
 */
// function editPage(obj){
//   var filePath = "https://raw.githubusercontent.com/NeuroTechX/ntx_slack_archive/master/"+obj.channel+'.md';
//   var propertiesObject = {access_token:github.getToken()};
// 	request.get({url:filePath, qs:propertiesObject}, function (fileerror, fileresponse, fileBody) {
//   	if (!fileerror && fileresponse.statusCode == 200) {
//
//       var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
//       fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
//
// 			//fs.writeFile("slack-links.md", fileBody, {encoding: 'base64'}, function(err){console.log("error encoding the file to b64")});
//       var content = Buffer.from(fileBody, 'ascii');
//       var b64content = content.toString('base64');
// 			var blobPath = "https://api.github.com/repos/NeuroTechX/ntx_slack_archive/contents/"+obj.channel+'.md';
//       var options = {
//         url: blobPath,
//         headers: {
//           'User-Agent': 'Edubot-GitHub-App'
//         },
//         qs:propertiesObject
//       };
// 			request.get(options, function (bloberror, blobresponse, blobBody) {
// 	    	if (!bloberror && blobresponse.statusCode == 200) {
//           var shaStr = JSON.parse(blobBody).sha;
//           //("Sha str")
// 					github.get().repos.updateFile({
// 						owner:"NeuroTechX",
// 						repo:"ntx_slack_archive",
// 						path:obj.channel+'.md',
// 						message:"Edubot Push",
// 						content:b64content,
// 						sha: shaStr
// 					}, function(err, res) {
//             buffer = [];
//           });
//         }
// 			});
//   	}
// 	});
// }
function editPage(obj){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:obj.channel+'.md',
    },
    function(err,res){
    	if (!err) {
        var taggedUsers = obj.text.match(/([<][@][U][A-Za-z0-9]+[>])/g);
        if(taggedUsers){
          var taggedUsersIds = taggedUsers.slice();
          for(var i=0;i<taggedUsersIds.length;i++){
            taggedUsersIds[i].replace(/(<|@|>)/g,'');
          }
          var ps = [];
          for(var i=0;i<taggedUsersIds.length;i++){
            ps.push(getUserInfoPromise(taggedUsersIds[i]));
          }
          Promise.all(ps).then(function(results){
            for(var i=0;i<taggedUsers.length;i++){
              obj.text.replace(taggedUsers[i],results[i]);
            }
          });
        }
        var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";
        var content = Buffer.from(fileBody, 'ascii');
        var b64content = content.toString('base64');
        var shaStr = res.sha;
    		github.get().repos.updateFile({
    			owner:"NeuroTechX",
    			repo:"ntx_slack_archive",
    			path:obj.channel+'.md',
    			message:"Edubot Push",
    			content:b64content,
    			sha: shaStr
    		}, function(err, res) {
        });
    	}
	});
}
/**
 * This function formats the timestamp to a user friendly format
 * @param {timestamp} ts the time stamp to format
 */
function formatDate(ts){
  return ts.toLocaleDateString("en-US") + " " + ts.toLocaleTimeString(["en-US"], {hour: '2-digit', minute:'2-digit'});
}
/**
 * This function creates a github archiving page
 * @param {string} obj data to push
 */
function createPage(obj){
      var fileBody = "######"+obj.channel+"\n\n";
      var quotedText = obj.text.replace(/([\n\r])/g, '\n\n> $1');
			fileBody+= ""+formatDate(obj.ts)+"\n\n **"+ obj.user +"**" + " :\n\n >" + quotedText + "\n\n";

      var content = Buffer.from(fileBody, 'ascii');
      var b64content = content.toString('base64');

      github.get().repos.createFile({
        owner:"NeuroTechX",
        repo:"ntx_slack_archive",
        path:obj.channel+'.md',
        message:"Edubot Push",
        content:b64content
      }, function(err, res) {
      });
}
function getUserInfoPromise(uid){
  return new Promise(function(resolve, reject) {
    kv.get("bot_token",function(err,bToken){
      if(err)
        _("error while loading bot token");
      else if(!err && bToken){
        slapp.client.users.info({token:bToken,user:uid}, (err, data) => {
          if(err)
            reject(err);
          else
            resolve(data.user.name);
        });
      }
    });
  });
}
module.exports = {
  receive:receive,
  handle_restart:handle_restart,
  start:start
}
<|endoftext|>


<commit_before>var app = angular.module('gitGud', [])
<commit_msg>installed ngSanitize<commit_after>var app = angular.module('gitGud', ["ngSanitize"])
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Parse a very small subset of HTML.  This ensures that insecure HTML /
 * javascript cannot be injected into the new tab page.
 * @param {string} s The string to parse.
 * @param {Array.<string>=} opt_extraTags Optional extra allowed tags.
 * @param {Object.<string, function(Node, string):boolean>=} opt_extraAttrs
 *     Optional extra allowed attributes (all tags are run through these).
 * @throws {Error} In case of non supported markup.
 * @return {DocumentFragment} A document fragment containing the DOM tree.
 */
var parseHtmlSubset = (function() {
  'use strict';

  var allowedAttributes = {
    'href': function(node, value) {
      // Only allow a[href] starting with http:// and https://
      return node.tagName == 'A' && (value.indexOf('chrome://') == 0 ||
          value.indexOf('https://') == 0);
    },
    'target': function(node, value) {
      // Allow a[target] but reset the value to "".
      if (node.tagName != 'A')
        return false;
      node.setAttribute('target', '');
      return true;
    }
  };

  /**
   * Whitelist of tag names allowed in parseHtmlSubset.
   * @type {!Array.<string>}
   * @const
   */
  var allowedTags = ['A', 'B', 'STRONG'];

  function merge() {
    var clone = {};
    for (var i = 0; i < arguments.length; ++i) {
      if (typeof arguments[i] == 'object') {
        for (var key in arguments[i]) {
          if (arguments[i].hasOwnProperty(key))
            clone[key] = arguments[i][key];
        }
      }
    }
    return clone;
  }

  function walk(n, f) {
    f(n);
    for (var i = 0; i < n.childNodes.length; i++) {
      walk(n.childNodes[i], f);
    }
  }

  function assertElement(tags, node) {
    if (tags.indexOf(node.tagName) == -1)
      throw Error(node.tagName + ' is not supported');
  }

  function assertAttribute(attrs, attrNode, node) {
    var n = attrNode.nodeName;
    var v = attrNode.nodeValue;
    if (!attrs.hasOwnProperty(n) || !attrs[n](node, v))
      throw Error(node.tagName + '[' + n + '="' + v + '"] is not supported');
  }

  return function(s, opt_extraTags, opt_extraAttrs) {
    var extraTags =
        (opt_extraTags || []).map(function(str) { return str.toUpperCase(); });
    var tags = allowedTags.concat(extraTags);
    var attrs = merge(allowedAttributes, opt_extraAttrs || {});

    var r = document.createRange();
    r.selectNode(document.body);
    // This does not execute any scripts.
    var df = r.createContextualFragment(s);
    walk(df, function(node) {
      switch (node.nodeType) {
        case Node.ELEMENT_NODE:
          assertElement(tags, node);
          var nodeAttrs = node.attributes;
          for (var i = 0; i < nodeAttrs.length; ++i) {
            assertAttribute(attrs, nodeAttrs[i], node);
          }
          break;

        case Node.COMMENT_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.TEXT_NODE:
          break;

        default:
          throw Error('Node type ' + node.nodeType + ' is not supported');
      }
    });
    return df;
  };
})();
<commit_msg>Update comment.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Parse a very small subset of HTML.  This ensures that insecure HTML /
 * javascript cannot be injected into the new tab page.
 * @param {string} s The string to parse.
 * @param {Array.<string>=} opt_extraTags Optional extra allowed tags.
 * @param {Object.<string, function(Node, string):boolean>=} opt_extraAttrs
 *     Optional extra allowed attributes (all tags are run through these).
 * @throws {Error} In case of non supported markup.
 * @return {DocumentFragment} A document fragment containing the DOM tree.
 */
var parseHtmlSubset = (function() {
  'use strict';

  var allowedAttributes = {
    'href': function(node, value) {
      // Only allow a[href] starting with chrome:// and https://
      return node.tagName == 'A' && (value.indexOf('chrome://') == 0 ||
          value.indexOf('https://') == 0);
    },
    'target': function(node, value) {
      // Allow a[target] but reset the value to "".
      if (node.tagName != 'A')
        return false;
      node.setAttribute('target', '');
      return true;
    }
  };

  /**
   * Whitelist of tag names allowed in parseHtmlSubset.
   * @type {!Array.<string>}
   * @const
   */
  var allowedTags = ['A', 'B', 'STRONG'];

  function merge() {
    var clone = {};
    for (var i = 0; i < arguments.length; ++i) {
      if (typeof arguments[i] == 'object') {
        for (var key in arguments[i]) {
          if (arguments[i].hasOwnProperty(key))
            clone[key] = arguments[i][key];
        }
      }
    }
    return clone;
  }

  function walk(n, f) {
    f(n);
    for (var i = 0; i < n.childNodes.length; i++) {
      walk(n.childNodes[i], f);
    }
  }

  function assertElement(tags, node) {
    if (tags.indexOf(node.tagName) == -1)
      throw Error(node.tagName + ' is not supported');
  }

  function assertAttribute(attrs, attrNode, node) {
    var n = attrNode.nodeName;
    var v = attrNode.nodeValue;
    if (!attrs.hasOwnProperty(n) || !attrs[n](node, v))
      throw Error(node.tagName + '[' + n + '="' + v + '"] is not supported');
  }

  return function(s, opt_extraTags, opt_extraAttrs) {
    var extraTags =
        (opt_extraTags || []).map(function(str) { return str.toUpperCase(); });
    var tags = allowedTags.concat(extraTags);
    var attrs = merge(allowedAttributes, opt_extraAttrs || {});

    var r = document.createRange();
    r.selectNode(document.body);
    // This does not execute any scripts.
    var df = r.createContextualFragment(s);
    walk(df, function(node) {
      switch (node.nodeType) {
        case Node.ELEMENT_NODE:
          assertElement(tags, node);
          var nodeAttrs = node.attributes;
          for (var i = 0; i < nodeAttrs.length; ++i) {
            assertAttribute(attrs, nodeAttrs[i], node);
          }
          break;

        case Node.COMMENT_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.TEXT_NODE:
          break;

        default:
          throw Error('Node type ' + node.nodeType + ' is not supported');
      }
    });
    return df;
  };
})();
<|endoftext|>


<commit_before>/* globals define */

(function () {
  'use strict';

  define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'routers/app-router',
    'controllers/controller',
    'controllers/event-bus',
    'models/settings-model',
    'models/user-model',
    'models/sidebar-model',
    'collections/post-collection',
    'views/header-view',
    'views/sidebar-view',
    'views/footer-view'
  ], function ($, _, Backbone, Marionette, AppRouter, Controller, EventBus, Settings, User, Sidebar, Posts, HeaderView, SidebarView, FooterView) {

    var App   = new Backbone.Marionette.Application(),
        user  = new User({ID: 'me'});

    App.navigate = function(route, options){
      options = options || {};
      this.appRouter.navigate(route, options);
    };

    App.titleChange = function(title) {
      var separator = ' | ';
      var newTitle  = '';

      if (_.isFunction(title)) {
        newTitle = title.apply(this, arguments) + separator;

      } else if (_.isString(title)) {
        newTitle = title + separator;
      }

      document.title = newTitle + Settings.get('name');
    };

    function isMobile() {
      var ua = (navigator.userAgent || navigator.vendor || window.opera, window, window.document);
      return (/iPhone|iPod|iPad|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
    }

    function initializeLayout (menus, sidebars) {
      App.header.show(new HeaderView({menus: menus}));

      if (sidebars && sidebars.sidebar) {
        App.widgets.show(new SidebarView({model: new Sidebar(sidebars.sidebar)}));
      }

      App.footer.show(new FooterView());

      App.appRouter = new AppRouter({
        controller: new Controller({
          app:   App,
          posts: new Posts(),
          user:  user,
          menus: menus
        })
      });

      if(Backbone.history) {
        Backbone.history.start({pushState: true, root: Settings.get('path')});
      }
    }

    function getMenus () {
      return $.get(Settings.get('apiUrl') + '/b3:menus');
    }

    function getSidebars () {
      return $.get(Settings.get('apiUrl') + '/b3:sidebars');
    }

    App.mobile = isMobile();

    App.addInitializer(function() {
      getMenus().then(function (menus) {
        getSidebars().done(function (sidebars) {
          user.fetch();
          initializeLayout(menus, sidebars);
        });
      }); /* TODO: need a fail view .fail(); */

      EventBus.bind('router:nav', function (options) {
        App.navigate(options.route, options.options);
      });

      EventBus.bind('title:change', function (title) {
        App.titleChange(title);
      });

      App.addRegions({
        header:  '#header',
        main:    '#main',
        widgets: '#widgets',
        footer:  '#footer'
      });
    });

    return App;
  });

})();
<commit_msg>Move to top of window when navigating<commit_after>/* globals define */

(function () {
  'use strict';

  define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'routers/app-router',
    'controllers/controller',
    'controllers/event-bus',
    'models/settings-model',
    'models/user-model',
    'models/sidebar-model',
    'collections/post-collection',
    'views/header-view',
    'views/sidebar-view',
    'views/footer-view'
  ], function ($, _, Backbone, Marionette, AppRouter, Controller, EventBus, Settings, User, Sidebar, Posts, HeaderView, SidebarView, FooterView) {

    var App   = new Backbone.Marionette.Application(),
        user  = new User({ID: 'me'});

    App.navigate = function(route, options){
      options = options || {};
      this.appRouter.navigate(route, options);
      if (!options.trigger) {
        window.scrollTo(0, 0);
      }
    };

    App.titleChange = function(title) {
      var separator = ' | ';
      var newTitle  = '';

      if (_.isFunction(title)) {
        newTitle = title.apply(this, arguments) + separator;

      } else if (_.isString(title)) {
        newTitle = title + separator;
      }

      document.title = newTitle + Settings.get('name');
    };

    function isMobile() {
      var ua = (navigator.userAgent || navigator.vendor || window.opera, window, window.document);
      return (/iPhone|iPod|iPad|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
    }

    function initializeLayout (menus, sidebars) {
      App.header.show(new HeaderView({menus: menus}));

      if (sidebars && sidebars.sidebar) {
        App.widgets.show(new SidebarView({model: new Sidebar(sidebars.sidebar)}));
      }

      App.footer.show(new FooterView());

      App.appRouter = new AppRouter({
        controller: new Controller({
          app:   App,
          posts: new Posts(),
          user:  user,
          menus: menus
        })
      });

      if(Backbone.history) {
        Backbone.history.start({pushState: true, root: Settings.get('path')});
      }
    }

    function getMenus () {
      return $.get(Settings.get('apiUrl') + '/b3:menus');
    }

    function getSidebars () {
      return $.get(Settings.get('apiUrl') + '/b3:sidebars');
    }

    App.mobile = isMobile();

    App.addInitializer(function() {
      getMenus().then(function (menus) {
        getSidebars().done(function (sidebars) {
          user.fetch();
          initializeLayout(menus, sidebars);
        });
      }); /* TODO: need a fail view .fail(); */

      EventBus.bind('router:nav', function (options) {
        App.navigate(options.route, options.options);
      });

      EventBus.bind('title:change', function (title) {
        App.titleChange(title);
      });

      App.addRegions({
        header:  '#header',
        main:    '#main',
        widgets: '#widgets',
        footer:  '#footer'
      });
    });

    return App;
  });

})();
<|endoftext|>


<commit_before>import 'core-js/fn/array/find';
import {
  isValidNumber,
} from 'phoneformat.js';
import HashMap from './HashMap';
import callActions from '../enums/callActions';
import callDirections from '../enums/callDirections';
import callResults from '../enums/callResults';
import telephonyStatuses from '../enums/telephonyStatuses';
import terminationTypes from '../enums/terminationTypes';
import isSameLocalNumber from './isSameLocalNumber';

/* call direction helpers */
export function isInbound(call = {}) {
  return call.direction === callDirections.inbound;
}

export function isOutbound(call = {}) {
  return call.direction === callDirections.outbound;
}

/* status helpers */
export function isRinging(call = {}) {
  return call.telephonyStatus === telephonyStatuses.ringing;
}

const callResultsToMissedMap = HashMap.fromSet({
  set: Object.keys(callResults).map(key => callResults[key]),
  getValue: result => (
    [
      callResults.missed,
      callResults.hangUp,
      callResults.busy,
      callResults.voiceMail,
      callResults.rejected,
    ].indexOf(result) > -1
  ),
});
export function isMissed(call = {}) {
  return !!callResultsToMissedMap[call.result];
}

export function hasRingingCalls(calls = []) {
  return !!calls.find(isRinging);
}

export function isEnded(call = {}) {
  return call.telephonyStatus === telephonyStatuses.noCall &&
    call.terminationType === terminationTypes.final;
}

export function hasEndedCalls(calls) {
  return !!calls.find(isEnded);
}

export function isOnHold(call = {}) {
  return call.telephonyStatus === telephonyStatuses.onHold;
}

export function isIntermediateCall(call = {}) {
  return call.terminationType === terminationTypes.intermediate;
}

/* sort functions */

export function sortBySessionId(a, b) {
  if (a.sessionId === b.sessionId) return 0;
  return a.sessionId > b.sessionId ?
    1 :
    -1;
}
export function sortByStartTime(a, b) {
  if (a.startTime === b.startTime) return 0;
  return a.startTime > b.startTime ?
    -1 :
    1;
}

export function normalizeStartTime(call) {
  return {
    ...call,
    startTime: (new Date(call.startTime)).getTime(),
  };
}

export function normalizeFromTo(call) {
  return {
    ...call,
    from: typeof call.from === 'object' ?
      call.from :
      { phoneNumber: call.from },
    to: typeof call.to === 'object' ?
      call.to :
      { phoneNumber: call.to },
  };
}

/* ringout leg helpers */
export function areTwoLegs(inbound, outbound) {
  if (isInbound(inbound) && isOutbound(outbound)) {
    switch (Math.abs(inbound.sessionId - outbound.sessionId)) {
      case 1000:
      case 2000:
      case 3000:
      case 4000: {
        // presence
        if (
          inbound.from && inbound.to &&
          outbound.from && outbound.to &&
          isSameLocalNumber(inbound.from.phoneNumber, outbound.to.phoneNumber) &&
          isSameLocalNumber(inbound.to.phoneNumber, outbound.from.phoneNumber)
        ) {
          return true;
        }
        // call-log
        if (
          inbound.from && inbound.to &&
          outbound.from && outbound.to &&
          inbound.action === callActions.phoneCall &&
          (
            outbound.action === callActions.ringOutWeb ||
            outbound.action === callActions.ringOutPC ||
            outbound.action === callActions.ringOutMobile
          ) &&
          (
            inbound.from.phoneNumber === outbound.from.phoneNumber ||
            inbound.from.extensionNumber === outbound.from.extensionNumber
          ) &&
          inbound.to.phoneNumber === outbound.to.phoneNumber
        ) {
          return true;
        }
        break;
      }
      default:
        return false;
    }
  }
  return false;
}

export function removeInboundRingOutLegs(calls) {
  const output = [];
  const outbounds = calls.filter(isOutbound);
  calls.filter(isInbound).forEach((inbound) => {
    const outboundIndex = outbounds.findIndex(call => areTwoLegs(inbound, call));
    if (outboundIndex > -1) {
      const outbound = outbounds.splice(outboundIndex, 1)[0];

      if (inbound.action && outbound.action) {
        // from call-log
        const call = {
          ...outbound,
          outboundLeg: outbound,
          inboundLeg: inbound,
          from: {
            ...inbound.to,
          },
          to: {
            ...inbound.from,
          },
          result: inbound.result,
        };
        output.push(call);
      } else {
        const call = {
          ...outbound,
          outboundLeg: outbound,
          inboundLeg: inbound,
        };
        // Handle inboundLeg.from is '+19072028624', but outboundLeg.to is '9072028624'
        // https://jira.ringcentral.com/browse/RCINT-3127
        if (
          isValidNumber(inbound.from && inbound.from.phoneNumber) &&
          isSameLocalNumber(inbound.from.phoneNumber, outbound.to && outbound.to.phoneNumber)
        ) {
          call.to = {
            ...outbound.to,
            phoneNumber: inbound.from.phoneNumber,
          };
          outbound.to.phoneNumber = inbound.from.phoneNumber;
        }
        if (isOnHold(inbound)) {
          call.telephonyStatus = telephonyStatuses.onHold;
        }
        output.push(call);
      }

      // output.push(outbound);
    } else {
      output.push(inbound);
    }
  });
  return output.concat(outbounds);
}

export function removeDuplicateIntermediateCalls(calls) {
  const resultCalls = [];
  const indexMap = {};
  calls.forEach((call) => {
    const isIntermediate = isIntermediateCall(call);
    if (!indexMap[call.sessionId]) {
      indexMap[call.sessionid] = {
        index: resultCalls.length,
        isIntermediate,
      };
      resultCalls.push(call);
    } else if (!isIntermediate) {
      indexMap[call.sessionId].isIntermediate = false;
      resultCalls[indexMap[call.sessionId].index] = call;
    }
  });
  return resultCalls;
}
<commit_msg>fix typo voiceMail to voicemail (#257)<commit_after>import 'core-js/fn/array/find';
import {
  isValidNumber,
} from 'phoneformat.js';
import HashMap from './HashMap';
import callActions from '../enums/callActions';
import callDirections from '../enums/callDirections';
import callResults from '../enums/callResults';
import telephonyStatuses from '../enums/telephonyStatuses';
import terminationTypes from '../enums/terminationTypes';
import isSameLocalNumber from './isSameLocalNumber';

/* call direction helpers */
export function isInbound(call = {}) {
  return call.direction === callDirections.inbound;
}

export function isOutbound(call = {}) {
  return call.direction === callDirections.outbound;
}

/* status helpers */
export function isRinging(call = {}) {
  return call.telephonyStatus === telephonyStatuses.ringing;
}

const callResultsToMissedMap = HashMap.fromSet({
  set: Object.keys(callResults).map(key => callResults[key]),
  getValue: result => (
    [
      callResults.missed,
      callResults.hangUp,
      callResults.busy,
      callResults.voicemail,
      callResults.rejected,
    ].indexOf(result) > -1
  ),
});
export function isMissed(call = {}) {
  return !!callResultsToMissedMap[call.result];
}

export function hasRingingCalls(calls = []) {
  return !!calls.find(isRinging);
}

export function isEnded(call = {}) {
  return call.telephonyStatus === telephonyStatuses.noCall &&
    call.terminationType === terminationTypes.final;
}

export function hasEndedCalls(calls) {
  return !!calls.find(isEnded);
}

export function isOnHold(call = {}) {
  return call.telephonyStatus === telephonyStatuses.onHold;
}

export function isIntermediateCall(call = {}) {
  return call.terminationType === terminationTypes.intermediate;
}

/* sort functions */

export function sortBySessionId(a, b) {
  if (a.sessionId === b.sessionId) return 0;
  return a.sessionId > b.sessionId ?
    1 :
    -1;
}
export function sortByStartTime(a, b) {
  if (a.startTime === b.startTime) return 0;
  return a.startTime > b.startTime ?
    -1 :
    1;
}

export function normalizeStartTime(call) {
  return {
    ...call,
    startTime: (new Date(call.startTime)).getTime(),
  };
}

export function normalizeFromTo(call) {
  return {
    ...call,
    from: typeof call.from === 'object' ?
      call.from :
      { phoneNumber: call.from },
    to: typeof call.to === 'object' ?
      call.to :
      { phoneNumber: call.to },
  };
}

/* ringout leg helpers */
export function areTwoLegs(inbound, outbound) {
  if (isInbound(inbound) && isOutbound(outbound)) {
    switch (Math.abs(inbound.sessionId - outbound.sessionId)) {
      case 1000:
      case 2000:
      case 3000:
      case 4000: {
        // presence
        if (
          inbound.from && inbound.to &&
          outbound.from && outbound.to &&
          isSameLocalNumber(inbound.from.phoneNumber, outbound.to.phoneNumber) &&
          isSameLocalNumber(inbound.to.phoneNumber, outbound.from.phoneNumber)
        ) {
          return true;
        }
        // call-log
        if (
          inbound.from && inbound.to &&
          outbound.from && outbound.to &&
          inbound.action === callActions.phoneCall &&
          (
            outbound.action === callActions.ringOutWeb ||
            outbound.action === callActions.ringOutPC ||
            outbound.action === callActions.ringOutMobile
          ) &&
          (
            inbound.from.phoneNumber === outbound.from.phoneNumber ||
            inbound.from.extensionNumber === outbound.from.extensionNumber
          ) &&
          inbound.to.phoneNumber === outbound.to.phoneNumber
        ) {
          return true;
        }
        break;
      }
      default:
        return false;
    }
  }
  return false;
}

export function removeInboundRingOutLegs(calls) {
  const output = [];
  const outbounds = calls.filter(isOutbound);
  calls.filter(isInbound).forEach((inbound) => {
    const outboundIndex = outbounds.findIndex(call => areTwoLegs(inbound, call));
    if (outboundIndex > -1) {
      const outbound = outbounds.splice(outboundIndex, 1)[0];

      if (inbound.action && outbound.action) {
        // from call-log
        const call = {
          ...outbound,
          outboundLeg: outbound,
          inboundLeg: inbound,
          from: {
            ...inbound.to,
          },
          to: {
            ...inbound.from,
          },
          result: inbound.result,
        };
        output.push(call);
      } else {
        const call = {
          ...outbound,
          outboundLeg: outbound,
          inboundLeg: inbound,
        };
        // Handle inboundLeg.from is '+19072028624', but outboundLeg.to is '9072028624'
        // https://jira.ringcentral.com/browse/RCINT-3127
        if (
          isValidNumber(inbound.from && inbound.from.phoneNumber) &&
          isSameLocalNumber(inbound.from.phoneNumber, outbound.to && outbound.to.phoneNumber)
        ) {
          call.to = {
            ...outbound.to,
            phoneNumber: inbound.from.phoneNumber,
          };
          outbound.to.phoneNumber = inbound.from.phoneNumber;
        }
        if (isOnHold(inbound)) {
          call.telephonyStatus = telephonyStatuses.onHold;
        }
        output.push(call);
      }

      // output.push(outbound);
    } else {
      output.push(inbound);
    }
  });
  return output.concat(outbounds);
}

export function removeDuplicateIntermediateCalls(calls) {
  const resultCalls = [];
  const indexMap = {};
  calls.forEach((call) => {
    const isIntermediate = isIntermediateCall(call);
    if (!indexMap[call.sessionId]) {
      indexMap[call.sessionid] = {
        index: resultCalls.length,
        isIntermediate,
      };
      resultCalls.push(call);
    } else if (!isIntermediate) {
      indexMap[call.sessionId].isIntermediate = false;
      resultCalls[indexMap[call.sessionId].index] = call;
    }
  });
  return resultCalls;
}
<|endoftext|>


<commit_before>define([
  // Libraries.
  "jquery",
  "lodash",
  "backbone",

  // Plugins.
  "plugins/backbone.layoutmanager"
],

function($, _, Backbone) {

  // Provide a global location to place configuration settings and module
  // creation.
  var app = {
    // The root path to run the application.
    root: "/"
  };

  // Localize or create a new JavaScript Template object.
  var JST = window.JST = window.JST || {};

  // Configure LayoutManager with Backbone Boilerplate defaults.
  Backbone.LayoutManager.configure({
    paths: {
      layout: "app/templates/layouts/",
      template: "app/templates/"
    },

    fetch: function(path) {
      path = path + ".html";

      if (!JST[path]) {
        $.ajax({ url: "/" + path, async: false }).then(function(contents) {
          JST[path] = _.template(contents);
        });
      }

      return JST[path];
    }
  });

  // Mix Backbone.Events, modules, and layout management into the app object.
  return _.extend(app, {
    // Create a custom object with a nested Views object.
    module: function(additionalProps) {
      return _.extend({ Views: {} }, additionalProps);
    },

    // Helper for using layouts.
    useLayout: function(name) {
      // If already using this Layout, then don't re-inject into the DOM.
      if (this.layout && this.layout.options.template === name) {
        return this.layout;
      }

      // If a layout already exists, remove it from the DOM.
      if (this.layout) {
        this.layout.remove();
      }

      // Create a new Layout.
      var layout = new Backbone.Layout({
        template: name,
        className: "layout " + name,
        id: "layout"
      });

      // Insert into the DOM.
      $("#main").empty().append(layout.el);

      // Render the layout.
      layout.render();

      // Cache the refererence.
      this.layout = layout;

      // Return the reference, for chainability.
      return layout;
    }
  }, Backbone.Events);

});
<commit_msg>updated root fetch status<commit_after>define([
  // Libraries.
  "jquery",
  "lodash",
  "backbone",

  // Plugins.
  "plugins/backbone.layoutmanager"
],

function($, _, Backbone) {

  // Provide a global location to place configuration settings and module
  // creation.
  var app = {
    // The root path to run the application.
    root: "/"
  };

  // Localize or create a new JavaScript Template object.
  var JST = window.JST = window.JST || {};

  // Configure LayoutManager with Backbone Boilerplate defaults.
  Backbone.LayoutManager.configure({
    paths: {
      layout: "app/templates/layouts/",
      template: "app/templates/"
    },

    fetch: function(path) {
      path = path + ".html";

      if (!JST[path]) {
        $.ajax({ url: app.root + path, async: false }).then(function(contents) {
          JST[path] = _.template(contents);
        });
      }

      return JST[path];
    }
  });

  // Mix Backbone.Events, modules, and layout management into the app object.
  return _.extend(app, {
    // Create a custom object with a nested Views object.
    module: function(additionalProps) {
      return _.extend({ Views: {} }, additionalProps);
    },

    // Helper for using layouts.
    useLayout: function(name) {
      // If already using this Layout, then don't re-inject into the DOM.
      if (this.layout && this.layout.options.template === name) {
        return this.layout;
      }

      // If a layout already exists, remove it from the DOM.
      if (this.layout) {
        this.layout.remove();
      }

      // Create a new Layout.
      var layout = new Backbone.Layout({
        template: name,
        className: "layout " + name,
        id: "layout"
      });

      // Insert into the DOM.
      $("#main").empty().append(layout.el);

      // Render the layout.
      layout.render();

      // Cache the refererence.
      this.layout = layout;

      // Return the reference, for chainability.
      return layout;
    }
  }, Backbone.Events);

});
<|endoftext|>