<commit_before>#!/bin/env node
//Generate unofficial rss feed and start a express server to serve them
//The web server staff was officialy based on the OpenShift template.
//Because that is where I want it to run.

var express = require('express');
var request = require('request');
var rss = require('./rssmaker');
var fs = require('fs');
var feedsToCreate = require('./feeds.json');

var SampleApp = function() {

    var self = this;

    self.feedLoadInterval = 600000; //10 minutes

    // Set up server IP address and port # using env variables/defaults.
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        }
    };

    //List of feeds automatically generated
    self.feed_list = {};

    self.routes = { };

    // Populate the cache.
    self.populateCache = function() {
        // Create the cache object
        if (typeof self.zcache === "undefined") {
            self.zcache = {};
        }
        // Initialize cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

     /* Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    self.cache_set = function(key, value) {
        self.zcache[key] = value;
    };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    // Setup termination handlers (for exit and a list of signals).
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });
        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    // Create the routing table entries + handlers for the application.
    self.createRoutes = function() {

        self.routes['/test'] = function(req, res) {
            console.log(req.url);
            res.send(self.zcache);
        };

        self.routes['/rss/:feedname'] = function(req, res) {
            res.send(self.cache_get(req.params.feedname));
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
        self.routes['/feedlist'] = function(req, res) {
            res.setHeader('Content-Type', 'text/json');
            res.send(JSON.stringify(self.feed_list));
        }
    };

    // Initialize the server (express) and create the routes and register the handlers.
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();
        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    // Generates the rss feeds whose description is passed in parameter and stach them in the cache
    self.makeFeed = function(feeds) {
        var feedname;

        for ( var i=0; i < feeds.length; i++) {
            feedname = feeds[i].name;
            self.feed_list[feedname] = "rss/" + feedname;

            (function (feed) {
                var options = {
                        url: feed.rssfeed.site_url,
                        headers: {
                            'User-Agent': 'request'
                        }
                    };

                request(options, function(error, response, html){
                    if(!error) {
                        console.log('Feed generated : ' + feed.name);
                        var result = rss( html, feed.rssfeed, feed.rssmaker);
                        self.cache_set(feed.name, result);
                    } else {
                        console.log('Error generating feed for ' + feed.name);
                        self.cache_set(feed.name, ' something went wrong : ' + error);
                    }
                });
            })(feeds[i])
        }
    };

    // Initializes the sample application.
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();

        self.makeFeed(feedsToCreate);
        //setInterval(self.makeFeed(feedsToCreate), 600000);

        self.setupTerminationHandlers();
        // Create the express server and routes.
        self.initializeServer();
    };

    // Start the server (starts up the sample application).
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
        self.app.use(express.static('static'));
    };
};

var zapp = new SampleApp();
zapp.initialize();
zapp.start();<commit_msg>Add comments<commit_after>#!/bin/env node
//Generate unofficial rss feed and start a express server to serve them
//The web server staff was officialy based on the OpenShift template.
//Because that is where I want it to run.

var express = require('express');
var request = require('request');
var rss = require('./rssmaker');
var fs = require('fs');
var feedsToCreate = require('./feeds.json');

var SampleApp = function() {

    var self = this;

    self.feedLoadInterval = 600000; //10 minutes

    // Set up server IP address and port # using env variables/defaults.
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        }
    };

    //List of feeds automatically generated
    self.feed_list = {};

    self.routes = { };

    // Populate the cache.
    self.populateCache = function() {
        // Create the cache object
        if (typeof self.zcache === "undefined") {
            self.zcache = {};
        }
        // Initialize cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

     /* Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    self.cache_set = function(key, value) {
        self.zcache[key] = value;
    };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    // Setup termination handlers (for exit and a list of signals).
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });
        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    // Create the routing table entries + handlers for the application.
    self.createRoutes = function() {

        // To check the cache, this is for debug
        /*
        /self.routes['/cache'] = function(req, res) {
            console.log(req.url);
            res.send(self.zcache);
        };
        */

        // The route to get one of the feed generated
        self.routes['/rss/:feedname'] = function(req, res) {
            res.send(self.cache_get(req.params.feedname));
        };
        // Main route
        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
        //Return the feed list, called by the main page in ajax
        self.routes['/feedlist'] = function(req, res) {
            res.setHeader('Content-Type', 'text/json');
            res.send(JSON.stringify(self.feed_list));
        }
    };

    // Initialize the server (express) and create the routes and register the handlers.
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();
        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    // Generates the rss feeds whose description is passed in parameter and stach them in the cache
    self.makeFeed = function(feeds) {
        var feedname;

        for ( var i=0; i < feeds.length; i++) {
            feedname = feeds[i].name;
            self.feed_list[feedname] = "rss/" + feedname;

            (function (feed) {
                var options = {
                        url: feed.rssfeed.site_url,
                        headers: {
                            'User-Agent': 'request'
                        }
                    };

                request(options, function(error, response, html){
                    if(!error) {
                        console.log('Feed generated : ' + feed.name);
                        var result = rss( html, feed.rssfeed, feed.rssmaker);
                        self.cache_set(feed.name, result);
                    } else {
                        console.log('Error generating feed for ' + feed.name);
                        self.cache_set(feed.name, ' something went wrong : ' + error);
                    }
                });
            })(feeds[i])
        }
    };

    // Initializes the sample application.
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();

        self.makeFeed(feedsToCreate);
        //setInterval(self.makeFeed(feedsToCreate), 600000);

        self.setupTerminationHandlers();
        // Create the express server and routes.
        self.initializeServer();
    };

    // Start the server (starts up the sample application).
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
        self.app.use(express.static('static'));
    };
};

var zapp = new SampleApp();
zapp.initialize();
zapp.start();<|endoftext|>


<commit_before>/**
 * Main library entry point. The module will return a function. If you are using it inside of another project then you
 * should require in grasshopper and execute the function. If you are using GH as a standalone app then you should
 * execute bin/grasshopper-js
 *
 * @param proxy - Express app that you want to use to act as a proxy to the grasshopper api
 */
module.exports = function(options){
    'use strict';

    var fs = require('fs'),
        http = require('http'),
        https = require('https'),
        morgan = require('morgan'),
        express = require('express'),
        bodyParser = require('body-parser'),
        bridgetown = require('bridgetown-api'),
        grasshopper = require('grasshopper-core').init(options),
        methodOverride = require('method-override'),
        setHeaders = require('./middleware/setHeaders'),
        ghapiRouter = express.Router(),
        PORT = (process.argv.length == 3 && process.argv[2] !== 'test') ? process.argv[2] : (process.env.PORT || 3000),
        bodyParserLimit = options.bodyParser.limit || false,
        serverOptions = {},
        ssl = false,
        useProxy = false,
        expressApp,

    //Setup bridgetown configuration
    bridgetown.configure(function(){
        this.validate.token(function(authentication){
            return grasshopper.request(authentication.token).users.current();
        });
    });

    //Configure Express App
    ghapiRouter.use(express.static(__dirname + '/public'));

    //Set the global route params for the given application route.
    ghapiRouter.route('*').all([setHeaders, morgan('default'), methodOverride(), bodyParser( bodyParserLimit || {limit: '2mb'})]);

    if( grasshopper.config.server ) {
        if( grasshopper.config.server.https ) {
            serverOptions.key = fs.readFileSync(grasshopper.config.server.https.key);
            serverOptions.cert = fs.readFileSync(grasshopper.config.server.https.cert);
            ssl = true;
        }

        if( grasshopper.config.server.proxy === true ) {
            useProxy = true;
        }
    }

    //Load in API Routes
    require('./routes/token')(ghapiRouter);
    require('./routes/google')(ghapiRouter);
    require('./routes/users')(ghapiRouter);
    require('./routes/contentTypes')(ghapiRouter);
    require('./routes/content')(ghapiRouter);
    require('./routes/nodes')(ghapiRouter);
    require('./routes/system')(ghapiRouter);

    //Only start a server if a proxy is not available.
    if(!useProxy){

        expressApp = express();
        // Only setup router if no proxy if passed in
        // If there is a proxy, then assume the user will setup the router with their desired mount path when they see fit
        routePath = expressApp.get('grasshopper route prefix') || '/';
        expressApp.use(routePath, ghapiRouter);

        if(ssl) {
            https.createServer(serverOptions, expressApp).listen(PORT, function(){
                console.log('Listening securely on port ' + PORT + '...');
            });
        }
        else {
            http.createServer(expressApp).listen(PORT, function(){
                console.log('Listening on port ' + PORT + '...');
            });
        }

    }

    return {
        bridgetown : bridgetown,
        router : ghapiRouter,
        core : grasshopper
    };
};
<commit_msg>passing jshint<commit_after>/**
 * Main library entry point. The module will return a function. If you are using it inside of another project then you
 * should require in grasshopper and execute the function. If you are using GH as a standalone app then you should
 * execute bin/grasshopper-js
 *
 * @param proxy - Express app that you want to use to act as a proxy to the grasshopper api
 */
