<commit_before>/* Copyright © 2015 PointSource, LLC. All rights reserved. */
var _ = require('lodash'),
    winston = require('winston'),
    path = require('path'),
    cluster = require('cluster'),
    stackTrace = require('stack-trace'),
    util = require('util');

exports.init = function(config) {

    var cfg = config.get('logger');

    var showLocation = cfg.showLocation;

    var logger = new (winston.Logger)({
        levels: cfg.levels
    });

    var workerCount = config.get('cluster').maxWorkers; //if workerCount === 1, don't display the pid

    winston.addColors(cfg.colors);

    //first attempt to load a code-based logger from <app>/logger.js
    //If that doesn't work we'll continue to use the normal config
    try {
        var extLogger = require(global.__appDir + '/' + 'logger');
        extLogger.init(logger);
    } catch (err) {
        setupTransports(cfg, logger);
    }

    _.keys(cfg.levels).forEach(function(level) {

        module.exports[level.toLowerCase()] = function() {

            var args = [].slice.call(arguments); //convert to pure array
            if (workerCount !== 1) { //cluster mode
                var meta = {};
                if (_.isObject(args[args.length - 1])) {
                    meta = args[args.length - 1];
                } else {
                    [].push.call(args, meta);
                }

                //if we're logging on behalf of a worker process, this will already be set
                if (!meta.pid) {
                    meta.pid =  process.pid;
                }

                //if we're in clustered mode, throw the service name in the metadata
                if (showLocation) {
                    var location = getLocation();
                    if (location) {
                        meta.service = location;
                    }
                }
            }

            if (cluster.isWorker) {
                var str = JSON.stringify({
                    level: level,
                    args: args
                });
                process.send(str);
            } else {
                if (workerCount === 1 && showLocation) {
                    var location = getLocation();
                    if (location) {
                        args[0] = location + ' - ' + args[0];
                    }
                }
                logger[level.toLowerCase()].apply(logger, args);
                buffer(level.toLowerCase(), args);
            }

        };
    });

    module.exports['components'] = cfg.components;
    module.exports['logger'] = logger;
    module.exports['levels'] = cfg.levels;
    module.exports['getComponentLogger'] = function(component) {
        var theLogger = this.logger;
        if(!this.components || !this.components[component] || !this.components[component].loglevels) {
            theLogger.error('The component logger ' + component + ' is not configured or not configured properly. Using base logger.');
            return theLogger;
        }
        var loglevels = this.components[component].loglevels;
        var logger = this;
        var tmp = {'component':component};
        var self = this;
        _.keys(this.levels).forEach(function(lev){
            tmp[lev] = function() {
                var args = [].slice.call(arguments);
                args[0] = "" + this.component + ' - ' + args[0];
                tlevels = [];
                //look through transports and save current log levels
                Object.keys(theLogger.transports).forEach(function(k) {
                    tlevels.push([k, theLogger.transports[k].level]);
                    var newLevel = loglevels[k];
                    if(newLevel) { // if overridden by component, set the loglevel for this transport
                        theLogger.transports[k].level = newLevel;
                    }
                });
                self[lev](args);
                tlevels.forEach(function(levelinfo) { // restore all the transport loglevels
                    theLogger.transports[levelinfo[0]].level = levelinfo[1];
                });
            }
        });
        return tmp;
    };

    //The buffer stores all logged data, regardless of log level
    //rather than relying on array.push/slice which are slow,
    //we keep the buffer a fixed size and just loop the index around
    var crashDumpCfg = config.get('crashDump') || {};
    var bufferIdx = 0;
    var bufferLength = crashDumpCfg.length;
    var bufferData = [];
    var bufferEnabled = crashDumpCfg.enabled;

    function buffer(level, args) {
        if (bufferEnabled) {
            bufferData[bufferIdx] = {args: args, ts: Date.now(), level: level};
            bufferIdx++;
            if (bufferIdx > bufferLength) {
                bufferIdx = 0;
            }
        }
    }

    //TODO: support different dump types, e.g. console vs file
    exports.dumpBuffer = function(err) {

        if (bufferEnabled) {
            console.log('---------- Crash Report ' + (new Date().toString()) + ' ----------');
            console.log('PID:         ', process.pid);
            console.log('Uptime:      ', process.uptime() + 's');
            console.log('Heap used:   ', process.memoryUsage().heapUsed);
            console.log('Heap total:  ', process.memoryUsage().heapTotal);

            var log = function (data) {
                console.log('' + data.ts + ' ' + data.level + ': ' + util.format.apply(null, data.args));
            }
            for (var i = bufferIdx; i < bufferData.length; i++) {
                log(bufferData[i]);
            }

            for (var i = 0; i < bufferIdx; i++) {
                log(bufferData[i]);
            }
        }
    };

};

//Determine the name of the service or javascript module that called logger
function getLocation() {
    var trace = stackTrace.get();

    //trace.forEach(function(e){
    //    console.log('mytrace: ' + e.getFileName());
    //});

    //use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
    //  However, component loggers put an extra level in, so search down until the location is not 'logger'
    //  There's code to search a long way down the stack, but in practice the next (3) will be hit and used
    //    since its name is not logger.
    var idx = 2;
    var modNm = 'logger';
    var rmodNm = null;
    var skip = ['logger', 'logger.js'];
    while((skip.indexOf(modNm) >= 0) && trace.length > idx) {
        var fpath = trace[idx].getFileName();
        ++idx;
        if(fpath.slice(0,'native'.length) == 'native') {
            continue; // skip native modules
        }
        modNm = null;
        var mod = null;
        try {
            mod = require(fpath);
        } catch(err) {
            // do nothing here, it's checked later
        }
        if(mod) { //__id is injected into services by the loader
            if(!mod.__id) {
                modNm = fpath.split('/').pop();
                rmodNm = modNm;
            } else {
                modNm = mod.__id;
                if(modNm != null) {
                    rmodNm = modNm;
                }
            }
        } else {
            modNm = fpath.split('/').pop();
            rmodNm = modNm;
        }
    }
    return rmodNm;
}

function setupTransports(cfg, logger) {
    var func = 'setupTransports';
    //dynamically add transports based on the config
    //Each transport will have a package, which is the package name of the transport, e.g. winston-papertrail
    //and a field, which is the field within the transport containing the instance, e.g. Papertrail
    cfg.transports.forEach(function(transport) {
        transport.options = transport.options || {};
        if(transport.options.timestamp) {
            var ts = transport.options.timestamp.trim();
            var tsl = ts.toLowerCase();
            if(tsl == 'true') {
                transport.options.timestamp = true;
            } else if(tsl == 'false') {
                transport.options.timestamp = false;
            } else {
                try {
                    var tsm = require(global.__appDir + '/' + ts);
                    if(typeof tsm.init === 'function' && typeof tsm.timestamp === 'function') {
                        transport.options.timestamp = tsm.timestamp;
                        tsm.init(); // allow one-time init if necessary, but require the function to be there
                    } else {
                        transport.options.timestamp = true;
                        throw new Error('timestamp module must contain timestamp and init functions.');
                    }
                    try {
                        console.log(func + ': type of transport.options.timestamp is now: ' + typeof tsm.timestamp);
                    } catch(err) {
                        console.log(func + ': error parsing timestamp type (true/false/modulename) - ' + err);
                    }
                } catch( err ) {
                    //not sure, set it to true....
                    console.log(func + ': defaulting timestamp to true. ' + err);
                }
            }
        }
        var locationsToTry = [
            transport.package,
            path.join(global.__appDir, 'node_modules', transport.package),
            path.join(global.__appDir, transport.package)
        ];
        var mod = null;
        for (var i = 0; i < locationsToTry.length; i++) {
            try {
                mod = require(locationsToTry[i]);
                break;
            } catch (err) {
                //try next
            }
        }
        if (mod === null) {
            throw new Error('Could not locate logger transport package ' + transport.package + '.');
        }

        var obj = mod;

        //if transport field is something like transports.Console, split at the dots and dereference each part
        transport.field.split('.').forEach(function(field) {
            obj = obj[field];
        });
        logger.add(obj, transport.options);
    });

}

<commit_msg>Fix error when timestamp set to boolean<commit_after>/* Copyright © 2015 PointSource, LLC. All rights reserved. */
var _ = require('lodash'),
    winston = require('winston'),
    path = require('path'),
    cluster = require('cluster'),
    stackTrace = require('stack-trace'),
    util = require('util');

exports.init = function (config) {

    var cfg = config.get('logger');

    var showLocation = cfg.showLocation;

    var logger = new (winston.Logger)({
        levels: cfg.levels
    });

    var workerCount = config.get('cluster').maxWorkers; //if workerCount === 1, don't display the pid

    winston.addColors(cfg.colors);

    //first attempt to load a code-based logger from <app>/logger.js
    //If that doesn't work we'll continue to use the normal config
    try {
        var extLogger = require(global.__appDir + '/' + 'logger');
        extLogger.init(logger);
    } catch (err) {
        setupTransports(cfg, logger);
    }

    _.keys(cfg.levels).forEach(function (level) {

        module.exports[level.toLowerCase()] = function () {

            var args = [].slice.call(arguments); //convert to pure array
            if (workerCount !== 1) { //cluster mode
                var meta = {};
                if (_.isObject(args[args.length - 1])) {
                    meta = args[args.length - 1];
                } else {
                    [].push.call(args, meta);
                }

                //if we're logging on behalf of a worker process, this will already be set
                if (!meta.pid) {
                    meta.pid = process.pid;
                }

                //if we're in clustered mode, throw the service name in the metadata
                if (showLocation) {
                    var location = getLocation();
                    if (location) {
                        meta.service = location;
                    }
                }
            }

            if (cluster.isWorker) {
                var str = JSON.stringify({
                    level: level,
                    args: args
                });
                process.send(str);
            } else {
                if (workerCount === 1 && showLocation) {
                    var location = getLocation();
                    if (location) {
                        args[0] = location + ' - ' + args[0];
                    }
                }
                logger[level.toLowerCase()].apply(logger, args);
                buffer(level.toLowerCase(), args);
            }

        };
    });

    module.exports['components'] = cfg.components;
    module.exports['logger'] = logger;
    module.exports['levels'] = cfg.levels;
    module.exports['getComponentLogger'] = function (component) {
        var theLogger = this.logger;
        if (!this.components || !this.components[component] || !this.components[component].loglevels) {
            theLogger.error('The component logger ' + component + ' is not configured or not configured properly. Using base logger.');
            return theLogger;
        }
        var loglevels = this.components[component].loglevels;
        var logger = this;
        var tmp = {'component': component};
        var self = this;
        _.keys(this.levels).forEach(function (lev) {
            tmp[lev] = function () {
                var args = [].slice.call(arguments);
                args[0] = "" + this.component + ' - ' + args[0];
                var tlevels = [];
                //look through transports and save current log levels
                Object.keys(theLogger.transports).forEach(function (k) {
                    tlevels.push([k, theLogger.transports[k].level]);
                    var newLevel = loglevels[k];
                    if (newLevel) { // if overridden by component, set the loglevel for this transport
                        theLogger.transports[k].level = newLevel;
                    }
                });
                self[lev](args);
                tlevels.forEach(function (levelinfo) { // restore all the transport loglevels
                    theLogger.transports[levelinfo[0]].level = levelinfo[1];
                });
            };
        });
        return tmp;
    };

    //The buffer stores all logged data, regardless of log level
    //rather than relying on array.push/slice which are slow,
    //we keep the buffer a fixed size and just loop the index around
    var crashDumpCfg = config.get('crashDump') || {};
    var bufferIdx = 0;
    var bufferLength = crashDumpCfg.length;
    var bufferData = [];
    var bufferEnabled = crashDumpCfg.enabled;

    function buffer(level, args) {
        if (bufferEnabled) {
            bufferData[bufferIdx] = {args: args, ts: Date.now(), level: level};
            bufferIdx++;
            if (bufferIdx > bufferLength) {
                bufferIdx = 0;
            }
        }
    }

    //TODO: support different dump types, e.g. console vs file
    exports.dumpBuffer = function (err) {

        if (bufferEnabled) {
            console.log('---------- Crash Report ' + (new Date().toString()) + ' ----------');
            console.log('PID:         ', process.pid);
            console.log('Uptime:      ', process.uptime() + 's');
            console.log('Heap used:   ', process.memoryUsage().heapUsed);
            console.log('Heap total:  ', process.memoryUsage().heapTotal);

            var log = function (data) {
                console.log('' + data.ts + ' ' + data.level + ': ' + util.format.apply(null, data.args));
            };

            for (var i = bufferIdx; i < bufferData.length; i++) {
                log(bufferData[i]);
            }

            for (var i = 0; i < bufferIdx; i++) {
                log(bufferData[i]);
            }
        }
    };

};

