<commit_before>var fs = require('fs');  // file system
var uuid = require('node-uuid');
var events = require('events');
var net = require('net');
var jobLib = require('./job');

var sbatchPath = 'sbatch';
var squeuePath = 'squeue';

var TCPport = 2222;
var TCPip = null;
var scheduler_id = uuid.v4();
var dataLength = 0;
var id = '00000'
var core = null;

var cacheDir = null;

var jobsArray = {};

var eventEmitter = new events.EventEmitter();

var exhaustBool = false; // set to true at any push, set to false at exhausted event raise

var emulator = false; // Trying to keep api/events intact while running job as fork on local

var isStarted = false;

/**
* List all the job ids of slurm that are both in this process and in the squeue command.
* Only used in the stop function.
* Caution : the ids or not listed in order.
*/
var _listSlurmJobID = function() {
    var emitter = new events.EventEmitter();

    // run squeue command
    var exec_cmd = require('child_process').exec;
    exec_cmd(squeuePath + ' -o \"\%j \%i\"', function (err, stdout, stderr) {
        if (err) {
            emitter.emit('errSqueue', err);
            return;
        }
        // list of slurmIDs of the jobs to kill
        var toKill = new Array();

        // squeue results
        var squeueIDs = ('' + stdout).replace(/\"/g, '');
        // regex
        var reg_NslurmID = new RegExp ('^ardockTask_[a-z0-9-]+_hex_[0-9]{1,2}', 'i');
        var reg_slurmID = new RegExp ('[0-9]+$');

        // for each job in the squeue
        squeueIDs.split('\n').forEach (function (line) {
            // use the regex
            if (reg_NslurmID.test(line) && reg_slurmID.test(line)) {
                var NslurmID = reg_NslurmID.exec(line);
                var slurmID = reg_slurmID.exec(line);
                // in case we found NslurmID in the jobs of our process
                if (jobsArray.hasOwnProperty(NslurmID)) {
                    console.log('Job ' + slurmID + ' must be killed');
                    toKill.push(slurmID[0]);
                }
            }
        });
        if (toKill.length === 0) emitter.emit('finished');
        else emitter.emit('jobLeft', toKill);
    });
    return emitter;
}

/**
 * perform a squeue action
 *
 * @param  {String}JobID, optional
 * @return {String}
 */
module.exports = {
    /**
    * Expose the module emitter, mostly for signaling exhaustion of the job pool
    *
    * @param  {String}eventName, {Function}callback
    * @return N/A
    */
    emulate : function(){ emulator = true; },
    isEmulated : function(){ return emulator; },
    on : function(eventName, callback) { //
        eventEmitter.on(eventName, callback);
    },
    cacheDir : function() {return cacheDir;},
    /**
    * Display on console.log the current list of "pushed" jobs and their status
    *
    * @param  None
    * @return null
    */
    jobsView : function(){
        var displayString = '###############################\n'
                          + '###### Current jobs pool ######\n'
                          + '###############################\n';
        var c = 0;
        for (var key in jobsArray) {;
            c++;
            displayString += '# ' + key + ' : ' + jobsArray[key].status + '\n';
        }
        if (c===0)
            displayString += '          EMPTY               \n';
        console.log(displayString);
        return null;

    },
    /**
    * Submit a job to manager,
    *
    * @param  {Object}JobSpecs
    * @return {EventEmitter} jobEmitter
    */
    push : function(jobOpt) {
        //console.log("jobOpt");
        //console.log(jobOpt);
        var self = this;
        // var partition, qos = null;
        // if (jobOpt.gid) {
        //     if (jobOpt.gid === "ws_users") {
        //         partition = 'ws-dev';
        //         qos = 'ws-dev';
        //     }
        // }

        var newJob = jobLib.createJob({
            'emulated' : emulator ? true : false,
            'id' : 'id' in jobOpt ? jobOpt.id : null,
            'cwd' : 'cwd' in jobOpt ? jobOpt.cwd : null,
            'cwdClone' : 'cwdClone' in jobOpt ? jobOpt.cwdClone : false,
            'sbatch' : sbatchPath,
            'rootDir' : cacheDir,
            'adress' : TCPip, 'port' : TCPport,
            'ttl' : 50000,
            'partition' : 'partition' in jobOpt ? jobOpt.partition : null,
            'qos' : 'qos' in  jobOpt ? jobOpt.qos : null,
            'cmd' : 'cmd' in jobOpt ? jobOpt.cmd : null,
            'script' : 'script' in jobOpt ? jobOpt.script : null,
            'exportVar' : 'exportVar' in jobOpt ? jobOpt.exportVar : null,
            'tWall' : 'tWall' in jobOpt ? jobOpt.tWall : null,
            'nNodes' : 'nNodes' in jobOpt ? jobOpt.nNodes : null,
            'nCores' : 'nCores' in jobOpt ? jobOpt.nCores : null,
            'modules' : 'modules' in jobOpt ? jobOpt.modules : null,
            'gres' : 'gres' in jobOpt ? jobOpt.gres : null
        });
	if ('gid' in jobOpt) newJob['gid'] = jobOpt.gid;
        if ('uid' in jobOpt) newJob['uid'] = jobOpt.uid;

	jobsArray[newJob.id] = { 'obj' : newJob, 'status' : 'CREATED' };

        self.jobsView();

        newJob.emitter.on('submitted', function(j){
            jobsArray[j.id].status = 'SUBMITTED';
            self.jobsView();
        })

        exhaustBool = true;

        return newJob.emitter;
    },
    /**
    * Starts the job manager
    *
    * @param  {Object}ManagerSpecs
    * @param {ManagerSpecs} cacheDir{String} Directory used for jobs caching
    * @param {ManagerSpecs} tcp{String} ip adress of the master node for netSocket
    * @param {ManagerSpecs} port{String} port number of the netSocket
    * @param {ManagerSpecs} slurmBinaries{String} path to slurm executable binaries
    * @return {String}
    */
    start : function(opt) {
        if (isStarted) return;

        if (!opt) {
            throw "Options required to start manager : \"cacheDir\", \"tcp\", \"port\"";
        }
        cacheDir = opt.cacheDir + '/' + scheduler_id;
        TCPip = opt.tcp;
        TCPport = opt.port;

        if ('slurmBinaries' in opt) {
            sbatchPath = opt['slurmBinaries'] + '/sbatch';
            squeuePath = opt['slurmBinaries'] + '/squeue';
        }

        if (opt.hasOwnProperty('forceCache')) {
            cacheDir = opt.forceCache;
        }

        console.log("Attempting to create cache for process at " + cacheDir);
        try {
            fs.mkdirSync(cacheDir);
        } catch(e) {
            if ( e.code != 'EEXIST' ) throw e;
            console.log("Cache found already found at " + cacheDir);
        }

        console.log('[' + TCPip + '] opening socket at port ' + TCPport);
        var s = _openSocket(TCPport);
        data = '';
        s.on('listening',function(socket){
            eventEmitter.emit("ready");
            isStarted = true;
            console.log("Starting pulse monitoring");
            console.log("cache Directory is " + cacheDir);
            core = setInterval(function(){_pulse()},500);

            /*socket.on('data', function (chunk) {
                data += chunk.toString();
                console.log(chunk.toString());
            })*/
        })
        .on('data', function(data){ // TO RESUME HERE
                _parseMessage(data);
            // parse job id

            // clean ref in arrayJob

            //raise the "finish" event in job.emit("finish");

        });

    },

    /**
    * Try to kill all sbatch jobs of this process,
    * by viewing the jobIds defined in nslurm,
    * and comparing them to the jobIds defined in slurm.
    * It needs to use the squeue and scancel commands.
    */
    stop : function(bean) {
        var self = this;
        var emitter = new events.EventEmitter();

        // define squeue and scancel pathways
        if ('slurmBinaries' in bean.managerSettings) {
            squeuePath = bean.managerSettings['slurmBinaries'] + '/squeue';
            scancelPath = bean.managerSettings['slurmBinaries'] + '/scancel';
        }
        //console.log('Jobs of this process : ' + Object.keys(jobsArray));

        _listSlurmJobID()
        .on('errSqueue', function (data) {
            console.log('Error for squeue command : ' + data);
            emitter.emit('errSqueue');
        })
        .on('finished', function () {
            console.log('All jobs are already killed');
            emitter.emit('cleanExit');
        })
        .on('jobLeft', function (toKill) {
            // run scancel command
            console.log('Try to cancel the job ' + toKill);
            var exec_cmd = require('child_process').exec;
            exec_cmd(scancelPath + ' ' + toKill.join(' '), function (err, stdout, stderr) {
                if (err) {
                    console.log('Error for scancel command : ' + err);
                    emitter.emit('errScancel');
                    return;
                }
                console.log('End of trying to kill the jobs : ' + toKill);
                emitter.emit('exit');
            });
        });
        return emitter;
    },

    set_id : function (val){
        id = val
    },
    see_id : function() {
        console.log("id is " + id);
    },
    test : function(){
        const spawn = require('child_process').spawn;
        const ls = spawn('ls', ['-lh', '/data']);

        ls.stdout.on('data', function (data){
            console.log('stdout: ' + data );
        });

        ls.stderr.on('data', function (data) {
            console.log('stderr: ' + data );
        });

        ls.on('close', function(code) {
            console.log('child process exited with code ' + code);
        });
    },

    /**
    * Perform a squeue call,
    *
    * @param  {Object}JobSpecs
    * @return N/A
    */
    squeue: function(jobId) {
        console.log('trying')
        var spawn = require('child_process').spawn;
        var log = '';
        //var cmd = "ps";

        //var logger = spawn('ps', ['-aux']);
        var logger = spawn('squeue', []);
        logger.stdout.on('data',function(data){
            log += data.toString();
          //  console.log("some>> " + data);
        });
        logger.stderr.on('data',function(data){
            log += data.toString();
           // console.log("some>> " + data);
        });
        logger.on('close', function(){
            console.log('closing');
            console.log(log);
        });

    //return String("This is a squeue");
    }

};

// Private Module functions

function _parseMessage(string) {
    //console.log("trying to parse " + string);
    var re = /^JOB_STATUS[\s]+([\S]+)[\s]+([\S]+)$/
    var matches = string.match(re);
    if (! matches) return;

    var jid = matches[1];
    var uStatus = matches[2];
    if (!jobsArray.hasOwnProperty(jid)) {
        console.log('unregistred job id ' + jid);
        eventEmitter.emit('unregistredJob', jid);
        return;
        //throw 'unregistred job id ' + jid;
    }

    console.log('Status Updating [job ' + jid + ' ] : from \'' +
                jobsArray[jid].status  + '\' to \'' + uStatus + '\'');
    jobsArray[jid].status = uStatus;
    if (uStatus === "FINISHED")
        _pull(jid);
};

function _pull(jid) { //handling job termination
    console.log("Pulling " + jid);
    //console.dir(jobsArray[jid]);
    var jRef = jobsArray[jid];
    delete jobsArray[jid];
    var stdout = jRef.obj.stdout();
    var stderr = jRef.obj.stderr();
    jRef.obj.emit("completed",
       stdout, stderr, jRef.obj
    );
     // Does object persist ?
};

function _openSocket(port) {

    //var data = '';

    var server = net.createServer(function (socket) {
        socket.write('#####nSlurm scheduler socket####\r\n');
        socket.pipe(socket);
        socket.on('data', function(buf){
            //console.log("incoming data");
            //console.log(buf.toString());
            eventEmitter.emit('data', buf.toString());
        })
        .on('error', function(){
            // callback must be specified to trigger close event
        });

    });
    server.listen(port);

    server.on('error', function(e){
        console.log('error' + e);
        eventEmitter.emit('error', e);
    });
    server.on('listening', function(){
        console.log('Listening on ' + port + '...');
        eventEmitter.emit('listening');
    });
    server.on('connection', function(s){

        //console.log('connection w/ ' + data);
        s.on('close', function(){
          //  console.log('Packet connexion closed');
        });
        //console.dir(s);
        //ntEmitter.emit('success', server);
    });

    return eventEmitter;
}

function _openSocketDRPEC(fileName){
    var rstream = null;
    console.log("---> " + fileName);

    var eventEmitter = new events.EventEmitter();
    fs.stat(fileName, function(err, stat) {
        console.log("pouet");
        if(err == null) {
            console.log('File exists');
            rstream = fs.createReadStream(fileName);
            eventEmitter.emit('open', rstream);
        } else if(err.code == 'ENOENT') {
            console.log("creating file")
            fs.writeFile(fileName, 'Some log\n');
            rstream = fs.createReadStream(fileName);
            eventEmitter.emit('open', rstream);
        } else {
            eventEmitter.emit('error', err.code);
        }
    });
    return eventEmitter;
}

function _pulse(){
    var c = 0;
    for (var k in jobsArray) c++;
    if( c === 0 ) {
        if (exhaustBool) {
            eventEmitter.emit("exhausted");
            exhaustBool = false;
        }
    }
    //console.log("boum");
}
var job_template = {'name' : 'john Doe', 'runtime' : 'forever'};

<commit_msg>jobProfiles selection. probable previous cacheDirs adding<commit_after>var fs = require('fs');  // file system
var uuid = require('node-uuid');
var events = require('events');
var net = require('net');
var jobLib = require('./job');

var sbatchPath = 'sbatch';
var squeuePath = 'squeue';

var TCPport = 2222;
var TCPip = null;
var scheduler_id = uuid.v4();
var dataLength = 0;
var id = '00000'
var core = null;

var cacheDir = null;
var probPreviousCacheDir = []; // list of the probable cacheDir used in previous nslurm instances

var jobProfiles = {};

var jobsArray = {};

var eventEmitter = new events.EventEmitter();

var exhaustBool = false; // set to true at any push, set to false at exhausted event raise

var emulator = false; // Trying to keep api/events intact while running job as fork on local

var isStarted = false;

/**
* List all the job ids of slurm that are both in this process and in the squeue command.
* Only used in the stop function.
* Caution : the ids or not listed in order.
*/
var _listSlurmJobID = function() {
    var emitter = new events.EventEmitter();

    // run squeue command
    var exec_cmd = require('child_process').exec;
    exec_cmd(squeuePath + ' -o \"\%j \%i\"', function (err, stdout, stderr) {
        if (err) {
            emitter.emit('errSqueue', err);
            return;
        }
        // list of slurmIDs of the jobs to kill
        var toKill = new Array();

        // squeue results
        var squeueIDs = ('' + stdout).replace(/\"/g, '');
        // regex
        var reg_NslurmID = new RegExp ('^ardockTask_[a-z0-9-]+_hex_[0-9]{1,2}', 'i');
        var reg_slurmID = new RegExp ('[0-9]+$');

        // for each job in the squeue
        squeueIDs.split('\n').forEach (function (line) {
            // use the regex
            if (reg_NslurmID.test(line) && reg_slurmID.test(line)) {
                var NslurmID = reg_NslurmID.exec(line);
                var slurmID = reg_slurmID.exec(line);
                // in case we found NslurmID in the jobs of our process
                if (jobsArray.hasOwnProperty(NslurmID)) {
                    console.log('Job ' + slurmID + ' must be killed');
                    toKill.push(slurmID[0]);
                }
            }
        });
        if (toKill.length === 0) emitter.emit('finished');
        else emitter.emit('jobLeft', toKill);
    });
    return emitter;
}

/**
 * perform a squeue action
 *
 * @param  {String}JobID, optional
 * @return {String}
 */
module.exports = {
    /**
    * Expose the module emitter, mostly for signaling exhaustion of the job pool
    *
    * @param  {String}eventName, {Function}callback
    * @return N/A
    */
    emulate : function(){ emulator = true; },
    isEmulated : function(){ return emulator; },
    on : function(eventName, callback) { //
        eventEmitter.on(eventName, callback);
    },
    cacheDir : function() {return cacheDir;},
    probPreviousCacheDir : function() {return probPreviousCacheDir;},

    /*
    * Select a job profile (depending on "partition", "qos", "gid", "uid", etc.)
    */
    selectJobProfile : function(key) {
        if (! jobProfiles) console.log("WARNING : No jobProfiles detected !");
        else {
            if (jobProfiles.hasOwnProperty(key)) return jobProfiles[key];
            else throw "ERROR : No " + key + " in jobProfiles !";
        }
    },

    /**
    * Display on console.log the current list of "pushed" jobs and their status
    *
    * @param  None
    * @return null
    */
    jobsView : function(){
        var displayString = '###############################\n'
                          + '###### Current jobs pool ######\n'
                          + '###############################\n';
        var c = 0;
        for (var key in jobsArray) {;
            c++;
            displayString += '# ' + key + ' : ' + jobsArray[key].status + '\n';
        }
        if (c===0)
            displayString += '          EMPTY               \n';
        console.log(displayString);
        return null;

    },
    /**
    * Submit a job to manager,
    *
    * @param  {Object}JobSpecs
    * @return {EventEmitter} jobEmitter
    */
    push : function(jobOpt) {
        //console.log("jobOpt");
        //console.log(jobOpt);
        var self = this;
        // var partition, qos = null;
        // if (jobOpt.gid) {
        //     if (jobOpt.gid === "ws_users") {
        //         partition = 'ws-dev';
        //         qos = 'ws-dev';
        //     }
        // }

        var newJob = jobLib.createJob({
            'emulated' : emulator ? true : false,
            'id' : 'id' in jobOpt ? jobOpt.id : null,
            'cwd' : 'cwd' in jobOpt ? jobOpt.cwd : null,
            'cwdClone' : 'cwdClone' in jobOpt ? jobOpt.cwdClone : false,
            'sbatch' : sbatchPath,
            'rootDir' : cacheDir,
            'adress' : TCPip, 'port' : TCPport,
            'ttl' : 50000,
            'partition' : 'partition' in jobOpt ? jobOpt.partition : null,
            'qos' : 'qos' in  jobOpt ? jobOpt.qos : null,
            'cmd' : 'cmd' in jobOpt ? jobOpt.cmd : null,
            'script' : 'script' in jobOpt ? jobOpt.script : null,
            'exportVar' : 'exportVar' in jobOpt ? jobOpt.exportVar : null,
            'tWall' : 'tWall' in jobOpt ? jobOpt.tWall : null,
            'nNodes' : 'nNodes' in jobOpt ? jobOpt.nNodes : null,
            'nCores' : 'nCores' in jobOpt ? jobOpt.nCores : null,
            'modules' : 'modules' in jobOpt ? jobOpt.modules : null,
            'gres' : 'gres' in jobOpt ? jobOpt.gres : null
        });
	if ('gid' in jobOpt) newJob['gid'] = jobOpt.gid;
        if ('uid' in jobOpt) newJob['uid'] = jobOpt.uid;

	jobsArray[newJob.id] = { 'obj' : newJob, 'status' : 'CREATED' };

        self.jobsView();

        newJob.emitter.on('submitted', function(j){
            jobsArray[j.id].status = 'SUBMITTED';
            self.jobsView();
        })

        exhaustBool = true;

        return newJob.emitter;
    },
    /**
    * Starts the job manager
    *
    * @param  {Object}ManagerSpecs
    * @param {ManagerSpecs} cacheDir{String} Directory used for jobs caching
    * @param {ManagerSpecs} tcp{String} ip adress of the master node for netSocket
    * @param {ManagerSpecs} port{String} port number of the netSocket
    * @param {ManagerSpecs} slurmBinaries{String} path to slurm executable binaries
    * @return {String}
    */
    start : function(opt) {
        if (isStarted) return;

        if (!opt) {
            throw "Options required to start manager : \"cacheDir\", \"tcp\", \"port\"";
        }
        cacheDir = opt.cacheDir + '/' + scheduler_id;
        TCPip = opt.tcp;
        TCPport = opt.port;
        jobProfiles = opt.jobProfiles;

        if ('slurmBinaries' in opt) {
            sbatchPath = opt['slurmBinaries'] + '/sbatch';
            squeuePath = opt['slurmBinaries'] + '/squeue';
        }

        if (opt.hasOwnProperty('forceCache')) {
            cacheDir = opt.forceCache;
        }

        if (opt.hasOwnProperty('probPreviousCacheDir')) {
            probPreviousCacheDir = opt.probPreviousCacheDir;
        }

        console.log("Attempting to create cache for process at " + cacheDir);
        try {
            fs.mkdirSync(cacheDir);
        } catch(e) {
            if ( e.code != 'EEXIST' ) throw e;
            console.log("Cache found already found at " + cacheDir);
        }

        console.log('[' + TCPip + '] opening socket at port ' + TCPport);
        var s = _openSocket(TCPport);
        data = '';
        s.on('listening',function(socket){
            eventEmitter.emit("ready");
            isStarted = true;
            console.log("Starting pulse monitoring");
            console.log("cache Directory is " + cacheDir);
            core = setInterval(function(){_pulse()},500);

            /*socket.on('data', function (chunk) {
                data += chunk.toString();
                console.log(chunk.toString());
            })*/
        })
        .on('data', function(data){ // TO RESUME HERE
                _parseMessage(data);
            // parse job id

            // clean ref in arrayJob

            //raise the "finish" event in job.emit("finish");

        });

    },

    /**
    * Try to kill all sbatch jobs of this process,
    * by viewing the jobIds defined in nslurm,
    * and comparing them to the jobIds defined in slurm.
    * It needs to use the squeue and scancel commands.
    */
    stop : function(bean) {
        var self = this;
        var emitter = new events.EventEmitter();

        // define squeue and scancel pathways
        if ('slurmBinaries' in bean.managerSettings) {
            squeuePath = bean.managerSettings['slurmBinaries'] + '/squeue';
            scancelPath = bean.managerSettings['slurmBinaries'] + '/scancel';
        }
        //console.log('Jobs of this process : ' + Object.keys(jobsArray));

        _listSlurmJobID()
        .on('errSqueue', function (data) {
            console.log('Error for squeue command : ' + data);
            emitter.emit('errSqueue');
        })
        .on('finished', function () {
            console.log('All jobs are already killed');
            emitter.emit('cleanExit');
        })
        .on('jobLeft', function (toKill) {
            // run scancel command
            console.log('Try to cancel the job ' + toKill);
            var exec_cmd = require('child_process').exec;
            exec_cmd(scancelPath + ' ' + toKill.join(' '), function (err, stdout, stderr) {
                if (err) {
                    console.log('Error for scancel command : ' + err);
                    emitter.emit('errScancel');
                    return;
                }
                console.log('End of trying to kill the jobs : ' + toKill);
                emitter.emit('exit');
            });
        });
        return emitter;
    },

    set_id : function (val){
        id = val
    },
    see_id : function() {
        console.log("id is " + id);
    },
    test : function(){
        const spawn = require('child_process').spawn;
        const ls = spawn('ls', ['-lh', '/data']);

        ls.stdout.on('data', function (data){
            console.log('stdout: ' + data );
        });

        ls.stderr.on('data', function (data) {
            console.log('stderr: ' + data );
        });

        ls.on('close', function(code) {
            console.log('child process exited with code ' + code);
        });
    },

    /**
    * Perform a squeue call,
    *
    * @param  {Object}JobSpecs
    * @return N/A
    */
    squeue: function(jobId) {
        console.log('trying')
        var spawn = require('child_process').spawn;
        var log = '';
        //var cmd = "ps";

        //var logger = spawn('ps', ['-aux']);
        var logger = spawn('squeue', []);
        logger.stdout.on('data',function(data){
            log += data.toString();
          //  console.log("some>> " + data);
        });
        logger.stderr.on('data',function(data){
            log += data.toString();
           // console.log("some>> " + data);
        });
        logger.on('close', function(){
            console.log('closing');
            console.log(log);
        });

    //return String("This is a squeue");
    }

};

// Private Module functions

function _parseMessage(string) {
    //console.log("trying to parse " + string);
    var re = /^JOB_STATUS[\s]+([\S]+)[\s]+([\S]+)$/
    var matches = string.match(re);
    if (! matches) return;

    var jid = matches[1];
    var uStatus = matches[2];
    if (!jobsArray.hasOwnProperty(jid)) {
        console.log('unregistred job id ' + jid);
        eventEmitter.emit('unregistredJob', jid);
        return;
        //throw 'unregistred job id ' + jid;
    }

    console.log('Status Updating [job ' + jid + ' ] : from \'' +
                jobsArray[jid].status  + '\' to \'' + uStatus + '\'');
    jobsArray[jid].status = uStatus;
    if (uStatus === "FINISHED")
        _pull(jid);
};

function _pull(jid) { //handling job termination
    console.log("Pulling " + jid);
    //console.dir(jobsArray[jid]);
    var jRef = jobsArray[jid];
    delete jobsArray[jid];
    var stdout = jRef.obj.stdout();
    var stderr = jRef.obj.stderr();
    jRef.obj.emit("completed",
       stdout, stderr, jRef.obj
    );
     // Does object persist ?
};

function _openSocket(port) {

    //var data = '';

    var server = net.createServer(function (socket) {
        socket.write('#####nSlurm scheduler socket####\r\n');
        socket.pipe(socket);
        socket.on('data', function(buf){
            //console.log("incoming data");
            //console.log(buf.toString());
            eventEmitter.emit('data', buf.toString());
        })
        .on('error', function(){
            // callback must be specified to trigger close event
        });

    });
    server.listen(port);

    server.on('error', function(e){
        console.log('error' + e);
        eventEmitter.emit('error', e);
    });
    server.on('listening', function(){
        console.log('Listening on ' + port + '...');
        eventEmitter.emit('listening');
    });
    server.on('connection', function(s){

        //console.log('connection w/ ' + data);
        s.on('close', function(){
          //  console.log('Packet connexion closed');
        });
        //console.dir(s);
        //ntEmitter.emit('success', server);
    });

    return eventEmitter;
}

function _openSocketDRPEC(fileName){
    var rstream = null;
    console.log("---> " + fileName);

    var eventEmitter = new events.EventEmitter();
    fs.stat(fileName, function(err, stat) {
        console.log("pouet");
        if(err == null) {
            console.log('File exists');
            rstream = fs.createReadStream(fileName);
            eventEmitter.emit('open', rstream);
        } else if(err.code == 'ENOENT') {
            console.log("creating file")
            fs.writeFile(fileName, 'Some log\n');
            rstream = fs.createReadStream(fileName);
            eventEmitter.emit('open', rstream);
        } else {
            eventEmitter.emit('error', err.code);
        }
    });
    return eventEmitter;
}

function _pulse(){
    var c = 0;
    for (var k in jobsArray) c++;
    if( c === 0 ) {
        if (exhaustBool) {
            eventEmitter.emit("exhausted");
            exhaustBool = false;
        }
    }
    //console.log("boum");
}
var job_template = {'name' : 'john Doe', 'runtime' : 'forever'};

<|endoftext|>


<commit_before>// Entry point<commit_msg>Updated<commit_after>var debug = require('debug')('express-route-finder');
var path = require('path');
var fs   = require('fs');

module.exports = RouteFinder;

function RouteFinder ()
{
	this.FileNameMask  = /\.routes?\.js$/i;
	this.RoutesRootDir = null;
	this.SearchType = RouteFinder.SearchType.breadthFirst;
}

RouteFinder.SearchType =
{
	breadthFirst : "breadthFirst",
	depthFirst : "depthFirst"
};

RouteFinder.prototype.register = function (app)
{
	if (!app) throw "express-route-finder: Missing required parameter: app (express application)";
	if (this.RoutesRootDir === null) throw "express-route-finder: RoutesRootDir is not defined";
	if (!RouteFinder.SearchType.hasOwnProperty(this.SearchType)) this.SearchType = RouteFinder.SearchType.breadthFirst;

	var routes = (this.SearchType === RouteFinder.SearchType.breadthFirst)
		? breadthFirstSearch().bind(this)
		: depthFirstSearch().bind(this);

	routes.forEach(function (item)
	{
		debug("adding route: " + item.route);
		app.add(item.route, item.path);
	});
};

RouteFinder.prototype.setRootDir = function (rootdir)
{
	fs.access(rootdir, fs.R_OK);
	debug("setting root search directory to " + rootdir);
	this.RoutesRootDir = rootdir;
	return this;
};

RouteFinder.prototype.setFileNameMask = function (filenamemask)
{
	debug("setting file name mask to " + filenamemask);
	this.FileNameMask = filenamemask;
	return this;
};

RouteFinder.prototype.setSearchType = function (searchtype)
{
	if (!RouteFinder.SearchType.hasOwnProperty(searchtype)) throw "express-route-finder invalid search type (" + searchtype + "), use RouteFinder.SearchType enum";
	debug("setting search type to " + searchtype);
	this.SearchType = searchtype;
	return this;
};

function breadthFirstSearch ()
{
	var mask      = this.FileNameMask;
	var locations = [this.RoutesRootDir];
	var results   = [];
	var currentFolder;

	function searchFolder (folder)
	{
		fs.readdirSync(folder).forEach(function (item)
		{
			var itemPath = path.join(folder, item);
			var stats = fs.statSync(itemPath);

			if (stats.isDirectory())
			{
				locations.push(itemPath);
			}
			else if ((stats.isFile()) && (mask.test(item)))
			{
				results.push(makeRoute(item, itemPath));
			}
		});
	};

	while (locations.length > 0)
	{
		currentFolder = locations.shift();
		searchFolder(currentFolder);
	}

	return results;
}

function depthFirstSearch ()
{
	var mask = this.FileNameMask;

	function searchFolder (folder)
	{
		var results = [];

		fs.readdirSync(folder).forEach(function (item)
		{
			var itemPath = path.join(folder, item);
			var stats = fs.statSync(itemPath);

			if (stats.isDirectory())
			{
				results.push(searchFolder(itemPath));
			}
			else if ((stats.isFile()) && (mask.test(item)))
			{
				results.push(makeRoute(item, itemPath));
			}
		});
	};

	return searchFolder(this.RoutesRootDir);
}

function makeRoute (filename, filepath)
{
	var route = filename.replace(/^index\./, '').replace(/\.?routes?\.js$/i, '');

	// change dots to slashes
	if (route.indexOf('.') > 0)	route = route.replace(/\./g, '/');

	// change dashes to camelCase
	route = route.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });

	return { route : '/' + route, path : filepath };
}<|endoftext|>