module.exports = function(options){
    'use strict';

    console.log('OPTIONS YEAH');
    console.log(options);
    console.log('OPTIONS YEAH');

    var fs = require('fs'),
        http = require('http'),
        https = require('https'),
        morgan = require('morgan'),
        express = require('express'),
        bodyParser = require('body-parser'),
        bridgetown = require('bridgetown-api'),
        grasshopper = require('grasshopper-core').init(options),
        methodOverride = require('method-override'),
        setHeaders = require('./middleware/setHeaders'),
        ghapiRouter = express.Router(),
        PORT = (process.argv.length == 3 && process.argv[2] !== 'test') ? process.argv[2] : (process.env.PORT || 3000),
        bodyParserLimit = false,
        serverOptions = {},
        ssl = false,
        useProxy = false,
        expressApp,
        routePath;

    if (options && options.bodyParser.limit) {
        bodyParserLimit = options.bodyParser.limit;
    }

    //Setup bridgetown configuration
    bridgetown.configure(function(){
        this.validate.token(function(authentication){
            return grasshopper.request(authentication.token).users.current();
        });
    });

    //Configure Express App
    ghapiRouter.use(express.static(__dirname + '/public'));

    //Set the global route params for the given application route.
    ghapiRouter.route('*').all([setHeaders, morgan('default'), methodOverride(), bodyParser( bodyParserLimit || {limit: '2mb'})]);

    if( grasshopper.config.server ) {
        if( grasshopper.config.server.https ) {
            serverOptions.key = fs.readFileSync(grasshopper.config.server.https.key);
            serverOptions.cert = fs.readFileSync(grasshopper.config.server.https.cert);
            ssl = true;
        }

        if( grasshopper.config.server.proxy === true ) {
            useProxy = true;
        }
    }

    //Load in API Routes
    require('./routes/token')(ghapiRouter);
    require('./routes/google')(ghapiRouter);
    require('./routes/users')(ghapiRouter);
    require('./routes/contentTypes')(ghapiRouter);
    require('./routes/content')(ghapiRouter);
    require('./routes/nodes')(ghapiRouter);
    require('./routes/system')(ghapiRouter);

    //Only start a server if a proxy is not available.
    if(!useProxy){

        expressApp = express();
        // Only setup router if no proxy if passed in
        // If there is a proxy, then assume the user will setup the router with their desired mount path when they see fit
        routePath = expressApp.get('grasshopper route prefix') || '/';
        expressApp.use(routePath, ghapiRouter);

        if(ssl) {
            https.createServer(serverOptions, expressApp).listen(PORT, function(){
                console.log('Listening securely on port ' + PORT + '...');
            });
        }
        else {
            http.createServer(expressApp).listen(PORT, function(){
                console.log('Listening on port ' + PORT + '...');
            });
        }

    }

    return {
        bridgetown : bridgetown,
        router : ghapiRouter,
        core : grasshopper
    };
};
<|endoftext|>


<commit_before>/*eslint-env node */
/**
*Created:...................11/07/2016
*Author:....................Emmanuel Henley
*Author Contact:............ehenl001@fiu.edu
*Last Edited:...............11/11/2016
*Last Edited by:............same as author
*Last Edited by contact:....same as author
*
*
*Server for the HenleyLunn EMR app
**/

var express = require("express");
var app = express();
var http = require("http");

var host = "localhost";
var port = 3030;
var cloudant = {
	url: "https://a39147b3-f95b-4e5d-8d0d-a9b7384280fb-bluemix.cloudant.com/_all_dbs"
};

if (process.env.hasOwnProperty("VCAP_SERVICES")) {
  // Running on Bluemix. Parse out the port and host that we've been assigned.
  var env = JSON.parse(process.env.VCAP_SERVICES);
  var host = process.env.VCAP_APP_HOST;
  var port = process.env.VCAP_APP_PORT;

  //Parse out Cloudant settings
  cloudant = env["cloudantNoSQLDB"][0].credentials;
}

var nano = require("nano")(cloudant.url);
var db = nano.db.use("user_login");

//variables for the sso
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');

//for the sso
app.use(cookieParser());
app.use(session({resave: 'true', saveUninitialized: 'true' , secret: 'keyboard cat'}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
   done(null, user);
});

passport.deserializeUser(function(obj, done) {
   done(null, obj);
});

// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.
var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
var ssoConfig = services.SingleSignOn[0];
var client_id = ssoConfig.credentials.clientId;
var client_secret = ssoConfig.credentials.secret;
var authorization_url = ssoConfig.credentials.authorizationEndpointUrl;
var token_url = ssoConfig.credentials.tokenEndpointUrl;
var issuer_id = ssoConfig.credentials.issuerIdentifier;
var callback_url = '/patientExamination';

var OpenIDConnectStrategy = require('passport-idaas-openidconnect').IDaaSOIDCStrategy;
var Strategy = new OpenIDConnectStrategy({
                 authorizationURL : authorization_url,
                 tokenURL : token_url,
                 clientID : client_id,
                 scope: 'openid',
                 response_type: 'code',
                 clientSecret : client_secret,
                 callbackURL : callback_url,
                 skipUserProfile: true,
                 issuer: issuer_id},
	function(iss, sub, profile, accessToken, refreshToken, params, done)  {
	         	process.nextTick(function() {
		profile.accessToken = accessToken;
		profile.refreshToken = refreshToken;
		done(null, profile);
         	});
});

passport.use(Strategy);
app.get('/login', passport.authenticate('openidconnect', {}));

function ensureAuthenticated(req, res, next) {
	if(!req.isAuthenticated()) {
	          	req.session.originalUrl = req.originalUrl;
		res.redirect('/login');
	} else {
		return next();
	}
}

//for auth
app.get('/patientExamination',function(req,res,next) {
             var redirect_url = req.session.originalUrl;
             passport.authenticate('openidconnect', {
                     successRedirect: redirect_url,
                     failureRedirect: '/failure',
          })(req,res,next);
        });

//Set path to Jade template directory
app.set("views", __dirname + "/views");

//Set path to Fonts directory
app.set("fonts", __dirname + "/fonts");

//Set path to JavaScript files
app.set("js", __dirname + "/js");

//Set path to CSS files
app.set("css", __dirname + "/css");

//Set path to images files
app.set("images", __dirname + "/images");

//Set path to static files
app.use(express.static(__dirname + "/public"));

//Bind the root '/' URL to the login page
app.get("/", function(req, res){
	res.render("login.jade", {title: "Login"});
});

//Bind the '/patientExamination' URL to the drview page
app.get("/patientExamination", function(req, res){
	res.render("drView.jade", {title: "Patient Examination"});
});

//Bind the '/patientVitals' URL to the nurseview page
app.get("/patientVitals", function (req, res){
	res.render("nurseView.jade", {title: "Patient Pre-Examination"});
});

//Bind the '/scheduleAndBilling' URL to the receptionistView page
app.get("/billing-and-scheduling", function (req, res){
	res.render("receptionistView.jade", {title: "Patient Billing and Scheduling"});
});

var server = app.listen(port, function(){
	console.log("Server running on port %d on host %s", server.address().port, host);
});

process.on("exit", function(){
	console.log("Server is shutting down!");
});<commit_msg>corrected auth methods<commit_after>/*eslint-env node */
/**
*Created:...................11/07/2016
*Author:....................Emmanuel Henley
*Author Contact:............ehenl001@fiu.edu
*Last Edited:...............11/11/2016
*Last Edited by:............same as author
*Last Edited by contact:....same as author
*
*
*Server for the HenleyLunn EMR app
**/

var express = require("express");
var app = express();
var http = require("http");

var host = "localhost";
var port = 3030;
var cloudant = {
	url: "https://a39147b3-f95b-4e5d-8d0d-a9b7384280fb-bluemix.cloudant.com/_all_dbs"
};

if (process.env.hasOwnProperty("VCAP_SERVICES")) {
  // Running on Bluemix. Parse out the port and host that we've been assigned.
  var env = JSON.parse(process.env.VCAP_SERVICES);
  var host = process.env.VCAP_APP_HOST;
  var port = process.env.VCAP_APP_PORT;

  //Parse out Cloudant settings
  cloudant = env["cloudantNoSQLDB"][0].credentials;
}

var nano = require("nano")(cloudant.url);
var db = nano.db.use("user_login");

//variables for the sso
var passport = require('passport');
var OpenIDConnectStrategy = require('passport-idaas-openidconnect').IDaaSOIDCStrategy;

//for the sso
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
   done(null, user);
});

passport.deserializeUser(function(obj, done) {
   done(null, obj);
});

// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.
var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
var ssoConfig = services.SingleSignOn[0];
var client_id = ssoConfig.credentials.clientId;
var client_secret = ssoConfig.credentials.secret;
var authorization_url = ssoConfig.credentials.authorizationEndpointUrl;
var token_url = ssoConfig.credentials.tokenEndpointUrl;
var issuer_id = ssoConfig.credentials.issuerIdentifier;
var callback_url = '/';

var OpenIDConnectStrategy = require('passport-idaas-openidconnect').IDaaSOIDCStrategy;
var Strategy = new OpenIDConnectStrategy({
                 authorizationURL : authorization_url,
                 tokenURL : token_url,
                 clientID : client_id,
                 scope: 'openid',
                 response_type: 'code',
                 clientSecret : client_secret,
                 callbackURL : callback_url,
                 skipUserProfile: true,
                 issuer: issuer_id},
	function (iss, sub, profile, accessToken, refreshToken, params, done){
	         	process.nextTick(function (){
		profile.accessToken = accessToken;
		profile.refreshToken = refreshToken;
		done(null, profile);
         	})
});

passport.use(Strategy);
app.get('/login', passport.authenticate('openidconnect', {}));

function ensureAuthenticated(req, res, next) {
	if(!req.isAuthenticated()) {
	          	req.session.originalUrl = req.originalUrl;
		res.redirect('/login');
	} else {
		return next();
	}
}

app.get('/',function(req,res,next) {
            passport.authenticate('openidconnect',{
                 successRedirect: '/patientExamination',
                 failureRedirect: '/failure',
          })(req,res,next);
                 });

//Set path to Jade template directory
app.set("views", __dirname + "/views");

//Set path to Fonts directory
app.set("fonts", __dirname + "/fonts");

//Set path to JavaScript files
app.set("js", __dirname + "/js");

//Set path to CSS files
app.set("css", __dirname + "/css");

//Set path to images files
app.set("images", __dirname + "/images");

//Set path to static files
app.use(express.static(__dirname + "/public"));

//Bind the root '/' URL to the login page
app.get("/", function(req, res){
	res.render("login.jade", {title: "Login"});
});

//Bind the '/patientExamination' URL to the drview page
app.get("/patientExamination", function(req, res){
	res.render("drView.jade", {title: "Patient Examination"});
});

//Bind the '/patientVitals' URL to the nurseview page
app.get("/patientVitals", function (req, res){
	res.render("nurseView.jade", {title: "Patient Pre-Examination"});
});

//Bind the '/scheduleAndBilling' URL to the receptionistView page
app.get("/billing-and-scheduling", function (req, res){
	res.render("receptionistView.jade", {title: "Patient Billing and Scheduling"});
});

var server = app.listen(port, function(){
	console.log("Server running on port %d on host %s", server.address().port, host);
});

process.on("exit", function(){
	console.log("Server is shutting down!");
});<|endoftext|>