//Determine the name of the service or javascript module that called logger
function getLocation() {
    var trace = stackTrace.get();

    //trace.forEach(function(e){
    //    console.log('mytrace: ' + e.getFileName());
    //});

    //use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
    //  However, component loggers put an extra level in, so search down until the location is not 'logger'
    //  There's code to search a long way down the stack, but in practice the next (3) will be hit and used
    //    since its name is not logger.
    var idx = 2;
    var modNm = 'logger';
    var rmodNm = null;
    var skip = ['logger', 'logger.js'];
    while ((skip.indexOf(modNm) >= 0) && trace.length > idx) {
        var fpath = trace[idx].getFileName();
        ++idx;
        if (fpath.slice(0, 'native'.length) === 'native') {
            continue; // skip native modules
        }
        modNm = null;
        var mod = null;
        try {
            mod = require(fpath);
        } catch (err) {
            // do nothing here, it's checked later
        }
        if (mod) { //__id is injected into services by the loader
            if (!mod.__id) {
                modNm = fpath.split('/').pop();
                rmodNm = modNm;
            } else {
                modNm = mod.__id;
                if (modNm !== null) {
                    rmodNm = modNm;
                }
            }
        } else {
            modNm = fpath.split('/').pop();
            rmodNm = modNm;
        }
    }
    return rmodNm;
}

function setupTransports(cfg, logger) {
    var func = 'setupTransports';
    //dynamically add transports based on the config
    //Each transport will have a package, which is the package name of the transport, e.g. winston-papertrail
    //and a field, which is the field within the transport containing the instance, e.g. Papertrail
    cfg.transports.forEach(function (transport) {
        transport.options = transport.options || {};
        if (typeof transport.options.timestamp !== 'undefined') {
            var ts = transport.options.timestamp;

            if (ts === true || ts === false) {
                //don't need to do anything -- already handled by winston
            } else {
                //is a string
                var tsl = ts.toLowerCase();
                try {
                    var tsm = require(global.__appDir + '/' + ts);
                    if (typeof tsm.init === 'function' && typeof tsm.timestamp === 'function') {
                        transport.options.timestamp = tsm.timestamp;
                        tsm.init(); // allow one-time init if necessary, but require the function to be there
                    } else {
                        transport.options.timestamp = true;
                        throw new Error('timestamp module must contain timestamp and init functions.');
                    }
                    try {
                        console.log(func + ': type of transport.options.timestamp is now: ' + typeof tsm.timestamp);
                    } catch (err) {
                        console.log(func + ': error parsing timestamp type (true/false/modulename) - ' + err);
                    }
                } catch (err) {
                    //not sure, set it to true....
                    console.log(func + ': defaulting timestamp to true. ' + err);
                }
            }

        }
        var locationsToTry = [
            transport.package,
            path.join(global.__appDir, 'node_modules', transport.package),
            path.join(global.__appDir, transport.package)
        ];
        var mod = null;
        for (var i = 0; i < locationsToTry.length; i++) {
            try {
                mod = require(locationsToTry[i]);
                break;
            } catch (err) {
                //try next
            }
        }
        if (mod === null) {
            throw new Error('Could not locate logger transport package ' + transport.package + '.');
        }

        var obj = mod;

        //if transport field is something like transports.Console, split at the dots and dereference each part
        transport.field.split('.').forEach(function (field) {
            obj = obj[field];
        });
        logger.add(obj, transport.options);
    });

}

<|endoftext|>


<commit_before>'use strict';

var studentList = [];
var wrap = document.getElementById('test');

console.log('hello world');

function Student (firstName, lastName, imgSrc, linkdIn, gitHubURL) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.imgSrc = imgSrc;
  this.linkdIn = linkdIn;
  this.gitHubURL = gitHubURL;
  studentList.push(this);
  this.studentID = studentID();
}
var studentID = function() {
  return Math.random() + '' + Math.random();
};

function StudentGroupProject (students, imgSrc, title, discription, repoURL, deployedURL) {
  this.students = studentList;
  this.imgSrc = imgSrc;
  this.title = title;
  this.discription = discription;
  this.repoURL = repoURL;
  this.deployedURL = deployedURL;

}

function handleStudentSubmit(event){
  // stop the browser from reloading
  event.preventDefault();
  var form = event.target;

  var studentFName = form.firstName.value;
  var studentLname = form.lastName.value;
  var studentImage = form.studentImg.value;
  var studentLink = form.linkdIn.value;
  var studentGitHub = form.gitHub.value;

  form.firstName.value = '';
  form.lastName.value = '';
  form.studentImg.value = '';
  form.linkdIn.value = '';
  form.gitHub.value = '';

  var studentUpload = new Student (studentFName, studentLname, studentImage, studentLink, studentGitHub);
  localStorage.data = JSON.stringify(studentList);

}
try {
  var storeCreateFrom = document.getElementById('submit');
  storeCreateFrom.addEventListener('submit', handleStudentSubmit);
} catch (error) {
  console.log('error');
}
<commit_msg>Local Storage 2<commit_after>'use strict';

var studentList = [];
var wrap = document.getElementById('test');
var data;

console.log('hello world');

function Student (firstName, lastName, imgSrc, linkdIn, gitHubURL) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.imgSrc = imgSrc;
  this.linkdIn = linkdIn;
  this.gitHubURL = gitHubURL;
  studentList.push(this);
  this.studentID = studentID();
}
var studentID = function() {
  return Math.random() + '' + Math.random();
};

function StudentGroupProject (students, imgSrc, title, discription, repoURL, deployedURL) {
  this.students = studentList;
  this.imgSrc = imgSrc;
  this.title = title;
  this.discription = discription;
  this.repoURL = repoURL;
  this.deployedURL = deployedURL;

}

function handleStudentSubmit(event){
  // stop the browser from reloading
  event.preventDefault();
  var form = event.target;

  var studentFName = form.firstName.value;
  var studentLname = form.lastName.value;
  var studentImage = form.studentImg.value;
  var studentLink = form.linkdIn.value;
  var studentGitHub = form.gitHub.value;

  form.firstName.value = '';
  form.lastName.value = '';
  form.studentImg.value = '';
  form.linkdIn.value = '';
  form.gitHub.value = '';

var studentUpload = new Student (studentFName, studentLname, studentImage, studentLink, studentGitHub);
  console.log(studentList);
  localStorage.data = JSON.stringify(studentList);
  console.log(localStorage.data);
}
try {
  var storeCreateFrom = document.getElementById('submit');
  storeCreateFrom.addEventListener('submit', handleStudentSubmit);
} catch (error) {
  console.log('error');
}

studentList = JSON.parse(localStorage.data);
console.log(studentList);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import editor from './Editor';
import Notifier from './Notification.js';
import classSet from 'classnames';

class TableEditColumn extends Component {
  constructor(props) {
    super(props);
    this.timeouteClear = 0;
    this.state = {
      shakeEditor: false
    };
  }

  handleKeyPress = e => {
    if (e.keyCode === 13) {
      // Pressed ENTER
      const value = e.currentTarget.type === 'checkbox' ?
                      this._getCheckBoxValue(e) : e.currentTarget.value;

      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
    } else if (e.keyCode === 27) {
      this.props.completeEdit(
        null, this.props.rowIndex, this.props.colIndex);
    } else if (e.type === 'click') {  // textarea click save button
      const value = e.target.parentElement.firstChild.value;
      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(
          value, this.props.rowIndex, this.props.colIndex);
    }
  }

  handleBlur = e => {
    e.stopPropagation();
    if (this.props.blurToSave) {
      const value = e.currentTarget.type === 'checkbox' ?
                      this._getCheckBoxValue(e) : e.currentTarget.value;
      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(
          value, this.props.rowIndex, this.props.colIndex);
    }
  }

  handleCustomUpdate = value => {
    this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
  }

  validator(value) {
    const ts = this;
    if (ts.props.editable.validator) {
      const valid = ts.props.editable.validator(value);
      if (valid !== true) {
        ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel');
        const input = ts.refs.inputRef;
        // animate input
        ts.clearTimeout();
        ts.setState({ shakeEditor: true });
        ts.timeouteClear = setTimeout(() => {
          ts.setState({ shakeEditor: false });
        }, 300);
        input.focus();
        return false;
      }
    }
    return true;
  }
  clearTimeout() {
    if (this.timeouteClear !== 0) {
      clearTimeout(this.timeouteClear);
      this.timeouteClear = 0;
    }
  }
  componentDidMount() {
    this.refs.inputRef.focus();
  }

  componentWillUnmount() {
    this.clearTimeout();
  }