<commit_before>'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');
var ReactDOM = require('react-dom');

var ClickOutComponent = (function (_React$Component) {
  _inherits(ClickOutComponent, _React$Component);

  function ClickOutComponent() {
    _classCallCheck(this, ClickOutComponent);

    _get(Object.getPrototypeOf(ClickOutComponent.prototype), 'constructor', this).call(this);
  }

  _createClass(ClickOutComponent, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var self = this,
          el = ReactDOM.findDOMNode(this),
          reactId = el.getAttribute('data-reactid');

      self.__windowListener = function (e) {
        if (e.__clickInElReactId === reactId) return;

        var clickOutHandler = self.onClickOut || self.props.onClickOut;
        if (!clickOutHandler) {
          return console.warn('onClickOut is not defined.');
        }

        clickOutHandler.call(self, e);
      };

      self.__elementListener = function (e) {
        e.__clickInElReactId = reactId;
      };

      setTimeout(function () {
        window.addEventListener('click', self.__windowListener);
        el.addEventListener('click', self.__elementListener);
      }, 0);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('click', this.__windowListener);
      ReactDOM.findDOMNode(this).removeEventListener('click', this.__elementListener);
    }
  }, {
    key: 'render',
    value: function render() {
      return Array.isArray(this.props.children) ? React.createElement(
        'div',
        null,
        this.props.children
      ) : React.Children.only(this.props.children);
    }
  }]);

  return ClickOutComponent;
})(React.Component);