<commit_before>var restify = require('restify'),
	request = require('request'),
	account = process.env.TWILIO_ACCOUNT,
	number = process.env.TWILIO_NUMBER,
	token = process.env.TWILIO_TOKEN,
	baseUrl = "https://api.twilio.com/2010-04-01/",
	notificationUrl = baseUrl + 'Accounts/' + account + '/Messages.json',
	notifications = {
		"snow": "Calling all Snow Angels! Can you shovel today?"
	};

// Handle notification requests.
function notify(req, res, next) {

	// For each number.
	for(var property in req.body) {

		// Standardize recipient number.  (Remove non-numbers.)  (Remove initial '1' if present.)
		var recipient = req.body[property].replace(/[^0-9]/g, "").replace(/^1(.*)/g, "$1");
		console.log("Queueing message to " + recipient);

		// Queue message.
		request.post(
			{
				auth: {
					"user": account,
					"pass": token
				},
				url: notificationUrl,
				form: {
					"To": "+1" + recipient,
					"From": number,
					"Body": notifications[req.params.notification]
				}
			},
			function(error, httpResponse, body) {
				if(error) {
					console.log(error);
				} else if(body) {
					console.log(body);
				}
			}
		);
	}
	res.send(201);
	next();
}

// Create server.
var server = restify.createServer();

// Configure server.
server.use(restify.bodyParser({ mapParams: false }));
server.post('/notifications/:notification', notify);

// Start server.
server.listen(process.env.NOTIFY_PORT, function() {
	console.log('%s listening at %s', server.name, server.url);
});
<commit_msg>Checked request body.<commit_after>var restify = require('restify'),
	request = require('request'),
	account = process.env.TWILIO_ACCOUNT,
	number = process.env.TWILIO_NUMBER,
	token = process.env.TWILIO_TOKEN,
	baseUrl = "https://api.twilio.com/2010-04-01/",
	notificationUrl = baseUrl + 'Accounts/' + account + '/Messages.json',
	notifications = {
		"snow": "Calling all Snow Angels! Can you shovel today?"
	};

// Handle notification requests.
function notify(req, res, next) {
	if(!req.body) {
		res.send(400);
		next();
	}

	// For each number.
	for(var property in req.body) {

		// Standardize recipient number.  (Remove non-numbers.)  (Remove initial '1' if present.)
		var recipient = req.body[property].replace(/[^0-9]/g, "").replace(/^1(.*)/g, "$1");
		console.log("Queueing message to " + recipient);

		// Queue message.
		request.post(
			{
				auth: {
					"user": account,
					"pass": token
				},
				url: notificationUrl,
				form: {
					"To": "+1" + recipient,
					"From": number,
					"Body": notifications[req.params.notification]
				}
			},
			function(error, httpResponse, body) {
				if(error) {
					console.log(error);
				} else if(body) {
					console.log(body);
				}
			}
		);
	}
	res.send(201);
	next();
}

// Create server.
var server = restify.createServer();

// Configure server.
server.use(restify.bodyParser({ mapParams: false }));
server.post('/notifications/:notification', notify);

// Start server.
server.listen(process.env.NOTIFY_PORT, function() {
	console.log('%s listening at %s', server.name, server.url);
});
<|endoftext|>


<commit_before>import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';

class Editor extends Parchment.Container {
  constructor(domNode) {
    // TODO fix?
    if (domNode.innerHTML.indexOf('\n') > -1) {
      domNode.innerHTML = domNode.innerHTML.replace(/\n\s*/g, '');
    }
    super(domNode);
    this.ensureChild();
    this.enable();
    this.delta = this.getDelta();
    this.observer = new MutationObserver((mutations) => {
      this.update(mutations);   // Do not pass additional params from MutationObserver handler
    });
    this.observer.observe(this.domNode, {
      attributes: true,
      characterData: true,
      childList: true,
      subtree: true
    });
  }

  applyAttributes(index, length, attr) {
    Object.keys(attr).forEach(function (key) {
      let obj = attr[key];
      let attributor = Parchment.match(key, Parchment.Type.ATTRIBUTE);

      // Only attempt formatting if a valid attributor was found
      if (attributor) {
        this.formatAt(index, length, key, obj)
      }
    }, this)
  }

  applyDelta(delta) {
    delta.ops.reduce((index, op) => {
      if (op.insert != null) {
        if (typeof op.insert === 'string') {
          let length = op.insert.length;
          let attr = op.attributes;

          this.insertAt(index, op.insert);

          if (typeof attr === 'object') {
            this.applyAttributes(index, length, attr);
          }

          return index + length;
        } else {
          this.insertAt(index, op.attributes);
          return index + 1;
        }
      } else if (typeof op.delete === 'number') {
        this.deleteAt(index, op.delete);
        return index;
      } else if (typeof op.retain === 'number') {
        Object.keys(op.attributes || {}).forEach((name) => {
          this.formatAt(index, op.retain, name, op.attributes[name]);
        });
        return index + op.retain;
      }
    }, 0);
  }

  deleteAt(index, length) {
    let [first, firstOffset] = this.children.find(index);
    let [last, lastOffset] = this.children.find(index + length);
    super.deleteAt(index, length);
    if (last != null && first !== last && firstOffset > 0) {
      let lastChild = first.children.tail;
      last.moveChildren(first);
      last.remove();
      if (lastChild != null) {
        lastChild.merge();
      }
    }
    this.ensureChild();
  }

  enable(enabled = true) {
    this.domNode.setAttribute('contenteditable', enabled);
  }

  ensureChild() {
    if (this.children.length === 0) {
      this.appendChild(Parchment.create('block'));
    }
  }

  findPath(index) {
    if (index >= this.getLength()) {
      return [];
    } else {
      return super.findPath(index).slice(1);  // Exclude self
    }
  }

  getDelta() {
    return this.getLines().reduce((delta, child) => {
      return delta.concat(child.getDelta());
    }, new Delta());
  }

  getLines(index = 0, length = this.getLength()) {
    return this.getDescendants(index, length, Parchment.Block);
  }

  onUpdate(delta) { }

  remove() {
    this.children.forEach(function(child) {
      child.remove();
    });
  }

  update(...args) {
    let mutations;
    if (Array.isArray(args[0])) {
      mutations = args[0];
      args = args.slice(1);
    } else {
      mutations = this.observer.takeRecords();
    }
    if (mutations.length === 0) return new Delta();
    let oldDelta = this.delta;
    // TODO optimize
    this.build();
    this.delta = this.getDelta();
    let change = oldDelta.diff(this.delta);
    console.log(change);
    if (change.length() > 0) {
      this.onUpdate(change, ...args);
    }
    this.observer.takeRecords();  // Prevent changes from rebuilds
    return change;
  }
}

export { Editor as default };
<commit_msg>removed unused log<commit_after>import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';

class Editor extends Parchment.Container {
  constructor(domNode) {
    // TODO fix?
    if (domNode.innerHTML.indexOf('\n') > -1) {
      domNode.innerHTML = domNode.innerHTML.replace(/\n\s*/g, '');
    }
    super(domNode);
    this.ensureChild();
    this.enable();
    this.delta = this.getDelta();
    this.observer = new MutationObserver((mutations) => {
      this.update(mutations);   // Do not pass additional params from MutationObserver handler
    });
    this.observer.observe(this.domNode, {
      attributes: true,
      characterData: true,
      childList: true,
      subtree: true
    });
  }

  applyAttributes(index, length, attr) {
    Object.keys(attr).forEach(function (key) {
      let obj = attr[key];
      let attributor = Parchment.match(key, Parchment.Type.ATTRIBUTE);

      // Only attempt formatting if a valid attributor was found
      if (attributor) {
        this.formatAt(index, length, key, obj)
      }
    }, this)
  }

  applyDelta(delta) {
    delta.ops.reduce((index, op) => {
      if (op.insert != null) {
        if (typeof op.insert === 'string') {
          let length = op.insert.length;
          let attr = op.attributes;

          this.insertAt(index, op.insert);

          if (typeof attr === 'object') {
            this.applyAttributes(index, length, attr);
          }

          return index + length;
        } else {
          this.insertAt(index, op.attributes);
          return index + 1;
        }
      } else if (typeof op.delete === 'number') {
        this.deleteAt(index, op.delete);
        return index;
      } else if (typeof op.retain === 'number') {
        Object.keys(op.attributes || {}).forEach((name) => {
          this.formatAt(index, op.retain, name, op.attributes[name]);
        });
        return index + op.retain;
      }
    }, 0);
  }

  deleteAt(index, length) {
    let [first, firstOffset] = this.children.find(index);
    let [last, lastOffset] = this.children.find(index + length);
    super.deleteAt(index, length);
    if (last != null && first !== last && firstOffset > 0) {
      let lastChild = first.children.tail;
      last.moveChildren(first);
      last.remove();
      if (lastChild != null) {
        lastChild.merge();
      }
    }
    this.ensureChild();
  }

  enable(enabled = true) {
    this.domNode.setAttribute('contenteditable', enabled);
  }

  ensureChild() {
    if (this.children.length === 0) {
      this.appendChild(Parchment.create('block'));
    }
  }

  findPath(index) {
    if (index >= this.getLength()) {
      return [];
    } else {
      return super.findPath(index).slice(1);  // Exclude self
    }
  }

  getDelta() {
    return this.getLines().reduce((delta, child) => {
      return delta.concat(child.getDelta());
    }, new Delta());
  }

  getLines(index = 0, length = this.getLength()) {
    return this.getDescendants(index, length, Parchment.Block);
  }

  onUpdate(delta) { }

  remove() {
    this.children.forEach(function(child) {
      child.remove();
    });
  }

  update(...args) {
    let mutations;
    if (Array.isArray(args[0])) {
      mutations = args[0];
      args = args.slice(1);
    } else {
      mutations = this.observer.takeRecords();
    }
    if (mutations.length === 0) return new Delta();
    let oldDelta = this.delta;
    // TODO optimize
    this.build();
    this.delta = this.getDelta();
    let change = oldDelta.diff(this.delta);
    if (change.length() > 0) {
      this.onUpdate(change, ...args);
    }
    this.observer.takeRecords();  // Prevent changes from rebuilds
    return change;
  }
}