  render() {
    const { editable, format, fieldValue, customEditor } = this.props;
    const { shakeEditor } = this.state;
    const attr = {
      ref: 'inputRef',
      onKeyDown: this.handleKeyPress,
      onBlur: this.handleBlur
    };
    // put placeholder if exist
    editable.placeholder && (attr.placeholder = editable.placeholder);

    const editorClass = classSet({ 'animated': shakeEditor, 'shake': shakeEditor });
    let cellEditor;
    if (customEditor) {
      const customEditorProps = {
        row: this.props.row,
        ...attr,
        defaultValue: fieldValue || '',
        ...customEditor.customEditorParameters
      };
      cellEditor = customEditor.getElement(this.handleCustomUpdate, customEditorProps);
    } else {
      cellEditor = editor(editable, attr, format, editorClass, fieldValue || '');
    }

    return (

        { cellEditor }
        <Notifier ref='notifier'/>

    );
  }

  _getCheckBoxValue(e) {
    let value = '';
    const values = e.currentTarget.value.split(':');
    value = e.currentTarget.checked ? values[0] : values[1];
    return value;
  }
}

TableEditColumn.propTypes = {
  completeEdit: PropTypes.func,
  rowIndex: PropTypes.number,
  colIndex: PropTypes.number,
  blurToSave: PropTypes.bool,
  editable: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object ]),
  format: PropTypes.oneOfType([ PropTypes.bool, PropTypes.func ]),
  row: PropTypes.any,
  fieldValue: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.bool,
    PropTypes.number,
    PropTypes.array,
    PropTypes.object
  ])
};

export default TableEditColumn;
<commit_msg>fix #630. Actually, maybe I should give each column with a type definition to avoid this problem. Cause of after editing, the number value will become a string.<commit_after>import React, { Component, PropTypes } from 'react';
import editor from './Editor';
import Notifier from './Notification.js';
import classSet from 'classnames';

class TableEditColumn extends Component {
  constructor(props) {
    super(props);
    this.timeouteClear = 0;
    this.state = {
      shakeEditor: false
    };
  }

  handleKeyPress = e => {
    if (e.keyCode === 13) {
      // Pressed ENTER
      const value = e.currentTarget.type === 'checkbox' ?
                      this._getCheckBoxValue(e) : e.currentTarget.value;

      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
    } else if (e.keyCode === 27) {
      this.props.completeEdit(
        null, this.props.rowIndex, this.props.colIndex);
    } else if (e.type === 'click') {  // textarea click save button
      const value = e.target.parentElement.firstChild.value;
      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(
          value, this.props.rowIndex, this.props.colIndex);
    }
  }

  handleBlur = e => {
    e.stopPropagation();
    if (this.props.blurToSave) {
      const value = e.currentTarget.type === 'checkbox' ?
                      this._getCheckBoxValue(e) : e.currentTarget.value;
      if (!this.validator(value)) {
        return;
      }
      this.props.completeEdit(
          value, this.props.rowIndex, this.props.colIndex);
    }
  }

  handleCustomUpdate = value => {
    this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
  }

  validator(value) {
    const ts = this;
    if (ts.props.editable.validator) {
      const valid = ts.props.editable.validator(value);
      if (valid !== true) {
        ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel');
        const input = ts.refs.inputRef;
        // animate input
        ts.clearTimeout();
        ts.setState({ shakeEditor: true });
        ts.timeouteClear = setTimeout(() => {
          ts.setState({ shakeEditor: false });
        }, 300);
        input.focus();
        return false;
      }
    }
    return true;
  }
  clearTimeout() {
    if (this.timeouteClear !== 0) {
      clearTimeout(this.timeouteClear);
      this.timeouteClear = 0;
    }
  }
  componentDidMount() {
    this.refs.inputRef.focus();
  }

  componentWillUnmount() {
    this.clearTimeout();
  }

  render() {
    const { editable, format, customEditor } = this.props;
    const { shakeEditor } = this.state;
    const attr = {
      ref: 'inputRef',
      onKeyDown: this.handleKeyPress,
      onBlur: this.handleBlur
    };
    let { fieldValue } = this.props;
    // put placeholder if exist
    editable.placeholder && (attr.placeholder = editable.placeholder);

    const editorClass = classSet({ 'animated': shakeEditor, 'shake': shakeEditor });
    let cellEditor;
    if (customEditor) {
      const customEditorProps = {
        row: this.props.row,
        ...attr,
        defaultValue: fieldValue || '',
        ...customEditor.customEditorParameters
      };
      cellEditor = customEditor.getElement(this.handleCustomUpdate, customEditorProps);
    } else {
      fieldValue = fieldValue === 0 ? '0' : fieldValue;
      cellEditor = editor(editable, attr, format, editorClass, fieldValue || '');
    }

    return (

        { cellEditor }
        <Notifier ref='notifier'/>

    );
  }

  _getCheckBoxValue(e) {
    let value = '';
    const values = e.currentTarget.value.split(':');
    value = e.currentTarget.checked ? values[0] : values[1];
    return value;
  }
}

TableEditColumn.propTypes = {
  completeEdit: PropTypes.func,
  rowIndex: PropTypes.number,
  colIndex: PropTypes.number,
  blurToSave: PropTypes.bool,
  editable: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object ]),
  format: PropTypes.oneOfType([ PropTypes.bool, PropTypes.func ]),
  row: PropTypes.any,
  fieldValue: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.bool,
    PropTypes.number,
    PropTypes.array,
    PropTypes.object
  ])
};

export default TableEditColumn;
<|endoftext|>


<commit_before>;(function rekapiCore (global) {

  if (!_) {
    throw 'underscore.js is required for Kapi.';
  }

  if (!Tweenable) {
    throw 'shifty.js is required for Kapi.';
  }

  var gk
      ,defaultConfig;

  /**
   * @param {HTMLCanvas} canvas
   * @param {string} dimension The dimension (either "height" or "width") to
   *    get or set.
   * @param {number} opt_new_size The new value to set for `dimension`.
   */
  function canvas_dimension (canvas, dimension, opt_new_size) {
    if (typeof opt_new_size !== 'undefined') {
      canvas[dimension] = opt_new_size;
      canvas.style[dimension] = opt_new_size + 'px';
    }

    return canvas[dimension];
  }

  /**
	 * Sorts an array numerically, from smallest to largest.
	 * @param {Array} array The Array to sort.
	 * @returns {Array} The sorted Array.
	 */
  function sortNumerically (array) {
		return array.sort(function (a, b) {
			return a - b;
		});
	}

	function calculateCurrentMillisecond (kapi) {

	}

	function renderCurrentMillisecond (kapi) {

	}

	function tick (kapi) {
	  kapi._loopId = setTimeout(function () {
	    //kapi.render(now());
	  }, 1000 / kapi.config.fps);
	}

  function noop () {
    // NOOP!
  }

  defaultConfig = {
    'fps': 30
  };

  /**
   * @param {HTMLCanvas} canvas
   * @param {Object} config
   * @param {Object} events
   */
  gk = global.Kapi || function Kapi (canvas, config, events) {
    this.canvas = canvas;
    this.canvas_context = canvas.getContext('2d');

    this.config = {};
    this._actors = {};
    this._drawOrder = [];

    this._loopId = null;
    this._loopTimestamp = null;
    this._animationLength = null;

    _.extend(this.config, config);
    _.defaults(this.config, defaultConfig);

    return this;
  };

  gk.prototype.height = function (opt_height) {
    return canvas_dimension(this.canvas, 'height', opt_height);
  };

  gk.prototype.width = function (opt_width) {
    return canvas_dimension(this.canvas, 'width', opt_width);
  };

  gk.prototype.animationLength = function () {
    return this._animationLength;
  };

  /**
   * Get or set a style on the Kapi canvas.
   * @param {string} styleName
   * @param {number|string} opt_styleValue The value to set for `styleName`
   */
  gk.prototype.canvas_style = function (styleName, opt_styleValue) {
    if (typeof opt_styleValue !== 'undefined') {
      this.canvas.style[styleName] = opt_styleValue;
    }

    return this.canvas.style[styleName];
  }

  /**
   * Gets the 2d context of the Kapi's canvas.
   */
  gk.prototype.context = function () {
    return this.canvas_context;
  };

  /**
   * @param {number} millisecond
   */
  gk.prototype.render = function (millisecond) {
    var i, len
        ,currentActor
        ,curr;

    len = this._drawOrder.length;
    curr = Tweenable.util.now();

    for (i = 0; i < len; i++) {
      currentActor = this._actors[this._drawOrder[i]];
      currentActor.calculatePosition(millisecond);
    }
  };

  gk.prototype.updateInternalState = function () {
    var allKeyframeLists;

    allKeyframeLists = [];

    _.each(this._drawOrder, function (i) {
      allKeyframeLists = allKeyframeLists.concat(allKeyframeLists,
          this._actors[i]._keyframeList);
    }, this);

    this._animationLength = Math.max.apply(Math, allKeyframeLists);

    return this;
  };

  /**
   * @param {Kapi.Actor} actor
   * @param {Object} opt_initialState
   */
  gk.prototype.add = function (actor, opt_initialState) {
    actor.set(opt_initialState);
    this._actors[actor.id] = actor;
    this._drawOrder.push(actor.id);
  };

  gk.prototype.play = function () {
    this._loopTimestamp = now();
    tick(this);
  };

  gk.util = {};

  _.extend(gk.util, {
    'noop': noop
    ,'sortNumerically': sortNumerically
  });

  global.Kapi = gk;

} (this));<commit_msg>Whitespace cleaning.<commit_after>;(function rekapiCore (global) {

  if (!_) {
    throw 'underscore.js is required for Kapi.';
  }

  if (!Tweenable) {
    throw 'shifty.js is required for Kapi.';
  }

  var gk
      ,defaultConfig;

  /**
   * @param {HTMLCanvas} canvas
   * @param {string} dimension The dimension (either "height" or "width") to
   *    get or set.
   * @param {number} opt_new_size The new value to set for `dimension`.
   */
  function canvas_dimension (canvas, dimension, opt_new_size) {
    if (typeof opt_new_size !== 'undefined') {
      canvas[dimension] = opt_new_size;
      canvas.style[dimension] = opt_new_size + 'px';
    }

    return canvas[dimension];
  }

  /**
   * Sorts an array numerically, from smallest to largest.
   * @param {Array} array The Array to sort.
   * @returns {Array} The sorted Array.
   */
  function sortNumerically (array) {
    return array.sort(function (a, b) {
      return a - b;
    });
  }

  function calculateCurrentMillisecond (kapi) {

  }

  function renderCurrentMillisecond (kapi) {

  }

  function tick (kapi) {
    kapi._loopId = setTimeout(function () {
      //kapi.render(now());
    }, 1000 / kapi.config.fps);
  }

  function noop () {
    // NOOP!
  }

  defaultConfig = {
    'fps': 30
  };

  /**
   * @param {HTMLCanvas} canvas
   * @param {Object} config
   * @param {Object} events
   */
  gk = global.Kapi || function Kapi (canvas, config, events) {
    this.canvas = canvas;
    this.canvas_context = canvas.getContext('2d');

    this.config = {};
    this._actors = {};
    this._drawOrder = [];

    this._loopId = null;
    this._loopTimestamp = null;
    this._animationLength = null;

    _.extend(this.config, config);
    _.defaults(this.config, defaultConfig);

    return this;
  };

  gk.prototype.height = function (opt_height) {
    return canvas_dimension(this.canvas, 'height', opt_height);
  };

  gk.prototype.width = function (opt_width) {
    return canvas_dimension(this.canvas, 'width', opt_width);
  };

  gk.prototype.animationLength = function () {
    return this._animationLength;
  };

  /**
   * Get or set a style on the Kapi canvas.
   * @param {string} styleName
   * @param {number|string} opt_styleValue The value to set for `styleName`
   */
  gk.prototype.canvas_style = function (styleName, opt_styleValue) {
    if (typeof opt_styleValue !== 'undefined') {
      this.canvas.style[styleName] = opt_styleValue;
    }

    return this.canvas.style[styleName];
  }

  /**
   * Gets the 2d context of the Kapi's canvas.
   */
  gk.prototype.context = function () {
    return this.canvas_context;
  };

  /**
   * @param {number} millisecond
   */
  gk.prototype.render = function (millisecond) {
    var i, len
        ,currentActor
        ,curr;

    len = this._drawOrder.length;
    curr = Tweenable.util.now();

    for (i = 0; i < len; i++) {
      currentActor = this._actors[this._drawOrder[i]];
      currentActor.calculatePosition(millisecond);
    }
  };

  gk.prototype.updateInternalState = function () {
    var allKeyframeLists;

    allKeyframeLists = [];

    _.each(this._drawOrder, function (i) {
      allKeyframeLists = allKeyframeLists.concat(allKeyframeLists,
          this._actors[i]._keyframeList);
    }, this);

    this._animationLength = Math.max.apply(Math, allKeyframeLists);

    return this;
  };

  /**
   * @param {Kapi.Actor} actor
   * @param {Object} opt_initialState
   */
  gk.prototype.add = function (actor, opt_initialState) {
    actor.set(opt_initialState);
    this._actors[actor.id] = actor;
    this._drawOrder.push(actor.id);
  };

  gk.prototype.play = function () {
    this._loopTimestamp = now();
    tick(this);
  };

  gk.util = {};

  _.extend(gk.util, {
    'noop': noop
    ,'sortNumerically': sortNumerically
  });

  global.Kapi = gk;

} (this));<|endoftext|>


