<commit_before>// test/float.js
//
// Test CRUD for floating-point scalars
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows'),
    databank = require('../databank'),
    Databank = databank.Databank;

var floatContext = function(driver, params) {

    var context = {};

    context["When we create a " + driver + " databank"] = {

        topic: function() {
            params.schema = {
                'probability': {
                    pkey: 'weather'
                }
            };
            return Databank.get(driver, params);
        },
        'We can connect to it': {
            topic: function(bank) {
                bank.connect(params, this.callback);
            },
            'without an error': function(err) {
                assert.ifError(err);
            },
            'and we can insert a number': {
                topic: function(bank) {
                    bank.create('probability', 'rain', 0.30, this.callback);
                },
                'without an error': function(err, value) {
                    assert.ifError(err);
                    assert.isNumber(value);
                    assert.equal(value - 0.30 < 0.0001, true);
                },
                'and we can fetch it': {
                    topic: function(created, bank) {
                        bank.read('probability', 'rain', this.callback);
                    },
                    'without an error': function(err, value) {
			assert.ifError(err);
                        assert.isNumber(value);
                        assert.equal(value - 0.30 < 0.0001, true);
                    },
                    'and we can update it': {
                        topic: function(read, created, bank) {
                            bank.update('probability', 'rain', 0.45, this.callback);
                        },
                        'without an error': function(err, value) {
			    assert.ifError(err);
			    assert.isNumber(value);
                            assert.equal(value - 0.45 < 0.0001, true);
                        },
                        'and we can read it again': {
                            topic: function(updated, read, created, bank) {
				bank.read('probability', 'rain', this.callback);
                            },
                            'without an error': function(err, value) {
				assert.ifError(err);
			        assert.isNumber(value);
                                assert.equal(value - 0.45 < 0.0001, true);
                            },
                            'and we can save it': {
                                topic: function(readAgain, updated, read, created, bank) {
				    bank.save('probability', 'rain', 0.25, this.callback);
                                },
                                'without an error': function(err, value) {
				    assert.ifError(err);
			            assert.isNumber(value);
                                    assert.equal(value - 0.25 < 0.0001, true);
                                },
                                'and we can read it once more': {
                                    topic: function(saved, readAgain, updated, read, created, bank) {
				        bank.read('probability', 'rain', this.callback);
                                    },
                                    'without an error': function(err, value) {
				        assert.ifError(err);
			                assert.isNumber(value);
                                        assert.equal(value - 0.45 < 0.0001, true);
                                    },
			            'and we can delete it': {
				        topic: function(readOnceMore, saved, readAgain, updated, read, created, bank) {
				            bank.del('probability', 'rain', this.callback);
				        },
				        'without an error': function(err) {
				            assert.ifError(err);
				        },
                                        'and we can save to create': {
                                            topic: function(readOnceMore, saved, readAgain, updated, read, created, bank) {
				                bank.save('probability', 'fog', 0.10, this.callback);
                                            },
                                            'without an error': function(err, value) {
				                assert.ifError(err);
			                        assert.isNumber(value);
                                                assert.equal(value - 0.10 < 0.0001, true);
                                            },
			                    'and we can delete it': {
				                topic: function(saveCreated, readOnceMore, saved, readAgain, updated, read, created, bank) {
				                    bank.del('probability', 'fog', this.callback);
				                },
				                'without an error': function(err) {
				                    assert.ifError(err);
				                },
				                'and we can disconnect': {
				                    topic: function(saveCreated, readOnceMore, saved, readAgain, updated, read, created, bank) {
					                bank.disconnect(this.callback);
				                    },
				                    'without an error': function(err) {
					                assert.ifError(err);
				                    }
				                }
			                    }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    return context;
};

module.exports = floatContext;
<commit_msg>disconnect in teardown for float test<commit_after>// test/float.js
//
// Test CRUD for floating-point scalars
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows'),
    databank = require('../databank'),
    Databank = databank.Databank;

var floatContext = function(driver, params) {

    var context = {};

    context["When we create a " + driver + " databank"] = {

        topic: function() {
            params.schema = {
                'probability': {
                    pkey: 'weather'
                }
            };
            return Databank.get(driver, params);
        },
        'We can connect to it': {
            topic: function(bank) {
                bank.connect(params, this.callback);
            },
            'without an error': function(err) {
                assert.ifError(err);
            },
	    teardown: function(bank) {
		bank.disconnect(this.callback);
	    },
            'and we can insert a number': {
                topic: function(bank) {
                    bank.create('probability', 'rain', 0.30, this.callback);
                },
                'without an error': function(err, value) {
                    assert.ifError(err);
                    assert.isNumber(value);
                    assert.equal(value - 0.30 < 0.0001, true);
                },
                'and we can fetch it': {
                    topic: function(created, bank) {
                        bank.read('probability', 'rain', this.callback);
                    },
                    'without an error': function(err, value) {
			assert.ifError(err);
                        assert.isNumber(value);
                        assert.equal(value - 0.30 < 0.0001, true);
                    },
                    'and we can update it': {
                        topic: function(read, created, bank) {
                            bank.update('probability', 'rain', 0.45, this.callback);
                        },
                        'without an error': function(err, value) {
			    assert.ifError(err);
			    assert.isNumber(value);
                            assert.equal(value - 0.45 < 0.0001, true);
                        },
                        'and we can read it again': {
                            topic: function(updated, read, created, bank) {
				bank.read('probability', 'rain', this.callback);
                            },
                            'without an error': function(err, value) {
				assert.ifError(err);
			        assert.isNumber(value);
                                assert.equal(value - 0.45 < 0.0001, true);
                            },
                            'and we can save it': {
                                topic: function(readAgain, updated, read, created, bank) {
				    bank.save('probability', 'rain', 0.25, this.callback);
                                },
                                'without an error': function(err, value) {
				    assert.ifError(err);
			            assert.isNumber(value);
                                    assert.equal(value - 0.25 < 0.0001, true);
                                },
                                'and we can read it once more': {
                                    topic: function(saved, readAgain, updated, read, created, bank) {
				        bank.read('probability', 'rain', this.callback);
                                    },
                                    'without an error': function(err, value) {
				        assert.ifError(err);
			                assert.isNumber(value);
                                        assert.equal(value - 0.45 < 0.0001, true);
                                    },
			            'and we can delete it': {
				        topic: function(readOnceMore, saved, readAgain, updated, read, created, bank) {
				            bank.del('probability', 'rain', this.callback);
				        },
				        'without an error': function(err) {
				            assert.ifError(err);
				        },
                                        'and we can save to create': {
                                            topic: function(readOnceMore, saved, readAgain, updated, read, created, bank) {
				                bank.save('probability', 'fog', 0.10, this.callback);
                                            },
                                            'without an error': function(err, value) {
				                assert.ifError(err);
			                        assert.isNumber(value);
                                                assert.equal(value - 0.10 < 0.0001, true);
                                            },
			                    'and we can delete it': {
				                topic: function(saveCreated, readOnceMore, saved, readAgain, updated, read, created, bank) {
				                    bank.del('probability', 'fog', this.callback);
				                },
				                'without an error': function(err) {
				                    assert.ifError(err);
				                }
			                    }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    return context;
};

module.exports = floatContext;
<|endoftext|>


<commit_before>var http = require('http')
  , url = require('url')
  , port = process.env.PORT || 3000;

var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});
  if (queryData.delay) {
    setTimeout(function(){
      response.end("Response from Traffic Jam with " + queryData.delay + 'ms delay');
    }, queryData.delay);
  } else {
    response.end("Response from Traffic Jam");
  }
});

server.listen(3000);
<commit_msg>assign to correct port<commit_after>var http = require('http')
  , url = require('url')
  , port = process.env.PORT || 3000;

var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});
  if (queryData.delay) {
    setTimeout(function(){
      response.end("Response from Traffic Jam with " + queryData.delay + 'ms delay');
    }, queryData.delay);
  } else {
    response.end("Response from Traffic Jam");
  }
});

server.listen(port);
<|endoftext|>


<commit_before>'use strict';

function configure (collection, storage, pushover) {

  function create (obj, fn) {
    obj.created_at = (new Date( )).toISOString( );
    api( ).insert(obj, function (err, doc) {
      fn(null, doc);

      if (pushover) {

        var text = (obj.glucose ? 'Blood glucose: ' + obj.glucose + ' (' + obj.glucoseType + ')' : '') +
          (obj.carbs ? '\nCarbs: ' + obj.carbs : '') +
          (obj.insulin ? '\nInsulin: ' + obj.insulin : '')+
          (obj.enteredBy ? '\nEntered By: ' + obj.enteredBy : '') +
          (obj.notes ? '\nNotes: ' + obj.notes : '');

        var msg = {
          expire: 14400, // 4 hours
          message: text,
          title: obj.eventType,
          sound: 'persistent',
          timestamp: new Date( ),
          priority: 1,
          retry: 30
        };

        pushover.send( msg, function( err, result ) {
          console.log(result);
        });
      }

    });
  }

  function list (fn) {
    return api( ).find({ }).sort({created_at: -1}).toArray(fn);
  }

  function api ( ) {
    return storage.pool.db.collection(collection);
  }

  api.list = list;
  api.create = create;
  return api;
}
module.exports = configure;
<commit_msg>better treatment notification sound<commit_after>'use strict';

function configure (collection, storage, pushover) {

  function create (obj, fn) {
    obj.created_at = (new Date( )).toISOString( );
    api( ).insert(obj, function (err, doc) {
      fn(null, doc);

      if (pushover) {

        var text = (obj.glucose ? 'Blood glucose: ' + obj.glucose + ' (' + obj.glucoseType + ')' : '') +
          (obj.carbs ? '\nCarbs: ' + obj.carbs : '') +
          (obj.insulin ? '\nInsulin: ' + obj.insulin : '')+
          (obj.enteredBy ? '\nEntered By: ' + obj.enteredBy : '') +
          (obj.notes ? '\nNotes: ' + obj.notes : '');

        var msg = {
          expire: 14400, // 4 hours
          message: text,
          title: obj.eventType,
          sound: 'gamelan',
          timestamp: new Date( ),
          priority: 1,
          retry: 30
        };

        pushover.send( msg, function( err, result ) {
          console.log(result);
        });
      }

    });
  }

  function list (fn) {
    return api( ).find({ }).sort({created_at: -1}).toArray(fn);
  }

  function api ( ) {
    return storage.pool.db.collection(collection);
  }

  api.list = list;
  api.create = create;
  return api;
}
module.exports = configure;
<|endoftext|>


<commit_before>"use strict";
var PID_FILENAME = "ircas.pid";
var fs = require("fs");
var q = require("q");
var logging = require("./logging");
var Validator = require("./config/validator");
var log = logging.get("hotreload");

var reloading = false;

var reloadConfig = function() {
    log.info("Reloading config file....");
    var config;
    try {
        var configValidator = new Validator(Validator.getFileLocation());
        config = configValidator.validate();
    }
    catch (e) {
        log.error("Failed to load config file: " + e);
        return q.reject();
    }
    log.info("Loaded config file.");
    return q();
};

module.exports.setup = function() {
    // write out the pid file
    fs.writeFileSync(PID_FILENAME, "" + process.pid);

    // SIGUSR1 is reserved by node for debugging
    process.on("SIGUSR2", function() {
        log.info("SIGUSR2 received.");
        /*
        if (!reloading) {
            log.info(" @@@@@@@@@@ HOT RELOAD @@@@@@@@@@ ");
            reloading = true;
            reloadConfig().finally(function() {
                reloading = false;
            });
        } */
    });
};
<commit_msg>Comment out the right things<commit_after>/**
"use strict";
var PID_FILENAME = "ircas.pid";
var fs = require("fs");
var q = require("q");
var logging = require("./logging");
var Validator = require("./config/validator");
var log = logging.get("hotreload");

var reloading = false;

var reloadConfig = function() {
    log.info("Reloading config file....");
    var config;
    try {
        var configValidator = new Validator(Validator.getFileLocation());
        config = configValidator.validate();
    }
    catch (e) {
        log.error("Failed to load config file: " + e);
        return q.reject();
    }
    log.info("Loaded config file.");
    return q();
};
*/

module.exports.setup = function() { /*
    // write out the pid file
    fs.writeFileSync(PID_FILENAME, "" + process.pid);

    // SIGUSR1 is reserved by node for debugging
    process.on("SIGUSR2", function() {
        log.info("SIGUSR2 received.");

        if (!reloading) {
            log.info(" @@@@@@@@@@ HOT RELOAD @@@@@@@@@@ ");
            reloading = true;
            reloadConfig().finally(function() {
                reloading = false;
            });
        }
    }); */
};
<|endoftext|>


<commit_before>var page = require('webpage').create(),
    system = require('system'),
    address = system.args[1],
    start = (new Date()).toLocaleString(),
    fails = 0,
    bads = 0;

page.onConsoleMessage = function(msg) {
    console.log('console:' + msg);
};

page.onResourceRequested = function(request) {
    var url = request.url,
        bad = url.match(/^http:\/\//);

    console.log((bad ? 'BAD: ' : 'good:') + url.replace(/^(.{30,30}).{10,}(.{30,30})$/, '$1 ... $2'));
    bads += bad ? 1 : 0;
};

page.open(address, function(status) {
    console.log('DONE!');
    if (status !== 'success') {
        console.log('PAGE STATUS:' + status);
    }
    phantom.exit(bads);
});
<commit_msg>refine<commit_after>var page = require('webpage').create(),
    system = require('system'),
    address = system.args[1],
    start = (new Date()).toLocaleString(),
    fails = 0,
    bads = 0;

page.onConsoleMessage = function(msg) {
    console.log('console:' + msg);
};

page.onResourceRequested = function(request) {
    var url = request.url,
        bad = url.match(/^http:\/\//);

    console.log((bad ? 'BAD: ' : 'good:') + url.replace(/^(.{30,30}).{10,}(.{30,30})$/, '$1 ... $2'));
    bads += bad ? 1 : 0;
};

page.open(address, function(status) {
    console.log('PAGE STATUS:' + status);
    console.log('BAD:' + bads);
    phantom.exit(bads);
});
<|endoftext|>


<commit_before>// Copyright © 2014 Intel Corporation. All rights reserved.
// Use  of this  source  code is  governed by  an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.

var Config = null;
var Console = null;
var Downloader = null;
var Shell = require ("shelljs");
var Path = require ('path');
var SDK = require ('./iOSSDK');

function iOSPlatform(PlatformBase, baseData) {
    /**
     * Interface for project implementations.
     * @constructor
     * @protected
     */
    function iOSProject(PlatformBase, baseData) {

        PlatformBase.call(this, baseData);
        Console = console;
    }

    iOSProject.prototype = PlatformBase.prototype;
    /**
     * Generate project template.
     * @function generate
     * @param {String} packageId Package name in com.example.Foo format.
     * @param {Function} callback see {@link Project~projectOperationCb}.
     * @abstract
     * @memberOf Project
     */
    iOSProject.prototype.generate =
        function(options, callback) {

            // TODO implement generation of project.
            Console.log("iOSProject: Generating " + this.packageId);

            var template_dir = Path.join(__dirname, '..', 'data', 'AppShell');
            var parts = this.packageId.split('.');
            var project_name = parts[parts.length - 1];
            var project_dir = this.platformPath;

            if (project_name == "" || project_name == null) {
                callback("Please provide the project name.");
                return;
            }

            if (Shell.test('-d', project_dir)) {
                callback("The project has been already existed: " + project_dir);
                return;
            }

            if (!Shell.test('-d', template_dir)) {
                callback("Can not find project template files: " + template_dir);
                return;
            }
            Shell.mkdir('-p', this.pkgPath);
            Shell.cp('-Rf', template_dir, this.prjPath);
            Shell.mv(Path.join(this.prjPath, 'AppShell'), project_dir);
            Shell.pushd(project_dir);
            Shell.ls (".").filter (function (file) {
                var new_file = file.replace (/AppShell/gi, project_name);
                if (file != new_file)
                    Shell.mv ('-f', file, new_file);
            });
            var xcodeproj = project_name+".xcodeproj";
            Shell.find (xcodeproj).filter (function (file) {
                if (Shell.test ('-f', file)) {
                    Shell.sed ('-i', /AppShell/gi, project_name, file);
                    Shell.mv('-f', file, file.replace (/AppShell/gi, project_name));
                }
            });

            // Replace package name in info.plist.
            var info_file = Path.join(project_dir, project_name, 'Info.plist');
            var project_name_prefix = Path.basename(project_dir, '.' + project_name);
            if (Shell.test('-f', info_file)) {
                Shell.sed('-i', /org.crosswalk-project/gi, project_name_prefix, info_file);
            }
            Shell.popd();

            if (Shell.test('-d', this.appPath)) {
                Shell.rm('-rf', this.appPath);
            }

            Shell.mv('-f', Path.join(project_dir, 'www'), this.appPath);

            // Null means success, error string means failure.
            callback(null);
        };

    iOSProject.prototype.update =
        function(callback) {

            // TODO implement updating of project to new Crosswalk version.
            // This function is not supported yet.
            Console.log("iOSProject: Updating project has not implemented.");

            // Null means success, error string means failure.
            callback(null);
        };

    iOSProject.prototype.refresh =
        function(callback) {

            // TODO implement updating of project to new Crosswalk version.
            // Maybe this function will be not needed, and removed in the future.
            Console.log("iOSProject: Refreshing project has not implemented.");

            // Null means success, error string means failure.
            callback(null);
        };

    /**
     * Build application package.
     * @function build
     * @param {String[]} abi Array of ABIs, supported armeabi-v7a, x86.
     * @param {Boolean} release Whether to build debug or release package.
     * @param {Function} callback see {@link Project~projectOperationCb}.
     * @abstract
     * @memberOf Project
     */
    iOSProject.prototype.build =
        function(abis, release, callback) {

            var packageId = Path.basename(Shell.pwd());
            // TODO implement updating of project to new Crosswalk version.
            Console.log("iOSProject: Building project " + packageId);

            var Fs = require ('fs');

            var project_dir = this.platformPath;
            var parts = packageId.split('.');
            var project_name = parts[parts.length-1];

            if (project_name == "" || project_name == null) {
                console.log("Please provide the project name.");
                return;
            }

            Console.log('Start to update the web resources.');

            if (Shell.test('-d', Path.join(project_dir, 'www'))) {
                Shell.rm('-rf', Path.join(project_dir, 'www'));
            }

            Shell.cp('-Rf', this.appPath, project_dir);
            Shell.mv('-f', Path.join(project_dir, 'app'), Path.join(project_dir, 'www'));

            Shell.pushd(project_dir);
            var project_path = Path.join(project_dir, project_name + '.xcodeproj', 'project.pbxproj');
            var project = require ('xcode').project(project_path);
            var Manifest = require(Path.join(project_dir, 'www', 'manifest.json'));
            project.parse(function (err) {
                Fs.writeFileSync(Path.join(project_dir, 'www', 'manifest.plist'), require('plist').build(Manifest));
                // Add the real resource files.
                Shell.pushd(Path.join(project_dir, 'www'));
                // Remove the default resource files first.
                project.removeResourceFile('index.html');
                project.removeResourceFile('icon.png');
                Shell.find('.').filter(function (file) {
                    if (Shell.test('-f', file)) {
                        project.addResourceFile(file);
                    }
                });
                Shell.popd();

                Fs.writeFileSync(project_path, project.writeSync());
                Console.log('Finished update resources.');
                Console.log('Start to build ipa file.');
                var sdk = new SDK({'path': project_dir, 'id': packageId});
                if (sdk.build(['arm64', 'armv7', 'armv7s'], release)) {
                    this.exportPackage(Shell.ls(Path.join(project_dir, 'build', project_name + '*.ipa'))[0]);
                }
            }.bind(this));
            Shell.popd();
            // Null means success, error string means failure.
            callback(null);
        };
    return new iOSProject(PlatformBase, baseData);
}

module.exports = iOSPlatform;
<commit_msg>Change to use packageId for replacing the CFBundleIdentifier prefix<commit_after>// Copyright © 2014 Intel Corporation. All rights reserved.
// Use  of this  source  code is  governed by  an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.

var Config = null;
var Console = null;
var Downloader = null;
var Shell = require ("shelljs");
var Path = require ('path');
var SDK = require ('./iOSSDK');

function iOSPlatform(PlatformBase, baseData) {
    /**
     * Interface for project implementations.
     * @constructor
     * @protected
     */
    function iOSProject(PlatformBase, baseData) {

        PlatformBase.call(this, baseData);
        Console = console;
    }

    iOSProject.prototype = PlatformBase.prototype;
    /**
     * Generate project template.
     * @function generate
     * @param {String} packageId Package name in com.example.Foo format.
     * @param {Function} callback see {@link Project~projectOperationCb}.
     * @abstract
     * @memberOf Project
     */
    iOSProject.prototype.generate =
        function(options, callback) {

            // TODO implement generation of project.
            Console.log("iOSProject: Generating " + this.packageId);

            var template_dir = Path.join(__dirname, '..', 'data', 'AppShell');
            var parts = this.packageId.split('.');
            var project_name = parts[parts.length - 1];
            var project_dir = this.platformPath;

            if (project_name == "" || project_name == null) {
                callback("Please provide the project name.");
                return;
            }

            if (Shell.test('-d', project_dir)) {
                callback("The project has been already existed: " + project_dir);
                return;
            }

            if (!Shell.test('-d', template_dir)) {
                callback("Can not find project template files: " + template_dir);
                return;
            }
            Shell.mkdir('-p', this.pkgPath);
            Shell.cp('-Rf', template_dir, this.prjPath);
            Shell.mv(Path.join(this.prjPath, 'AppShell'), project_dir);
            Shell.pushd(project_dir);
            Shell.ls (".").filter (function (file) {
                var new_file = file.replace (/AppShell/gi, project_name);
                if (file != new_file)
                    Shell.mv ('-f', file, new_file);
            });
            var xcodeproj = project_name+".xcodeproj";
            Shell.find (xcodeproj).filter (function (file) {
                if (Shell.test ('-f', file)) {
                    Shell.sed ('-i', /AppShell/gi, project_name, file);
                    Shell.mv('-f', file, file.replace (/AppShell/gi, project_name));
                }
            });

            // Replace package name in info.plist.
            var info_file = Path.join(project_dir, project_name, 'Info.plist');
            var project_name_prefix = Path.basename(this.packageId, '.' + project_name);
            if (Shell.test('-f', info_file)) {
                Shell.sed('-i', /org.crosswalk-project/gi, project_name_prefix, info_file);
            }
            Shell.popd();

            if (Shell.test('-d', this.appPath)) {
                Shell.rm('-rf', this.appPath);
            }

            Shell.mv('-f', Path.join(project_dir, 'www'), this.appPath);

            // Null means success, error string means failure.
            callback(null);
        };

    iOSProject.prototype.update =
        function(callback) {

            // TODO implement updating of project to new Crosswalk version.
            // This function is not supported yet.
            Console.log("iOSProject: Updating project has not implemented.");

            // Null means success, error string means failure.
            callback(null);
        };

    iOSProject.prototype.refresh =
        function(callback) {

            // TODO implement updating of project to new Crosswalk version.
            // Maybe this function will be not needed, and removed in the future.
            Console.log("iOSProject: Refreshing project has not implemented.");

            // Null means success, error string means failure.
            callback(null);
        };

    /**
     * Build application package.
     * @function build
     * @param {String[]} abi Array of ABIs, supported armeabi-v7a, x86.
     * @param {Boolean} release Whether to build debug or release package.
     * @param {Function} callback see {@link Project~projectOperationCb}.
     * @abstract
     * @memberOf Project
     */
    iOSProject.prototype.build =
        function(abis, release, callback) {

            var packageId = Path.basename(Shell.pwd());
            // TODO implement updating of project to new Crosswalk version.
            Console.log("iOSProject: Building project " + packageId);

            var Fs = require ('fs');

            var project_dir = this.platformPath;
            var parts = packageId.split('.');
            var project_name = parts[parts.length-1];

            if (project_name == "" || project_name == null) {
                console.log("Please provide the project name.");
                return;
            }

            Console.log('Start to update the web resources.');

            if (Shell.test('-d', Path.join(project_dir, 'www'))) {
                Shell.rm('-rf', Path.join(project_dir, 'www'));
            }

            Shell.cp('-Rf', this.appPath, project_dir);
            Shell.mv('-f', Path.join(project_dir, 'app'), Path.join(project_dir, 'www'));

            Shell.pushd(project_dir);
            var project_path = Path.join(project_dir, project_name + '.xcodeproj', 'project.pbxproj');
            var project = require ('xcode').project(project_path);
            var Manifest = require(Path.join(project_dir, 'www', 'manifest.json'));
            project.parse(function (err) {
                Fs.writeFileSync(Path.join(project_dir, 'www', 'manifest.plist'), require('plist').build(Manifest));
                // Add the real resource files.
                Shell.pushd(Path.join(project_dir, 'www'));
                // Remove the default resource files first.
                project.removeResourceFile('index.html');
                project.removeResourceFile('icon.png');
                Shell.find('.').filter(function (file) {
                    if (Shell.test('-f', file)) {
                        project.addResourceFile(file);
                    }
                });
                Shell.popd();

                Fs.writeFileSync(project_path, project.writeSync());
                Console.log('Finished update resources.');
                Console.log('Start to build ipa file.');
                var sdk = new SDK({'path': project_dir, 'id': packageId});
                if (sdk.build(['arm64', 'armv7', 'armv7s'], release)) {
                    this.exportPackage(Shell.ls(Path.join(project_dir, 'build', project_name + '*.ipa'))[0]);
                }
            }.bind(this));
            Shell.popd();
            // Null means success, error string means failure.
            callback(null);
        };
    return new iOSProject(PlatformBase, baseData);
}

module.exports = iOSPlatform;
<|endoftext|>


<commit_before>'use strict';

/**
 * Init system for Node.js, main file.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var util = require('util');
var events = require('events');
var testing = require('testing');

// globals
var EVENTS = ['first', 'start', 'stop', 'last'];

var InitSystem = function()
{
	var self = this;

	// attributes
	var inited = false;
	var started = false;
	var standaloneCallback = null;

	// init
	init();

	function init()
	{
		events.EventEmitter.call(self);
		setImmediate(function()
		{
			setTimeout(function()
			{
				reallyInit();
			}, 0);
		});
	}

	function reallyInit()
	{
		if (inited)
		{
			self.emit('warning', 'Could not init again');
			return;
		}
		inited = true;
	}
};

util.inherits(InitSystem, events.EventEmitter);
module.exports = InitSystem;

function testInitSystem(callback)
{
	testing.success(callback);
}

/**
 * Run all tests.
 */
exports.test = function(callback)
{
	testing.run([testInitSystem], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	exports.test(testing.show);
}

<commit_msg>First functional version.<commit_after>'use strict';

/**
 * Init system for Node.js, main file.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var Log = require('log');
var util = require('util');
var events = require('events');
var testing = require('testing');

// globals
var log = new Log('info');

// constants
var EVENTS = ['first', 'start', 'stop', 'last'];

var InitSystem = function()
{
	var self = this;

	// attributes
	var standaloneCallback = null;
	var flags = {};
	var callbackQueues = {};
	var initing = false;
	var finishing = false;

	// init
	init();

	function init()
	{
		EVENTS.forEach(function(event)
		{
			callbackQueues[event] = [];
			self[event] = getAdder(event);
		});
		events.EventEmitter.call(self);
		self.on('error', showError);
		setImmediate(function()
		{
			setTimeout(function()
			{
				reallyInit();
			}, 0);
		});
	}

	function getAdder(event)
	{
		return function(callback)
		{
			if (flags[event])
			{
				return self.emit('error', 'Could not add ' + event + ' to queue after it has run');
			}
			callbackQueues[event].push(callback);
		};
	}

	function showError(error)
	{
		log.error('Initialization error: %s', error);
	}

	function reallyInit()
	{
		if (initing)
		{
			self.emit('error', 'Could not init again');
			return;
		}
		initing = true;
		runAll('first', function(error)
		{
			if (error)
			{
				return self.emit('error', 'Could not run first callbacks: ' + error);
			}
			runAll('start', function(error)
			{
				if (error)
				{
					return self.emit('error', 'Could not run start callbacks: ' + error);
				}
				self.emit('ready');
				if (standaloneCallback)
				{
					runStandalone();
				}
			});
		});
	}

	function runAll(event, callback)
	{
		if (flags[event])
		{
			return callback('Callbacks for ' + event + ' already run');
		}
		runQueue(callbackQueues[event], function(error)
		{
			if (error)
			{
				return callback(error);
			}
			flags[event] = true;
			return callback(null);
		});
	}

	function runQueue(queue, callback)
	{
		if (!queue.length)
		{
			return callback(null);
		}
		var next = queue.shift();
		next(callback);
	}

	function runStandalone()
	{
		standaloneCallback(function(error)
		{
			if (error)
			{
				if (error)
				{
					return self.emit('error', 'Could not run start callbacks: ' + error);
				}
			}
		});
	}

	self.finish = function()
	{
		if (finishing)
		{
			return self.emit('error', 'Could not finish again');
		}
		finishing = true;
		runAll('stop', function(error)
		{
			if (error)
			{
				return self.emit('error', 'Could not run stop callbacks: ' + error);
			}
			runAll('last', function(error)
			{
				if (error)
				{
					return self.emit('error', 'Could not run last callbacks: ' + error);
				}
				self.emit('end');
			});
		});
	};
};

util.inherits(InitSystem, events.EventEmitter);
module.exports = InitSystem;

function testInitSystem(callback)
{
	var system = new InitSystem();
	system.on('error', function(error)
	{
		console.trace('here');
		testing.failure(error, callback);
	});
	system.first(function(next)
	{
		log.debug('first');
		next(null);
	});
	system.start(function(next)
	{
		log.debug('start');
		system.finish();
		next(null);
	});
	system.stop(function(next)
	{
		log.debug('stop');
		next(null);
	});
	system.last(function(next)
	{
		log.debug('last');
		next(null);
	});
	system.on('started', function()
	{
		system.finish();
	});
	system.on('end', function()
	{
		testing.success(callback);
	});
}

/**
 * Run all tests.
 */
exports.test = function(callback)
{
	testing.run([testInitSystem], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	exports.test(testing.show);
}

<|endoftext|>


<commit_before>'use babel'

import { readFile, realpath } from 'fs'
import { renderToString } from 'katex'

// Asynchronously load the resource specified by `url` into Atom.
export function loadResource (url) {
  realpath(url, (err, url) => {
    if (err) return
    readFile(url, (err, css) => {
      if (err) return
      let style = document.createElement('style')
      style.setAttribute('source-path', url)
      style.setAttribute('priority', 0)
      style.innerText = css
      let headScript = document.querySelector('atom-styles')
      headScript.appendChild(style)
    })
  })
}

function htmlDecode (input) {
  let txt = document.createElement("textarea")
  txt.innerHTML = input
  return txt.value
}

export function texify (input) {
  htmlDecoded = htmlDecode(input)
  if (!htmlDecoded) return input
  return htmlDecoded.replace(/\$.*?\$/g, (substr) => {
    substr = substr.substring(1, substr.length-1)
    let r = renderToString(substr, {throwOnError: false})
    return r
  })
}
<commit_msg>adjust regex<commit_after>'use babel'

import { readFile, realpath } from 'fs'
import { renderToString } from 'katex'

// Asynchronously load the resource specified by `url` into Atom.
export function loadResource (url) {
  realpath(url, (err, url) => {
    if (err) return
    readFile(url, (err, css) => {
      if (err) return
      let style = document.createElement('style')
      style.setAttribute('source-path', url)
      style.setAttribute('priority', 0)
      style.innerText = css
      let headScript = document.querySelector('atom-styles')
      headScript.appendChild(style)
    })
  })
}

function htmlDecode (input) {
  let txt = document.createElement("textarea")
  txt.innerHTML = input
  return txt.value
}

export function texify (input) {
  htmlDecoded = htmlDecode(input)
  if (!htmlDecoded) return input
  // This is pretty ... bad. Should properly handle HTML tags etc...
  return htmlDecoded.replace(/(\$.*?\$|``.*?``)/g, (substr) => {
    substr = substr.substring(1, substr.length-1)
    let r = renderToString(substr, {throwOnError: false})
    return r
  })
}
<|endoftext|>


<commit_before>/**
 * Module to loosely coupled shell execution.
 * @module kbox.util.shell
 */

'use strict';

// Node modules
var spawn = require('child_process').spawn;
var path = require('path');
var fs = require('fs-extra');

// npm modules
var _ = require('lodash');
var _shell = require('shelljs');
var windows = require('node-windows');
var esc = require('shell-escape');
var VError = require('verror');

// Kalabox modules
var core = require('../core.js');
var Promise = require('../promise.js');

/*
 * Helper method to get a GUI admin wrapper
 */
var getGuiAdminWrapper = function(cmdString) {

  /*
   * Helper for applescript wrapper
   */
  var asWrap = function(cmdString) {
    var scriptPath = path.join(__dirname, 'applescript', 'runAsApp.scpt');
    console.log(scriptPath);
    return [
      'osascript',
      scriptPath,
      '\'' + cmdString.replace(/\"/g, '\\"') + '\''
    ].join(' ');
  };

  // Return path based on platform
  switch (process.platform) {
    case 'win32': return cmdString;
    //@todo: Does this work on fedora?
    case 'linux': return esc([
        'pkexec',
        '--user',
        'root',
        'sudo',
        'sh',
        '-c',
        cmdString
      ]);
    case 'darwin': return asWrap(cmdString);
  }

};

/*
 * Helper method to get a CLI admin wrapper
 */
var getCliAdminWrapper = function(cmdString, opts) {

  // Cli wrapper for POSIX
  if (process.platform !== 'win32') {

    /*
     * Helper to run sudo with a password if that
     * password is provided as options.password
     */
    if (opts && opts.password) {
      return esc([
        'echo',
        opts.password,
        '|',
        'sudo',
        '-S',
        'sh',
        '-c',
        cmdString
      ]);
    }

    // Else just normal sudo
    return esc(['sudo', 'sh', '-c', cmdString]);

  }

  // Otherwise return the command as is
  return cmdString;

};

/*
 * Helper to wrap a command with needed things to run as an admin
 */
var getAdminWrapper = function(cmds, options) {

  // Join cmds if needed
  if (_.isArray(cmds)) {
    cmds = cmds.join(' && ');
  }

  // Return the delegated wrapper based on the mode
  switch (core.deps.get('mode')) {
    case 'cli': return getCliAdminWrapper(cmds, options);
    case 'gui': return getGuiAdminWrapper(cmds);
  }

};

/**
 * Executes a shell command.
 * @arg {string|array} cmd - The shell command to run or an array of commands.
 * @arg {object} opts - Options
 * @example
 * return kbox.util.shell.exec(cmd, opts)
 * .then(function(output) {
 *   // things
 * });
 */
var exec = exports.exec = function(cmd, opts) {

  // Merge in our options
  var defaults = {silent: true};
  var options = (opts) ? _.extend(defaults, opts) : defaults;

  // Logging functions.
  var execLog = core.log.make('UTIL EXEC');
  execLog.debug(cmd, opts);

  // Promisify the exec
  return new Promise(function(resolve, reject) {
    _shell.exec(esc(cmd), options, function(code, output) {
      if (code !== 0) {
        reject(new VError('code: ' + code + 'err:' + output));
      }
      else {
        resolve(output);
      }
    });
  });

};

/**
 * Executes a shell command.
 * @arg {string} cmd - The shell command to run.
 * @example
 * var child = kbox.util.shell.execAsync(cmd);
 * child.stdout.on('data', function(data) {
 *   console.log(data);
 * });
 * child.stdout.on('end', function() {
 *   callback();
 * });
 */
var execAsync = exports.execAsync = function(cmd) {

  // Promisify exec
  return new Promise(function(resolve, reject) {

    // Logging functions.
    var execLog = core.log.make('UTIL EXEC ADMIN');
    execLog.debug(cmd);

    // Use stdio options and then create the child
    var child = _shell.exec(cmd, {async:true, silent:true});

    // Collector for buffer
    var stdOut = '';
    var stdErr = '';

    // Log our stuff
    child.stdout.on('data', function(buffer) {
      execLog.info(_.trim(String(buffer)));
      stdOut = stdOut + String(buffer);
    });

    // Reject if we get an error
    child.stderr.on('data', function(buffer) {
      execLog.debug(_.trim(String(buffer)));
      stdErr = stdErr + String(buffer);
    });

    // Callback when done
    child.on('close', function(code) {
      if (code !== 0) {
        reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
      }
      else {
        resolve(stdOut);
      }
    });

  });

};

/**
 * Spawns a shell command. And optionally collects things
 * @arg {array} cmd - An array of commands. Split by spaces.
 * @arg {object} opts - Options on what to do
 * @example
 * return kbox.util.shell.execAdminAsync(cmd, opts)
 * .then(function(output) {
 *   // things
 * });
 */
exports.spawn = function(cmd, opts) {

  // Promisify the spawn
  return new Promise(function(resolve, reject) {

    // Merge provided options with defaults
    var defaults = {stdio: ['pipe', 'pipe', 'pipe']};
    var options = (opts) ? _.extend(defaults, opts) : defaults;

    // Use stdio options and then create the child
    var entrypoint = cmd.shift();

    // Run the spawn
    var run = spawn(entrypoint, cmd, options);

    // Set of logging functions.
    var spawnLog = core.log.make(path.basename(entrypoint).toUpperCase());
    spawnLog.debug([entrypoint, cmd, options]);

    // Collector for buffer
    var stdOut = '';
    var stdErr = '';

    // Collect data if stdout is being piped
    if (options.stdio === 'pipe' || options.stdio[1] === 'pipe') {
      run.stdout.on('data', function(buffer) {
        spawnLog.info(_.trim(String(buffer)));
        stdOut = stdOut + String(buffer);
      });
    }

    // Reject if we get an error
    run.on('error', function(buffer) {
      spawnLog.info(_.trim(String(buffer)));
      stdErr = stdErr + String(buffer);
    });

    // Callback when done
    run.on('close', function(code) {
      spawnLog.info('Run exited with code: ' + code);
      if (code !== 0) {
        reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
      }
      else {
        resolve(stdOut);
      }
    });

  });
};

/**
 * Asynchroniously Executes command(s) that requires admin permissions
 * @arg {string|array} commands - The shell command or an array of commands to run.
 * @arg {object} opts - Options to pass in
 * @example
 * var child = kbox.util.shell.execAdminAsync(cmds, opts);
 * child.stdout.on('data', function(data) {
 *   console.log(data);
 * });
 * child.stdout.on('end', function() {
 *   callback();
 * });
 */
exports.execAdminAsync = function(cmds, opts) {
  return execAsync(getAdminWrapper(cmds, opts));
};

/**
 * Executes commands that requires admin permissions
 * @arg {string|array} commands - The shell command or an array of commands to run.
 * @arg {object} opts - Options to pass in
 * @example
 * return kbox.util.shell.execAdmin(cmd)
 * .then(function(data){
 *   if (data === 'whatimlookingfor') {
 *     return true;
 *   }
 * });
 */
exports.execAdmin = function(cmds, opts) {
  return exec(getAdminWrapper(cmds), opts);
};

/**
 * Executes an elevated command on windows
 * @arg {string} command - The command to run.
 * @example
 * var cmd = 'netsh interface ipv4 set address name="' + adapter + '" ' +
        'static ' + ip + ' store=persistent';
 * return kbox.util.shell.execElevated(cmd)
 * .then(function(data) {
 *   return data;
 * });
 */
exports.execElevated = function(cmd) {
  return Promise.fromNode(function(callback) {
    var elevateLog = core.log.make('WIN ELEVATED');
    elevateLog.info(cmd);
    windows.elevate(cmd, {}, callback);
  });
};

/**
 * Escapes the spaces in an array or string into a string to make it more CLI friendly
 * @arg {string|array} command - The command to run.
 */
exports.escSpaces = function(s, platform) {

  var p = platform || process.platform;

  if (_.isArray(s)) {
    s = s.join(' ');
  }
  if (p === 'win32') {
    return s.replace(/ /g, '^ ');
  }
  else {
    return s.replace(/ /g, '\ ');
  }
};

/**
 * Escapes an array or string into a string to make it more CLI friendly
 * @arg {string|array} command - The command to run.
 */
exports.esc = esc;

/**
 * Do a which
 */
exports.which = _shell.which;
<commit_msg>#991: Fix silly jshint warning.<commit_after>/**
 * Module to loosely coupled shell execution.
 * @module kbox.util.shell
 */

'use strict';

// Node modules
var spawn = require('child_process').spawn;
var path = require('path');

// npm modules
var _ = require('lodash');
var _shell = require('shelljs');
var windows = require('node-windows');
var esc = require('shell-escape');
var VError = require('verror');

// Kalabox modules
var core = require('../core.js');
var Promise = require('../promise.js');

/*
 * Helper method to get a GUI admin wrapper
 */
var getGuiAdminWrapper = function(cmdString) {

  /*
   * Helper for applescript wrapper
   */
  var asWrap = function(cmdString) {
    var scriptPath = path.join(__dirname, 'applescript', 'runAsApp.scpt');
    console.log(scriptPath);
    return [
      'osascript',
      scriptPath,
      '\'' + cmdString.replace(/\"/g, '\\"') + '\''
    ].join(' ');
  };

  // Return path based on platform
  switch (process.platform) {
    case 'win32': return cmdString;
    //@todo: Does this work on fedora?
    case 'linux': return esc([
        'pkexec',
        '--user',
        'root',
        'sudo',
        'sh',
        '-c',
        cmdString
      ]);
    case 'darwin': return asWrap(cmdString);
  }

};

/*
 * Helper method to get a CLI admin wrapper
 */
var getCliAdminWrapper = function(cmdString, opts) {

  // Cli wrapper for POSIX
  if (process.platform !== 'win32') {

    /*
     * Helper to run sudo with a password if that
     * password is provided as options.password
     */
    if (opts && opts.password) {
      return esc([
        'echo',
        opts.password,
        '|',
        'sudo',
        '-S',
        'sh',
        '-c',
        cmdString
      ]);
    }

    // Else just normal sudo
    return esc(['sudo', 'sh', '-c', cmdString]);

  }

  // Otherwise return the command as is
  return cmdString;

};

/*
 * Helper to wrap a command with needed things to run as an admin
 */
var getAdminWrapper = function(cmds, options) {

  // Join cmds if needed
  if (_.isArray(cmds)) {
    cmds = cmds.join(' && ');
  }

  // Return the delegated wrapper based on the mode
  switch (core.deps.get('mode')) {
    case 'cli': return getCliAdminWrapper(cmds, options);
    case 'gui': return getGuiAdminWrapper(cmds);
  }

};

/**
 * Executes a shell command.
 * @arg {string|array} cmd - The shell command to run or an array of commands.
 * @arg {object} opts - Options
 * @example
 * return kbox.util.shell.exec(cmd, opts)
 * .then(function(output) {
 *   // things
 * });
 */
var exec = exports.exec = function(cmd, opts) {

  // Merge in our options
  var defaults = {silent: true};
  var options = (opts) ? _.extend(defaults, opts) : defaults;

  // Logging functions.
  var execLog = core.log.make('UTIL EXEC');
  execLog.debug(cmd, opts);

  // Promisify the exec
  return new Promise(function(resolve, reject) {
    _shell.exec(esc(cmd), options, function(code, output) {
      if (code !== 0) {
        reject(new VError('code: ' + code + 'err:' + output));
      }
      else {
        resolve(output);
      }
    });
  });

};

/**
 * Executes a shell command.
 * @arg {string} cmd - The shell command to run.
 * @example
 * var child = kbox.util.shell.execAsync(cmd);
 * child.stdout.on('data', function(data) {
 *   console.log(data);
 * });
 * child.stdout.on('end', function() {
 *   callback();
 * });
 */
var execAsync = exports.execAsync = function(cmd) {

  // Promisify exec
  return new Promise(function(resolve, reject) {

    // Logging functions.
    var execLog = core.log.make('UTIL EXEC ADMIN');
    execLog.debug(cmd);

    // Use stdio options and then create the child
    var child = _shell.exec(cmd, {async:true, silent:true});

    // Collector for buffer
    var stdOut = '';
    var stdErr = '';

    // Log our stuff
    child.stdout.on('data', function(buffer) {
      execLog.info(_.trim(String(buffer)));
      stdOut = stdOut + String(buffer);
    });

    // Reject if we get an error
    child.stderr.on('data', function(buffer) {
      execLog.debug(_.trim(String(buffer)));
      stdErr = stdErr + String(buffer);
    });

    // Callback when done
    child.on('close', function(code) {
      if (code !== 0) {
        reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
      }
      else {
        resolve(stdOut);
      }
    });

  });

};

/**
 * Spawns a shell command. And optionally collects things
 * @arg {array} cmd - An array of commands. Split by spaces.
 * @arg {object} opts - Options on what to do
 * @example
 * return kbox.util.shell.execAdminAsync(cmd, opts)
 * .then(function(output) {
 *   // things
 * });
 */
exports.spawn = function(cmd, opts) {

  // Promisify the spawn
  return new Promise(function(resolve, reject) {

    // Merge provided options with defaults
    var defaults = {stdio: ['pipe', 'pipe', 'pipe']};
    var options = (opts) ? _.extend(defaults, opts) : defaults;

    // Use stdio options and then create the child
    var entrypoint = cmd.shift();

    // Run the spawn
    var run = spawn(entrypoint, cmd, options);

    // Set of logging functions.
    var spawnLog = core.log.make(path.basename(entrypoint).toUpperCase());
    spawnLog.debug([entrypoint, cmd, options]);

    // Collector for buffer
    var stdOut = '';
    var stdErr = '';

    // Collect data if stdout is being piped
    if (options.stdio === 'pipe' || options.stdio[1] === 'pipe') {
      run.stdout.on('data', function(buffer) {
        spawnLog.info(_.trim(String(buffer)));
        stdOut = stdOut + String(buffer);
      });
    }

    // Reject if we get an error
    run.on('error', function(buffer) {
      spawnLog.info(_.trim(String(buffer)));
      stdErr = stdErr + String(buffer);
    });

    // Callback when done
    run.on('close', function(code) {
      spawnLog.info('Run exited with code: ' + code);
      if (code !== 0) {
        reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
      }
      else {
        resolve(stdOut);
      }
    });

  });
};

/**
 * Asynchroniously Executes command(s) that requires admin permissions
 * @arg {string|array} commands - The shell command or an array of commands to run.
 * @arg {object} opts - Options to pass in
 * @example
 * var child = kbox.util.shell.execAdminAsync(cmds, opts);
 * child.stdout.on('data', function(data) {
 *   console.log(data);
 * });
 * child.stdout.on('end', function() {
 *   callback();
 * });
 */
exports.execAdminAsync = function(cmds, opts) {
  return execAsync(getAdminWrapper(cmds, opts));
};

/**
 * Executes commands that requires admin permissions
 * @arg {string|array} commands - The shell command or an array of commands to run.
 * @arg {object} opts - Options to pass in
 * @example
 * return kbox.util.shell.execAdmin(cmd)
 * .then(function(data){
 *   if (data === 'whatimlookingfor') {
 *     return true;
 *   }
 * });
 */
exports.execAdmin = function(cmds, opts) {
  return exec(getAdminWrapper(cmds), opts);
};

/**
 * Executes an elevated command on windows
 * @arg {string} command - The command to run.
 * @example
 * var cmd = 'netsh interface ipv4 set address name="' + adapter + '" ' +
        'static ' + ip + ' store=persistent';
 * return kbox.util.shell.execElevated(cmd)
 * .then(function(data) {
 *   return data;
 * });
 */
exports.execElevated = function(cmd) {
  return Promise.fromNode(function(callback) {
    var elevateLog = core.log.make('WIN ELEVATED');
    elevateLog.info(cmd);
    windows.elevate(cmd, {}, callback);
  });
};

/**
 * Escapes the spaces in an array or string into a string to make it more CLI friendly
 * @arg {string|array} command - The command to run.
 */
exports.escSpaces = function(s, platform) {

  var p = platform || process.platform;

  if (_.isArray(s)) {
    s = s.join(' ');
  }
  if (p === 'win32') {
    return s.replace(/ /g, '^ ');
  }
  else {
    return s.replace(/ /g, '\ ');
  }
};

/**
 * Escapes an array or string into a string to make it more CLI friendly
 * @arg {string|array} command - The command to run.
 */
exports.esc = esc;

/**
 * Do a which
 */
exports.which = _shell.which;
<|endoftext|>


<commit_before>
/*!
 * Jade - Lexer
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Initialize `Lexer` with the given `str`.
 *
 * @param {String} str
 * @api private
 */

var Lexer = module.exports = function Lexer(str) {
    this.input = str.replace(/\r\n|\r/g, '\n').replace(/\t/g, '  ');
    this.deferredTokens = [];
    this.lastIndents = 0;
    this.lineno = 1;
};

/**
 * Lexer prototype.
 */

Lexer.prototype = {

    /**
     * Construct a token with the given `type` `line` and `val`.
     *
     * @param {String} type
     * @param {String} val
     * @param {Number} line
     * @return {Object}
     * @api private
     */

    tok: function(type, val, line){
        return {
            type: type,
            line: line === undefined ? this.lineno : line,
            val: val
        }
    },

    /**
     * Consume the given `len` of input.
     *
     * @param {Number} len
     * @api private
     */

    consume: function(len){
        this.input = this.input.substr(len);
    },

    /**
     * Scan for `type` with the given `regexp`.
     *
     * @param {String} type
     * @param {RegExp} regexp
     * @return {Object}
     * @api private
     */

    scan: function(regexp, type){
        var captures;
        if (captures = regexp.exec(this.input)) {
            this.consume(captures[0].length);
            return this.tok(type, captures[1]);
        }
    },

    /**
     * Single token lookahead.
     *
     * @return {Object}
     * @api private
     */

    get peek(){
        return this.stash = this.advance;
    },

    /**
     * Stashed token.
     */

    get stashed() {
        if (!this.stash) return;
        var tok = this.stash;
        delete this.stash;
        return tok;
    },

    /**
     * Deferred token.
     */

    get deferred() {
        if (!this.deferredTokens.length) return;
        return this.deferredTokens.shift();
    },

    /**
     * end-of-source.
     */

    get eos() {
        if (this.input.length) return;
        return this.lastIndents-- > 0
            ? this.tok('outdent')
            : this.tok('eos');
    },

    /**
     * Comment.
     */

    get comment() {
        var captures;
        if (captures = /^ *\/\/(-)?([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('comment', captures[2]);
            tok.buffer = captures[1] !== '-';
            return tok;
        }
    },

    /**
     * Tag.
     */

    get tag() {
        return this.scan(/^(\w[:-\w]*)/, 'tag');
    },

    /**
     * Filter.
     */

    get filter() {
        return this.scan(/^:(\w+)/, 'filter');
    },

    /**
     * Doctype.
     */

    get doctype() {
        return this.scan(/^!!! *(\w+)?/, 'doctype');
    },

    /**
     * Id.
     */

    get id() {
        return this.scan(/^#([\w-]+)/, 'id');
    },

    /**
     * Class.
     */

    get className() {
        return this.scan(/^\.([\w-]+)/, 'class');
    },

    /**
     * Text.
     */

    get text() {
        return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
    },

    /**
     * Each.
     */

    get each() {
        var captures;
        if (captures = /^- *each *(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('each', captures[1]);
            tok.key = captures[2] || 'index';
            tok.code = captures[3];
            return tok;
        }
    },

    /**
     * Code.
     */

    get code() {
        var captures;
        if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var flags = captures[1];
            captures[1] = captures[2];
            var tok = this.tok('code', captures[1]);
            tok.escape = flags[0] === '=';
            tok.buffer = flags[0] === '=' || flags[1] === '=';
            return tok;
        }
    },

    /**
     * Attributes.
     */

    get attrs() {
        var captures;
        if (captures = /^\((.+)\)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('attrs', captures[1]),
                attrs = tok.val.split(/ *, *(?=[\w-]+ *[:=]|[\w-]+ *$)/);
            tok.attrs = {};
            for (var i = 0, len = attrs.length; i < len; ++i) {
                var pair = attrs[i];

                // Support = and :
                var colon = pair.indexOf(':'),
                    equal = pair.indexOf('=');

                // Boolean
                if (colon < 0 && equal < 0) {
                    var key = pair,
                        val = true;
                } else {
                    // Split on first = or :
                    var split = equal >= 0
                        ? equal
                        : colon;
                    if (colon >= 0 && colon < equal) split = colon;
                    var key = pair.substr(0, split),
                        val = pair.substr(++split, pair.length);
                }
                tok.attrs[key.trim().replace(/^['"]|['"]$/g, '')] = val;
            }
            return tok;
        }
    },

    /**
     * Indent.
     */

    get indent() {
        var captures;
        if (captures = /^\n( *)/.exec(this.input)) {
            ++this.lineno;
            this.consume(captures[0].length);
            var tok = this.tok('indent', captures[1]),
                indents = tok.val.length / 2;
            if (this.input[0] === '\n') {
                tok.type = 'newline';
                return tok;
            } else if (indents % 1 !== 0) {
                throw new Error('Invalid indentation, got '
                    + tok.val.length + ' space'
                    + (tok.val.length > 1 ? 's' : '')
                    + ', must be a multiple of two.');
            } else if (indents === this.lastIndents) {
                tok.type = 'newline';
            } else if (indents > this.lastIndents + 1) {
                throw new Error('Invalid indentation, got '
                    + indents + ' expected '
                    + (this.lastIndents + 1) + '.');
            } else if (indents < this.lastIndents) {
                var n = this.lastIndents - indents;
                tok.type = 'outdent';
                while (--n) {
                    this.deferredTokens.push({
                        type: 'outdent',
                        line: this.lineno
                    });
                }
            }
            this.lastIndents = indents;
            return tok;
        }
    },

    /**
     * Return the next token object.
     *
     * @return {Object}
     * @api private
     */

    get advance(){
        return this.stashed
            || this.deferred
            || this.eos
            || this.comment
            || this.tag
            || this.filter
            || this.each
            || this.code
            || this.doctype
            || this.id
            || this.className
            || this.attrs
            || this.indent
            || this.text;
    }
};
<commit_msg>Added Lexer#defer()<commit_after>
/*!
 * Jade - Lexer
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Initialize `Lexer` with the given `str`.
 *
 * @param {String} str
 * @api private
 */

var Lexer = module.exports = function Lexer(str) {
    this.input = str.replace(/\r\n|\r/g, '\n').replace(/\t/g, '  ');
    this.deferredTokens = [];
    this.lastIndents = 0;
    this.lineno = 1;
};

/**
 * Lexer prototype.
 */

Lexer.prototype = {

    /**
     * Construct a token with the given `type` `line` and `val`.
     *
     * @param {String} type
     * @param {String} val
     * @param {Number} line
     * @return {Object}
     * @api private
     */

    tok: function(type, val, line){
        return {
            type: type,
            line: line === undefined ? this.lineno : line,
            val: val
        }
    },

    /**
     * Consume the given `len` of input.
     *
     * @param {Number} len
     * @api private
     */

    consume: function(len){
        this.input = this.input.substr(len);
    },

    /**
     * Scan for `type` with the given `regexp`.
     *
     * @param {String} type
     * @param {RegExp} regexp
     * @return {Object}
     * @api private
     */

    scan: function(regexp, type){
        var captures;
        if (captures = regexp.exec(this.input)) {
            this.consume(captures[0].length);
            return this.tok(type, captures[1]);
        }
    },

    /**
     * Defer the given `tok`.
     *
     * @param {Object} tok
     * @api private
     */

    defer: function(tok){
        this.deferredTokens.push(tok);
    },

    /**
     * Single token lookahead.
     *
     * @return {Object}
     * @api private
     */

    get peek(){
        return this.stash = this.advance;
    },

    /**
     * Stashed token.
     */

    get stashed() {
        if (!this.stash) return;
        var tok = this.stash;
        delete this.stash;
        return tok;
    },

    /**
     * Deferred token.
     */

    get deferred() {
        if (!this.deferredTokens.length) return;
        return this.deferredTokens.shift();
    },

    /**
     * end-of-source.
     */

    get eos() {
        if (this.input.length) return;
        return this.lastIndents-- > 0
            ? this.tok('outdent')
            : this.tok('eos');
    },

    /**
     * Comment.
     */

    get comment() {
        var captures;
        if (captures = /^ *\/\/(-)?([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('comment', captures[2]);
            tok.buffer = captures[1] !== '-';
            return tok;
        }
    },

    /**
     * Tag.
     */

    get tag() {
        return this.scan(/^(\w[:-\w]*)/, 'tag');
    },

    /**
     * Filter.
     */

    get filter() {
        return this.scan(/^:(\w+)/, 'filter');
    },

    /**
     * Doctype.
     */

    get doctype() {
        return this.scan(/^!!! *(\w+)?/, 'doctype');
    },

    /**
     * Id.
     */

    get id() {
        return this.scan(/^#([\w-]+)/, 'id');
    },

    /**
     * Class.
     */

    get className() {
        return this.scan(/^\.([\w-]+)/, 'class');
    },

    /**
     * Text.
     */

    get text() {
        return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
    },

    /**
     * Each.
     */

    get each() {
        var captures;
        if (captures = /^- *each *(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('each', captures[1]);
            tok.key = captures[2] || 'index';
            tok.code = captures[3];
            return tok;
        }
    },

    /**
     * Code.
     */

    get code() {
        var captures;
        if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
            this.consume(captures[0].length);
            var flags = captures[1];
            captures[1] = captures[2];
            var tok = this.tok('code', captures[1]);
            tok.escape = flags[0] === '=';
            tok.buffer = flags[0] === '=' || flags[1] === '=';
            return tok;
        }
    },

    /**
     * Attributes.
     */

    get attrs() {
        var captures;
        if (captures = /^\((.+)\)/.exec(this.input)) {
            this.consume(captures[0].length);
            var tok = this.tok('attrs', captures[1]),
                attrs = tok.val.split(/ *, *(?=[\w-]+ *[:=]|[\w-]+ *$)/);
            tok.attrs = {};
            for (var i = 0, len = attrs.length; i < len; ++i) {
                var pair = attrs[i];

                // Support = and :
                var colon = pair.indexOf(':'),
                    equal = pair.indexOf('=');

                // Boolean
                if (colon < 0 && equal < 0) {
                    var key = pair,
                        val = true;
                } else {
                    // Split on first = or :
                    var split = equal >= 0
                        ? equal
                        : colon;
                    if (colon >= 0 && colon < equal) split = colon;
                    var key = pair.substr(0, split),
                        val = pair.substr(++split, pair.length);
                }
                tok.attrs[key.trim().replace(/^['"]|['"]$/g, '')] = val;
            }
            return tok;
        }
    },

    /**
     * Indent.
     */

    get indent() {
        var captures;
        if (captures = /^\n( *)/.exec(this.input)) {
            ++this.lineno;
            this.consume(captures[0].length);
            var tok = this.tok('indent', captures[1]),
                indents = tok.val.length / 2;
            if (this.input[0] === '\n') {
                tok.type = 'newline';
                return tok;
            } else if (indents % 1 !== 0) {
                throw new Error('Invalid indentation, got '
                    + tok.val.length + ' space'
                    + (tok.val.length > 1 ? 's' : '')
                    + ', must be a multiple of two.');
            } else if (indents === this.lastIndents) {
                tok.type = 'newline';
            } else if (indents > this.lastIndents + 1) {
                throw new Error('Invalid indentation, got '
                    + indents + ' expected '
                    + (this.lastIndents + 1) + '.');
            } else if (indents < this.lastIndents) {
                var n = this.lastIndents - indents;
                tok.type = 'outdent';
                while (--n) {
                    this.defer(this.tok('outdent'));
                }
            }
            this.lastIndents = indents;
            return tok;
        }
    },

    /**
     * Return the next token object.
     *
     * @return {Object}
     * @api private
     */

    get advance(){
        return this.stashed
            || this.deferred
            || this.eos
            || this.comment
            || this.tag
            || this.filter
            || this.each
            || this.code
            || this.doctype
            || this.id
            || this.className
            || this.attrs
            || this.indent
            || this.text;
    }
};
<|endoftext|>


<commit_before>var moment = require('moment');
var Jobs = require('../models/jobs_model');
var User = require('../models/user_model');
var JobsQueue = require('../models/jobQueue_model');
var config = require('../config');
var twilio = require('twilio');
var client = twilio(config.accountSid, config.authToken);

exports.checkJobs = function() {
  var jobStream = Jobs.find().stream();
  jobStream.on('data', function(job) {
    addToQueue(job);
    console.log(moment(job.jobDate).utc().format());
  });
};

exports.checkQueue = function() {
  var queueStream = JobsQueue.find().stream();
  queueStream.on('data', function(job) {
    sendToTwilio(job);
  });
};

function addToQueue(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(1, 'days').utc().format();
  // if the job date is within the next 24 hrs, add to Queue
  if (moment(jobDate).isBefore(moment(later))) {
    //look for Concierge
    var newConcierge;
    User.findOneRandom({concierge: true}, {conciergeAvailable: true}, function(err, result) {
      if (err) return console.log('could not match with Concierge: ' + err);
      console.log('matched concierge with this user: ' + result);
      newConcierge = result;
      var newQueue = new JobsQueue({
        jobDate: job.jobDate,
        parent: job.parent,
        parentName: {
          first: job.parentName.first,
          last: job.parentName.last
        },
        parentNumber: job.parentNumber,
        optionsList: job.optionsList,
        recurring: job.recurring,
        pickedConcierge: newConcierge._id
      });
      newQueue.save(function(err, data) {
        if (err) return console.log('error saving job to Queue');
        console.log('newQueue job id: ' + data._id);
        console.log('saved job to queue');
        console.log('The concierge users id is: ' + newConcierge._id);
        User.findById(newConcierge._id, function(err, user) {
          if (err) return console.log('error finding concierge: ' + err);
          if (user === null) return console.log('user is null');
          user.conciergeJobs.push(data._id);
          user.save(function(err, data) {
            console.log('added Queued Job to Concierges Job array.');
          });
        });
      });
    });
    // if recurring job, add 1 day to the jobs current date.
    if (job.recurring === true) {
      var newJobDate = moment(job.jobDate).add(1, 'days').utc().format();
      var tempJob = job;
      job.jobDate = newJobDate;
      job = job.toObject();
      delete job._id;
      Jobs.findOneAndUpdate({'_id': tempJob._id}, job, function(err, date) {
        if (err) return console.log('error updating recurring job in db: ' + err);
        console.log('successfully updated job: ' + tempJob._id);
      });
    }
    // if not recurring, remove the job from the Jobs database.
    else {
      Jobs.remove({'_id': job._id}, function(err) {
        if (err) return console.log('unable to remove job: ' + job._id);
      });
    }
  }
}

function sendToTwilio(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(5, 'minutes').utc().format();
  // if the job date is within the next 5 minutes, send to Twilio
  if (moment(jobDate).isBefore(moment(later))) {
    client.makeCall({
            to: '3607393580',
            from: config.twilioNumber,
            url: process.env.URL + '/outbound/' + job.parentName.first + '/' + job.parentName.last + '/' + job.parentNumber + '/'
        }, function(err, message) {
          console.log(err);
          if (err) {
            console.log('error making a call: ' + err);
          } else {
            console.log('call successfully made!');
          }
        });
    JobsQueue.remove({'_id': job._id}, function(err) {
      if (err) return console.log('unable to remove job from Queue: ' + job._id);
    });
  }
}
<commit_msg>concierge wip<commit_after>var moment = require('moment');
var Jobs = require('../models/jobs_model');
var User = require('../models/user_model');
var JobsQueue = require('../models/jobQueue_model');
var config = require('../config');
var twilio = require('twilio');
var client = twilio(config.accountSid, config.authToken);

exports.checkJobs = function() {
  var jobStream = Jobs.find().stream();
  jobStream.on('data', function(job) {
    addToQueue(job);
    console.log(moment(job.jobDate).utc().format());
  });
};

exports.checkQueue = function() {
  var queueStream = JobsQueue.find().stream();
  queueStream.on('data', function(job) {
    sendToTwilio(job);
  });
};

function addToQueue(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(1, 'days').utc().format();
  // if the job date is within the next 24 hrs, add to Queue
  if (moment(jobDate).isBefore(moment(later))) {
    //look for Concierge
    var newConcierge;
    User.findOneRandom({concierge: true}, {conciergeAvailable: true}, function(err, result) {
      if (err) return console.log('could not match with Concierge: ' + err);
      console.log('matched concierge with this user: ' + result);
      newConcierge = result;
      var newQueue = new JobsQueue({
        jobDate: job.jobDate,
        parent: job.parent,
        parentName: {
          first: job.parentName.first,
          last: job.parentName.last
        },
        parentNumber: job.parentNumber,
        optionsList: job.optionsList,
        recurring: job.recurring,
        pickedConcierge: newConcierge._id
      });
      newQueue.save(function(err, data) {
        if (err) return console.log('error saving job to Queue');
        console.log('newQueue job id: ' + data._id);
        console.log('saved job to queue');
        console.log('The concierge users id is: ' + newConcierge._id);
        User.findById(newConcierge._id, function(err, user) {
          if (err) return console.log('error finding concierge: ' + err);
          if (user === null) return console.log('user is null');
          user.conciergeJobs.push(data._id);
          user.save(function(err, data) {
            console.log('added Queued Job to Concierges Job array.');
          });
        });
      });
    });
    // if recurring job, add 1 day to the jobs current date.
    if (job.recurring === true) {
      var newJobDate = moment(job.jobDate).add(1, 'days').utc().format();
      var tempJob = job;
      job.jobDate = newJobDate;
      job = job.toObject();
      delete job._id;
      Jobs.findOneAndUpdate({'_id': tempJob._id}, job, function(err, date) {
        if (err) return console.log('error updating recurring job in db: ' + err);
        console.log('successfully updated job: ' + tempJob._id);
      });
    }
    // if not recurring, remove the job from the Jobs database.
    else {
      Jobs.remove({'_id': job._id}, function(err) {
        if (err) return console.log('unable to remove job: ' + job._id);
      });
    }
  }
}

function sendToTwilio(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(5, 'minutes').utc().format();
  // if the job date is within the next 5 minutes, send to Twilio
  if (moment(jobDate).isBefore(moment(later))) {
    User.findById(job.pickedConcierge, function(err, concierge) {
      if (err) return console.log('error finding picked concierge before call.');
      if (concierge === null) return console.log('concierge is null when finding before call.');
      client.makeCall({
              to: concierge.phone,
              from: config.twilioNumber,
              url: process.env.URL + '/outbound/' + job.parentName.first + '/' + job.parentName.last + '/' + job.parentNumber + '/'
          }, function(err, message) {
            console.log(err);
            if (err) {
              console.log('error making a call: ' + err);
            } else {
              console.log('call successfully made!');
            }
      });
    });

    JobsQueue.remove({'_id': job._id}, function(err) {
      if (err) return console.log('unable to remove job from Queue: ' + job._id);
    });
  }
}
<|endoftext|>