export { Editor as default };
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-ul
 *
 * iotagent-ul is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-ul is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-ul.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[iot_support@tid.es]
 *
 * Modified by: Daniel Calvo - ATOS Research & Innovation
 * Modified by: Fermin Galan - Telefónica
 */

/* eslint-disable no-unused-vars */

const iotagentMqtt = require('../../../');
const config = require('./config-test.js');
const nock = require('nock');
const async = require('async');

const utils = require('../../utils');
const request = utils.request;
const should = require('should');
const iotAgentLib = require('iotagent-node-lib');
const amqp = require('amqplib/callback_api');
const apply = async.apply;
let contextBrokerMock;
let oldTransport;
let amqpConn;
let channel;

function startConnection(exchange, callback) {
    amqp.connect('amqp://localhost', function (err, conn) {
        amqpConn = conn;

        conn.createChannel(function (err, ch) {
            ch.assertExchange(exchange, 'topic', {});

            channel = ch;
            callback(err);
        });
    });
}

describe('AMQP Transport binding: commands', function () {
    beforeEach(function (done) {
        const provisionOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/devices',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionCommand5.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };

        config.logLevel = 'INFO';

        nock.cleanAll();

        contextBrokerMock = nock('http://192.168.1.1:1026')
            .matchHeader('fiware-service', 'smartgondor')
            .matchHeader('fiware-servicepath', '/gardens')
            .post('/v2/registrations')
            .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' });

        contextBrokerMock
            .matchHeader('fiware-service', 'smartgondor')
            .matchHeader('fiware-servicepath', '/gardens')
            .post('/v2/entities?options=upsert')
            .reply(204);

        oldTransport = config.defaultTransport;
        config.defaultTransport = 'AMQP';

        async.series(
            [
                apply(iotagentMqtt.start, config),
                apply(utils.request, provisionOptions),
                apply(startConnection, config.amqp.exchange)
            ],
            done
        );
    });

    afterEach(function (done) {
        nock.cleanAll();

        amqpConn.close();

        config.defaultTransport = oldTransport;

        async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done);
    });

    describe('When a command arrive to the Agent for a device with the AMQP protocol', function () {
        const commandOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/v2/op/update',
            method: 'POST',
            json: utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateCommand1.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': 'gardens'
            }
        };

        beforeEach(function () {
            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .patch(
                    '/v2/entities/Second%20MQTT%20Device/attrs?type=AnMQTTDevice',
                    utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus1.json')
                )
                .reply(204);
        });

        it('should return a 204 OK without errors', function (done) {
            request(commandOptions, function (error, response, body) {
                should.not.exist(error);
                response.statusCode.should.equal(204);
                done();
            });
        });
        it('should update the status in the Context Broker', function (done) {
            request(commandOptions, function (error, response, body) {
                contextBrokerMock.done();
                done();
            });
        });
        it('should publish the command information in the AMQP topic', function (done) {
            const commandMsg = 'MQTT_2@PING|data=22';
            let payload;

            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);

            channel.assertQueue('client-queue', { exclusive: false }, function (err, q) {
                channel.bindQueue(q.queue, config.amqp.exchange, '.' + config.defaultKey + '.MQTT_2.cmd');

                channel.consume(
                    q.queue,
                    function (msg) {
                        payload = msg.content.toString();
                    },
                    { noAck: true }
                );

                request(commandOptions, function (error, response, body) {
                    setTimeout(function () {
                        should.exist(payload);
                        payload.should.equal(commandMsg);
                        done();
                    }, 1000);
                });
            });
        });
    });

    describe('When a command update arrives to the AMQP command topic', function () {
        beforeEach(function () {
            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/op/update', utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus2.json'))
                .reply(204);
        });

        it('should send an update request to the Context Broker', function (done) {
            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);
            channel.publish(config.amqp.exchange, '.1234.MQTT_2.cmdexe', Buffer.from('MQTT_2@PING|1234567890'));

            setTimeout(function () {
                contextBrokerMock.done();
                done();
            }, 1000);
        });
    });

    describe('When a command update arrives with a single text value', function () {
        const provisionOptionsAlt = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/devices',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionCommand6.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };
        const configurationOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/services',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionGroup1.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };
        const commandOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/v2/op/update',
            method: 'POST',
            json: utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateCommand3.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': 'gardens'
            }
        };

        beforeEach(function (done) {
            nock.cleanAll();

            contextBrokerMock = nock('http://192.168.1.1:1026')
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/registrations')
                .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' });

            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/entities?options=upsert')
                .reply(204);

            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post(
                    '/v2/entities/Fourth%20MQTT%20Device/attrs?type=MQTTCommandDevice',
                    utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus3.json')
                )
                .reply(204);

            request(configurationOptions, function (error, response, body) {
                request(provisionOptionsAlt, function (error, response, body) {
                    done();
                });
            });
        });

        it('should publish the command information in the AMQP topic', function (done) {
            const commandMsg = 'MQTT_4@PING|22';
            let payload;

            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);

            channel.assertQueue('client-queue', { exclusive: false }, function (err, q) {
                channel.bindQueue(q.queue, config.amqp.exchange, '.ALTERNATIVE.MQTT_4.cmd');

                channel.consume(
                    q.queue,
                    function (msg) {
                        payload = msg.content.toString();
                    },
                    { noAck: true }
                );

                request(commandOptions, function (error, response, body) {
                    setTimeout(function () {
                        should.exist(payload);
                        payload.should.equal(commandMsg);
                        done();
                    }, 1000);
                });
            });
        });
    });
});
<commit_msg>Update test/unit/ngsiv2/commandsAmqp-test.js<commit_after>/*
 * Copyright 2017 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-ul
 *
 * iotagent-ul is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-ul is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-ul.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[iot_support@tid.es]
 *
 * Modified by: Daniel Calvo - ATOS Research & Innovation
 * Modified by: Fermin Galan - Telefónica
 */

/* eslint-disable no-unused-vars */

const iotagentMqtt = require('../../../');
const config = require('./config-test.js');
const nock = require('nock');
const async = require('async');

const utils = require('../../utils');
const request = utils.request;
const should = require('should');
const iotAgentLib = require('iotagent-node-lib');
const amqp = require('amqplib/callback_api');
const apply = async.apply;
let contextBrokerMock;
let oldTransport;
let amqpConn;
let channel;

function startConnection(exchange, callback) {
    amqp.connect('amqp://localhost', function (err, conn) {
        amqpConn = conn;

        conn.createChannel(function (err, ch) {
            ch.assertExchange(exchange, 'topic', {});

            channel = ch;
            callback(err);
        });
    });
}