module.exports = ClickOutComponent;
<commit_msg>Compiled<commit_after>'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');
var ReactDOM = require('react-dom');

var ClickOutComponent = (function (_React$Component) {
  _inherits(ClickOutComponent, _React$Component);

  function ClickOutComponent() {
    _classCallCheck(this, ClickOutComponent);

    _get(Object.getPrototypeOf(ClickOutComponent.prototype), 'constructor', this).call(this);
  }

  _createClass(ClickOutComponent, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var self = this,
          el = ReactDOM.findDOMNode(this),
          reactId = el.getAttribute('data-reactid');

      self.__windowListener = function (e) {
        if (e.__clickInElReactId === reactId) return;

        var clickOutHandler = self.onClickOut || self.props.onClickOut;
        if (!clickOutHandler) {
          return console.warn('onClickOut is not defined.');
        }

        clickOutHandler.call(self, e);
      };

      self.__elementListener = function (e) {
        e.__clickInElReactId = reactId;
      };

      setTimeout(function () {
        if (this.__unmounted) {
          return;
        }
        window.addEventListener('click', self.__windowListener);
        el.addEventListener('click', self.__elementListener);
      }, 0);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('click', this.__windowListener);
      ReactDOM.findDOMNode(this).removeEventListener('click', this.__elementListener);
      this.__unmounted = true;
    }
  }, {
    key: 'render',
    value: function render() {
      return Array.isArray(this.props.children) ? React.createElement(
        'div',
        null,
        this.props.children
      ) : React.Children.only(this.props.children);
    }
  }]);

  return ClickOutComponent;
})(React.Component);

module.exports = ClickOutComponent;
<|endoftext|>


<commit_before>'use strict';

var SkyRemote = require('sky-remote');
var SkyQCheck = require('sky-q');
var Accessory, Service, Characteristic;

module.exports = function(homebridge) {

	Accessory = homebridge.platformAccessory;
	Service = homebridge.hap.Service;
	Characteristic = homebridge.hap.Characteristic;
	homebridge.registerAccessory("homebridge-sky-q-play", "SkyQPlay", SkyQAccessory);
};

function SkyQAccessory(log, config, api) {

	this.log = log;
	this.config = config;
	this.name = config.name || 'Sky Q';

	if (this.config.cmd) {

		this.cmd = JSON.parse("[" + this.config.cmd + "]");
	} else {

		this.cmd = 'power';
		this.stateful = true;
	}

	var remoteControl = new SkyRemote(config.ipAddress);
	var boxCheck = new SkyQCheck({ip:config.ipAddress})
	this.skyQ = remoteControl;
	this.box = boxCheck;
}