<commit_before>module.exports = { getFilterFromParams };

function getFilterFromParams(params) {
  const search = {};
  if (params.searchField === 'auteur') {
    search[params.searchField] = params.searchString;
  } else if (params.searchField !== 'all') {
    search[params.searchField] = {
      $regex: params.searchString,
      $options: 'gi'
    };
  } else {
    search.$or = [
      { hashtags: { $regex: params.searchString, $options: 'gi' } },
      { 'aromes.nom': { $regex: params.searchString, $options: 'gi' } },
      {
        'aromes.marque': { $regex: params.searchString, $options: 'gi' }
      },
      { notes: { $regex: params.searchString, $options: 'gi' } },
      { auteur: params.searchString }
    ];
  }
  return search;
}
<commit_msg>Adds name in searched elements<commit_after>module.exports = { getFilterFromParams };

function getFilterFromParams(params) {
  const search = {};
  if (params.searchField === 'auteur') {
    search[params.searchField] = params.searchString;
  } else if (params.searchField !== 'all') {
    search[params.searchField] = {
      $regex: params.searchString,
      $options: 'gi'
    };
  } else {
    search.$or = [
      { nom: { $regex: params.searchString, $options: 'gi' } },
      { hashtags: { $regex: params.searchString, $options: 'gi' } },
      { 'aromes.nom': { $regex: params.searchString, $options: 'gi' } },
      {
        'aromes.marque': { $regex: params.searchString, $options: 'gi' }
      },
      { notes: { $regex: params.searchString, $options: 'gi' } },
      { auteur: params.searchString }
    ];
  }
  return search;
}
<|endoftext|>


<commit_before>var p = require('./parse/parse')

var redis = require('redis')
    client = redis.createClient()

var express = require('express')
    app = express()

var uuid = require('uuid')
    cors = require('cors')
    bodyParser = require('body-parser')
    path = require('path')

app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())
app.use(express.static(path.join(__dirname, 'public')))

app.post('/api', function (req, res, next) {
    var schema = req.body.schema
    var id = uuid.v4()
    client.set(id, schema)
    res.send({id: id})
});

app.get('/api/:id', function (req, res) {
    if (req.params.id.indexOf('favicon.ico') != -1){
        // ignore requests for a favicon
    }
    else {
        client.get(req.params.id, function (err, reply) {
            if (err != null) {
                console.log(err)
                res.send(500, JSON.stringify({error: 'Unknown error'}));
            }
            else if (reply == null) {
                res.send(404, JSON.stringify({error: 'Unknown ID'}))
            }
            else {
                var schemaObj = JSON.parse(reply)
                var returnVal = p.generate(schemaObj)
                res.send(JSON.stringify(returnVal))
            }
        })
    }
});

app.listen(80, function() {
    console.log('listening...')
})

<commit_msg>use process port number<commit_after>var p = require('./parse/parse')

var redis = require('redis')
    client = redis.createClient()

var express = require('express')
    app = express()

var uuid = require('uuid')
    cors = require('cors')
    bodyParser = require('body-parser')
    path = require('path')

app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())
app.use(express.static(path.join(__dirname, 'public')))

app.post('/api', function (req, res, next) {
    var schema = req.body.schema
    var id = uuid.v4()
    client.set(id, schema)
    res.send({id: id})
});

app.get('/api/:id', function (req, res) {
    if (req.params.id.indexOf('favicon.ico') != -1){
        // ignore requests for a favicon
    }
    else {
        client.get(req.params.id, function (err, reply) {
            if (err != null) {
                console.log(err)
                res.send(500, JSON.stringify({error: 'Unknown error'}));
            }
            else if (reply == null) {
                res.send(404, JSON.stringify({error: 'Unknown ID'}))
            }
            else {
                var schemaObj = JSON.parse(reply)
                var returnVal = p.generate(schemaObj)
                res.send(JSON.stringify(returnVal))
            }
        })
    }
});

app.listen(process.env.PORT || 80, function() {
    console.log('listening...')
})

<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var https = require('https');
var fs         = require("fs");
var key_file   = "certs/file.pem";
var cert_file  = "certs/file.crt";

var config     = {
  key: fs.readFileSync(key_file),
 cert: fs.readFileSync(cert_file)
};

var routes = require('./routes/index');

var app = express();
https.createServer(config, app).listen(443);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(logger('dev'));                                     // log every request to the console
app.use(bodyParser.json());                                 // pull information from html in POST
app.use(bodyParser.urlencoded());                           // pull information from html in POST
app.use(cookieParser());                                    // used for csrf
app.use(express.static(path.join(__dirname, 'public')));    // set the static files location /public/img will be /img for users

app.use('/', routes);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;<commit_msg>http fix<commit_after>var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var https = require('https');
var fs         = require("fs");
var key_file   = "certs/file.pem";
var cert_file  = "certs/file.crt";

var config     = {
  key: fs.readFileSync(key_file),
 cert: fs.readFileSync(cert_file)
};

var routes = require('./routes/index');

var app = express();
//https.createServer(config, app).listen(443);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(logger('dev'));                                     // log every request to the console
app.use(bodyParser.json());                                 // pull information from html in POST
app.use(bodyParser.urlencoded());                           // pull information from html in POST
app.use(cookieParser());                                    // used for csrf
app.use(express.static(path.join(__dirname, 'public')));    // set the static files location /public/img will be /img for users

app.use('/', routes);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>// Based on https://github.com/fbsamples/messenger-platform-samples/tree/master/node
const crypto = require('crypto');
const EventEmitter = require('events');

const bodyParser = require('body-parser');
const Cacheman = require('cacheman');
const dashbot = require('dashbot');
const debug = require('debug')('lenses:messenger');
const express = require('express');
const exphbs = require('express-handlebars');
const logError = require('debug')('lenses:messenger:error');
const request = require('request');

const {
  VALIDATION_TOKEN,
  APP_SECRET,
  PAGE_ACCESS_TOKEN,
  SERVER_URL,
  PAGE_ID,
  DASHBOT_KEY
} = require('./config');

const cache = new Cacheman('sessions');

function verifyRequestSignature(req, res, buf) {
  const signature = req.headers['x-hub-signature'];

  if (!signature) {
    throw new Error(`Couldn't validate the signature with app secret: ${APP_SECRET}`);
  }

  const [method, signatureHash] = signature.split('=');
  // TODO assert method === 'sha1'
  const expectedHash = crypto.createHmac(method, APP_SECRET).update(buf).digest('hex');

  if (signatureHash !== expectedHash) {
    throw new Error(`Couldn't validate the request signature: ${APP_SECRET}`);
  }
};

// MESSAGE TYPES
////////////////

// NOTE: I'm not sure if this should be used. This wrapper may be too thin.
// For now, keep it around as a reference.

const msg = {
  text: (text) => ({
    text,
    metadata: 'DEVELOPER_DEFINED_METADATA'
  }),
  image: (url) => ({
    attachment: {
      type: 'image',
      payload: {url}
    }
  }),
  audio: (url) => ({
    attachment: {
      type: 'audio',
      payload: {url}
    }
  }),
  video: (url) => ({
    attachment: {
      type: 'video',
      payload: {url}
    }
  }),
  file: (url) => ({
    attachment: {
      type: 'file',
      payload: {url}
    }
  })
};

// MESSENGER CLIENT
///////////////////

class Messenger extends EventEmitter {
  constructor({port, hookPath = '/webhook', linkPath = '/link'} = {}) {
    super();

    // XXX this is awkward, I should learn how to use destructuring better or is that too fancy?
    this.options = {
      port: port || process.env.PORT || 3000,
      hookPath,
      linkPath
    };

    this.app = express();
    this.app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    this.app.set('view engine', 'handlebars');

    this.app.use(bodyParser.json({ verify: verifyRequestSignature }));
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.app.use(express.static('public'));

    if (DASHBOT_KEY) {
      this.dashbotClient = dashbot(DASHBOT_KEY).facebook;
    } else {
      debug('No DASHBOT_KEY specified; no data will be sent to DashBot.');
    }

    // Facebook Messenger verification
    this.app.get(hookPath, (req, res) => {
      if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === VALIDATION_TOKEN) {
        debug('Validating webhook');
        res.status(200).send(req.query['hub.challenge']);
      } else {
        debug('Failed validation. Make sure the validation tokens match.');
        res.sendStatus(403);
      }
    });