describe('AMQP Transport binding: commands', function () {
    beforeEach(function (done) {
        const provisionOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/devices',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionCommand5.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };

        config.logLevel = 'INFO';

        nock.cleanAll();

        contextBrokerMock = nock('http://192.168.1.1:1026')
            .matchHeader('fiware-service', 'smartgondor')
            .matchHeader('fiware-servicepath', '/gardens')
            .post('/v2/registrations')
            .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' });

        contextBrokerMock
            .matchHeader('fiware-service', 'smartgondor')
            .matchHeader('fiware-servicepath', '/gardens')
            .post('/v2/entities?options=upsert')
            .reply(204);

        oldTransport = config.defaultTransport;
        config.defaultTransport = 'AMQP';

        async.series(
            [
                apply(iotagentMqtt.start, config),
                apply(request, provisionOptions),
                apply(startConnection, config.amqp.exchange)
            ],
            done
        );
    });

    afterEach(function (done) {
        nock.cleanAll();

        amqpConn.close();

        config.defaultTransport = oldTransport;

        async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done);
    });

    describe('When a command arrive to the Agent for a device with the AMQP protocol', function () {
        const commandOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/v2/op/update',
            method: 'POST',
            json: utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateCommand1.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': 'gardens'
            }
        };

        beforeEach(function () {
            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .patch(
                    '/v2/entities/Second%20MQTT%20Device/attrs?type=AnMQTTDevice',
                    utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus1.json')
                )
                .reply(204);
        });

        it('should return a 204 OK without errors', function (done) {
            request(commandOptions, function (error, response, body) {
                should.not.exist(error);
                response.statusCode.should.equal(204);
                done();
            });
        });
        it('should update the status in the Context Broker', function (done) {
            request(commandOptions, function (error, response, body) {
                contextBrokerMock.done();
                done();
            });
        });
        it('should publish the command information in the AMQP topic', function (done) {
            const commandMsg = 'MQTT_2@PING|data=22';
            let payload;

            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);

            channel.assertQueue('client-queue', { exclusive: false }, function (err, q) {
                channel.bindQueue(q.queue, config.amqp.exchange, '.' + config.defaultKey + '.MQTT_2.cmd');

                channel.consume(
                    q.queue,
                    function (msg) {
                        payload = msg.content.toString();
                    },
                    { noAck: true }
                );

                request(commandOptions, function (error, response, body) {
                    setTimeout(function () {
                        should.exist(payload);
                        payload.should.equal(commandMsg);
                        done();
                    }, 1000);
                });
            });
        });
    });

    describe('When a command update arrives to the AMQP command topic', function () {
        beforeEach(function () {
            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/op/update', utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus2.json'))
                .reply(204);
        });

        it('should send an update request to the Context Broker', function (done) {
            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);
            channel.publish(config.amqp.exchange, '.1234.MQTT_2.cmdexe', Buffer.from('MQTT_2@PING|1234567890'));

            setTimeout(function () {
                contextBrokerMock.done();
                done();
            }, 1000);
        });
    });

    describe('When a command update arrives with a single text value', function () {
        const provisionOptionsAlt = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/devices',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionCommand6.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };
        const configurationOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/iot/services',
            method: 'POST',
            json: utils.readExampleFile('./test/deviceProvisioning/provisionGroup1.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': '/gardens'
            }
        };
        const commandOptions = {
            url: 'http://localhost:' + config.iota.server.port + '/v2/op/update',
            method: 'POST',
            json: utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateCommand3.json'),
            headers: {
                'fiware-service': 'smartgondor',
                'fiware-servicepath': 'gardens'
            }
        };

        beforeEach(function (done) {
            nock.cleanAll();

            contextBrokerMock = nock('http://192.168.1.1:1026')
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/registrations')
                .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' });

            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post('/v2/entities?options=upsert')
                .reply(204);

            contextBrokerMock
                .matchHeader('fiware-service', 'smartgondor')
                .matchHeader('fiware-servicepath', '/gardens')
                .post(
                    '/v2/entities/Fourth%20MQTT%20Device/attrs?type=MQTTCommandDevice',
                    utils.readExampleFile('./test/unit/ngsiv2/contextRequests/updateStatus3.json')
                )
                .reply(204);

            request(configurationOptions, function (error, response, body) {
                request(provisionOptionsAlt, function (error, response, body) {
                    done();
                });
            });
        });

        it('should publish the command information in the AMQP topic', function (done) {
            const commandMsg = 'MQTT_4@PING|22';
            let payload;

            channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options);

            channel.assertQueue('client-queue', { exclusive: false }, function (err, q) {
                channel.bindQueue(q.queue, config.amqp.exchange, '.ALTERNATIVE.MQTT_4.cmd');

                channel.consume(
                    q.queue,
                    function (msg) {
                        payload = msg.content.toString();
                    },
                    { noAck: true }
                );

                request(commandOptions, function (error, response, body) {
                    setTimeout(function () {
                        should.exist(payload);
                        payload.should.equal(commandMsg);
                        done();
                    }, 1000);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

const webpackConfig = require("./build/webpack.config");

module.exports = function(config) {
    config.set({
        basePath: ".",
        files: [
            { pattern: "./src/test.ts", watched: false }
        ],
        frameworks: [ "jasmine" ],
        exclude: [],
        preprocessors: {
            "./src/test.ts": [ "webpack", "sourcemap" ]
        },
        webpack: webpackConfig,
        webpackMiddleware: {
            noInfo: true,
            stats: "errors-only"
        },
        reporters: [ "mocha", "coverage" ],
        coverageReporter: {
            dir: "coverage/",
            reporters: [
                { type: "json", subdir: "report-json" }
            ]
        },
        browsers: [ "Chrome" ],
        logLevel: config.LOG_INFO,
        port: 9876,
        colors: true,
        autoWatch: false,
        singleRun: true
    });
};
<commit_msg>Trimmed down some more config, pre-coverage.<commit_after>"use strict";

const webpackConfig = require("./build/webpack.config");

module.exports = function(config) {
    config.set({
        basePath: ".",
        files: [
            { pattern: "./src/test.ts", watched: false }
        ],
        frameworks: [ "jasmine" ],
        exclude: [],
        preprocessors: {
            "./src/test.ts": [ "webpack" ]
        },
        webpack: webpackConfig,
        webpackMiddleware: {
            noInfo: true,
            stats: "errors-only"
        },
        reporters: [ "mocha" ],
        browsers: [ "Chrome" ],
        logLevel: config.LOG_INFO,
        port: 9876,
        colors: true,
        autoWatch: false,
        singleRun: true
    });
};
<|endoftext|>


<commit_before>const { assocWith } = require('@articulate/funky')
const qs  = require('qs')
const url = require('url')

const {
  converge, evolve, identity, merge, pick, pipe, prop
} = require('ramda')

const pathParts =
  pipe(
    prop('url'),
    url.parse,
    evolve({ query: qs.parse }),
    pick(['pathname', 'query'])
  )

const protocol = req =>
  req.headers['x-forwarded-proto'] ||
  req.connection.encrypted ? 'https' : 'http'

exports.parseUrl =
  pipe(
    converge(merge, [ identity, pathParts ]),
    assocWith('protocol', protocol)
  )
<commit_msg>Change connection (deprecated) to socket (#56)<commit_after>const { assocWith } = require('@articulate/funky')
const qs  = require('qs')
const url = require('url')

const {
  converge, evolve, identity, merge, pick, pipe, prop
} = require('ramda')

const pathParts =
  pipe(
    prop('url'),
    url.parse,
    evolve({ query: qs.parse }),
    pick(['pathname', 'query'])
  )

const protocol = req =>
  req.headers['x-forwarded-proto'] ||
  req.socket.encrypted ? 'https' : 'http'

exports.parseUrl =
  pipe(
    converge(merge, [ identity, pathParts ]),
    assocWith('protocol', protocol)
  )
<|endoftext|>


<commit_before>/* global d3 */
/* global topojson */

(function(){
  'use strict';

  var GridMap = {
    width: null,
    height: null,
    grid_rows: null,
    grid_cols: null,
    countries: null,
    canvas: null,
    context: null,
    margin: null,
    projection: null,
    graticule: d3.geo.graticule(),
    geojson: null,
    rotate_longitude: 0,
    rotate_latitude: 0,
    path: null,
    container: null,
  };
  d3.geo.GridMap = GridMap;

  var defaultColorScale = d3.scale.quantize()
    .domain([0,255])
    .range(['#f00', '#c01', '#a02', '#303', '#404', '#505','#606','#707','#808',
    '#909','#a0a','#b0b','#c0c','#d0d','#e0e', '#f00']);

  GridMap.initEvents = function() {

    var self = this;
    var scale = 150;
    var drag = d3.behavior.drag()
      .on('dragstart', function () {
      })
      .on('drag', function () {
        self.rotate_longitude += 100 * d3.event.dx / zoom.scale();
        self.rotate_latitude -= 100 * d3.event.dy / zoom.scale();
        self.projection.rotate([self.rotate_longitude, self.rotate_latitude]);
        self.drawWorld();
      })
      .on('dragend', function () {
        self.draw();
      });

    var zoom = d3.behavior.zoom()
      .on('zoomstart', function() {
      })
      .on('zoomend', function() {
        self.draw();
      })
      .on('zoom', function(d) {
        scale = d3.event.scale;
        self.area = 20000 / scale / scale;
        self.projection.scale(scale);
        self.drawWorld();
      })
      .scale(this.width/6)
      .scaleExtent([this.width/6, 1000]);

    this.container.call(drag);
    this.container.call(zoom);

  };

  GridMap.init = function (_container, gridSize, options) {

    var self = this;
    this.grid_cols = gridSize[0];
    this.grid_rows = gridSize[1];

    this.container = d3.select(_container);
    var rect = this.container.node().getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.landColor = options.landColor || 'rgba(237,178,48,1)';
    this.seaColor = options.seaColor || 'rgba(21,98,180,.8)';
    this.landOutlineColor = options.landOutlineColor || 'rgba(100,100,100,.8)';
    this.graticuleColor = options.graticuleColor || 'rgba(100,100,100,.3)';
    this.geoJsonColor = options.geoJsonColor || 'rgba(0,0,0,1)';

    self.area = 1; // minimum area threshold for simplification

    var clip = d3.geo.clipExtent()
        .extent([[-self.width/4, -self.height/4], [self.width/4, self.height/4]]);

    var simplify = d3.geo.transform({
      point: function(x, y, z) {
        if (z >= self.area) {
          this.stream.point(x, y);
        }
      }
    });

    this.projection = options.projection || d3.geo.mollweide();
    this.projection
      .translate([this.width/2, this.height/2])
      .scale(this.width/6)
      .clipExtent([[0, 0], [self.width, self.height]])
      .precision(0.1);

    this.margin = options.margin || {top: 10, right: 10, bottom: 10, left: 10};

    topojson.presimplify(options.countries);

    this.canvas = this.container.append('canvas')
      .datum(topojson.feature(options.countries, options.countries.objects.countries))
      .attr('width', this.width)
      .attr('height', this.height);

    this.context = this.canvas.node().getContext('2d');
    this.colorScale = options.colorScale || defaultColorScale;

    this.simplifyingPath = d3.geo.path()
      .projection({stream: function(s) {return simplify.stream(clip.stream(self.projection.stream(s)));}})
      .context(this.context);

    this.path = d3.geo.path()
      .projection(this.projection)
      .context(this.context);

    this.initCellIdToCoordinates();
    this.initEvents();
    d3.select(window).on('resize', this.resize.bind(this));

    self.draw();
  };

  GridMap.worldGeoJSON = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'Polygon',
            coordinates: [[
              [-179.999, 89.999],
              [179.999, 89.999],
              [179.999, -89.999],
              [-179.999, -89.9999],
              [-179.999, 89.999]
            ]]
          }
        }
      ]
    };

  GridMap.drawWorld = function() {

    this.context.clearRect(0, 0, this.width, this.height);

    //draw world background (the sea). acting funny for now
    this.context.beginPath();
    this.path(this.worldGeoJSON);
    this.context.fillStyle = this.seaColor;
    this.context.fill();

    // draw countries
    this.context.beginPath();
    this.canvas.each(this.simplifyingPath);
    this.context.strokeStyle = this.landOutlineColor;
    this.context.lineWidth = 1;
    this.context.fillStyle = this.landColor;
    this.context.fill();
    this.context.stroke();

    // overlay graticule.  Requires it's own path so
    // it won't get clipped/simplified
    this.context.beginPath();
    this.path(this.graticule());
    this.context.lineWidth = 1;
    this.context.strokeStyle = this.graticuleColor;
    this.context.stroke();
  };

  GridMap.draw = function(_geojson) {
    if (_geojson) {
      this.geojson = _geojson;
    }

    this.drawWorld();

    var self = this;
    if (this.geojson && this.geojson.features) {
      this.geojson.features.forEach(function(feature){
        var color = null;
        if (feature.properties.rgba) {
          color = 'rgba(' + feature.properties.rgba.join(',') + ')';
        } else {
          color = self.colorScale(feature.properties.value);
        }
        self.context.beginPath();
        self.path(feature);
        self.context.strokeStyle = this.geoJsonColor;
        self.context.lineWidth = 0.5;
        self.context.stroke();
        self.context.fillStyle = color;
        self.context.fill();
      });
    }
  };

  GridMap.resize = function() {
    this.width = parseInt(this.container.style('width'), 10);
    this.width = this.width - this.margin.left - this.margin.right;
    d3.select('canvas').attr('width', this.width);
    this.projection
      .translate([this.width/2, this.height/2])
      .clipExtent([[0, 0], [this.width, this.height]]);
    this.initEvents();
    this.draw();
  };

  GridMap.setDataUnsparseTypedArray = function (data) {
    this.geojson = this.uInt8ArrayToGeoJSON(data);
    this.draw();
  };
  GridMap.setDataArrayBuffer = function (data) {
    this.geojson = this.arrayBufferToGeoJSON(data);
    this.draw();
  };
  GridMap.setDataGeoJSON = function (data) {
    this.geojson = data;
    this.draw();
  };

  GridMap.uInt8ArrayToGeoJSON = function(array) {
    // given a UInt8ClampedArray containing data in
    // RGBA format, returns GeoJSON

    // The format is expected to be
    // a sequence of Uint8 elements representing RGBA
    // values for each cell from cell ID 1 to the final cell ID,
    // in column first order.

    var geojson = {
       type: "FeatureCollection",
       features: []
    };

    for (var i=0; i<array.length; i+=4) {
      var cell_id = i/4 + 1;
      var r = array[i];
      var g = array[i+1];
      var b = array[i+2];
      var a = array[i+3];

      if (r === 0 && g === 0 && b === 0 && a === 0) {
        continue;
      }
      var coordinates = this.cellIdToCoordinates[cell_id];

      var feature = {
         type: 'Feature',
         id: i,
         geometry: {
             type: 'Polygon',
             coordinates: [coordinates]
         },
         properties: {
          rgba: [r,g,b,a]
        }
      };
      geojson.features.push(feature);
    }

    return geojson;
  };

  GridMap.arrayBufferToGeoJSON = function(buff) {
    // given an ArrayBuffer buff containing data in
    // packed binary format, returns GeoJSON

    // The packed binary format is expected to be
    // a sequence of Uint32 elements in which the most
    // significant byte is the cell value and the
    // lowest 3 bytes represent the cell ID.

    var geojson = {
       type: 'FeatureCollection',
       features: []
    };

    var typedArray = new Uint32Array(buff);
    for (var i=0; i<typedArray.length; i++) {
      var packed = typedArray[i];
      var cell_id = packed & 0xfffff;
      var abundance = packed >> 24;
      var coordinates = this.cellIdToCoordinates[cell_id];

      var feature = {
         type: 'Feature',
         id: i,
         geometry: {
             type: 'Polygon',
             coordinates: [coordinates]
         },
         properties: {value: abundance }
      };
      geojson.features.push(feature);
    }
    return geojson;
  };

  GridMap._cellIdToLonLat = function(id) {
      id--;
      var lon = -180 + (id % 720)/720.0 * 360 ;
      var lat = 90 - ~~(id / 720)/2;
      return [lon, lat];
  };

  GridMap.cellIdToCoordinates = [null];

  GridMap.initCellIdToCoordinates = function() {

    var x_size = 0.5; // this.grid_cols / 360;
    var y_size = 0.5; //this.grid_rows / 180;
    for (var i=1; i<=this.grid_rows * this.grid_cols; i++) {
        var lonLat = this._cellIdToLonLat(i);
        var coordinates = [
          lonLat,
          [lonLat[0] + x_size, lonLat[1]],
          [lonLat[0] + x_size, lonLat[1]-y_size],
          [lonLat[0], lonLat[1]-y_size],
          lonLat
        ];
        this.cellIdToCoordinates[i] = coordinates;
    }
  };

})();
<commit_msg>fix this/self bug<commit_after>/* global d3 */
/* global topojson */

(function(){
  'use strict';

  var GridMap = {
    width: null,
    height: null,
    grid_rows: null,
    grid_cols: null,
    countries: null,
    canvas: null,
    context: null,
    margin: null,
    projection: null,
    graticule: d3.geo.graticule(),
    geojson: null,
    rotate_longitude: 0,
    rotate_latitude: 0,
    path: null,
    container: null,
  };
  d3.geo.GridMap = GridMap;

  var defaultColorScale = d3.scale.quantize()
    .domain([0,255])
    .range(['#f00', '#c01', '#a02', '#303', '#404', '#505','#606','#707','#808',
    '#909','#a0a','#b0b','#c0c','#d0d','#e0e', '#f00']);

  GridMap.initEvents = function() {

    var self = this;
    var scale = 150;
    var drag = d3.behavior.drag()
      .on('dragstart', function () {
      })
      .on('drag', function () {
        self.rotate_longitude += 100 * d3.event.dx / zoom.scale();
        self.rotate_latitude -= 100 * d3.event.dy / zoom.scale();
        self.projection.rotate([self.rotate_longitude, self.rotate_latitude]);
        self.drawWorld();
      })
      .on('dragend', function () {
        self.draw();
      });

    var zoom = d3.behavior.zoom()
      .on('zoomstart', function() {
      })
      .on('zoomend', function() {
        self.draw();
      })
      .on('zoom', function(d) {
        scale = d3.event.scale;
        self.area = 20000 / scale / scale;
        self.projection.scale(scale);
        self.drawWorld();
      })
      .scale(this.width/6)
      .scaleExtent([this.width/6, 1000]);

    this.container.call(drag);
    this.container.call(zoom);

  };

  GridMap.init = function (_container, gridSize, options) {

    var self = this;
    this.grid_cols = gridSize[0];
    this.grid_rows = gridSize[1];

    this.container = d3.select(_container);
    var rect = this.container.node().getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.landColor = options.landColor || 'rgba(237,178,48,1)';
    this.seaColor = options.seaColor || 'rgba(21,98,180,.8)';
    this.landOutlineColor = options.landOutlineColor || 'rgba(100,100,100,.8)';
    this.graticuleColor = options.graticuleColor || 'rgba(100,100,100,.3)';
    this.geoJsonColor = options.geoJsonColor || 'rgba(0,0,0,1)';

    self.area = 1; // minimum area threshold for simplification

    var clip = d3.geo.clipExtent()
        .extent([[-self.width/4, -self.height/4], [self.width/4, self.height/4]]);

    var simplify = d3.geo.transform({
      point: function(x, y, z) {
        if (z >= self.area) {
          this.stream.point(x, y);
        }
      }
    });

    this.projection = options.projection || d3.geo.mollweide();
    this.projection
      .translate([this.width/2, this.height/2])
      .scale(this.width/6)
      .clipExtent([[0, 0], [self.width, self.height]])
      .precision(0.1);

    this.margin = options.margin || {top: 10, right: 10, bottom: 10, left: 10};

    topojson.presimplify(options.countries);

    this.canvas = this.container.append('canvas')
      .datum(topojson.feature(options.countries, options.countries.objects.countries))
      .attr('width', this.width)
      .attr('height', this.height);

    this.context = this.canvas.node().getContext('2d');
    this.colorScale = options.colorScale || defaultColorScale;

    this.simplifyingPath = d3.geo.path()
      .projection({stream: function(s) {return simplify.stream(clip.stream(self.projection.stream(s)));}})
      .context(this.context);

    this.path = d3.geo.path()
      .projection(this.projection)
      .context(this.context);

    this.initCellIdToCoordinates();
    this.initEvents();
    d3.select(window).on('resize', this.resize.bind(this));

    self.draw();
  };

  GridMap.worldGeoJSON = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'Polygon',
            coordinates: [[
              [-179.999, 89.999],
              [179.999, 89.999],
              [179.999, -89.999],
              [-179.999, -89.9999],
              [-179.999, 89.999]
            ]]
          }
        }
      ]
    };

  GridMap.drawWorld = function() {

    this.context.clearRect(0, 0, this.width, this.height);

    //draw world background (the sea). acting funny for now
    this.context.beginPath();
    this.path(this.worldGeoJSON);
    this.context.fillStyle = this.seaColor;
    this.context.fill();

    // draw countries
    this.context.beginPath();
    this.canvas.each(this.simplifyingPath);
    this.context.strokeStyle = this.landOutlineColor;
    this.context.lineWidth = 1;
    this.context.fillStyle = this.landColor;
    this.context.fill();
    this.context.stroke();

    // overlay graticule.  Requires it's own path so
    // it won't get clipped/simplified
    this.context.beginPath();
    this.path(this.graticule());
    this.context.lineWidth = 1;
    this.context.strokeStyle = this.graticuleColor;
    this.context.stroke();
  };

  GridMap.draw = function(_geojson) {
    if (_geojson) {
      this.geojson = _geojson;
    }

    this.drawWorld();

    var self = this;
    if (this.geojson && this.geojson.features) {
      this.geojson.features.forEach(function(feature){
        var color = null;
        if (feature.properties.rgba) {
          color = 'rgba(' + feature.properties.rgba.join(',') + ')';
        } else {
          color = self.colorScale(feature.properties.value);
        }
        self.context.beginPath();
        self.path(feature);
        self.context.strokeStyle = self.geoJsonColor;
        self.context.lineWidth = 0.5;
        self.context.stroke();
        self.context.fillStyle = color;
        self.context.fill();
      });
    }
  };

  GridMap.resize = function() {
    this.width = parseInt(this.container.style('width'), 10);
    this.width = this.width - this.margin.left - this.margin.right;
    d3.select('canvas').attr('width', this.width);
    this.projection
      .translate([this.width/2, this.height/2])
      .clipExtent([[0, 0], [this.width, this.height]]);
    this.initEvents();
    this.draw();
  };

  GridMap.setDataUnsparseTypedArray = function (data) {
    this.geojson = this.uInt8ArrayToGeoJSON(data);
    this.draw();
  };
  GridMap.setDataArrayBuffer = function (data) {
    this.geojson = this.arrayBufferToGeoJSON(data);
    this.draw();
  };
  GridMap.setDataGeoJSON = function (data) {
    this.geojson = data;
    this.draw();
  };

  GridMap.uInt8ArrayToGeoJSON = function(array) {
    // given a UInt8ClampedArray containing data in
    // RGBA format, returns GeoJSON

    // The format is expected to be
    // a sequence of Uint8 elements representing RGBA
    // values for each cell from cell ID 1 to the final cell ID,
    // in column first order.

    var geojson = {
       type: "FeatureCollection",
       features: []
    };

    for (var i=0; i<array.length; i+=4) {
      var cell_id = i/4 + 1;
      var r = array[i];
      var g = array[i+1];
      var b = array[i+2];
      var a = array[i+3];

      if (r === 0 && g === 0 && b === 0 && a === 0) {
        continue;
      }
      var coordinates = this.cellIdToCoordinates[cell_id];

      var feature = {
         type: 'Feature',
         id: i,
         geometry: {
             type: 'Polygon',
             coordinates: [coordinates]
         },
         properties: {
          rgba: [r,g,b,a]
        }
      };
      geojson.features.push(feature);
    }

    return geojson;
  };

  GridMap.arrayBufferToGeoJSON = function(buff) {
    // given an ArrayBuffer buff containing data in
    // packed binary format, returns GeoJSON

    // The packed binary format is expected to be
    // a sequence of Uint32 elements in which the most
    // significant byte is the cell value and the
    // lowest 3 bytes represent the cell ID.

    var geojson = {
       type: 'FeatureCollection',
       features: []
    };

    var typedArray = new Uint32Array(buff);
    for (var i=0; i<typedArray.length; i++) {
      var packed = typedArray[i];
      var cell_id = packed & 0xfffff;
      var abundance = packed >> 24;
      var coordinates = this.cellIdToCoordinates[cell_id];

      var feature = {
         type: 'Feature',
         id: i,
         geometry: {
             type: 'Polygon',
             coordinates: [coordinates]
         },
         properties: {value: abundance }
      };
      geojson.features.push(feature);
    }
    return geojson;
  };

  GridMap._cellIdToLonLat = function(id) {
      id--;
      var lon = -180 + (id % 720)/720.0 * 360 ;
      var lat = 90 - ~~(id / 720)/2;
      return [lon, lat];
  };

  GridMap.cellIdToCoordinates = [null];

  GridMap.initCellIdToCoordinates = function() {

    var x_size = 0.5; // this.grid_cols / 360;
    var y_size = 0.5; //this.grid_rows / 180;
    for (var i=1; i<=this.grid_rows * this.grid_cols; i++) {
        var lonLat = this._cellIdToLonLat(i);
        var coordinates = [
          lonLat,
          [lonLat[0] + x_size, lonLat[1]],
          [lonLat[0] + x_size, lonLat[1]-y_size],
          [lonLat[0], lonLat[1]-y_size],
          lonLat
        ];
        this.cellIdToCoordinates[i] = coordinates;
    }
  };

})();
<|endoftext|>