SkyQAccessory.prototype = {

	setPowerState: function(powerOn, callback) {

		var log = this.log;
		var name = this.name;

		log('Sending "' + this.cmd + '" command to ' + name + '...');

		this.skyQ.press(this.cmd, function(error) {

			if (error) {

				log('Failed to send cmd ' + name + '. ' + error);
			}

			if (this.stateful) {

				callback();
			} else {

				callback(new Error(1)); //Only way to keep the switch from turning on/off
			}
		});
	},

	identify: function(callback) {

		this.log("Identify...");

		callback();
	},

	getState: function(callback) {
		if (this.stateful) {

			this.box.getPowerState().then(isOn=>{
	  		if (isOn) {

			    this.log(this.name + " is on :-)")
			  } else {

			    this.log(this.name + " is in standby :-(")
			  }
			  callback(null, isOn);

			}).catch(err=>{

			  this.log("Unable to determine power state")
			  this.log("Perhaps looking at this error will help you figure out why" + err)
			  callback(err || new Error('Error getting state of ' + this.name));
			})
		} else {

		  callback(null, 0);
		}
	},

	getServices: function() {

		var switchService = new Service.Switch(this.name);

		var characteristic = switchService.getCharacteristic(Characteristic.On).on('set', this.setPowerState.bind(this));

		characteristic.on('get', this.getState.bind(this));

		return [switchService];
	}
};
<commit_msg>Fixed cmd splitting<commit_after>'use strict';

var SkyRemote = require('sky-remote');
var SkyQCheck = require('sky-q');
var Accessory, Service, Characteristic;

module.exports = function(homebridge) {

	Accessory = homebridge.platformAccessory;
	Service = homebridge.hap.Service;
	Characteristic = homebridge.hap.Characteristic;
	homebridge.registerAccessory("homebridge-sky-q-play", "SkyQPlay", SkyQAccessory);
};

function SkyQAccessory(log, config, api) {

	this.log = log;
	this.config = config;
	this.name = config.name || 'Sky Q';

	if (this.config.cmd) {

		this.cmd = this.config.cmd.split(',');
	} else {

		this.cmd = 'power';
		this.stateful = true;
	}
	if (this.cmd == 'power') {
                this.stateful = true;
        }
	var remoteControl = new SkyRemote(config.ipAddress);
	var boxCheck = new SkyQCheck({ip:config.ipAddress})
	this.skyQ = remoteControl;
	this.box = boxCheck;
}

SkyQAccessory.prototype = {

	setPowerState: function(powerOn, callback) {

		var log = this.log;
		var name = this.name;

		log('Sending "' + this.cmd + '" command to ' + name + '...');

		this.skyQ.press(this.cmd, function(error) {

			if (error) {

				log('Failed to send cmd ' + name + '. ' + error);
			}

			if (this.stateful) {

				callback();
			} else {

				callback(new Error(1)); //Only way to keep the switch from turning on/off
			}
		});
	},

	identify: function(callback) {

		this.log("Identify...");

		callback();
	},

	getState: function(callback) {
		if (this.stateful) {

			this.box.getPowerState().then(isOn=>{
	  		if (isOn) {

			    this.log(this.name + " is on :-)")
			  } else {

			    this.log(this.name + " is in standby :-(")
			  }
			  callback(null, isOn);

			}).catch(err=>{

			  this.log("Unable to determine power state")
			  this.log("Perhaps looking at this error will help you figure out why" + err)
			  callback(err || new Error('Error getting state of ' + this.name));
			})
		} else {

		  callback(null, 0);
		}
	},

	getServices: function() {

		var switchService = new Service.Switch(this.name);

		var characteristic = switchService.getCharacteristic(Characteristic.On).on('set', this.setPowerState.bind(this));

		characteristic.on('get', this.getState.bind(this));

		return [switchService];
	}
};
<|endoftext|>


<commit_before>var OMXPlayer = require('./lib/omxplayer');

var configuration = {

};

var omxplayer = new OMXPlayer(configuration);
omxplayer.start("movie.mkv");

var omxPlayerService = omxplayer._sessionBus.getService('org.mpris.MediaPlayer2.omxplayer');
console.log("Omx player service=", omxPlayerService);

omxPlayerService.getInterface('/org/mpris/MediaPlayer2', 'org.freedesktop.Notifications', function(error,
		omxPlayerNotificationsInterface) {
	if (error) {
		console.error("Get interface error:", error);
		return;
	}
	console.log("Omx player interface=", omxPlayerNotificationsInterface);
});
<commit_msg>First tests<commit_after>var OMXPlayer = require('./lib/omxplayer');

var configuration = {

};

var omxplayer = new OMXPlayer(configuration);
omxplayer.start("movie.mkv");

var omxPlayerService = omxplayer._sessionBus.getService('org.mpris.MediaPlayer2.omxplayer');
console.log("Omx player service=", omxPlayerService);

omxPlayerService.getInterface('/org/mpris/MediaPlayer2', 'org.freedesktop.DBus.Properties.Position', function(error,
		omxPlayerNotificationsInterface) {
	if (error) {
		console.error("Get interface error:", error);
		return;
	}
	console.log("Omx player interface=", omxPlayerNotificationsInterface);
});
<|endoftext|>


<commit_before>String.prototype.toKa = function(){
	var text = '', target = this.split(''), chars = 'abgdevzTiklmnopJrstufqRySCcZwWxjhY'
	target.map(function(element, index){
		/*text += index >= 0 ?
			chars.indexOf(element) != -1 ?
				String.fromCharCode(chars.indexOf(element) + 4304):
				element:
			''*/
		if(index >= 0){
			if(chars.indexOf(element) != -1){
				if(element != 'Y'){
					text += String.fromCharCode(chars.indexOf(element) + 4304)
				}else{
					text += 'ჸ'
				}
			}else{
				text += element
			}
		}
	})
	return text
}
window.addEventListener('load', function(){
	document.querySelectorAll('.toKa').forEach(function(element){
		element.addEventListener('keypress', function(evt){
			if(document.querySelector('.switcher') == null || document.querySelector('.switcher').checked){
				var charCode = (evt.charCode) ? evt.which : evt.keyCode
				if (this.selectionStart != undefined) {
		            var startPos = this.selectionStart
    				var endPos = this.selectionEnd
		            var myVal = this.value
		            var prefix = '', endfix = '', translated = ''
		            prefix = myVal.substring(0, startPos)
		            endfix = myVal.substring(endPos, this.value.length)
		            translated = String.fromCharCode(charCode).toKa()
		            this.value = prefix + translated + endfix
		            this.selectionStart = startPos + translated.length
		            this.selectionEnd = startPos + translated.length
			    } else {
					this.value += String.fromCharCode(charCode).toKa()
			    }
				evt.preventDefault()
			}
		})
	})

	document.addEventListener('keypress', function(evt){
		var trgt = document.querySelector('.switcher')
		var charCode = (evt.charCode) ? evt.which : evt.keyCode
		if(trgt == null) return
		if(charCode == 96){
			trgt.checked = trgt.checked == true ? false : true
			evt.preventDefault()
		}
	})
})

<commit_msg>mozial bug almos fixed<commit_after>String.prototype.toKa = function(e){
	var text = '', target = this.split(''), chars = 'abgdevzTiklmnopJrstufqRySCcZwWxjhY'
	target.map(function(element, index){
		if(index >= 0){
			if(chars.indexOf(element) !== -1){
				if(element != 'Y'){
					text += String.fromCharCode(chars.indexOf(element) + 4304)
				}else{
					text += 'ჸ'
				}
			}else{
				if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
					if(!e.altKey || !e.ctrlKey || !e.metaKey)
						text += element
				}else{
					text += element
				}
			}
		}
	})
	return text
}
window.addEventListener('load', function(){
	document.querySelectorAll('.toKa').forEach(function(element){
		element.addEventListener('keypress', function(evt){
			if(document.querySelector('.switcher') == null || document.querySelector('.switcher').checked){
				var charCode = (evt.charCode) ? evt.which : evt.keyCode
				// alert(charCode)
				if (this.selectionStart != undefined) {
		            var startPos = this.selectionStart
    				var endPos = this.selectionEnd
		            var myVal = this.value
		            var prefix = '', endfix = '', translated = ''
		            prefix = myVal.substring(0, startPos)
		            endfix = myVal.substring(endPos, this.value.length)
		            translated = String.fromCharCode(charCode).toKa()
		            this.value = prefix + translated + endfix
		            this.selectionStart = startPos + translated.length
		            this.selectionEnd = startPos + translated.length
			    } else {
					this.value += String.fromCharCode(charCode).toKa()
			    }
			    evt.stopPropagation()
				evt.preventDefault()
			}
		})
	})

	document.addEventListener('keypress', function(evt){
		var trgt = document.querySelector('.switcher')
		var charCode = (evt.charCode) ? evt.which : evt.keyCode
		if(trgt == null) return
		if(charCode == 96){
			trgt.checked = trgt.checked == true ? false : true
			evt.stopPropagation()
			evt.preventDefault()
		}
	})
})

<|endoftext|>


<commit_before>'use strict';

const Hapi = require('hapi');
const Good = require('good');
const notp = require('notp');
const GoodLoggly = require('good-loggly');

const twilioClient = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

const EventEmitter = require('events');
const emitter = new EventEmitter();

const server = new Hapi.Server();

server.connection({
  port: process.env.PORT || 1337
});

const options = {
  reporters: [
    {
      reporter: require('good-console'),
      events: {
        response: '*',
        log: '*',
        request: '*'
      }
    },
    {
      reporter: GoodLoggly,
      events: {
        response: '*',
        log: '*',
        request: '*'
      },
      config: {
        token: process.env.LOGGLY_TOKEN,
        subdomain: process.env.LOGGLY_SUBDOMAIN,
        name: 'kmoe',
        hostname: 'kmoe.heroku.com',
        tags: ['good-loggly']
      }
    }
  ]
};