    this.app.post(hookPath, (req, res) => {
      const data = req.body;
      if (this.dashbotClient) {
        this.dashbotClient.logIncoming(data);
      }
      // `data` reference:
      // https://developers.facebook.com/docs/messenger-platform/webhook-reference#format
      if (data.object === 'page') {
        data.entry.forEach((pageEntry) => {
          pageEntry.messaging.forEach(this.routeEachMessage.bind(this));
        });
        res.sendStatus(200);
      }
    });

    this.app.post(linkPath, (req, res) => {
      this.onLink(req.body);
      res.sendStatus(200);
    });

    // App routes
    this.app.get('/login', (req, res) => res.render('login', {
      appId: process.env.FACEBOOK_APP_ID,
      serverUrl: SERVER_URL
    }));
    this.app.get('/send-to-messenger', (req, res) => res.render('send-to-messenger', {
      appId: process.env.FACEBOOK_APP_ID,
      pageId: PAGE_ID
    }));

    this.app.get('/', (req, res) => {
      res.send('👍');
    });
  }

  start() {
    this.app.listen(this.options.port, (err) => {
      if (err) throw err;
      debug('Server running on port %s', this.options.port);
      // TODO console.log(`Set your webhook to: `)
    });
  }

  routeEachMessage(messagingEvent) {
    const cacheKey = messagingEvent.sender.id;
    return cache.get(cacheKey)
      .then((session = {_key: cacheKey, count: 0}) => {
        session.count++;
        if (messagingEvent.optin) {
          debug('incoming authentication event');
          this.onAuth(messagingEvent, session);
        } else if (messagingEvent.message) {
          debug('incoming message');
          this.onMessage(messagingEvent, session);
        } else if (messagingEvent.delivery) {
          debug('incoming delivery event');
        } else if (messagingEvent.postback) {
          debug('incoming postback');
          this.onPostback(messagingEvent, session);
        } else if (messagingEvent.read) {
          debug('incoming read event');
        } else {
          debug('incoming unknown messagingEvent: %o', messagingEvent);
        }
        return session;
      })
      .then((session) => cache.set(cacheKey, session));
  }

  doLogin(senderId) {
    // Open question: is building the event object worth it for the 'emit'?
    const event = {
      sender: {id: senderId},
      recipient: {id: PAGE_ID},
      timestamp: new Date().getTime()
    };
    this.emit('login', {event, senderId});
    debug('Received login request for user %d', senderId);

    const messageData = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'generic',
          elements: [{
            title: 'Login With Facebook',
            subtitle: '',
            buttons: [{
              type: 'web_url',
              url: `${SERVER_URL}/login?userId=${senderId}`,
              title: 'Login With Facebook'
            }]
          }]
        }
      }
    };
    this.send(senderId, messageData);
  }

  // EVENTS
  /////////

  onAuth(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfAuth = event.timestamp;
    // The 'ref' is the data passed through the 'Send to Messenger' call
    const optinRef = event.optin.ref;
    this.emit('auth', {event, senderId, optinRef});
    debug('Received auth for user %d and page %d at %d with param:\n%o',
      senderId, recipientId, timeOfAuth, optinRef);
  }

  /*
    This is not an event triggered by Messenger, it is the post-back from the
    static Facebook login page that is made to look similar to an 'event'
  */
  onLink(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfLink = event.timestamp;

    const fbData = event.facebook;
    this.emit('link', {event, senderId, fbData});
    debug('Received link for user %d and page %d at %d with data:\n%o',
      senderId, recipientId, timeOfLink, fbData);

    this.send(senderId, msg.text('Thanks for logging in with Facebook.'));
    this.send(senderId,
      msg.text(`You'll always be more than just #${fbData.id} to us`));
  }

  onMessage(event, session) {
    var senderId = event.sender.id;
    var recipientId = event.recipient.id;
    const {message, timestamp} = event;

    this.emit('message', {event, senderId, session, message});
    debug('Received message for user %d and page %d at %d with message:\n%o',
      senderId, recipientId, timestamp, message);

    const {
      mid: messageId,
      app_id: appId,
      metadata,
      quick_reply: quickReply,
      // You may get a text or attachment but not both
      text,
      attachments
    } = message;

    if (message.is_echo) {
      debug('Received echo for message %s and app %d with metadata %s', messageId, appId, metadata);
      return;
    }

    if (quickReply) {
      debug('Quick reply for message %s with payload %s', messageId, quickReply.payload);
      this.send(senderId, msg.text('Quick reply tapped'));
      return;
    }

    if (text) {
      debug(text);
      this.emit('message.text', {event, senderId, session, text});
      return;
    }

    if (attachments) {
      // Currently, we can assume there is only one attachment in a message
      const attachment = attachments[0];
      let type = attachment.type;

      if (message.sticker_id) {
        // There's a special thumbsup button in the interface that comes in like a sticker
        // This magic number is intentional.
        type = (message.sticker_id === 369239263222822) ? 'thumbsup' : 'sticker';
      }

      this.emit(`message.${type}`, {event, senderId, session, attachment, url: attachment.payload.url});
      return;
    }
  }

  onPostback(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfPostback = event.timestamp;

    // The 'payload' param is a developer-defined field which is set in a postback
    // button for Structured Messages.
    const payload = event.postback.payload;

    debug("Received postback for user %d and page %d with payload '%s' at %d",
      senderId, recipientId, payload, timeOfPostback);

    this.emit('postback', {event, senderId, payload});
  }

  // HELPERS
  //////////

  send(recipientId, messageData) {
    // WISHLIST return a promise, just use `request-promise` instead of `request`
    const payload = {
      uri: 'https://graph.facebook.com/v2.8/me/messages',
      qs: { access_token: PAGE_ACCESS_TOKEN },
      method: 'POST',
      json: {
        dashbotTemplateId: 'right',
        recipient: {
          id: recipientId
        },
        message: messageData
      }
    };
    request(payload, (error, response, body) => {
      if (this.dashbotClient) {
        this.dashbotClient.logOutgoing(payload, body);
      }
      if (!error && response.statusCode === 200) {
        const {recipient_id: recipientId, message_id: messageId} = body;

        if (messageId) {
          debug('Successfully sent message with id %s to recipient %s', messageId, recipientId);
        } else {
          debug('Successfully called Send API for recipient %s', recipientId);
        }
      } else {
        logError('Failed calling Send API', response.statusCode, response.statusMessage, body.error);
      }
    });
  }
}