<commit_before>define([
	'goo/scripts/ScriptUtils'
], function (
	ScriptUtil
) {
	'use strict';

	describe('ScriptUtil', function () {
		it('defaults missing keys', function () {
			var parametersDefinition = [{
				key: 'a',
				type: 'int',
				'default': 123
			}, {
				key: 'b',
				type: 'string',
				'default': 'asd'
			}];

			var parametersValues = {};

			ScriptUtil.fillDefaultValues(parametersValues, parametersDefinition);

			var expected = {
				'a': 123,
				'b': 'asd'
			};

			expect(parametersValues).toEqual(expected);
		});

		it('defaults the defaults for all types', function () {
			var parametersDefinition = [{
				key: 'a',
				type: 'int'
			}, {
				key: 'b',
				type: 'float'
			}, {
				key: 'c',
				type: 'string'
			}, {
				key: 'd',
				type: 'vec3'
			}, {
				key: 'e',
				type: 'boolean'
			}, {
				key: 'f',
				type: 'texture'
			}, {
				key: 'g',
				type: 'entity'
			}];

			var parametersValues = {};

			ScriptUtil.fillDefaultValues(parametersValues, parametersDefinition);

			var expected = {
				'a': 0,
				'b': 0,
				'c': '',
				'd': [0, 0, 0],
				'e': false,
				'f': {},
				'g': {}
			};

			expect(parametersValues).toEqual(expected);
		});
	});
});<commit_msg>Forgot to update the tests<commit_after>define([
	'goo/scripts/ScriptUtils'
], function (
	ScriptUtil
) {
	'use strict';

	describe('ScriptUtil', function () {
		it('defaults missing keys', function () {
			var parametersDefinition = [{
				key: 'a',
				type: 'int',
				'default': 123
			}, {
				key: 'b',
				type: 'string',
				'default': 'asd'
			}];

			var parametersValues = {};

			ScriptUtil.fillDefaultValues(parametersValues, parametersDefinition);

			var expected = {
				'a': 123,
				'b': 'asd'
			};

			expect(parametersValues).toEqual(expected);
		});

		it('defaults the defaults for all types', function () {
			var parametersDefinition = [{
				key: 'a',
				type: 'int'
			}, {
				key: 'b',
				type: 'float'
			}, {
				key: 'c',
				type: 'string'
			}, {
				key: 'd',
				type: 'vec3'
			}, {
				key: 'e',
				type: 'boolean'
			}, {
				key: 'f',
				type: 'texture'
			}, {
				key: 'g',
				type: 'entity'
			}];

			var parametersValues = {};

			ScriptUtil.fillDefaultValues(parametersValues, parametersDefinition);

			var expected = {
				'a': 0,
				'b': 0,
				'c': '',
				'd': [0, 0, 0],
				'e': false,
				'f': null,
				'g': null
			};

			expect(parametersValues).toEqual(expected);
		});
	});
});<|endoftext|>