server.register({
  register: Good,
  options
}, (err) => {
  if (err) {
    throw err; // something bad happened loading the plugin
  }

  server.start((err) => {
    if (err) {
       throw err;
    }
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});

server.route({
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    server.log('info', 'base route');
    return reply('hello world');
  }
});

server.route({
  method: 'GET',
  path: '/auth',
  handler: (request, reply) => {
    if (request.info.hostname !== 'localhost') {
      return reply({
        error: 'just localhost for now'
      });
    }

    return reply('no');

    // return twilioClient.messages.create({
    //   to: process.env.PHONE_KATY,
    //   from: process.env.PHONE_SELF,
    //   body: 'NFC auth request from  ' + request.hostname,
    // }, (error, message) => {
    //   if (error) {
    //     return reply({
    //       error: error
    //     });
    //   }
    //   console.log('Twilio message sent: ' + message.sid);
    //   return reply({
    //     error: null,
    //     message: 'successful request, katy'
    //   });
    // });
  }
});

server.route({
  method: 'POST',
  path: '/auth',
  handler: (request, reply) => {
    console.log(request.payload);

    if (!request.payload) {
      emitter.emit('auth_failure');
      return reply('well shit, you forgot the payload');
    }

    if (notp.totp.verify(request.payload.token, process.env.TOTP_KEY)) {
      console.log('success verifying totp');
      emitter.emit('auth_success');
      return reply('SUCCESSSSSSS');
    } else {
      console.log('nope');
      emitter.emit('auth_failure');
      return reply('auth failed :(');
    }
  }
});

server.route({
  method: 'GET',
  path: '/verify',
  config: {
    timeout: {
      server: 100000
    },
  },
  handler: (request, reply) => {
    server.log('verification request from ', request.info.hostname);

    //send text to katy
    //include time limit

    emitter.on('auth_failure', () => {
      return reply('auth failed');
    });

    emitter.on('auth_success', () => {
      return reply('auth succeeded!!!!!!!1');
    });
  }
});<commit_msg>nothing<commit_after>'use strict';

const Hapi = require('hapi');
const Good = require('good');
const notp = require('notp');
const GoodLoggly = require('good-loggly');

const twilioClient = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

const EventEmitter = require('events');
const emitter = new EventEmitter();

const server = new Hapi.Server();

server.connection({
  port: process.env.PORT || 1337
});

const options = {
  reporters: [
    {
      reporter: require('good-console'),
      events: {
        response: '*',
        log: '*',
        request: '*'
      }
    },
    {
      reporter: GoodLoggly,
      events: {
        response: '*',
        log: '*',
        request: '*'
      },
      config: {
        token: process.env.LOGGLY_TOKEN,
        subdomain: process.env.LOGGLY_SUBDOMAIN,
        name: 'kmoe',
        hostname: 'kmoe.heroku.com',
        tags: ['good-loggly']
      }
    }
  ]
};

server.register({
  register: Good,
  options
}, (err) => {
  if (err) {
    throw err; // something bad happened loading the plugin
  }

  server.start((err) => {
    if (err) {
       throw err;
    }
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});

server.route({
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    server.log('info', 'base route');
    return reply('hello world');
  }
});

server.route({
  method: 'GET',
  path: '/auth',
  handler: (request, reply) => {
    if (request.info.hostname !== 'localhost') {
      return reply({
        error: 'just localhost for now'
      });
    }

    return reply('no');

    // return twilioClient.messages.create({
    //   to: process.env.PHONE_KATY,
    //   from: process.env.PHONE_SELF,
    //   body: 'NFC auth request from  ' + request.hostname,
    // }, (error, message) => {
    //   if (error) {
    //     return reply({
    //       error: error
    //     });
    //   }
    //   console.log('Twilio message sent: ' + message.sid);
    //   return reply({
    //     error: null,
    //     message: 'successful request, katy'
    //   });
    // });
  }
});

let pendingAuth;

server.route({
  method: 'POST',
  path: '/auth',
  handler: (request, reply) => {
    console.log(request.payload);

    pendingAuth = true;

    if (!request.payload) {
      emitter.emit('auth_failure');
      return reply('well shit, you forgot the payload');
    }

    if (notp.totp.verify(request.payload.token, process.env.TOTP_KEY)) {
      console.log('success verifying totp');
      emitter.emit('auth_success');
      return reply('SUCCESSSSSSS');
    } else {
      console.log('nope');
      emitter.emit('auth_failure');
      return reply('auth failed :(');
    }
  }
});

server.route({
  method: 'GET',
  path: '/verify',
  config: {
    timeout: {
      server: 100000,
    },
  },
  handler: (request, reply) => {
    server.log('verification request from ', request.info.hostname);

    //send text to katy
    //include time limit

    let response = reply('timeout').hold();

    emitter.on('auth_failure', () => {
      response = reply('auth failed').hold();
    });

    emitter.on('auth_success', () => {
      response = reply('auth succeeded!!!!!!!1').hold();
    });

    if (pendingAuth) {
      pendingAuth = false;
      return response.send();
    }
  }
});<|endoftext|>


<commit_before>'use strict';

var net = require('net');

/**
 * List of possible proxy headers that should be checked for the original client
 * IP address and forwarded port.
 *
 * @type {Array}
 * @private
 */
var proxies = [
  {
    ip: 'x-forwarded-for',
    port: 'x-forwarded-port',
    proto: 'x-forwarded-proto'
  }, {
    ip: 'z-forwarded-for',
    port: 'z-forwarded-port',   // Estimated guess, no standard header available.
    proto: 'z-forwarded-proto'  // Estimated guess, no standard header available.
  }, {
    ip: 'forwarded',
    port: 'forwarded-port',
    proto: 'forwarded-proto'    // Estimated guess, no standard header available.
  }, {
    ip: 'x-real-ip',
    port: 'x-real-port'         // Estimated guess, no standard header available.
  }
];

/**
 * Default IP address and port that should be returned when don't find any
 * (valid) matches.
 *
 * @type {Object}
 * @private
 */
var defaults = {
  ip: '127.0.0.1',
  port: 0
};

/**
 * Search the headers for a possible match against a known proxy header.
 *
 * @param {Object} headers The received HTTP headers.
 * @param {Array} whitelist White list of proxies that should be checked.
 * @returns {String|Undefined} A IP address or nothing.
 * @api private
 */
function forwarded(headers) {
  for (var i = 0, length = proxies.length; i < length; i++) {
    if (!(proxies[i].ip in headers)) continue;

    var ports = (headers[proxies[i].port] || '').split(',')
      , ips = (headers[proxies[i].ip] || '').split(',');

    //
    // As these headers can potentially be set by a 1337H4X0R we need to ensure
    // that all supplied values are valid IP addresses. If we receive a none
    // IP value inside the IP header field we are going to assume that this
    // header has been compromised and should be ignored
    //
    if (!ips.length || !ips.every(net.isIP)) return;

    //
    // We've gotten a match on a HTTP header, we need to parse it further as it
    // could consist of multiple hops. The pattern for multiple hops is:
    //
    //   client, proxy, proxy, proxy, etc.
    //
    // So extracting the first IP should be sufficient.
    //
    return {
      port: +ports.shift() || defaults.port,
      ip: ips.shift() || defaults.ip
    };
  }
}

/**
 * Parse out the address information..
 *
 * @param {Object} obj A socket like object that could contain a `remoteAddress`.
 * @param {Object} headers The received HTTP headers.
 * @param {Array} whitelist White list
 * @returns {String} The IP address.
 * @api private
 */
function parse(obj, headers, whitelist) {
  var proxied = forwarded(headers, whitelist)
    , connection = obj.connection
    , socket = connection
      ? connection.socket
      : obj.socket;

  //
  // We should always be testing for HTTP headers as remoteAddress would point
  // to proxies.
  //
  if (proxied) return proxied;

  // Check for the property on our given object.
  if ('remoteAddress' in obj) return {
    port: +obj.remotePort || defaults.port,
    ip: obj.remoteAddress || defaults.ip
  };

  // Edge case for Socket.IO and SockJS.
  if ('address' in obj && 'port' in obj) return {
    port: +obj.port || defaults.port,
    ip: obj.address || defaults.ip
  };

  if (connection && 'remoteAddress' in connection) return {
    port: +connection.remotePort || defaults.port,
    ip: connection.remoteAddress || defaults.ip
  };

  if (socket && 'remoteAddress' in socket) return {
    port: +socket.remotePort || defaults.port,
    ip: socket.remoteAddress || defaults.ip
  };

  return defaults;
}

//
// Expose the module.
//
module.exports = parse;
<commit_msg>[major] Added an Forwarded class to optimize for memory. Fixes #2<commit_after>'use strict';

var net = require('net');

/**
 * Forwarded instance.
 *
 * @param {String} ip The IP address.
 * @param {Number} port The port number.
 * @param {Boolean} secured The connection was secured.
 * @api private
 */
function Forwarded(ip, port, secured) {
  this.ip = ip || '127.0.0.1';
  this.secure = !!secured;
  this.port = +port || 0;
}

/**
 * List of possible proxy headers that should be checked for the original client
 * IP address and forwarded port.
 *
 * @type {Array}
 * @private
 */
var proxies = [
  {
    ip: 'x-forwarded-for',
    port: 'x-forwarded-port',
    proto: 'x-forwarded-proto'
  }, {
    ip: 'z-forwarded-for',
    port: 'z-forwarded-port',   // Estimated guess, no standard header available.
    proto: 'z-forwarded-proto'  // Estimated guess, no standard header available.
  }, {
    ip: 'forwarded',
    port: 'forwarded-port',
    proto: 'forwarded-proto'    // Estimated guess, no standard header available.
  }, {
    ip: 'x-real-ip',
    port: 'x-real-port'         // Estimated guess, no standard header available.
  }
];

/**
 * Search the headers for a possible match against a known proxy header.
 *
 * @param {Object} headers The received HTTP headers.
 * @param {Array} whitelist White list of proxies that should be checked.
 * @returns {String|Undefined} A IP address or nothing.
 * @api private
 */
function forwarded(headers) {
  for (var i = 0, length = proxies.length; i < length; i++) {
    if (!(proxies[i].ip in headers)) continue;

    var ports = (headers[proxies[i].port] || '').split(',')
      , ips = (headers[proxies[i].ip] || '').split(',');

    //
    // As these headers can potentially be set by a 1337H4X0R we need to ensure
    // that all supplied values are valid IP addresses. If we receive a none
    // IP value inside the IP header field we are going to assume that this
    // header has been compromised and should be ignored
    //
    if (!ips.length || !ips.every(net.isIP)) return;

    //
    // We've gotten a match on a HTTP header, we need to parse it further as it
    // could consist of multiple hops. The pattern for multiple hops is:
    //
    //   client, proxy, proxy, proxy, etc.
    //
    // So extracting the first IP should be sufficient.
    //
    return new Forwarded(ips.shift(), ports.shift());
  }
}

/**
 * Parse out the address information..
 *
 * @param {Object} obj A socket like object that could contain a `remoteAddress`.
 * @param {Object} headers The received HTTP headers.
 * @param {Array} whitelist White list
 * @returns {String} The IP address.
 * @api private
 */
module.exports = function parse(obj, headers, whitelist) {
  var proxied = forwarded(headers, whitelist)
    , connection = obj.connection
    , socket = connection
      ? connection.socket
      : obj.socket;

  //
  // We should always be testing for HTTP headers as remoteAddress would point
  // to proxies.
  //
  if (proxied) {
    return proxied;
  }

  // Check for the property on our given object.
  if ('object' === typeof obj) {
    if ('remoteAddress' in obj) {
      return new Forwarded(
        obj.remoteAddress,
        obj.remotePort
      );
    }

    // Edge case for Socket.IO and SockJS.
    if ('address' in obj && 'port' in obj) {
      return new Forwarded(
        obj.address,
        obj.port
      );
    }
  }

  if ('object' === typeof connection && 'remoteAddress' in connection) {
    return new Forwarded(
      connection.remoteAddress,
      connection.remotePort
    );
  }

  if ('object' === typeof socket && 'remoteAddress' in socket) {
    return new Forwarded(
      socket.remoteAddress,
      socket.remoteAddress
    );
  }

  return new Forwarded();
};
<|endoftext|>


<commit_before>var app = require('express')();
var _PORT_ = 8080;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req,res) {
	if (req.query.callback !== undefined)
	{
		console.log(req.query.callback);
		res.jsonp({"cards":[{"image":"http://i.imgur.com/eM2Uena.jpg","title":"Anamazingtitle","description":"Somethingaboutthiscard","ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"title":"Anamazingtitle2","description":"Somethingaboutthisothercard","ctas":[{"text":"300","value":"c2"}]},{"title":"Didn'tlikeanything?","description":"Searchforsomethingelse","ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
	else if (req.query.with_errors !== undefined)
	{
		res.json({"cards":[{"ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"ctas":[{"text":"300","value":"c2"}]},{"ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
	else
	{
		console.log("no callback");
		res.json({"cards":[{"image":"http://i.imgur.com/eM2Uena.jpg","title":"Anamazingtitle","description":"Somethingaboutthiscard","ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"title":"Anamazingtitle2","description":"Somethingaboutthisothercard","ctas":[{"text":"300","value":"c2"}]},{"title":"Didn'tlikeanything?","description":"Searchforsomethingelse","ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
});

app.listen(_PORT_, function() {
	console.log(`Server started on port: ${_PORT_}`);
});

<commit_msg>print error args<commit_after>var app = require('express')();
var _PORT_ = 8080;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req,res) {
	if (req.query.callback !== undefined)
	{
		console.log(req.query.callback);
		res.jsonp({"cards":[{"image":"http://i.imgur.com/eM2Uena.jpg","title":"Anamazingtitle","description":"Somethingaboutthiscard","ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"title":"Anamazingtitle2","description":"Somethingaboutthisothercard","ctas":[{"text":"300","value":"c2"}]},{"title":"Didn'tlikeanything?","description":"Searchforsomethingelse","ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
	else if (req.query.with_errors !== undefined)
	{
		console.log("errors "+req.query.with_errors);
		res.json({"cards":[{"ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"ctas":[{"text":"300","value":"c2"}]},{"ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
	else
	{
		console.log("no callback");
		res.json({"cards":[{"image":"http://i.imgur.com/eM2Uena.jpg","title":"Anamazingtitle","description":"Somethingaboutthiscard","ctas":[{"text":"125for1","value":"c1cta1"},{"text":"200for2","value":"c1cta2"}],"important":"yes"},{"title":"Anamazingtitle2","description":"Somethingaboutthisothercard","ctas":[{"text":"300","value":"c2"}]},{"title":"Didn'tlikeanything?","description":"Searchforsomethingelse","ctas":[{"text":"Search","value":"search"}],"important":"max"}]});
	}
});

app.listen(_PORT_, function() {
	console.log(`Server started on port: ${_PORT_}`);
});

<|endoftext|>


<commit_before>'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var fs = require('fs');
var path = require('path');
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var SourceMapConsumer = require('source-map').SourceMapConsumer;

var PLUGIN_NAME = 'gulp-sourcemap';

/**
 * Apply source map to the end of the source map chain
 *
 * @param sourceMap source map to be appended
 */
function applySourceMap(sourceMap) {
  /*jshint validthis:true */
  try {
    if (typeof sourceMap === 'string' || sourceMap instanceof String) {
      sourceMap = JSON.parse(sourceMap);
    }
    sourceMap.sources = [this.sourceMap.file];
    var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
    generator.applySourceMap(new SourceMapConsumer(this.sourceMap));
    this.sourceMap = JSON.parse(generator.toString());
  } catch (e) {
    gutil.log(gutil.colors.red('Error applying source map:'));
    console.error(e.stack);
  }
}

/**
 * Initialize source mapping chain
 */
module.exports.init = function init() {
  function sourceMapInit(file, encoding, callback) {
    /*jshint validthis:true */

    if (file.isNull()) {
      this.push(file);
      return callback();
    }

    if (file.isStream()) {
      return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    // initialize source map
    file.sourceMap = {
      version : 3,
      file: file.relative,
      names: [],
      mappings: '',
      sources: [file.relative],
      sourcesContent: [file.contents.toString()]
    };

    // add helper method to vinyl file
    file.applySourceMap = applySourceMap;

    this.push(file);
    callback();
  }

  return through.obj(sourceMapInit);
};

/**
 * Write the source map
 *
 * @param options options to change the way the source map is written
 *
 */
module.exports.write = function write(destPath, options) {
  if (options === undefined && Object.prototype.toString.call(destPath) === '[object Object]') {
    options = destPath;
    destPath = undefined;
  }
  options = options || {};

  // set defaults for options if unset
  if (options.includeContent === undefined)
    options.includeContent = true;
  if (options.addComment === undefined)
    options.addComment = true;

  function sourceMapWrite(file, encoding, callback) {
    /*jshint validthis:true */

    if (file.isNull() || !file.sourceMap) {
      this.push(file);
      return callback();
    }

    if (file.isStream()) {
      return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    var sourceMap = file.sourceMap;
    sourceMap.file = file.relative;

    if (options.sourceRoot)
      sourceMap.sourceRoot = options.sourceRoot;

    if (options.includeContent) {
      sourceMap.sourceRoot = options.sourceRoot || '/source/';
    } else {
      delete sourceMap.sourcesContent;
    }

    var comment;
    if (!destPath) {
      // encode source map into comment
      var base64Map = new Buffer(JSON.stringify(sourceMap)).toString('base64');
      comment = '\n//# sourceMappingURL=data:application/json;base64,' + base64Map;
    } else {
      // add new source map file to stream
      var sourceMapFile = new gutil.File({
        cwd: file.cwd,
        base: file.base,
        path: path.join(path.dirname(file.path), destPath, path.basename(file.path)) + '.map',
        contents: new Buffer(JSON.stringify(sourceMap))
      });
      this.push(sourceMapFile);

      comment = '\n//# sourceMappingURL=' + path.join(destPath, path.basename(file.path)) + '.map';
    }

    // append source map comment
    if (options.addComment)
      file.contents = Buffer.concat([file.contents, new Buffer(comment)]);

    this.push(file);
    callback();
  }

  return through.obj(sourceMapWrite);
};

module.exports.dest = function dest(options) {
  options = options || {};

  function sourceMapFilesWrite(file, encoding, callback) {
    /*jshint validthis:true */

  }

  return through.obj(sourceMapFilesWrite);
};
<commit_msg>Fixed: wrong source map path for sources in subdirs<commit_after>'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var fs = require('fs');
var path = require('path');
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var SourceMapConsumer = require('source-map').SourceMapConsumer;

var PLUGIN_NAME = 'gulp-sourcemap';

/**
 * Apply source map to the end of the source map chain
 *
 * @param sourceMap source map to be appended
 */
function applySourceMap(sourceMap) {
  /*jshint validthis:true */
  try {
    if (typeof sourceMap === 'string' || sourceMap instanceof String) {
      sourceMap = JSON.parse(sourceMap);
    }
    sourceMap.sources = [this.sourceMap.file];
    var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
    generator.applySourceMap(new SourceMapConsumer(this.sourceMap));
    this.sourceMap = JSON.parse(generator.toString());
  } catch (e) {
    gutil.log(gutil.colors.red('Error applying source map:'));
    console.error(e.stack);
  }
}

/**
 * Initialize source mapping chain
 */
module.exports.init = function init() {
  function sourceMapInit(file, encoding, callback) {
    /*jshint validthis:true */

    if (file.isNull()) {
      this.push(file);
      return callback();
    }

    if (file.isStream()) {
      return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    // initialize source map
    file.sourceMap = {
      version : 3,
      file: file.relative,
      names: [],
      mappings: '',
      sources: [file.relative],
      sourcesContent: [file.contents.toString()]
    };

    // add helper method to vinyl file
    file.applySourceMap = applySourceMap;

    this.push(file);
    callback();
  }

  return through.obj(sourceMapInit);
};

/**
 * Write the source map
 *
 * @param options options to change the way the source map is written
 *
 */
module.exports.write = function write(destPath, options) {
  if (options === undefined && Object.prototype.toString.call(destPath) === '[object Object]') {
    options = destPath;
    destPath = undefined;
  }
  options = options || {};

  // set defaults for options if unset
  if (options.includeContent === undefined)
    options.includeContent = true;
  if (options.addComment === undefined)
    options.addComment = true;

  function sourceMapWrite(file, encoding, callback) {
    /*jshint validthis:true */

    if (file.isNull() || !file.sourceMap) {
      this.push(file);
      return callback();
    }

    if (file.isStream()) {
      return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    var sourceMap = file.sourceMap;
    sourceMap.file = file.relative;

    if (options.sourceRoot)
      sourceMap.sourceRoot = options.sourceRoot;

    if (options.includeContent) {
      sourceMap.sourceRoot = options.sourceRoot || '/source/';
    } else {
      delete sourceMap.sourcesContent;
    }

    var comment;
    if (!destPath) {
      // encode source map into comment
      var base64Map = new Buffer(JSON.stringify(sourceMap)).toString('base64');
      comment = '\n//# sourceMappingURL=data:application/json;base64,' + base64Map;
    } else {
      // add new source map file to stream
      var sourceMapFile = new gutil.File({
        cwd: file.cwd,
        base: file.base,
        path: path.join(file.base, destPath, file.relative) + '.map',
        contents: new Buffer(JSON.stringify(sourceMap))
      });
      this.push(sourceMapFile);

      comment = '\n//# sourceMappingURL=' + path.join(path.relative(path.dirname(file.path), file.base), destPath, file.relative) + '.map';
    }

    // append source map comment
    if (options.addComment)
      file.contents = Buffer.concat([file.contents, new Buffer(comment)]);

    this.push(file);
    callback();
  }

  return through.obj(sourceMapWrite);
};

module.exports.dest = function dest(options) {
  options = options || {};

  function sourceMapFilesWrite(file, encoding, callback) {
    /*jshint validthis:true */

  }

  return through.obj(sourceMapFilesWrite);
};
<|endoftext|>


<commit_before>var fetch = fetch || require('node-fetch')

function jsref(ob, opts) {
  if (typeof ob !== 'object') return ob
  opts = opts || {}
  var root = opts.root || 'http://localhost/'
  var $ref = opts.$ref || '$ref'
  var vals = []
  var refs = {}

  var find = opts.find || function(url) {
    url = url.indexOf('http') ? root+url : url
    var [url,ref] = url.split('#')
    ref = (ref && ref.length) ? ref : opts.frag
    var rec = fetch(url, opts.http).then(res => res.json()).then(rec => ref ? extRefs('#'+ref,rec) : rec)
    return opts.deep ? rec.then(rec => jsref(rec, opts)) : rec
  }

  function extRefs(ref, val) {
    if (opts.refs && opts.refs[ref]) return opts.refs[ref]
    val = val || ob
    if (ref[0] != '#') return opts.lazy ? find(ref) : vals.push(find(ref))
    var keys = ref.substring(1).split(/[\.\/]/)
    if (!keys[0][1]) keys.shift()
    while(val && keys.length) val = val[keys.shift()]
    return val
  }

  function getRefs(ob) {
    if (ob && ob[$ref]) {
      if (!refs[ob[$ref]]) refs[ob[$ref]] = extRefs(ob[$ref])
    } else for (var i in ob) if (typeof ob[i] === 'object') getRefs(ob[i])
  }

  function fixRefs(ob) {
    if (ob && ob[$ref]) return refs[ob[$ref]] || ob
    for (var k in ob) if (typeof ob[k] === 'object') ob[k] = fixRefs(ob[k])
    return ob
  }

  getRefs(ob)

  if (opts.lazy) return Promise.resolve(fixRefs(ob))

  return Promise.all(vals).then(recs => {
    for (var r in refs) if (!isNaN(refs[r])) refs[r] = recs[refs[r]-1]
    return fixRefs(ob)
  })
}

if (typeof module !== 'undefined') module.exports = jsref
<commit_msg>browser<commit_after>var fetch = fetch || require('node-fetch')

function jsref(ob, opts) {
  if (typeof ob !== 'object') return ob
  opts = opts || {}
  var root = opts.root || 'http://localhost/'
  var $ref = opts.$ref || '$ref'
  var vals = []
  var refs = {}

  var find = opts.find || function(url) {
    url = url.indexOf('http') ? root+url : url
    var [url,ref] = url.split('#')
    ref = (ref && ref.length) ? ref : opts.frag
    var rec = fetch(url, opts.http).then(res => res.json()).then(rec => ref ? extRefs('#'+ref,rec) : rec)
    return opts.deep ? rec.then(rec => jsref(rec, opts)) : rec
  }

  function extRefs(ref, val) {
    if (opts.refs && opts.refs[ref]) return opts.refs[ref]
    val = val || ob
    if (ref[0] != '#') return opts.lazy ? find(ref) : vals.push(find(ref))
    var keys = ref.substring(1).split(/[\.\/]/)
    if (!keys[0][1]) keys.shift()
    while(val && keys.length) val = val[keys.shift()]
    return val
  }

  function getRefs(ob) {
    if (ob && ob[$ref]) {
      if (!refs[ob[$ref]]) refs[ob[$ref]] = extRefs(ob[$ref])
    } else for (var i in ob) if (typeof ob[i] === 'object') getRefs(ob[i])
  }

  function fixRefs(ob) {
    if (ob && ob[$ref]) return refs[ob[$ref]] || ob
    for (var k in ob) if (typeof ob[k] === 'object') ob[k] = fixRefs(ob[k])
    return ob
  }

  getRefs(ob)

  if (opts.lazy) return Promise.resolve(fixRefs(ob))

  return Promise.all(vals).then(recs => {
    for (var r in refs) if (!isNaN(refs[r])) refs[r] = recs[refs[r]-1]
    return fixRefs(ob)
  })
}

if (typeof module == 'object') module.exports = jsref
<|endoftext|>


<commit_before>(function (root) {

	var prepare = function(Ember) {
		Ember.whenNotRunning = function(name, original) {
			if(typeof name === 'function') {
				original = name;
				name = null;
			}

			name = name || 'isRunning';

			return function() {
				var self = this;

				if(this.get(name)) {
					return false;
				}

				this.set(name, true);

				//prepare arguments
				var end = function() {
					self.set(name, false);
				};

				var args = Array.prototype.slice.call(arguments, 0);
				args.unshift(end);

				//call original fn
				var retVar = original.apply(this, args);

				if(typeof retVar !== 'undefined') {
					if(retVar.then) {
						retVar.then(end, end);
					} else {
						end();
					}
				}
			};
		};

		if (Ember.EXTEND_PROTOTYPES === true) {
			Function.prototype.whenNotRunning = function(name) {
				return Ember.whenNotRunning(name, this);
			};
		}
	};

	//AMD
	if (typeof define !== 'undefined' && define.amd) {
		define(['ember'], function(Ember) {
			return prepare(Ember);
		});
	}

	//CommonJS
	else if (typeof module !== 'undefined' && module.exports) {
		module.exports = prepare(require('ember'));
	}

	//Script tag
	else {
		prepare(root.Ember);
	}

} (this));<commit_msg>better check of promises<commit_after>(function (root) {

	var prepare = function(Ember) {
		Ember.whenNotRunning = function(name, original) {
			if(typeof name === 'function') {
				original = name;
				name = null;
			}

			name = name || 'isRunning';

			return function() {
				var self = this;

				if(this.get(name)) {
					return false;
				}

				this.set(name, true);

				//prepare arguments
				var end = function() {
					self.set(name, false);
				};

				var args = Array.prototype.slice.call(arguments, 0);
				args.unshift(end);

				//call original fn
				var retVar = original.apply(this, args);

				if(typeof retVar !== 'undefined') {
					if(typeof retVar.then === 'function') {
						retVar.then(end, end);
					} else {
						end();
					}
				}
			};
		};

		if (Ember.EXTEND_PROTOTYPES === true) {
			Function.prototype.whenNotRunning = function(name) {
				return Ember.whenNotRunning(name, this);
			};
		}
	};

	//AMD
	if (typeof define !== 'undefined' && define.amd) {
		define(['ember'], function(Ember) {
			return prepare(Ember);
		});
	}

	//CommonJS
	else if (typeof module !== 'undefined' && module.exports) {
		module.exports = prepare(require('ember'));
	}

	//Script tag
	else {
		prepare(root.Ember);
	}

} (this));<|endoftext|>


<commit_before>var serialport = require('serialport');
var util = require('util');
var EventEmitter = require('events');

var debug = function() {};

function WaterRower( opts ) {
  var opts = opts || {};
  EventEmitter.call(this);

  this.comPort = opts.port || "";
  this.baudRate = opts.baudRate || 115200;
  this.pollRate = opts.pollRate || 800;
  this.lastPing = null;
  this.stateHandler = this.stateDisconnected;

  this.readings = {
    strokeCount: 0,
    totalSpeed: 0,
    averageSpeed: 0,
    distance: 0,
    heartRate: 0
  };

  debug("Creating new water rower");
  debug("\tlistening on port " + this.comPort);
  debug('\tlistening at rate ' + this.rate);
  debug('\tpolling at rate ' + this.pollRate);

  this.serialPort = new serialport.SerialPort( this.comPort, {
    baudrate: this.baudRate,
    disconnectedCallback: function () { this.emit('disconnect'); }.bind(this),
    parser: serialport.parsers.readline("\r\n")
  });

  this.serialPort.on("open", function () {
    debug('port ' + this.comPort + ' open');

    // tell the waterrower that we're wanting to talk to it.
    this.serialPort.write('USB\r\n');
  }.bind(this));

  this.serialPort.on("data", function(data) {
    var trimmedData = data.trim();
    debug('port ' + this.comPort + ' read ' + trimmedData );
    this.ingestMessage( data );
  }.bind(this));

  this.serialPort.on("closed", function () {
    debug('port ' + this.comPort + ' closed');
    this.emit('disconnect');
  }.bind(this));

  this.serialPort.on("error", function( err ) {
    debug('port ' + this.comPort + ' error ' + err);
    this.emit('error', err);
  }.bind(this));
}
util.inherits(WaterRower, EventEmitter);

var msgOnline = /^_WR_$/;
var msgPing = /^PING$/;
var msgError = /^ERROR$/;
var msgStrokeStart = /^SS$/;
var msgStrokeEnd = /^SE$/;
var msgStrokePulse = /^P([\dA-Fa-f]{2})$/;
var msgStrokeCount = /^IDD140([\dA-Fa-f]{4})$/;
var msgTotalSpeed = /^IDD148([\dA-Fa-f]{4})$/;
var msgAverageSpeed = /^IDD14A([\dA-Fa-f]{4})$/;
var msgDistance = /^IDD057([\dA-Fa-f]{4})$/;
var msgHeartrate = /^IDD1A0([\dA-Fa-f]{4})$/;

WaterRower.prototype.ingestMessage = function( msg ) {
  debug('port ' + this.comPort + ' dispatch ' + msg );

  // we consider *any* message, not just PING, as a confirmation of the controllers existence
  this.lastPing = Date.now();

  switch(true) {

    case msgError.test(msg):          this.emit('error', 'error from water rower');
                                      break;
    case msgStrokeStart.test(msg):    this.emit('stroke start');
                                      break;
    case msgStrokeEnd.test(msg):      this.emit('stroke end');
                                      break;
    case msgPing.test(msg):           // fallthrough
    default:                          this.stateHandler = this.stateHandler( msg );
                                      break;
  }
};

WaterRower.prototype.stateDisconnected = function ( msg ) {
  debug('in state disconnected ' + msg);

  if ( msgOnline.test(msg) ) {
    this.emit('connect');
    this.serialPort.emit('data', "let's start this party");
    return this.stateConnected;
  } else {
    return this.stateDisconnected;
  }
}

WaterRower.prototype.stateConnected = function ( msg ) {
  debug('in state connected');
  // in the conected state, we only care about starting the stroke_count chain
  this.emit('readings', this.readings);
  this.serialPort.write('IRD1400\r\n');
  return this.stateAwaitingStrokeCount;
}

WaterRower.prototype.stateAwaitingStrokeCount = function ( msg ) {
  debug('in state awaiting stroke count');

  var matches = msg.matches(msgStrokeCount);
  if (matches){
    // parse out the stroke count in the 'IDD140??\r\n' message,
    this.readings.strokeCount = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD148\r\n');
    return this.stateAwaitingTotalSpeed;
  } else {
    return this.stateAwaitingStrokeCount;
  }
}

WaterRower.prototype.stateAwaitingTotalSpeed = function ( msg ) {
  debug('in state awaiting total speed');

  var matches = msg.matches(msgTotalSpeed);
  if (matches){
    // parse out the total speed in the 'IDD148??\r\n' message,
    this.readings.totalSpeed = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD14A\r\n');
    return this.stateAwaitingAverageSpeed;
  } else {
    return this.stateAwaitingTotalSpeed;
  }
}

WaterRower.prototype.stateAwaitingAverageSpeed = function ( msg ) {
  debug('in state awaiting average speed');

  var matches = msg.matches(msgAverageSpeed);
  if (matches) {
    // parse out the average speed in the 'IDD057??\r\n' message,
    this.readings.averageSpeed = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD057\r\n');
    return this.stateAwaitingDistance;
  } else {
    return this.stateAwaitingAverageSpeed;
  }
}

WaterRower.prototype.stateAwaitingDistance = function ( msg ) {
  debug('in state awaiting distance');

  var matches = msg.matches(msgDistance);
  if (matches){
    // parse out the distance in the 'IDD057??\r\n' message,
    this.readings.distance = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD1A0\r\n');
    return this.stateAwaitingHeartrate;
  } else {
    return this.stateAwaitingDistance;
  }
}

WaterRower.prototype.stateAwaitingHeartrate = function ( msg ) {
  debug('in state awaiting heart rate');

  var matches = msg.matches(msgHeartrate);
  if (matches){
    // parse out the stroke count in the 'IDD057??\r\n' message,
    this.readings.heartRate = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD057\r\n');
    return this.stateConnected;
  } else {
    return this.stateAwaitingHeartrate;
  }
}

module.exports = function( opts ){
  var opts = opts || {};

  if (opts.debug) {
    debug = console.log;
  }
  return {
    WaterRower: WaterRower
  };
}
<commit_msg>Fix matches instead of match.<commit_after>var serialport = require('serialport');
var util = require('util');
var EventEmitter = require('events');

var debug = function() {};

function WaterRower( opts ) {
  var opts = opts || {};
  EventEmitter.call(this);

  this.comPort = opts.port || "";
  this.baudRate = opts.baudRate || 115200;
  this.pollRate = opts.pollRate || 800;
  this.lastPing = null;
  this.stateHandler = this.stateDisconnected;

  this.readings = {
    strokeCount: 0,
    totalSpeed: 0,
    averageSpeed: 0,
    distance: 0,
    heartRate: 0
  };

  debug("Creating new water rower");
  debug("\tlistening on port " + this.comPort);
  debug('\tlistening at rate ' + this.rate);
  debug('\tpolling at rate ' + this.pollRate);

  this.serialPort = new serialport.SerialPort( this.comPort, {
    baudrate: this.baudRate,
    disconnectedCallback: function () { this.emit('disconnect'); }.bind(this),
    parser: serialport.parsers.readline("\r\n")
  });

  this.serialPort.on("open", function () {
    debug('port ' + this.comPort + ' open');

    // tell the waterrower that we're wanting to talk to it.
    this.serialPort.write('USB\r\n');
  }.bind(this));

  this.serialPort.on("data", function(data) {
    var trimmedData = data.trim();
    debug('port ' + this.comPort + ' read ' + trimmedData );
    this.ingestMessage( data );
  }.bind(this));

  this.serialPort.on("closed", function () {
    debug('port ' + this.comPort + ' closed');
    this.emit('disconnect');
  }.bind(this));

  this.serialPort.on("error", function( err ) {
    debug('port ' + this.comPort + ' error ' + err);
    this.emit('error', err);
  }.bind(this));
}
util.inherits(WaterRower, EventEmitter);

var msgOnline = /^_WR_$/;
var msgPing = /^PING$/;
var msgError = /^ERROR$/;
var msgStrokeStart = /^SS$/;
var msgStrokeEnd = /^SE$/;
var msgStrokePulse = /^P([\dA-Fa-f]{2})$/;
var msgStrokeCount = /^IDD140([\dA-Fa-f]{4})$/;
var msgTotalSpeed = /^IDD148([\dA-Fa-f]{4})$/;
var msgAverageSpeed = /^IDD14A([\dA-Fa-f]{4})$/;
var msgDistance = /^IDD057([\dA-Fa-f]{4})$/;
var msgHeartrate = /^IDD1A0([\dA-Fa-f]{4})$/;

WaterRower.prototype.ingestMessage = function( msg ) {
  debug('port ' + this.comPort + ' dispatch ' + msg );

  // we consider *any* message, not just PING, as a confirmation of the controllers existence
  this.lastPing = Date.now();

  switch(true) {

    case msgError.test(msg):          this.emit('error', 'error from water rower');
                                      break;
    case msgStrokeStart.test(msg):    this.emit('stroke start');
                                      break;
    case msgStrokeEnd.test(msg):      this.emit('stroke end');
                                      break;
    case msgPing.test(msg):           // fallthrough
    default:                          this.stateHandler = this.stateHandler( msg );
                                      break;
  }
};

WaterRower.prototype.stateDisconnected = function ( msg ) {
  debug('in state disconnected ' + msg);

  if ( msgOnline.test(msg) ) {
    this.emit('connect');
    this.serialPort.emit('data', "let's start this party");
    return this.stateConnected;
  } else {
    return this.stateDisconnected;
  }
}

WaterRower.prototype.stateConnected = function ( msg ) {
  debug('in state connected');
  // in the conected state, we only care about starting the stroke_count chain
  this.emit('readings', this.readings);
  this.serialPort.write('IRD1400\r\n');
  return this.stateAwaitingStrokeCount;
}

WaterRower.prototype.stateAwaitingStrokeCount = function ( msg ) {
  debug('in state awaiting stroke count');

  var matches = msg.match(msgStrokeCount);
  if (matches){
    // parse out the stroke count in the 'IDD140??\r\n' message,
    this.readings.strokeCount = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD148\r\n');
    return this.stateAwaitingTotalSpeed;
  } else {
    return this.stateAwaitingStrokeCount;
  }
}

WaterRower.prototype.stateAwaitingTotalSpeed = function ( msg ) {
  debug('in state awaiting total speed');

  var matches = msg.match(msgTotalSpeed);
  if (matches){
    // parse out the total speed in the 'IDD148??\r\n' message,
    this.readings.totalSpeed = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD14A\r\n');
    return this.stateAwaitingAverageSpeed;
  } else {
    return this.stateAwaitingTotalSpeed;
  }
}

WaterRower.prototype.stateAwaitingAverageSpeed = function ( msg ) {
  debug('in state awaiting average speed');

  var matches = msg.match(msgAverageSpeed);
  if (matches) {
    // parse out the average speed in the 'IDD057??\r\n' message,
    this.readings.averageSpeed = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD057\r\n');
    return this.stateAwaitingDistance;
  } else {
    return this.stateAwaitingAverageSpeed;
  }
}

WaterRower.prototype.stateAwaitingDistance = function ( msg ) {
  debug('in state awaiting distance');

  var matches = msg.match(msgDistance);
  if (matches){
    // parse out the distance in the 'IDD057??\r\n' message,
    this.readings.distance = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD1A0\r\n');
    return this.stateAwaitingHeartrate;
  } else {
    return this.stateAwaitingDistance;
  }
}

WaterRower.prototype.stateAwaitingHeartrate = function ( msg ) {
  debug('in state awaiting heart rate');

  var matches = msg.match(msgHeartrate);
  if (matches){
    // parse out the stroke count in the 'IDD057??\r\n' message,
    this.readings.heartRate = Number.parseInt( matches[1], 16);

    this.serialPort.write('IRD057\r\n');
    return this.stateConnected;
  } else {
    return this.stateAwaitingHeartrate;
  }
}

module.exports = function( opts ){
  var opts = opts || {};

  if (opts.debug) {
    debug = console.log;
  }
  return {
    WaterRower: WaterRower
  };
}
<|endoftext|>


<commit_before>var fs = require("fs");
var thjs = require("telehash-js");
exports.debug = thjs.debug;
exports.info = thjs.info;

function install(self, args)
{
  // crypto
  require("telehash-cs1a").install(self, args);
  require("telehash-cs2a").install(self, args);
  require("telehash-cs3a").install(self, args);

  // networking
  require("telehash-ipv4").install(self, args);
  require("telehash-ipv6").install(self, args);
  require("telehash-http").install(self, args);

  // extensions
  require("telehash-stream").install(self, args);
  require("telehash-telesocket").install(self, args);
  require("telehash-thtp").install(self, args);
  require("telehash-token").install(self, args);
}

exports.init = function(args, cbDone)
{
  if(!args) args = {};
  var self = new thjs.switch();

  install(self, args);

  function seed()
  {
    require("telehash-seeds").install(self, args);

    self.online(function(err){
      cbDone(err, self);
    });
  }

  if(args.id)
  {
    if(typeof args.id == "string" && fs.existsSync(args.id)) args.id = require(args.id);
    if(typeof args.id == "object")
    {
      var err;
      if((err = self.load(args.id))) return cbDone("error loading id, "+err+": "+JSON.stringify(args.id));
      seed();
      return self;
    }
  }

  self.make(function(err,id){
    if(err) return cbDone("error creating id, "+err);
    if(typeof args.id == "string") fs.writeFileSync(args.id, JSON.stringify(id, null, 4));
    args.id = id;
    self.load(id);
    seed();
  });

  return self;
}

<commit_msg>pass bridge setting through<commit_after>var fs = require("fs");
var thjs = require("telehash-js");
exports.debug = thjs.debug;
exports.info = thjs.info;

function install(self, args)
{
  // crypto
  require("telehash-cs1a").install(self, args);
  require("telehash-cs2a").install(self, args);
  require("telehash-cs3a").install(self, args);

  // networking
  require("telehash-ipv4").install(self, args);
  require("telehash-ipv6").install(self, args);
  require("telehash-http").install(self, args);

  // extensions
  require("telehash-stream").install(self, args);
  require("telehash-telesocket").install(self, args);
  require("telehash-thtp").install(self, args);
  require("telehash-token").install(self, args);
}

exports.init = function(args, cbDone)
{
  if(!args) args = {};
  var self = new thjs.switch();
  if(args.bridge) self.isBridge(true);

  install(self, args);

  function seed()
  {
    require("telehash-seeds").install(self, args);

    self.online(function(err){
      cbDone(err, self);
    });
  }

  if(args.id)
  {
    if(typeof args.id == "string" && fs.existsSync(args.id)) args.id = require(args.id);
    if(typeof args.id == "object")
    {
      var err;
      if((err = self.load(args.id))) return cbDone("error loading id, "+err+": "+JSON.stringify(args.id));
      seed();
      return self;
    }
  }

  self.make(function(err,id){
    if(err) return cbDone("error creating id, "+err);
    if(typeof args.id == "string") fs.writeFileSync(args.id, JSON.stringify(id, null, 4));
    args.id = id;
    self.load(id);
    seed();
  });

  return self;
}

<|endoftext|>


<commit_before>'use strict';

exports = module.exports = function (gulp){
  var tasks = !gulp || gulp.tasks || (gulp._registry && gulp._registry._tasks);
  if(!tasks){
    throw new TypeError('pass a gulp instance to the module');
  }

  var readline = require('readline');
  var completer = require('./lib/completer');

  // create a simple readline interface
  //
  var repl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer: function completion(line){
      return completer(gulp, line);
    }
  });

  // exit on SIGINT, give a timestamp
  //
  repl.on('SIGINT', function(){
    process.stdout.write('\n');
    console.log(new Date());
    process.exit();
  });

  // dispatch tasks only if line wasn't empty
  //
  repl.on('line', function onLine(line){
    line = line.trim();
    if(!line){ return repl.prompt(); }

    var tasks;
    if(gulp._registry){
      tasks = gulp._registry && gulp._registry._tasks;
    } else { tasks = gulp.tasks; }

    var notFound = [];
    line = line.split(/[ ]+/).filter(function(name){
      if(tasks && !tasks[name]){
        notFound.push(name);
      } else { return true; }
    });

    if(notFound.length){
      var plural = notFound.length > 1;
      console.log(
        ' Warning: `%s` task%s %s undefined',
        notFound.join(', '),
        plural ? 's' : '',
        plural ? 'are' : 'is'
      );

      if(!line.length){ return repl.prompt(); }
    }

    var runner = gulp.parallel || gulp.start;
    var result = runner.apply(gulp, line);

    // gulp#4.0
    if(typeof result === 'function'){ result(); }
  });

  return repl;
};
<commit_msg>dev: make module compatible with gulp and gulp-runtime<commit_after>'use strict';

exports = module.exports = gulpRepl;

function gulpRepl(_, o){
  // lazyyy
  var util = require('./lib/util');
  var readline = require('readline');

  var gulp = util.getGulp(_);
  var tasks = util.getRegistry(gulp);

  /**
   * create a readline interface
  **/
  var repl = readline.createInterface({
    input: o && o.input || process.stdin,
    output: o && o.output || process.stdout,
    completer: o && o.completer || function(line){
      return util.completer(line, tasks);
    }
  });

  /**
   * queue tasks when line is not empty
  **/
  repl.on('line', function onLine(line){
    line = line.trim();

    if(!line){ return repl.prompt(); }

    var queue = {found: [], notFound: []};

    line.split(/[ ]+/).forEach(function(name, index, pending){
      var tail = pending.slice(index).join(' ');
      var task = tasks.get(tail) || tasks.get(name);

      if(task){ queue.found.push(task.label || name); } else {
        queue.notFound.push(name);
      }
    });

    if(queue.notFound.length){
      var plural = queue.notFound.length > 1;
      console.log(' `%s` task%s %s not defined yet',
        queue.notFound,
        plural ? 's' : '',
        plural ? 'are' : 'is'
      );
    }

    if(!queue.found.length){
      return repl.prompt();
    }

    var runner = gulp.parallel || gulp.start;
    var result = runner.apply(gulp, queue.found);
    if(typeof result === 'function'){
      result(); // gulp#4.0
    }
  });

  /**
   * exit on SIGINT with a timestamp
  **/
  repl.on('SIGINT', function(){
    process.stdout.write('\n');
    console.log(new Date());
    process.exit(0);
  });

  return repl;
}
<|endoftext|>