const internals = {};
internals.cache = cache;
exports.__internals__ = internals;
exports.Messenger = Messenger;
exports.msg = msg;
<commit_msg>Saving viewed looks to app cache - part 2: postback edition (#53)<commit_after>// Based on https://github.com/fbsamples/messenger-platform-samples/tree/master/node
const crypto = require('crypto');
const EventEmitter = require('events');

const bodyParser = require('body-parser');
const Cacheman = require('cacheman');
const dashbot = require('dashbot');
const debug = require('debug')('lenses:messenger');
const express = require('express');
const exphbs = require('express-handlebars');
const logError = require('debug')('lenses:messenger:error');
const request = require('request');

const {
  VALIDATION_TOKEN,
  APP_SECRET,
  PAGE_ACCESS_TOKEN,
  SERVER_URL,
  PAGE_ID,
  DASHBOT_KEY
} = require('./config');

const cache = new Cacheman('sessions');

function verifyRequestSignature(req, res, buf) {
  const signature = req.headers['x-hub-signature'];

  if (!signature) {
    throw new Error(`Couldn't validate the signature with app secret: ${APP_SECRET}`);
  }

  const [method, signatureHash] = signature.split('=');
  // TODO assert method === 'sha1'
  const expectedHash = crypto.createHmac(method, APP_SECRET).update(buf).digest('hex');

  if (signatureHash !== expectedHash) {
    throw new Error(`Couldn't validate the request signature: ${APP_SECRET}`);
  }
};

// MESSAGE TYPES
////////////////

// NOTE: I'm not sure if this should be used. This wrapper may be too thin.
// For now, keep it around as a reference.

const msg = {
  text: (text) => ({
    text,
    metadata: 'DEVELOPER_DEFINED_METADATA'
  }),
  image: (url) => ({
    attachment: {
      type: 'image',
      payload: {url}
    }
  }),
  audio: (url) => ({
    attachment: {
      type: 'audio',
      payload: {url}
    }
  }),
  video: (url) => ({
    attachment: {
      type: 'video',
      payload: {url}
    }
  }),
  file: (url) => ({
    attachment: {
      type: 'file',
      payload: {url}
    }
  })
};

// MESSENGER CLIENT
///////////////////

class Messenger extends EventEmitter {
  constructor({port, hookPath = '/webhook', linkPath = '/link'} = {}) {
    super();

    // XXX this is awkward, I should learn how to use destructuring better or is that too fancy?
    this.options = {
      port: port || process.env.PORT || 3000,
      hookPath,
      linkPath
    };

    this.app = express();
    this.app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    this.app.set('view engine', 'handlebars');

    this.app.use(bodyParser.json({ verify: verifyRequestSignature }));
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.app.use(express.static('public'));

    if (DASHBOT_KEY) {
      this.dashbotClient = dashbot(DASHBOT_KEY).facebook;
    } else {
      debug('No DASHBOT_KEY specified; no data will be sent to DashBot.');
    }

    // Facebook Messenger verification
    this.app.get(hookPath, (req, res) => {
      if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === VALIDATION_TOKEN) {
        debug('Validating webhook');
        res.status(200).send(req.query['hub.challenge']);
      } else {
        debug('Failed validation. Make sure the validation tokens match.');
        res.sendStatus(403);
      }
    });

    this.app.post(hookPath, (req, res) => {
      const data = req.body;
      if (this.dashbotClient) {
        this.dashbotClient.logIncoming(data);
      }
      // `data` reference:
      // https://developers.facebook.com/docs/messenger-platform/webhook-reference#format
      if (data.object === 'page') {
        data.entry.forEach((pageEntry) => {
          pageEntry.messaging.forEach(this.routeEachMessage.bind(this));
        });
        res.sendStatus(200);
      }
    });

    this.app.post(linkPath, (req, res) => {
      this.onLink(req.body);
      res.sendStatus(200);
    });

    // App routes
    this.app.get('/login', (req, res) => res.render('login', {
      appId: process.env.FACEBOOK_APP_ID,
      serverUrl: SERVER_URL
    }));
    this.app.get('/send-to-messenger', (req, res) => res.render('send-to-messenger', {
      appId: process.env.FACEBOOK_APP_ID,
      pageId: PAGE_ID
    }));

    this.app.get('/', (req, res) => {
      res.send('👍');
    });
  }

  start() {
    this.app.listen(this.options.port, (err) => {
      if (err) throw err;
      debug('Server running on port %s', this.options.port);
      // TODO console.log(`Set your webhook to: `)
    });
  }

  routeEachMessage(messagingEvent) {
    const cacheKey = messagingEvent.sender.id;
    return cache.get(cacheKey)
      .then((session = {_key: cacheKey, count: 0}) => {
        session.count++;
        if (messagingEvent.optin) {
          debug('incoming authentication event');
          this.onAuth(messagingEvent, session);
        } else if (messagingEvent.message) {
          debug('incoming message');
          this.onMessage(messagingEvent, session);
        } else if (messagingEvent.delivery) {
          debug('incoming delivery event');
        } else if (messagingEvent.postback) {
          debug('incoming postback');
          this.onPostback(messagingEvent, session);
        } else if (messagingEvent.read) {
          debug('incoming read event');
        } else {
          debug('incoming unknown messagingEvent: %o', messagingEvent);
        }
        return session;
      })
      .then((session) => cache.set(cacheKey, session));
  }

  doLogin(senderId) {
    // Open question: is building the event object worth it for the 'emit'?
    const event = {
      sender: {id: senderId},
      recipient: {id: PAGE_ID},
      timestamp: new Date().getTime()
    };
    this.emit('login', {event, senderId});
    debug('Received login request for user %d', senderId);

    const messageData = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'generic',
          elements: [{
            title: 'Login With Facebook',
            subtitle: '',
            buttons: [{
              type: 'web_url',
              url: `${SERVER_URL}/login?userId=${senderId}`,
              title: 'Login With Facebook'
            }]
          }]
        }
      }
    };
    this.send(senderId, messageData);
  }

  // EVENTS
  /////////

  onAuth(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfAuth = event.timestamp;
    // The 'ref' is the data passed through the 'Send to Messenger' call
    const optinRef = event.optin.ref;
    this.emit('auth', {event, senderId, optinRef});
    debug('Received auth for user %d and page %d at %d with param:\n%o',
      senderId, recipientId, timeOfAuth, optinRef);
  }

  /*
    This is not an event triggered by Messenger, it is the post-back from the
    static Facebook login page that is made to look similar to an 'event'
  */
  onLink(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfLink = event.timestamp;

    const fbData = event.facebook;
    this.emit('link', {event, senderId, fbData});
    debug('Received link for user %d and page %d at %d with data:\n%o',
      senderId, recipientId, timeOfLink, fbData);

    this.send(senderId, msg.text('Thanks for logging in with Facebook.'));
    this.send(senderId,
      msg.text(`You'll always be more than just #${fbData.id} to us`));
  }

  onMessage(event, session) {
    var senderId = event.sender.id;
    var recipientId = event.recipient.id;
    const {message, timestamp} = event;

    this.emit('message', {event, senderId, session, message});
    debug('Received message for user %d and page %d at %d with message:\n%o',
      senderId, recipientId, timestamp, message);

    const {
      mid: messageId,
      app_id: appId,
      metadata,
      quick_reply: quickReply,
      // You may get a text or attachment but not both
      text,
      attachments
    } = message;

    if (message.is_echo) {
      debug('Received echo for message %s and app %d with metadata %s', messageId, appId, metadata);
      return;
    }

    if (quickReply) {
      debug('Quick reply for message %s with payload %s', messageId, quickReply.payload);
      this.send(senderId, msg.text('Quick reply tapped'));
      return;
    }

    if (text) {
      debug(text);
      this.emit('message.text', {event, senderId, session, text});
      return;
    }

    if (attachments) {
      // Currently, we can assume there is only one attachment in a message
      const attachment = attachments[0];
      let type = attachment.type;

      if (message.sticker_id) {
        // There's a special thumbsup button in the interface that comes in like a sticker
        // This magic number is intentional.
        type = (message.sticker_id === 369239263222822) ? 'thumbsup' : 'sticker';
      }

      this.emit(`message.${type}`, {event, senderId, session, attachment, url: attachment.payload.url});
      return;
    }
  }

  onPostback(event, session) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfPostback = event.timestamp;

    // The 'payload' param is a developer-defined field which is set in a postback
    // button for Structured Messages.
    const payload = event.postback.payload;

    debug("Received postback for user %d and page %d with payload '%s' at %d",
      senderId, recipientId, payload, timeOfPostback);

    this.emit('postback', {event, senderId, session, payload});
  }

  // HELPERS
  //////////

  send(recipientId, messageData) {
    // WISHLIST return a promise, just use `request-promise` instead of `request`
    const payload = {
      uri: 'https://graph.facebook.com/v2.8/me/messages',
      qs: { access_token: PAGE_ACCESS_TOKEN },
      method: 'POST',
      json: {
        dashbotTemplateId: 'right',
        recipient: {
          id: recipientId
        },
        message: messageData
      }
    };
    request(payload, (error, response, body) => {
      if (this.dashbotClient) {
        this.dashbotClient.logOutgoing(payload, body);
      }
      if (!error && response.statusCode === 200) {
        const {recipient_id: recipientId, message_id: messageId} = body;

        if (messageId) {
          debug('Successfully sent message with id %s to recipient %s', messageId, recipientId);
        } else {
          debug('Successfully called Send API for recipient %s', recipientId);
        }
      } else {
        logError('Failed calling Send API', response.statusCode, response.statusMessage, body.error);
      }
    });
  }
}

const internals = {};
internals.cache = cache;
exports.__internals__ = internals;
exports.Messenger = Messenger;
exports.msg = msg;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var express = require('express')
var cors = require('cors')
var fs = require('fs');
var app = express();
var exec = require('child_process').exec;
var sha1 = require('sha1');
var bodyParser = require('body-parser');
var multer = require('multer');

var upload = multer();

const MAX_CODE_LENGTH = 20000;
const WRITE_PATH = '/data';
const PREFIX_CODE_1 = `#include <benchmark/benchmark_api.h>
`;
const SUFFIX_CODE_1 = `

static void Noop(benchmark::State& state) {
  while (state.KeepRunning());
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;

app.use(bodyParser.json());
app.use(cors());

function write(fileName, code) {
   return new Promise((resolve, reject) => {
       fs.writeFile(fileName, code, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function read(fileName, acceptMissing) {
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (err, data) => {
            if (err) {
                if (acceptMissing && err.code === 'ENOENT') {
                    resolve(null);
                } else {
                    reject(err);
                }
            } else {
                resolve(data);
            }
        });
    });
}

function runDockerCommand(fileName, request) {
    return './run-docker ' + fileName + ' ' + request.compiler + ' ' + request.optim + ' ' + request.cppVersion + ' ' + request.isAnnotated + ' ' + request.force;
}

function optionsToString(request) {
    let options = {
        "protocolVersion": request.protocolVersion,
        "compiler": request.compiler,
        "optim": request.optim,
        "cppVersion": request.cppVersion,
        "isAnnotated": request.isAnnotated
    };
    return JSON.stringify(options);
}

function execute(fileName, request) {
    let options = {
        timeout: 60000,
        killSignal: 'SIGKILL'
    }
    return new Promise((resolve, reject) => {
        exec(runDockerCommand(fileName, request), options, function (err, stdout, stderr) {
            if (err) {
                exec("./kill-docker " + fileName);
                reject("\u001b[0m\u001b[0;1;31mError or timeout\u001b[0m\u001b[1m
" + stdout + "
" + stderr);
            } else {
                resolve({
                    res: fs.readFileSync(fileName + '.out'),
                    stdout: stderr,
                    id: encodeName(makeName(request)),
                    annotation: request.isAnnotated ? fs.readFileSync(fileName + '.perf') : null
                });
            }
        });
    });
}

function groupResults(results) {
    return new Promise((resolve, reject) => {
        let code = unwrapCode(results[0]);
        let options = results[1];
        let graph = results[2];
        let annotation = results[3];
        resolve({ code: code, options: JSON.parse(options), graph: JSON.parse(graph), annotation: annotation });
    });
}

function makeName(request) {
    if (request.protocolVersion === 1)
        return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.protocolVersion);
    return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.isAnnotated + request.protocolVersion);
}

function wrapCode(inputCode) {
    return PREFIX_CODE_1 + inputCode + SUFFIX_CODE_1;
}

function unwrapCode(inputCode) {
    if (inputCode.startsWith(PREFIX_CODE_1)) {
        inputCode = inputCode.slice(PREFIX_CODE_1.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_1)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_1.length);
    }
    return inputCode;
}

function encodeName(id) {
    let short = new Buffer(id, 'hex').toString('base64');
    short = short.replace(new RegExp('/', 'g'), '-').replace(new RegExp('\\+', 'g'), '_');
    return short.slice(0, -1);
}

function decodeName(short) {
    short = short.replace(new RegExp('\\-', 'g'), '/').replace(new RegExp('_', 'g'), '+ ') + '=';
    return new Buffer(short, 'base64').toString('hex');
}

function benchmark(request) {
    if (request.code.length > MAX_CODE_LENGTH) {
        return Promise.reject('\u001b[0m\u001b[0;1;31mError: Unauthorized code length.\u001b[0m\u001b[1m');
    }
    let name = makeName(request);
    var dir = WRITE_PATH + '/' + name.substr(0, 2);
    var fileName = dir + '/' + name;
    return Promise.resolve(write(fileName + '.cpp', wrapCode(request.code)))
        .then(() => write(fileName + '.opt', optionsToString(request)))
        .then(() => execute(fileName, request));
}

function reload(encodedName) {
    let name = decodeName(encodedName);
    var dir = WRITE_PATH + '/' + name.substr(0, 2);
    var fileName = dir + '/' + name;
    return Promise.all([read(fileName + '.cpp'), read(fileName + '.opt'), read(fileName + '.out'), read(fileName + '.perf', true)])
        .then((values) => groupResults(values));
}

function makeGraphResult(values, message, id, annotation) {
    let result = { context: values.context };
    let noopTime = values.benchmarks[values.benchmarks.length - 1].cpu_time;
    result.benchmarks = values.benchmarks.map(obj => {
        return {
            name: obj.name,
            cpu_time: obj.cpu_time / noopTime
        }
    });
    return { result: result, message: message, id: id, annotation: annotation }
}

function makeWholeResult(done) {
    let result = {
        code: done.code,
        compiler: done.options.compiler,
        optim: done.options.optim,
        cppVersion: done.options.cppVersion,
        isAnnotated: done.options.isAnnotated,
        protocolVersion: done.options.protocolVersion
    };

    return Object.assign(result, makeGraphResult(done.graph, '', encodeName(makeName(result)), done.annotation));
}

app.post('/', upload.array(), function (req, res) {
    Promise.resolve(benchmark(req.body))
        .then((done) => res.json(makeGraphResult(JSON.parse(done.res), done.stdout, done.id)))
        .catch((err) => res.json({ message: err }));
});

app.get('/get/:id', upload.array(), function (req, res) {
    Promise.resolve(reload(req.params.id))
        .then((done) => res.json(makeWholeResult(done)))
        .catch(() => res.json({ message: 'Could not load given id' }));
});

app.listen(3000, function() {
    console.log('Listening to commands');
});

exports.makeName = makeName;
exports.encodeName = encodeName;
exports.decodeName = decodeName;
exports.wrapCode = wrapCode;
exports.unwrapCode = unwrapCode;
exports.groupResults = groupResults;
<commit_msg>Correct previous<commit_after>#!/usr/bin/env node

var express = require('express')
var cors = require('cors')
var fs = require('fs');
var app = express();
var exec = require('child_process').exec;
var sha1 = require('sha1');
var bodyParser = require('body-parser');
var multer = require('multer');

var upload = multer();

const MAX_CODE_LENGTH = 20000;
const WRITE_PATH = '/data';
const PREFIX_CODE_1 = `#include <benchmark/benchmark_api.h>
`;
const SUFFIX_CODE_1 = `