<commit_before>/*
 * This file is transpiled to create an ES5-compatible distribution in which
 * the package's main feature(s) are available via the window.Elix global.
 * If you're already using ES6 yourself, ignore this file, and instead import
 * the source file(s) you want from the src folder.
 */

// Import mixins
// import * as attributes from './mixins/attributes.js';
// import * as content from './mixins/content.js';
// import AttributeMarshallingMixin from './mixins/AttributeMarshallingMixin.js';
// import ClickSelectionMixin from './mixins/ClickSelectionMixin.js';
// import constants from './mixins/constants.js';
// import ContentItemsMixin from './mixins/ContentItemsMixin.js';
// import defaultScrollTarget from './mixins/defaultScrollTarget.js';
// import DefaultSlotContentMixin from './mixins/DefaultSlotContentMixin.js';
// import DirectionSelectionMixin from './mixins/DirectionSelectionMixin.js';
// import KeyboardDirectionMixin from './mixins/KeyboardDirectionMixin.js';
// import KeyboardMixin from './mixins/KeyboardMixin.js';
// import KeyboardPagedSelectionMixin from './mixins/KeyboardPagedSelectionMixin.js';
// import KeyboardPrefixSelectionMixin from './mixins/KeyboardPrefixSelectionMixin.js';
// import OpenCloseMixin from './mixins/OpenCloseMixin.js';
// import OverlayMixin from './mixins/OverlayMixin.js';
// import renderArrayAsElements from './mixins/renderArrayAsElements.js';
// import SelectionAriaMixin from './mixins/SelectionAriaMixin.js';
// import SelectionInViewMixin from './mixins/SelectionInViewMixin.js';
// import ShadowReferencesMixin from './mixins/ShadowReferencesMixin.js';
// import ShadowTemplateMixin from './mixins/ShadowTemplateMixin.js';
// import SingleSelectionMixin from './mixins/SingleSelectionMixin.js';
// import Symbol from './mixins/Symbol.js';
// import symbols from './mixins/symbols.js';
// import TransitionEffectMixin from './mixins/TransitionEffectMixin.js';

// Import elements
// import AlertDialog from './elements/AlertDialog.js';
import Dialog from './elements/Dialog.js';
// import Drawer from './elements/Drawer.js';
// import LabeledTabButton from './elements/LabeledTabButton.js';
// import LabeledTabs from './elements/LabeledTabs.js';
import ListBox from './elements/ListBox.js';
import Modes from './elements/Modes.js';
// import Popup from './elements/Popup.js';
import Tabs from './elements/Tabs.js';
import TabStrip from './elements/TabStrip.js';
// import TabStripWrapper from './elements/TabStripWrapper.js';
// import Toast from './elements/Toast.js';

// The complete list of all mixins and elements.
const Elix = {
  // AttributeMarshallingMixin,
  // attributes,
  // ClickSelectionMixin,
  // constants,
  // content,
  // ContentItemsMixin,
  // defaultScrollTarget,
  // DefaultSlotContentMixin,
  // Dialog,
  // DirectionSelectionMixin,
  // Drawer,
  // KeyboardDirectionMixin,
  // KeyboardMixin,
  // KeyboardPagedSelectionMixin,
  // KeyboardPrefixSelectionMixin,
  // LabeledTabButton,
  // LabeledTabs,
  ListBox,
  Modes,
  // AlertDialog,
  // OpenCloseMixin,
  // OverlayMixin,
  // Popup,
  // renderArrayAsElements,
  // SelectionAriaMixin,
  // SelectionInViewMixin,
  // ShadowReferencesMixin,
  // ShadowTemplateMixin,
  // SingleSelectionMixin,
  // Symbol,
  // symbols,
  Tabs,
  TabStrip,
  // TabStripWrapper,
  // TransitionEffectMixin,
  // Toast
};

// Create (or add to) Elix global.
window.Elix = Object.assign(window.Elix || {}, Elix);

export default Elix;
<commit_msg>Ensure Drawer gets build.<commit_after>/*
 * This file is transpiled to create an ES5-compatible distribution in which
 * the package's main feature(s) are available via the window.Elix global.
 * If you're already using ES6 yourself, ignore this file, and instead import
 * the source file(s) you want from the src folder.
 */

// Import mixins
// import * as attributes from './mixins/attributes.js';
// import * as content from './mixins/content.js';
// import AttributeMarshallingMixin from './mixins/AttributeMarshallingMixin.js';
// import ClickSelectionMixin from './mixins/ClickSelectionMixin.js';
// import constants from './mixins/constants.js';
// import ContentItemsMixin from './mixins/ContentItemsMixin.js';
// import defaultScrollTarget from './mixins/defaultScrollTarget.js';
// import DefaultSlotContentMixin from './mixins/DefaultSlotContentMixin.js';
// import DirectionSelectionMixin from './mixins/DirectionSelectionMixin.js';
// import KeyboardDirectionMixin from './mixins/KeyboardDirectionMixin.js';
// import KeyboardMixin from './mixins/KeyboardMixin.js';
// import KeyboardPagedSelectionMixin from './mixins/KeyboardPagedSelectionMixin.js';
// import KeyboardPrefixSelectionMixin from './mixins/KeyboardPrefixSelectionMixin.js';
// import OpenCloseMixin from './mixins/OpenCloseMixin.js';
// import OverlayMixin from './mixins/OverlayMixin.js';
// import renderArrayAsElements from './mixins/renderArrayAsElements.js';
// import SelectionAriaMixin from './mixins/SelectionAriaMixin.js';
// import SelectionInViewMixin from './mixins/SelectionInViewMixin.js';
// import ShadowReferencesMixin from './mixins/ShadowReferencesMixin.js';
// import ShadowTemplateMixin from './mixins/ShadowTemplateMixin.js';
// import SingleSelectionMixin from './mixins/SingleSelectionMixin.js';
// import Symbol from './mixins/Symbol.js';
// import symbols from './mixins/symbols.js';
// import TransitionEffectMixin from './mixins/TransitionEffectMixin.js';

// Import elements
// import AlertDialog from './elements/AlertDialog.js';
import Dialog from './elements/Dialog.js';
import Drawer from './elements/Drawer.js';
// import LabeledTabButton from './elements/LabeledTabButton.js';
// import LabeledTabs from './elements/LabeledTabs.js';
import ListBox from './elements/ListBox.js';
import Modes from './elements/Modes.js';
// import Popup from './elements/Popup.js';
import Tabs from './elements/Tabs.js';
import TabStrip from './elements/TabStrip.js';
// import TabStripWrapper from './elements/TabStripWrapper.js';
// import Toast from './elements/Toast.js';

// The complete list of all mixins and elements.
const Elix = {
  // AttributeMarshallingMixin,
  // attributes,
  // ClickSelectionMixin,
  // constants,
  // content,
  // ContentItemsMixin,
  // defaultScrollTarget,
  // DefaultSlotContentMixin,
  // Dialog,
  // DirectionSelectionMixin,
  Drawer,
  // KeyboardDirectionMixin,
  // KeyboardMixin,
  // KeyboardPagedSelectionMixin,
  // KeyboardPrefixSelectionMixin,
  // LabeledTabButton,
  // LabeledTabs,
  ListBox,
  Modes,
  // AlertDialog,
  // OpenCloseMixin,
  // OverlayMixin,
  // Popup,
  // renderArrayAsElements,
  // SelectionAriaMixin,
  // SelectionInViewMixin,
  // ShadowReferencesMixin,
  // ShadowTemplateMixin,
  // SingleSelectionMixin,
  // Symbol,
  // symbols,
  Tabs,
  TabStrip,
  // TabStripWrapper,
  // TransitionEffectMixin,
  // Toast
};

// Create (or add to) Elix global.
window.Elix = Object.assign(window.Elix || {}, Elix);

export default Elix;
<|endoftext|>


<commit_before>//
// Connects to database and runs server.
//
var cors = require('cors')
var moment = require('moment')
var bodyParser = require('body-parser')
var express = require('express')
var app = express()

var morgan = require('morgan')
var mongoose = require('mongoose')

var port = process.env.PORT || 9000
var DB = require('./config/database')

//
// Only start the application
// if the database is ready.
//
mongoose.connection.on('connected', function (ref) {
  app.use(morgan('dev'))
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: true
  }))

  //
  // Routes.
  //
  require('./app/routes.js')(app)

  //
  // Start server.
  //
  app.listen(port)
  console.log('Scraper Status API running on port ' + port)

})

mongoose.connection.on('error', function (err) {
  console.log('Could not connect to MongoDB.')
  throw err
})

//
// Attempt connection with MongoDB.
//
mongoose.connect('mongodb://localhost/test')
<commit_msg>bumping to version 0.1.3<commit_after>//
// Connects to database and runs server.
//
var cors = require('cors')
var moment = require('moment')
var bodyParser = require('body-parser')
var express = require('express')
var app = express()

var morgan = require('morgan')
var mongoose = require('mongoose')

var port = process.env.PORT || 9000
var DB = require('./config/database')

var _version = 'v.0.1.3'

//
// Only start the application
// if the database is ready.
//
mongoose.connection.on('connected', function (ref) {
  app.use(morgan('dev'))
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: true
  }))

  //
  // Routes.
  //
  require('./app/routes.js')(app)

  //
  // Start server.
  //
  app.listen(port)
  console.log('Scraper Status API running on port ' + port)

})

mongoose.connection.on('error', function (err) {
  console.log('Could not connect to MongoDB.')
  throw err
})

//
// Attempt connection with MongoDB.
//
mongoose.connect('mongodb://localhost/test')
<|endoftext|>


<commit_before>module.exports = function(config) {
	config.set({
		urlRoot: '/',
		frameworks: ['jasmine'],
		port: 3002,
		logLevel: config.LOG_INFO,
		reporters: ['dots'],
		browsers: [
			'PhantomJS'
		],
		files: [
			'./ima/test.js',
			'./build/static/js/polyfill.js',
			'./build/static/js/shim.js',
			'./build/static/js/vendor.client.js',
			'./build/static/js/locale/cs.js',
			'./build/static/js/app.client.js',
			'./app/tests/unit/**/*.js',
			'./app/tests/unit/*.js',
			'./ima/**/__tests__/*Spec.js'
		]/*,
		preprocessors: {
			'./app/test/*.js': ['babel'],*/
		//	'./node_modules/ima/**/__tests__/*Spec.js': ['babel']
		/*},
		babelPreprocessor: {
			options: {
				presets: ['es2015'],
				sourceMap: 'inline'
			},
			filename: function (file) {
				return file.originalPath.replace(/\.js$/, '.es5.js');
			},
			sourceFileName: function (file) {
				return file.originalPath;
			}
		}*/,
		customLaunchers: {
			Chrome_without_security: {
				base: 'Chrome',
				flags: ['--disable-web-security']
			}
		},
		plugins: [
			'karma-phantomjs-launcher',
			//'karma-babel-preprocessor',
			'karma-jasmine'
			//'karma-coverage'
		],
		phantomjsLauncher: {
			exitOnResourceError: true
		},
		autoWatch: true,
		singleRun: false,
		colors: true
	});
};
<commit_msg>fixed karma files list<commit_after>module.exports = function(config) {
	config.set({
		urlRoot: '/',
		frameworks: ['jasmine'],
		port: 3002,
		logLevel: config.LOG_INFO,
		reporters: ['dots'],
		browsers: [
			'PhantomJS'
		],
		files: [
			'./node_modules/ima/test.js',
			'./build/static/js/polyfill.js',
			'./build/static/js/shim.js',
			'./build/static/js/vendor.client.js',
			'./build/static/js/locale/cs.js',
			'./build/static/js/app.client.js',
			'./app/tests/unit/**/*.js',
			'./app/tests/unit/*.js',
			'./node_modules/ima/**/__tests__/*Spec.js'
		]/*,
		preprocessors: {
			'./app/test/*.js': ['babel'],*/
		//	'./node_modules/ima/**/__tests__/*Spec.js': ['babel']
		/*},
		babelPreprocessor: {
			options: {
				presets: ['es2015'],
				sourceMap: 'inline'
			},
			filename: function (file) {
				return file.originalPath.replace(/\.js$/, '.es5.js');
			},
			sourceFileName: function (file) {
				return file.originalPath;
			}
		}*/,
		customLaunchers: {
			Chrome_without_security: {
				base: 'Chrome',
				flags: ['--disable-web-security']
			}
		},
		plugins: [
			'karma-phantomjs-launcher',
			//'karma-babel-preprocessor',
			'karma-jasmine'
			//'karma-coverage'
		],
		phantomjsLauncher: {
			exitOnResourceError: true
		},
		autoWatch: true,
		singleRun: false,
		colors: true
	});
};
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');

module.exports = {
  recombine,
  decompose,
};

function recombine (entries, prefix, accumulator) {
  // No prefix means empty string, so we don't get keys starting with '.'
  const pre = prefix ? prefix + '.' : false;

  return _.reduce(
    entries,
    (acc, ent) => {
      let key, value;
      if (_.isArray(ent)) {
        [ key, value ] = ent;
      }
      else if (_.isObject(ent)) {
        ({ key, value } = ent);
      }

      return key && (!pre || key.startsWith(pre))
        ? _.set(acc, pre ? key.substr(pre.length) : key, value)
        : acc;
    },
    accumulator || {}
  );
}

function decompose (value, prefix, accumulator) {
  const acc = accumulator || [];

  // Recurse with new prefix if value is object
  if (_.isObjectLike(value) && !_.isArray(value)) {
    // No prefix means empty string, so we don't get keys starting with '.'
    const pre = prefix ? prefix + '.' : '';
    _.forOwn(value, (v, k) => decompose(v, pre + k, acc));
  }
  // Otherwise, stringify and push already-prefixed key to result array
  else {
    acc.push([prefix, value]);
  }
  return acc;
}
<commit_msg>Totally unnecessary ordering change<commit_after>'use strict';

const _ = require('lodash');

module.exports = {
  decompose,
  recombine,
};

function recombine (entries, prefix, accumulator) {
  // No prefix means empty string, so we don't get keys starting with '.'
  const pre = prefix ? prefix + '.' : false;

  return _.reduce(
    entries,
    (acc, ent) => {
      let key, value;
      if (_.isArray(ent)) {
        [ key, value ] = ent;
      }
      else if (_.isObject(ent)) {
        ({ key, value } = ent);
      }

      return key && (!pre || key.startsWith(pre))
        ? _.set(acc, pre ? key.substr(pre.length) : key, value)
        : acc;
    },
    accumulator || {}
  );
}

function decompose (value, prefix, accumulator) {
  const acc = accumulator || [];

  // Recurse with new prefix if value is object
  if (_.isObjectLike(value) && !_.isArray(value)) {
    // No prefix means empty string, so we don't get keys starting with '.'
    const pre = prefix ? prefix + '.' : '';
    _.forOwn(value, (v, k) => decompose(v, pre + k, acc));
  }
  // Otherwise, stringify and push already-prefixed key to result array
  else {
    acc.push([prefix, value]);
  }
  return acc;
}
<|endoftext|>