static void Noop(benchmark::State& state) {
  while (state.KeepRunning());
}
BENCHMARK(Noop);
BENCHMARK_MAIN()`;

app.use(bodyParser.json());
app.use(cors());

function write(fileName, code) {
   return new Promise((resolve, reject) => {
       fs.writeFile(fileName, code, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function read(fileName, acceptMissing) {
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (err, data) => {
            if (err) {
                if (acceptMissing && err.code === 'ENOENT') {
                    resolve(null);
                } else {
                    reject(err);
                }
            } else {
                resolve(data);
            }
        });
    });
}

function runDockerCommand(fileName, request) {
    return './run-docker ' + fileName + ' ' + request.compiler + ' ' + request.optim + ' ' + request.cppVersion + ' ' + request.isAnnotated + ' ' + request.force;
}

function optionsToString(request) {
    let options = {
        "protocolVersion": request.protocolVersion,
        "compiler": request.compiler,
        "optim": request.optim,
        "cppVersion": request.cppVersion,
        "isAnnotated": request.isAnnotated
    };
    return JSON.stringify(options);
}

function execute(fileName, request) {
    let options = {
        timeout: 60000,
        killSignal: 'SIGKILL'
    }
    return new Promise((resolve, reject) => {
        exec(runDockerCommand(fileName, request), options, function (err, stdout, stderr) {
            if (err) {
                exec("./kill-docker " + fileName);
                reject("\u001b[0m\u001b[0;1;31mError or timeout\u001b[0m\u001b[1m
" + stdout + "
" + stderr);
            } else {
                resolve({
                    res: fs.readFileSync(fileName + '.out'),
                    stdout: stderr,
                    id: encodeName(makeName(request)),
                    annotation: request.isAnnotated ? fs.readFileSync(fileName + '.perf') : null
                });
            }
        });
    });
}

function groupResults(results) {
    return new Promise((resolve, reject) => {
        let code = unwrapCode(results[0]);
        let options = results[1];
        let graph = results[2];
        let annotation = results[3];
        resolve({ code: code, options: JSON.parse(options), graph: JSON.parse(graph), annotation: annotation });
    });
}

function makeName(request) {
    if (request.protocolVersion === 1)
        return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.protocolVersion);
    return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.isAnnotated + request.protocolVersion);
}

function wrapCode(inputCode) {
    return PREFIX_CODE_1 + inputCode + SUFFIX_CODE_1;
}

function unwrapCode(inputCode) {
    if (inputCode.startsWith(PREFIX_CODE_1)) {
        inputCode = inputCode.slice(PREFIX_CODE_1.length);
    }
    if (inputCode.endsWith(SUFFIX_CODE_1)) {
        inputCode = inputCode.slice(0, -SUFFIX_CODE_1.length);
    }
    return inputCode;
}

function encodeName(id) {
    let short = new Buffer(id, 'hex').toString('base64');
    short = short.replace(new RegExp('/', 'g'), '-').replace(new RegExp('\\+', 'g'), '_');
    return short.slice(0, -1);
}

function decodeName(short) {
    short = short.replace(new RegExp('\\-', 'g'), '/').replace(new RegExp('_', 'g'), '+ ') + '=';
    return new Buffer(short, 'base64').toString('hex');
}

function benchmark(request) {
    if (request.code.length > MAX_CODE_LENGTH) {
        return Promise.reject('\u001b[0m\u001b[0;1;31mError: Unauthorized code length.\u001b[0m\u001b[1m');
    }
    let name = makeName(request);
    var dir = WRITE_PATH + '/' + name.substr(0, 2);
    var fileName = dir + '/' + name;
    return Promise.resolve(write(fileName + '.cpp', wrapCode(request.code)))
        .then(() => write(fileName + '.opt', optionsToString(request)))
        .then(() => execute(fileName, request));
}

function reload(encodedName) {
    let name = decodeName(encodedName);
    var dir = WRITE_PATH + '/' + name.substr(0, 2);
    var fileName = dir + '/' + name;
    return Promise.all([read(fileName + '.cpp'), read(fileName + '.opt'), read(fileName + '.out'), read(fileName + '.perf', true)])
        .then((values) => groupResults(values));
}

function makeGraphResult(values, message, id, annotation) {
    let result = { context: values.context };
    let noopTime = values.benchmarks[values.benchmarks.length - 1].cpu_time;
    result.benchmarks = values.benchmarks.map(obj => {
        return {
            name: obj.name,
            cpu_time: obj.cpu_time / noopTime
        }
    });
    return { result: result, message: message, id: id, annotation: annotation }
}

function makeWholeResult(done) {
    let result = {
        code: done.code,
        compiler: done.options.compiler,
        optim: done.options.optim,
        cppVersion: done.options.cppVersion,
        isAnnotated: done.options.isAnnotated,
        protocolVersion: done.options.protocolVersion
    };

    return Object.assign(result, makeGraphResult(done.graph, '', encodeName(makeName(result)), done.annotation));
}

app.post('/', upload.array(), function (req, res) {
    Promise.resolve(benchmark(req.body))
        .then((done) => res.json(makeGraphResult(JSON.parse(done.res), done.stdout, done.id, done.annotation)))
        .catch((err) => res.json({ message: err }));
});

app.get('/get/:id', upload.array(), function (req, res) {
    Promise.resolve(reload(req.params.id))
        .then((done) => res.json(makeWholeResult(done)))
        .catch(() => res.json({ message: 'Could not load given id' }));
});

app.listen(3000, function() {
    console.log('Listening to commands');
});

exports.makeName = makeName;
exports.encodeName = encodeName;
exports.decodeName = decodeName;
exports.wrapCode = wrapCode;
exports.unwrapCode = unwrapCode;
exports.groupResults = groupResults;
<|endoftext|>


<commit_before>$(function () {
    var t;
    $('#inputRoute, #inputPath').keyup(function () {
        clearTimeout(t);
        t = setTimeout(update, 500);
    });
    function update() {
        console.log('updating');
        var keys = [];
        var regexp = pathRegexp($('#inputRoute').val(), keys);
        $('#regexp-display').html(regexp.toString());
        if (keys.length) {
            $('#keys-display').html('
' + keys.map(function wrap(key) {
                return '
' + key.name + (key.optional?' (optional)':'') + '
';
            }).join('') + '
');
        } else {
            $('#keys-display').html('There are no keys captured by this route');
        }

        var path = $('#inputPath').val();
        var isMatch = regexp.test(path);
        if (isMatch) {
            $('.is-not-match').hide();
            $('.is-match').show();
            var result = regexp.exec(path);
            $('#keys-results-display').html('
' + keys.map(function (key, i) {
                return '
' + key.name + '

' +
                result[i + 1] + '
';
            }).join('') + '
');
        } else {
            $('.is-not-match').show();
            $('.is-match').hide();
        }
    }
    update();

    /**
     * Normalize the given path string,
     * returning a regular expression.
     *
     * An empty array should be passed,
     * which will contain the placeholder
     * key names. For example "/user/:id" will
     * then contain ["id"].
     *
     * @param  {String} path
     * @param  {Array} keys
     * @param  {Boolean} sensitive
     * @param  {Boolean} strict
     * @return {String}
     * @api private
     */
    function pathRegexp(path, keys, sensitive, strict) {
          path = path
            .concat(strict ? '' : '/?')
            .replace(/\/\(/g, '(?:/')
            .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
              keys.push({ name: key, optional: !! optional });
              slash = slash || '';
              return ''
                + (optional ? '' : slash)
                + '(?:'
                + (optional ? slash : '')
                + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
                + (optional || '')
                + (star ? '(/*)?' : '');
            })
            .replace(/([\/.])/g, '\\$1')
            .replace(/\*/g, '(.*)');
          return new RegExp('^' + path + '$', sensitive ? '' : 'i');
    }
});<commit_msg>Remove console log<commit_after>$(function () {
    var t;
    $('#inputRoute, #inputPath').keyup(function () {
        clearTimeout(t);
        t = setTimeout(update, 500);
    });
    function update() {
        var keys = [];
        var regexp = pathRegexp($('#inputRoute').val(), keys);
        $('#regexp-display').html(regexp.toString());
        if (keys.length) {
            $('#keys-display').html('
' + keys.map(function wrap(key) {
                return '
' + key.name + (key.optional?' (optional)':'') + '
';
            }).join('') + '
');
        } else {
            $('#keys-display').html('There are no keys captured by this route');
        }

        var path = $('#inputPath').val();
        var isMatch = regexp.test(path);
        if (isMatch) {
            $('.is-not-match').hide();
            $('.is-match').show();
            var result = regexp.exec(path);
            $('#keys-results-display').html('
' + keys.map(function (key, i) {
                return '
' + key.name + '

' +
                result[i + 1] + '
';
            }).join('') + '
');
        } else {
            $('.is-not-match').show();
            $('.is-match').hide();
        }
    }
    update();

    /**
     * Normalize the given path string,
     * returning a regular expression.
     *
     * An empty array should be passed,
     * which will contain the placeholder
     * key names. For example "/user/:id" will
     * then contain ["id"].
     *
     * @param  {String} path
     * @param  {Array} keys
     * @param  {Boolean} sensitive
     * @param  {Boolean} strict
     * @return {String}
     * @api private
     */
    function pathRegexp(path, keys, sensitive, strict) {
          path = path
            .concat(strict ? '' : '/?')
            .replace(/\/\(/g, '(?:/')
            .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
              keys.push({ name: key, optional: !! optional });
              slash = slash || '';
              return ''
                + (optional ? '' : slash)
                + '(?:'
                + (optional ? slash : '')
                + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
                + (optional || '')
                + (star ? '(/*)?' : '');
            })
            .replace(/([\/.])/g, '\\$1')
            .replace(/\*/g, '(.*)');
          return new RegExp('^' + path + '$', sensitive ? '' : 'i');
    }
});<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs');
var rest = require('restler');
var http = require('http');
var program = require('commander');
var pretty = require('prettyjson');
var pack = require('tar-pack').pack;

var host, port, config_file;

function set_globals() {
	host = program.host || '127.0.0.1';
	port = program.port || 9002;
	config_file = program.config || './config.json';

	if (program.verbose === true) {
		console.log('options:')
		console.log('  host:' + host);
		console.log('  port:' + port);
		console.log('  config_file:' + config_file);
	}
}

function netget(path, callback) {
	set_globals();

	var uri = 'http://' + host + ':' + port.toString() + path;

	rest.get(uri).on('complete', function(result, response) {
		if (result instanceof Error) {
			console.error('problem with request: ' + response.message);
			return;
		} else {
			callback(result);
		}
	});
}

function netpost(path, payload, callback) {
	set_globals();

	var uri = 'http://' + host + ':' + port.toString() + path;

	var options = {};
	options.data = JSON.stringify(payload);
	options.headers = {
		'Content-Type': 'application/json'
	};

	rest.post(uri, options).on('complete', function(result, response) {
		if (result instanceof Error) {
			console.error('problem with request: ' + response.message);
			return;
		} else {
			callback(result);
		}
	});
}

function do_version() {
	netget('/version', function(result) {
		console.log('service version: \n' + pretty.render(result));
	});
}

function do_apps() {
	netget('/drones', function(result) {
		console.log('detailed info on apps: \n' + pretty.render(result));
	});
}

function do_app(name) {
	netget('/drones/' + name, function(result) {
		console.log('detailed info on app:' + name + '\n' + pretty.render(result));
	});
}

function do_running() {
	netget('/drones/running', function(result) {
		console.log('running apps: \n' + pretty.render(result));
	});
}

function do_start() {
	set_globals();

	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	netpost('/drones/' + config.name + '/start', {'start': config}, function(result) {
		console.log('started app: ' + config.name + '\n' + pretty.render(result));
	});
}

function do_stop(name) {
	config = {
		'name': name,
	}

	netpost('/drones/' + config.name + '/stop', {'stop': config}, function(result) {
		console.log('stopped app(s): ' + config.name + '\n' + pretty.render(result));
	});
}

function do_restart(name) {
	config = {
		'name': name,
	}

	netpost('/drones/' + config.name + '/restart', {'restart': config}, function(result) {
		console.log('restarted app(s): ' + config.name + '\n' + pretty.render(result));
	});
}

function do_remove() {
	set_globals();

	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	netpost('/drones/' + config.name + '/clean', config, function(result) {
		console.log('removed app: ' + config.name + '\n' + pretty.render(result));
	});
}

function do_update() {
	set_globals();

	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	netpost('/drones/' + config.name + '/update', config, function(result) {
		console.log('updated app: ' + config.name + '\n' + pretty.render(result));
	});
}

program
	.usage('[options] command')
	.option('-s, --host [host]', 'host')
	.option('-p, --port [port]', 'port', parseInt)
	.option('-c, --config [config_file]', 'config file (defaults to config.json)')
	.option('-v, --verbose', 'verbose output');

program
	.command('version')
	.description('show service version')
	.action(function() {
  		do_version();
	});

program
	.command('running')
	.description('show running apps')
	.action(function() {
  		do_running();
	});

program
	.command('apps')
	.description('detailed info on apps')
	.action(function() {
  		do_apps();
	});

program
	.command('app <app_name>')
	.description('detailed info on app')
	.action(function(app_name) {
  		do_app(app_name);
	});

program
	.command('start [config_file]')
	.description('start app')
	.action(function() {
  		do_start();
	});

program
	.command('stop <app_name>')
	.description('stop all instances of app')
	.action(function(app_name) {
  		do_stop(app_name);
	});

program
	.command('restart <app_name>')
	.description('restart all instances of app')
	.action(function(app_name) {
  		do_restart(app_name);
	});

program
	.command('remove [config_file]')
	.description('stop app, remove source and dependencies (single user)')
	.action(function() {
  		do_remove();
	});

program
	.command('update [config_file]')
	.description('stop app, clean old source/dependencies, deploy, restart app')
	.action(function() {
  		do_update();
	});

program
	.command('*')
	.action(function() {
		program.help();
	});

program.parse(process.argv);

if (process.argv.length < 3) program.help();

<commit_msg>Added the ability to deploy applications from a git repository, a tar archive, a zip archive and a local directory. Still needs some work as it is not always working.<commit_after>#!/usr/bin/env node

var rest = require('restler');
var program = require('commander');
var pretty = require('prettyjson');

var host, port, config_file;

function set_globals() {
	host = program.host || '127.0.0.1';
	port = program.port || 9002;
	config_file = program.config || './config.json';

	if (program.verbose === true) {
		console.log('options:')
		console.log('  host:' + host);
		console.log('  port:' + port);
		console.log('  config_file:' + config_file);
	}
}

function netget(path, callback) {
	set_globals();

	var uri = 'http://' + host + ':' + port.toString() + path;

	rest.get(uri).on('complete', function(result, response) {
		if (result instanceof Error) {
			console.error('problem with request: ' + response.message);
			return;
		} else {
			callback(result);
		}
	});
}

function netpost(path, payload, callback) {
	set_globals();

	var uri = 'http://' + host + ':' + port.toString() + path;

	var options = {};
	options.data = JSON.stringify(payload);
	options.headers = {
		'Content-Type': 'application/json'
	};

	rest.post(uri, options).on('complete', function(result, response) {
		if (result instanceof Error) {
			console.error('problem with request: ' + response.message);
			return;
		} else {
			callback(result);
		}
	});
}

function netpost_file(path, file, callback) {
	set_globals();

	var fs = require('fs');
	var request = require('request');

	fs.stat(file, function(err, stat) {
		if (err) {
			console.error(err);
			return;
		}

		var uri = 'http://' + host + ':' + port.toString() + path;

		fs.createReadStream(file)
			.pipe(request.post({url: uri}, function (err, res, body) {
				if (err) {
					console.error(err);
					return;
				} else {
				 callback(JSON.parse(body));
				}
			}))
	});
}

function do_version() {
	netget('/version', function(result) {
		console.log('service version: \n' + pretty.render(result));
	});
}

function do_apps() {
	netget('/drones', function(result) {
		console.log('detailed info on apps: \n' + pretty.render(result));
	});
}

function do_app(name) {
	netget('/drones/' + name, function(result) {
		console.log('detailed info on app:' + name + '\n' + pretty.render(result));
	});
}

function do_running() {
	netget('/drones/running', function(result) {
		console.log('running apps: \n' + pretty.render(result));
	});
}

function do_start() {
	set_globals();

	var fs = require('fs');
	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	// All app starts are preceded by app deployment. A 'local' repository type
	// uses a push deployment to deploy a gzipped tar archive of the application
	// directory. All other repository types (git, npm, etc.) use a pull
	// deployment where Haibu pulls from the specified source location.

	if (config.repository && config.repository.type) {
		if (config.repository.type === 'local') {
			// push deployment
			var temp = require('temp');
			var spawn = require('child_process').spawn;

			var url = 'http://' + host + ':' + port + '/deploy/' + config.user + '/' + config.name;
			var tempfile = temp.path({suffix: '.tgz'});
console.log(tempfile);

			var args = ['cfz', tempfile, '.'];
			var options = {};
			options.cwd = process.cwd() + '/' + config.repository.directory;

			var tar = spawn('tar', args, options);
			tar.on('close', function(code) {
				if (code === 0) {
					netpost_file('/deploy/' + config.user + '/' + config.name, tempfile, function(result) {
						console.log('local app deployed: ' + config.name + '\n' + pretty.render(result));
					});
				} else {
					console.error('Failed to archive local directory: ' + config.repository.directory);
				}
			});
		} else {
			// pull deployment
			netpost('/drones/' + config.name + '/start', {'start': config}, function(result) {
				console.log('started app: ' + config.name + '\n' + pretty.render(result));
			});
		}
	} else {
		console.error('unable to extract repository type from: ' + config_file + '\n');
	}
}

function do_stop(name) {
	config = {
		'name': name,
	}

	netpost('/drones/' + config.name + '/stop', {'stop': config}, function(result) {
		console.log('stopped app(s): ' + config.name + '\n' + pretty.render(result));
	});
}

function do_restart(name) {
	config = {
		'name': name,
	}

	netpost('/drones/' + config.name + '/restart', {'restart': config}, function(result) {
		console.log('restarted app(s): ' + config.name + '\n' + pretty.render(result));
	});
}

function do_remove() {
	set_globals();

	var fs = require('fs');
	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	netpost('/drones/' + config.name + '/clean', config, function(result) {
		console.log('removed app: ' + config.name + '\n' + pretty.render(result));
	});
}

function do_update() {
	set_globals();

	var fs = require('fs');
	var config;

	try {
		config = JSON.parse(fs.readFileSync(config_file).toString());
	}
	catch(e) {
		console.error('problem parsing: ' + config_file + '\n' + e);
		return;
	}

	netpost('/drones/' + config.name + '/update', config, function(result) {
		console.log('updated app: ' + config.name + '\n' + pretty.render(result));
	});
}

program
	.usage('[options] command')
	.option('-s, --host [host]', 'host')
	.option('-p, --port [port]', 'port', parseInt)
	.option('-c, --config [config_file]', 'config file (defaults to config.json)')
	.option('-v, --verbose', 'verbose output');

program
	.command('version')
	.description('show service version')
	.action(function() {
  		do_version();
	});

program
	.command('running')
	.description('show running apps')
	.action(function() {
  		do_running();
	});

program
	.command('apps')
	.description('detailed info on apps')
	.action(function() {
  		do_apps();
	});

program
	.command('app <app_name>')
	.description('detailed info on app')
	.action(function(app_name) {
  		do_app(app_name);
	});

program
	.command('start [config_file]')
	.description('deploy and start app')
	.action(function() {
  		do_start();
	});

program
	.command('stop <app_name>')
	.description('stop all instances of app')
	.action(function(app_name) {
  		do_stop(app_name);
	});

program
	.command('restart <app_name>')
	.description('restart all instances of app')
	.action(function(app_name) {
  		do_restart(app_name);
	});

program
	.command('remove [config_file]')
	.description('stop app, remove source and dependencies (single user)')
	.action(function() {
  		do_remove();
	});

program
	.command('update [config_file]')
	.description('stop app, clean old source/dependencies, deploy, start app')
	.action(function() {
  		do_update();
	});

program
	.command('*')
	.action(function() {
		program.help();
	});

program.parse(process.argv);

if (process.argv.length < 3) program.help();

<|endoftext|>