<commit_before>var config = require('./config');
var socket = require('socket.io-client')(config.server);

/** API **/
socket.on('connect', function(){
    socket.emit('register', {name: config.name});
});

socket.on('event', function(data){});
socket.on('disconnect', function(){});

socket.on('start', start);
socket.on('shutdown', shutdown);
socket.on('restart', restart);
socket.on('sha', sendLastCommitSha);
socket.on('updateIfNeeded', updateIfNeeded);

const spawn = require('child_process').spawn;
const nodePath = process.env.HOME + '/chainpoint-node';

function onLog(data)    { sendLog(data, 'info'); }
function onError(data)  { sendLog(data, 'error'); }

function sendLog(data, level) {
    var cleaned = cleanData(data);
    for (var i = 0, len = cleaned.length; i < len; i++) {
        socket.emit('log', {level: level, data: cleaned[i]});
    }
}

function execLogs() {
    const logs = spawn('docker-compose', ['logs', '-f', '-t'], {cwd: nodePath});
    logs.stdout.on('data', onLog);
    logs.stderr.on('data', onError);

    logs.on('close', (code) => {
        const level = (code !== 0 ? 'error' : 'info');
        socket.emit('log', {level: level, data: ['Exited with code: ' + code]});
        console.log(`Logs process exited with code ${code}`);
    });
}

function getLastCommitSha() {
    return new Promise((resolve, reject) => {
        const git = spawn('git', ['rev-parse', 'HEAD'], {cwd: nodePath});

        var res = '';
        var err = '';

        git.stdout.on('data', (data) => {
            res += data;
        });

        git.stderr.on('data', (data) => {
            err += data;
        });

        git.on('close', (code) => {
            if(code === 0) {
                resolve(res.toString());
            }
            else reject(err);
        });
    });
}

function sendLastCommitSha() {
    getLastCommitSha
        .then(sha => socket.emit('sha', sha))
        .catch(err => onError(err))
}

function shutdown() {
    const make = spawn('make', ['down'], {cwd: nodePath});
    make.stdout.on('data', onLog);
    make.stderr.on('data', onError);

    make.on('close', (code) => {
        console.log('Exited shutdown with code ' + code);
        socket.emit('shutdown-finished', code);
    });
}

function start() {
    const make = spawn('make', ['up'], {cwd: nodePath});
    make.stdout.on('data', onLog);
    make.stderr.on('data', onError);

    make.on('close', (code) => {
        console.log('Exited start with code ' + code);
        socket.emit('start-finished', code);

        if(code === 0) {
            execLogs();
        }
    });
}

function updateIfNeeded(lastSha) {
    if(!lastSha) return console.error('updateIfNeeded: No sha sent');

    getLastCommitSha().then(localSha => {
        if(localSha !== lastSha) {
            const git = spawn('git', ['pull'], {cwd: process.env.HOME + '/chainpoint-node'});
            git.stdout.on('data', onLog);
            git.stderr.on('data', onError);

            git.on('close', (code) => {
                console.log('Exited update with code ' + code);
                socket.emit('update-finished', code);
            });
        }
    });
}

function restart(){

}

/**
 * Split input string on new lines and remove unicode characters
 * @param data
 * @returns {Array} cleaned strings
 */
function cleanData(stringArray) {
    const res = [];
    // Split lines, using a sync loop to keep order
    const dataArray = stringArray.toString().split(/\r?\n/);
    console.log(stringArray);
    console.log(dataArray);
    for (var i = 0, len = dataArray.length; i < len; i++) {
        const msg = dataArray[idx];
        if(msg.replace(/\s/g, '').length > 0) {
            // Remove unicode characters and push to results
            res.push(msg.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '').replace(/\r?\n|\r/g, ''));
        }
    }
    console.log(res);
    return res;
}
<commit_msg>Wrong iterator name<commit_after>var config = require('./config');
var socket = require('socket.io-client')(config.server);

/** API **/
socket.on('connect', function(){
    socket.emit('register', {name: config.name});
});

socket.on('event', function(data){});
socket.on('disconnect', function(){});

socket.on('start', start);
socket.on('shutdown', shutdown);
socket.on('restart', restart);
socket.on('sha', sendLastCommitSha);
socket.on('updateIfNeeded', updateIfNeeded);

const spawn = require('child_process').spawn;
const nodePath = process.env.HOME + '/chainpoint-node';

function onLog(data)    { sendLog(data, 'info'); }
function onError(data)  { sendLog(data, 'error'); }

function sendLog(data, level) {
    var cleaned = cleanData(data);
    for (var i = 0, len = cleaned.length; i < len; i++) {
        socket.emit('log', {level: level, data: cleaned[i]});
    }
}

function execLogs() {
    const logs = spawn('docker-compose', ['logs', '-f', '-t'], {cwd: nodePath});
    logs.stdout.on('data', onLog);
    logs.stderr.on('data', onError);

    logs.on('close', (code) => {
        const level = (code !== 0 ? 'error' : 'info');
        socket.emit('log', {level: level, data: ['Exited with code: ' + code]});
        console.log(`Logs process exited with code ${code}`);
    });
}

function getLastCommitSha() {
    return new Promise((resolve, reject) => {
        const git = spawn('git', ['rev-parse', 'HEAD'], {cwd: nodePath});

        var res = '';
        var err = '';

        git.stdout.on('data', (data) => {
            res += data;
        });

        git.stderr.on('data', (data) => {
            err += data;
        });

        git.on('close', (code) => {
            if(code === 0) {
                resolve(res.toString());
            }
            else reject(err);
        });
    });
}

function sendLastCommitSha() {
    getLastCommitSha
        .then(sha => socket.emit('sha', sha))
        .catch(err => onError(err))
}

function shutdown() {
    const make = spawn('make', ['down'], {cwd: nodePath});
    make.stdout.on('data', onLog);
    make.stderr.on('data', onError);

    make.on('close', (code) => {
        console.log('Exited shutdown with code ' + code);
        socket.emit('shutdown-finished', code);
    });
}

function start() {
    const make = spawn('make', ['up'], {cwd: nodePath});
    make.stdout.on('data', onLog);
    make.stderr.on('data', onError);

    make.on('close', (code) => {
        console.log('Exited start with code ' + code);
        socket.emit('start-finished', code);

        if(code === 0) {
            execLogs();
        }
    });
}

function updateIfNeeded(lastSha) {
    if(!lastSha) return console.error('updateIfNeeded: No sha sent');

    getLastCommitSha().then(localSha => {
        if(localSha !== lastSha) {
            const git = spawn('git', ['pull'], {cwd: process.env.HOME + '/chainpoint-node'});
            git.stdout.on('data', onLog);
            git.stderr.on('data', onError);

            git.on('close', (code) => {
                console.log('Exited update with code ' + code);
                socket.emit('update-finished', code);
            });
        }
    });
}

function restart(){

}

/**
 * Split input string on new lines and remove unicode characters
 * @param data
 * @returns {Array} cleaned strings
 */
function cleanData(stringArray) {
    const res = [];
    // Split lines, using a sync loop to keep order
    const dataArray = stringArray.toString().split(/\r?\n/);
    console.log(stringArray);
    console.log(dataArray);
    for (var i = 0, len = dataArray.length; i < len; i++) {
        const msg = dataArray[i];
        if(msg.replace(/\s/g, '').length > 0) {
            // Remove unicode characters and push to results
            res.push(msg.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '').replace(/\r?\n|\r/g, ''));
        }
    }
    console.log(res);
    return res;
}
<|endoftext|>


<commit_before>'use strict';

/**
 * serverless-mocha-plugin
 * - a plugin for TDD with serverless
 */

const path  = require('path'),
  fs        = require('fs'),
  lambdaWrapper = require('lambda-wrapper'),
  Mocha = require('mocha'),
  chai = require('chai'),
  Path = require('path'),
  BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)

const testFolder = 'test'; // Folder used my mocha for tests

module.exports = function(S) { // Always pass in the ServerlessPlugin Class

  /**
   * Adding/Manipulating Serverless classes
   * - You can add or manipulate Serverless classes like this
   */

  S.classes.Project.newStaticMethod     = function() { console.log("A new method!"); };
  S.classes.Project.prototype.newMethod = function() { S.classes.Project.newStaticMethod(); };

  /**
   * Extending the Plugin Class
   * - Here is how you can add custom Actions and Hooks to Serverless.
   * - This class is only required if you want to add Actions and Hooks.
   */

  class PluginBoilerplate extends S.classes.Plugin {

    /**
     * Constructor
     * - Keep this and don't touch it unless you know what you're doing.
     */

    constructor() {
      super();
      this.name = 'io.sc5.mocha';
    }

    /**
     * Register Actions
     * - function mocha-create
     */

    registerActions() {

      S.addAction(this._createAction.bind(this), {
        handler:       '_createAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-create',
        options:       [{ // These must be specified in the CLI like this "-option true" or "-o true"
        }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      S.addAction(this._runAction.bind(this), {
        handler:       '_runAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-run',
        options:       [          {
            option:      'region',
            shortcut:    'r',
            description: 'region you want to run your function in'
          },
          {
            option:      'stage',
            shortcut:    's',
            description: 'stage you want to run your function in'
          },
          {
            option:      'reporter',
            shortcut:    'R',
            description: 'specify the reporter to use'
          },
          {
            option:      'reporter-options',
            shortcut:    'O',
            description: 'reporter-specific options'
          }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      return BbPromise.resolve();
    }

    /**
     * Register Hooks
     * -  function create (post) creates mocha test file
     */

    registerHooks() {
      S.addHook(this._hookPostFuncCreate.bind(this), {
        action: 'functionCreate',
        event:  'post'
      });

      return BbPromise.resolve();
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _createAction(evt) {
      if (S.getProject().getFunction(evt.options.paths[0]) === undefined) {
        throw(new Error("Could not find function " + evt.options.paths[0]));
      }

      return createTest(evt.options.paths[0]);
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _runAction(evt) {
      return new BbPromise(function(resolve, reject) {
          let funcName = evt.options.paths;
          let mocha = new Mocha();
          //This could pose as an issue if several functions share a common ENV name but different values.

          let stage = evt.options.stage || S.getProject().getAllStages()[0].name;
          let region = evt.options.region || S.getProject().getAllRegions(stage)[0].name;

          SetEnvVars(evt.options.paths, {
            stage: stage,
            region: region
          });

          getFilePaths(evt.options.paths)
          .then(function(paths) {
              paths.forEach(function(path,idx) {
                mocha.addFile(path);
              })
              var reporter = evt.options.reporter;
              if ( reporter !== null) {
                var reporterOptions = {};
                if (evt.options["reporter-options"] !== null) {
                  evt.options["reporter-options"].split(",").forEach(function(opt) {
                    var L = opt.split("=");
                    if (L.length > 2 || L.length === 0) {
                      throw new Error("invalid reporter option '" + opt + "'");
                    } else if (L.length === 2) {
                      reporterOptions[L[0]] = L[1];
                    } else {
                      reporterOptions[L[0]] = true;
                    }
                  });
                }
                mocha.reporter(reporter, reporterOptions)
              }
              mocha.run(function(failures){
                process.on('exit', function () {
                  process.exit(failures);  // exit with non-zero status if there were failures
                });
              });
          }, function(error) {

            return reject(error);
          });
      });
    }
    /**
     * Hook for creating the mocha test placeholder after function creation
     */

    _hookPostFuncCreate(evt) {
      // TODO: only run with runtime node4.3
      if (evt.options.runtime != 'nodejs4.3') {
        console.log(evt.options.runtime);
        return;
      }
      let parsedPath = path.parse(evt.options.path);
      let funcName = parsedPath.base;

      return createTest(funcName);
    }
  }

  //Set environment variables
  function SetEnvVars(paths, config) {
    paths.forEach(function(path, idx){
      var funcName = Path.basename(path, '.js');
      var func = S.getProject().getFunction(funcName).toObjectPopulated(config);
      var envVars = func.environment;
      var fields = Object.keys(envVars);

      for (var key in fields) {
        process.env[fields[key]] = envVars[fields[key]];
      }
    });
  }

  // Create the test folder
  function createTestFolder() {
      return new BbPromise(function(resolve, reject) {

        fs.exists(testFolder, function(exists) {
            if (exists) {
                return resolve(testFolder);
            }
            fs.mkdir(testFolder, function(err) {
                if (err) {
                    return reject(err);
                }
                return resolve(testFolder);
            })
        })
      });
  }

  // Create the test file (and test folder)

  function createTest(funcName) {
    return createTestFolder().then(function(testFolder) {
      return new BbPromise(function(resolve, reject) {
        let funcFilePath = testFilePath(funcName);

        fs.exists(funcFilePath, function (exists) {
           if (exists) {
               return reject(new Error(`File ${funcFilePath} already exists`));
           }
           fs.writeFile(funcFilePath, newTestFile(funcName), function(err) {
               if (err) {
                   return reject(new Error(`Creating file ${funcFilePath} failed: ${err}`));
               }
               console.log(`serverless-mocha-plugin: created ${funcFilePath}`);
               return resolve(funcFilePath);
           })
        });
      });
    });
  }

  // getTestFiles. If no functions provided, returns all files
  function getFilePaths(funcs) {
    return new BbPromise(function(resolve, reject) {
        var paths = [];

        if (funcs && (funcs.length > 0)) {
            funcs.forEach(function(val, idx) {
                paths.push(testFilePath(val));
            });
            return resolve(paths);
        }
        // No funcs provided, list all test files
        fs.readdirSync(testFolder).filter(function(file){
          // Only keep the .js files
          return file.substr(-3) === '.js';
        }).forEach(function(file) {
            paths.push(path.join(testFolder, file));
        });
        return resolve(paths);
    });
  };

  // Returns the path to a function's test file
  function testFilePath(funcName) {
      return path.join(testFolder, `${funcName.replace(/.*\//g, '')}.js`);
  }

  function newTestFile(funcName) {
      return `'use strict';
// tests for ${funcName}
// Generated by serverless-mocha-plugin

const mod         = require('../${funcName}/handler.js');
const mochaPlugin = require('serverless-mocha-plugin');
const wrapper     = mochaPlugin.lambdaWrapper;
const expect      = mochaPlugin.chai.expect;

wrapper.init(mod);

describe('${funcName}', () => {
  it('implement tests here', (done) => {
    wrapper.run({}, (err, response) => {
      done('no tests implemented');
    });
  });
});
`;

  }
  // Export Plugin Class
  return PluginBoilerplate;
};

module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;
<commit_msg>Return the function not found error via promise<commit_after>'use strict';

/**
 * serverless-mocha-plugin
 * - a plugin for TDD with serverless
 */

const path  = require('path'),
  fs        = require('fs'),
  lambdaWrapper = require('lambda-wrapper'),
  Mocha = require('mocha'),
  chai = require('chai'),
  Path = require('path'),
  BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)

const testFolder = 'test'; // Folder used my mocha for tests

module.exports = function(S) { // Always pass in the ServerlessPlugin Class

  /**
   * Adding/Manipulating Serverless classes
   * - You can add or manipulate Serverless classes like this
   */

  S.classes.Project.newStaticMethod     = function() { console.log("A new method!"); };
  S.classes.Project.prototype.newMethod = function() { S.classes.Project.newStaticMethod(); };

  /**
   * Extending the Plugin Class
   * - Here is how you can add custom Actions and Hooks to Serverless.
   * - This class is only required if you want to add Actions and Hooks.
   */

  class PluginBoilerplate extends S.classes.Plugin {

    /**
     * Constructor
     * - Keep this and don't touch it unless you know what you're doing.
     */

    constructor() {
      super();
      this.name = 'io.sc5.mocha';
    }

    /**
     * Register Actions
     * - function mocha-create
     */

    registerActions() {

      S.addAction(this._createAction.bind(this), {
        handler:       '_createAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-create',
        options:       [{ // These must be specified in the CLI like this "-option true" or "-o true"
        }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      S.addAction(this._runAction.bind(this), {
        handler:       '_runAction',
        description:   'Create mocha test for function',
        context:       'function',
        contextAction: 'mocha-run',
        options:       [          {
            option:      'region',
            shortcut:    'r',
            description: 'region you want to run your function in'
          },
          {
            option:      'stage',
            shortcut:    's',
            description: 'stage you want to run your function in'
          },
          {
            option:      'reporter',
            shortcut:    'R',
            description: 'specify the reporter to use'
          },
          {
            option:      'reporter-options',
            shortcut:    'O',
            description: 'reporter-specific options'
          }],
        parameters: [ // Use paths when you multiple values need to be input (like an array).  Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3.  Serverless will automatically turn this into an array and attach it to evt.options within your plugin
          {
            parameter: 'paths',
            description: 'Path to function to test. If not defined, test all functions.',
            position: '0->' // Can be: 0, 0-2, 0->  This tells Serverless which params are which.  3-> Means that number and infinite values after it.
          }
        ]
      });

      return BbPromise.resolve();
    }

    /**
     * Register Hooks
     * -  function create (post) creates mocha test file
     */

    registerHooks() {
      S.addHook(this._hookPostFuncCreate.bind(this), {
        action: 'functionCreate',
        event:  'post'
      });

      return BbPromise.resolve();
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _createAction(evt) {
      if (S.getProject().getFunction(evt.options.paths[0]) === undefined) {
        return new BbPromise(function(resolve, reject) {
          reject(`MochaPluginError: Function ${evt.options.paths[0]} does not exist in your project`);
        });
      }

      return createTest(evt.options.paths[0]);
    }

    /**
     * Custom action serverless function mocha-create functioName
     */

    _runAction(evt) {
      return new BbPromise(function(resolve, reject) {
          let funcName = evt.options.paths;
          let mocha = new Mocha();
          //This could pose as an issue if several functions share a common ENV name but different values.

          let stage = evt.options.stage || S.getProject().getAllStages()[0].name;
          let region = evt.options.region || S.getProject().getAllRegions(stage)[0].name;

          SetEnvVars(evt.options.paths, {
            stage: stage,
            region: region
          });

          getFilePaths(evt.options.paths)
          .then(function(paths) {
              paths.forEach(function(path,idx) {
                mocha.addFile(path);
              })
              var reporter = evt.options.reporter;
              if ( reporter !== null) {
                var reporterOptions = {};
                if (evt.options["reporter-options"] !== null) {
                  evt.options["reporter-options"].split(",").forEach(function(opt) {
                    var L = opt.split("=");
                    if (L.length > 2 || L.length === 0) {
                      throw new Error("invalid reporter option '" + opt + "'");
                    } else if (L.length === 2) {
                      reporterOptions[L[0]] = L[1];
                    } else {
                      reporterOptions[L[0]] = true;
                    }
                  });
                }
                mocha.reporter(reporter, reporterOptions)
              }
              mocha.run(function(failures){
                process.on('exit', function () {
                  process.exit(failures);  // exit with non-zero status if there were failures
                });
              });
          }, function(error) {

            return reject(error);
          });
      });
    }
    /**
     * Hook for creating the mocha test placeholder after function creation
     */

    _hookPostFuncCreate(evt) {
      // TODO: only run with runtime node4.3
      if (evt.options.runtime != 'nodejs4.3') {
        console.log(evt.options.runtime);
        return;
      }
      let parsedPath = path.parse(evt.options.path);
      let funcName = parsedPath.base;

      return createTest(funcName);
    }
  }

  //Set environment variables
  function SetEnvVars(paths, config) {
    paths.forEach(function(path, idx){
      var funcName = Path.basename(path, '.js');
      var func = S.getProject().getFunction(funcName).toObjectPopulated(config);
      var envVars = func.environment;
      var fields = Object.keys(envVars);

      for (var key in fields) {
        process.env[fields[key]] = envVars[fields[key]];
      }
    });
  }

  // Create the test folder
  function createTestFolder() {
      return new BbPromise(function(resolve, reject) {

        fs.exists(testFolder, function(exists) {
            if (exists) {
                return resolve(testFolder);
            }
            fs.mkdir(testFolder, function(err) {
                if (err) {
                    return reject(err);
                }
                return resolve(testFolder);
            })
        })
      });
  }

  // Create the test file (and test folder)

  function createTest(funcName) {
    return createTestFolder().then(function(testFolder) {
      return new BbPromise(function(resolve, reject) {
        let funcFilePath = testFilePath(funcName);

        fs.exists(funcFilePath, function (exists) {
           if (exists) {
               return reject(new Error(`File ${funcFilePath} already exists`));
           }
           fs.writeFile(funcFilePath, newTestFile(funcName), function(err) {
               if (err) {
                   return reject(new Error(`Creating file ${funcFilePath} failed: ${err}`));
               }
               console.log(`serverless-mocha-plugin: created ${funcFilePath}`);
               return resolve(funcFilePath);
           })
        });
      });
    });
  }

  // getTestFiles. If no functions provided, returns all files
  function getFilePaths(funcs) {
    return new BbPromise(function(resolve, reject) {
        var paths = [];

        if (funcs && (funcs.length > 0)) {
            funcs.forEach(function(val, idx) {
                paths.push(testFilePath(val));
            });
            return resolve(paths);
        }
        // No funcs provided, list all test files
        fs.readdirSync(testFolder).filter(function(file){
          // Only keep the .js files
          return file.substr(-3) === '.js';
        }).forEach(function(file) {
            paths.push(path.join(testFolder, file));
        });
        return resolve(paths);
    });
  };

  // Returns the path to a function's test file
  function testFilePath(funcName) {
      return path.join(testFolder, `${funcName.replace(/.*\//g, '')}.js`);
  }

  function newTestFile(funcName) {
      return `'use strict';
// tests for ${funcName}
// Generated by serverless-mocha-plugin

const mod         = require('../${funcName}/handler.js');
const mochaPlugin = require('serverless-mocha-plugin');
const wrapper     = mochaPlugin.lambdaWrapper;
const expect      = mochaPlugin.chai.expect;

wrapper.init(mod);

describe('${funcName}', () => {
  it('implement tests here', (done) => {
    wrapper.run({}, (err, response) => {
      done('no tests implemented');
    });
  });
});
`;

  }
  // Export Plugin Class
  return PluginBoilerplate;
};

module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;
<|endoftext|>


<commit_before>const React = require('react-native');
const {
  Dimensions,
  View,
  Animated,
  ScrollView,
  Platform,
  StyleSheet,
  ViewPagerAndroid,
  PropTypes,
  InteractionManager,
} = React;

const DefaultTabBar = require('./DefaultTabBar');
const ScrollableTabBar = require('./ScrollableTabBar');

const ScrollableTabView = React.createClass({
  statics: {
    DefaultTabBar,
    ScrollableTabBar,
  },

  propTypes: {
    tabBarPosition: PropTypes.oneOf(['top', 'bottom', 'overlayTop', 'overlayBottom', ]),
    initialPage: PropTypes.number,
    page: PropTypes.number,
    onChangeTab: PropTypes.func,
    onScroll: PropTypes.func,
    renderTabBar: PropTypes.any,
    style: View.propTypes.style,
  },

  getDefaultProps() {
    return {
      tabBarPosition: 'top',
      initialPage: 0,
      page: -1,
      onChangeTab: () => {},
      onScroll: () => {},
    };
  },

  getInitialState() {
    return {
      currentPage: this.props.initialPage,
      scrollValue: new Animated.Value(this.props.initialPage),
      containerWidth: Dimensions.get('window').width,
    };
  },

  componentWillReceiveProps(props) {
    if (props.page >= 0 && props.page !== this.state.currentPage) {
      this.goToPage(props.page);
    }
  },

  goToPage(pageNumber) {
    this.props.onChangeTab({ i: pageNumber, ref: this._children()[pageNumber], });

    if (Platform.OS === 'ios') {
      const offset = pageNumber * this.state.containerWidth;
      this.scrollView.scrollTo(0, offset);
    } else {
      this.scrollView.setPage(pageNumber);
    }

    this.setState({currentPage: pageNumber, });
  },

  renderTabBar(props) {
    if (this.props.renderTabBar === false) {
      return null;
    } else if (this.props.renderTabBar) {
      return React.cloneElement(this.props.renderTabBar(), props);
    } else {
      return <DefaultTabBar {...props} />;
    }
  },

  renderScrollableContent() {
    if (Platform.OS === 'ios') {
      return (
        <ScrollView
          horizontal
          pagingEnabled
          style={styles.scrollableContentIOS}
          contentContainerStyle={styles.scrollableContentContainerIOS}
          contentOffset={{ x: this.props.initialPage * this.state.containerWidth, }}
          ref={(scrollView) => { this.scrollView = scrollView; }}
          onScroll={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateScrollValue(offsetX / this.state.containerWidth);
          }}
          onMomentumScrollBegin={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateSelectedPage(parseInt(offsetX / this.state.containerWidth, 10));
          }}
          onMomentumScrollEnd={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateSelectedPage(parseInt(offsetX / this.state.containerWidth, 10));
          }}
          scrollEventThrottle={16}
          showsHorizontalScrollIndicator={false}
          scrollEnabled={!this.props.locked}
          directionalLockEnabled
          alwaysBounceVertical={false}>
          {this._children().map((child, idx) => {
            return <View
              key={child.props.tabLabel + '_' + idx}
              style={{width: this.state.containerWidth, }}>
              {child}
            </View>;
          })}
        </ScrollView>
      );
    } else {
      return (
        <ViewPagerAndroid
         style={styles.scrollableContentAndroid}
         initialPage={this.props.initialPage}
         onPageSelected={this._updateSelectedPage}
         onPageScroll={(e) => {
           const { offset, position, } = e.nativeEvent;
           this._updateScrollValue(position + offset);
         }}
         ref={(scrollView) => { this.scrollView = scrollView; }}>
         {this._children().map((child, idx) => {
           return <View
             key={child.props.tabLabel + '_' + idx}
             style={{width: this.state.containerWidth, }}>
             {child}
           </View>;
         })}
        </ViewPagerAndroid>
      );
    }
  },

  _updateSelectedPage(currentPage) {
    let localCurrentPage = currentPage;
    if (typeof localCurrentPage === 'object') {
      localCurrentPage = currentPage.nativeEvent.position;
    }
    this.setState({currentPage: localCurrentPage, }, () => {
      this.props.onChangeTab({ i: localCurrentPage, });
    });
  },

  _updateScrollValue(value) {
    this.state.scrollValue.setValue(value);
    this.props.onScroll(value);
  },

  _handleLayout(e) {
    const { width, } = e.nativeEvent.layout;

    if (width !== this.state.containerWidth) {
      this.setState({ containerWidth: width, });
      InteractionManager.runAfterInteractions(() => {
        this.goToPage(this.state.currentPage);
      });
    }
  },

  // The following implementation allows for compatibility with version
  // of React Native that depend on React.Children prior to
  // facebook/react#6013105a9cf625cac18851683adbf2fd19b6833c
  _children() {
    let result = [];
    React.Children.forEach(this.props.children, (child) => result.push(child));
    return result;
  },

  render() {
    let overlayTabs = (this.props.tabBarPosition === 'overlayTop' || this.props.tabBarPosition === 'overlayBottom');
    let tabBarProps = {
      goToPage: this.goToPage,
      tabs: this._children().map((child) => child.props.tabLabel),
      activeTab: this.state.currentPage,
      scrollValue: this.state.scrollValue,
      containerWidth: this.state.containerWidth,
    };

    if (this.props.tabBarUnderlineColor) {
      tabBarProps.underlineColor = this.props.tabBarUnderlineColor;
    }
    if (this.props.tabBarBackgroundColor) {
      tabBarProps.backgroundColor = this.props.tabBarBackgroundColor;
    }
    if (this.props.tabBarActiveTextColor) {
      tabBarProps.activeTextColor = this.props.tabBarActiveTextColor;
    }
    if (this.props.tabBarInactiveTextColor) {
      tabBarProps.inactiveTextColor = this.props.tabBarInactiveTextColor;
    }
    if (overlayTabs) {
      tabBarProps.style = {
        position: 'absolute',
        left: 0,
        right: 0,
        [this.props.tabBarPosition === 'overlayTop' ? 'top' : 'bottom']: 0
      };
    }

    return (
      <View style={[styles.container, this.props.style, ]} onLayout={this._handleLayout}>
        {this.props.tabBarPosition === 'top' && this.renderTabBar(tabBarProps)}
        {this.renderScrollableContent()}
        {(this.props.tabBarPosition === 'bottom' || overlayTabs) && this.renderTabBar(tabBarProps)}
      </View>
    );
  },
});

module.exports = ScrollableTabView;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollableContentContainerIOS: {
    flex: 1,
  },
  scrollableContentIOS: {
    flexDirection: 'column',
  },
  scrollableContentAndroid: {
    flex: 1,
  },
});
<commit_msg>add automaticallyAdjustContentInsets prop to ScrollView<commit_after>const React = require('react-native');
const {
  Dimensions,
  View,
  Animated,
  ScrollView,
  Platform,
  StyleSheet,
  ViewPagerAndroid,
  PropTypes,
  InteractionManager,
} = React;

const DefaultTabBar = require('./DefaultTabBar');
const ScrollableTabBar = require('./ScrollableTabBar');

const ScrollableTabView = React.createClass({
  statics: {
    DefaultTabBar,
    ScrollableTabBar,
  },

  propTypes: {
    tabBarPosition: PropTypes.oneOf(['top', 'bottom', 'overlayTop', 'overlayBottom', ]),
    initialPage: PropTypes.number,
    page: PropTypes.number,
    onChangeTab: PropTypes.func,
    onScroll: PropTypes.func,
    renderTabBar: PropTypes.any,
    style: View.propTypes.style,
  },

  getDefaultProps() {
    return {
      tabBarPosition: 'top',
      initialPage: 0,
      page: -1,
      onChangeTab: () => {},
      onScroll: () => {},
    };
  },

  getInitialState() {
    return {
      currentPage: this.props.initialPage,
      scrollValue: new Animated.Value(this.props.initialPage),
      containerWidth: Dimensions.get('window').width,
    };
  },

  componentWillReceiveProps(props) {
    if (props.page >= 0 && props.page !== this.state.currentPage) {
      this.goToPage(props.page);
    }
  },

  goToPage(pageNumber) {
    this.props.onChangeTab({ i: pageNumber, ref: this._children()[pageNumber], });

    if (Platform.OS === 'ios') {
      const offset = pageNumber * this.state.containerWidth;
      this.scrollView.scrollTo(0, offset);
    } else {
      this.scrollView.setPage(pageNumber);
    }

    this.setState({currentPage: pageNumber, });
  },

  renderTabBar(props) {
    if (this.props.renderTabBar === false) {
      return null;
    } else if (this.props.renderTabBar) {
      return React.cloneElement(this.props.renderTabBar(), props);
    } else {
      return <DefaultTabBar {...props} />;
    }
  },

  renderScrollableContent() {
    if (Platform.OS === 'ios') {
      return (
        <ScrollView
          horizontal
          pagingEnabled
          automaticallyAdjustContentInsets={false}
          style={styles.scrollableContentIOS}
          contentContainerStyle={styles.scrollableContentContainerIOS}
          contentOffset={{ x: this.props.initialPage * this.state.containerWidth, }}
          ref={(scrollView) => { this.scrollView = scrollView; }}
          onScroll={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateScrollValue(offsetX / this.state.containerWidth);
          }}
          onMomentumScrollBegin={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateSelectedPage(parseInt(offsetX / this.state.containerWidth, 10));
          }}
          onMomentumScrollEnd={(e) => {
            const offsetX = e.nativeEvent.contentOffset.x;
            this._updateSelectedPage(parseInt(offsetX / this.state.containerWidth, 10));
          }}
          scrollEventThrottle={16}
          showsHorizontalScrollIndicator={false}
          scrollEnabled={!this.props.locked}
          directionalLockEnabled
          alwaysBounceVertical={false}>
          {this._children().map((child, idx) => {
            return <View
              key={child.props.tabLabel + '_' + idx}
              style={{width: this.state.containerWidth, }}>
              {child}
            </View>;
          })}
        </ScrollView>
      );
    } else {
      return (
        <ViewPagerAndroid
         style={styles.scrollableContentAndroid}
         initialPage={this.props.initialPage}
         onPageSelected={this._updateSelectedPage}
         onPageScroll={(e) => {
           const { offset, position, } = e.nativeEvent;
           this._updateScrollValue(position + offset);
         }}
         ref={(scrollView) => { this.scrollView = scrollView; }}>
         {this._children().map((child, idx) => {
           return <View
             key={child.props.tabLabel + '_' + idx}
             style={{width: this.state.containerWidth, }}>
             {child}
           </View>;
         })}
        </ViewPagerAndroid>
      );
    }
  },

  _updateSelectedPage(currentPage) {
    let localCurrentPage = currentPage;
    if (typeof localCurrentPage === 'object') {
      localCurrentPage = currentPage.nativeEvent.position;
    }
    this.setState({currentPage: localCurrentPage, }, () => {
      this.props.onChangeTab({ i: localCurrentPage, });
    });
  },

  _updateScrollValue(value) {
    this.state.scrollValue.setValue(value);
    this.props.onScroll(value);
  },

  _handleLayout(e) {
    const { width, } = e.nativeEvent.layout;

    if (width !== this.state.containerWidth) {
      this.setState({ containerWidth: width, });
      InteractionManager.runAfterInteractions(() => {
        this.goToPage(this.state.currentPage);
      });
    }
  },

  // The following implementation allows for compatibility with version
  // of React Native that depend on React.Children prior to
  // facebook/react#6013105a9cf625cac18851683adbf2fd19b6833c
  _children() {
    let result = [];
    React.Children.forEach(this.props.children, (child) => result.push(child));
    return result;
  },

  render() {
    let overlayTabs = (this.props.tabBarPosition === 'overlayTop' || this.props.tabBarPosition === 'overlayBottom');
    let tabBarProps = {
      goToPage: this.goToPage,
      tabs: this._children().map((child) => child.props.tabLabel),
      activeTab: this.state.currentPage,
      scrollValue: this.state.scrollValue,
      containerWidth: this.state.containerWidth,
    };

    if (this.props.tabBarUnderlineColor) {
      tabBarProps.underlineColor = this.props.tabBarUnderlineColor;
    }
    if (this.props.tabBarBackgroundColor) {
      tabBarProps.backgroundColor = this.props.tabBarBackgroundColor;
    }
    if (this.props.tabBarActiveTextColor) {
      tabBarProps.activeTextColor = this.props.tabBarActiveTextColor;
    }
    if (this.props.tabBarInactiveTextColor) {
      tabBarProps.inactiveTextColor = this.props.tabBarInactiveTextColor;
    }
    if (overlayTabs) {
      tabBarProps.style = {
        position: 'absolute',
        left: 0,
        right: 0,
        [this.props.tabBarPosition === 'overlayTop' ? 'top' : 'bottom']: 0
      };
    }

    return (
      <View style={[styles.container, this.props.style, ]} onLayout={this._handleLayout}>
        {this.props.tabBarPosition === 'top' && this.renderTabBar(tabBarProps)}
        {this.renderScrollableContent()}
        {(this.props.tabBarPosition === 'bottom' || overlayTabs) && this.renderTabBar(tabBarProps)}
      </View>
    );
  },
});

module.exports = ScrollableTabView;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollableContentContainerIOS: {
    flex: 1,
  },
  scrollableContentIOS: {
    flexDirection: 'column',
  },
  scrollableContentAndroid: {
    flex: 1,
  },
});
<|endoftext|>


<commit_before>var TelegramBot = require('node-telegram-bot-api');
var path = require('path');
var store = require('data-store')('app', {});
var t_token = require('./telegram-token.js'); // Set Telegram Bot Token
var token = t_token.token();
// Setup polling way
var bot = new TelegramBot(token, {polling: true});
// store.del({force: true});

// Any kind of message
bot.on('message', function (msg) {
  console.log(msg);
  var fromId = msg.chat.id || msg.from.id,
      message = msg.text || "",
      identifier = msg.chat.id.toString();
  if(message.match(/^\/settopic/i) ) {
    store.set(identifier, "##");
    bot.sendMessage(fromId, "Okay, Give me the Topic...");
  } else if(message.match(/^\/topic/i) ) {
    if(typeof(store.get(identifier)) !== 'undefined') {
      bot.sendMessage(fromId, "Topic is: *" + store.get(identifier) + "*", {parse_mode: "Markdown"});
    } else {
      bot.sendMessage(fromId, "No topic Set, try /settopic@chattopic_bot ");
    }
  } else {
    if(typeof(store.get(identifier)) !== 'undefined' && store.get(identifier) === "##") {
      store.set(identifier, msg.text);
      bot.sendMessage(fromId, "Topic Set to: *" + msg.text + "* by @" +  msg.from.username, {parse_mode: "Markdown"});
    }
  }
});
<commit_msg>Fixed #1 only the person ints topic can set topic<commit_after>var TelegramBot = require('node-telegram-bot-api');
var path = require('path');
var store = require('data-store')('app', {});
var t_token = require('./telegram-token.js'); // Set Telegram Bot Token
var token = t_token.token();
// Setup polling way
var bot = new TelegramBot(token, {polling: true});
// store.del({force: true});

// Any kind of message
bot.on('message', function (msg) {
  console.log(msg);
  var fromId = msg.chat.id || msg.from.id,
      message = msg.text || "",
      identifier = msg.chat.id.toString();
  if(message.match(/^\/settopic/i) ) {
    store.set(identifier, msg.from.id.toString());
    bot.sendMessage(fromId, "Okay, Give me the Topic...");
  } else if(message.match(/^\/topic/i) ) {
    if(typeof(store.get(identifier)) !== 'undefined') {
      bot.sendMessage(fromId, "Topic is: *" + store.get(identifier) + "*", {parse_mode: "Markdown"});
    } else {
      bot.sendMessage(fromId, "No topic Set, try /settopic@chattopic_bot ");
    }
  } else {
    if(typeof(store.get(identifier)) !== 'undefined' && store.get(identifier) === msg.from.id.toString()) {
      store.set(identifier, msg.text);
      bot.sendMessage(fromId, "Topic Set to: *" + msg.text + "* by @" +  msg.from.username, {parse_mode: "Markdown"});
    }
  }
});
<|endoftext|>


<commit_before>var Express = require('express');
var ImageProxy = require('./libs/image-proxy');
var Timeline = require('./libs/timeline');

var app = Express();
var port = 8585;

/**
 * @brief Twitter timeline
 * @return Twitter timeline content in JSON
 */
app.get('/:pass/tweets', function (req, res) {
    if ( ! Timeline.queryAuthorized(req))
    {
        res.end();
        return;
    }

    Timeline.getTimeline(function(error, timeline) {
      if (timeline == undefined) {
        res.send('');
      }

      res.json(timeline);
    });
})

/**
 * @brief Twitter image proxy
 * @return Twitter target image through nodeJS
 */
 app.get('/tweetImage/*', function (req, res) {
   ImageProxy.proxyImage(req, res);
})

// Run the server
app.listen(port, function () {
    console.log('Twitter proxy running on ' + port + ' !')
})
<commit_msg>Changed to size 2 tabs for JS<commit_after>var Express = require('express');
var ImageProxy = require('./libs/image-proxy');
var Timeline = require('./libs/timeline');

var app = Express();
var port = 8585;

/**
* @brief Returns true if query is authorized
*/
function queryAuthorized (req) {
  return (req.params.pass == "1645328")
}

/**
 * @brief Twitter timeline
 * @return Twitter timeline content in JSON
 */
app.get('/:pass/tweets', function (req, res) {
  if ( !queryAuthorized(req))
  {
    res.end();
    return;
  }

  Timeline.getTimeline(function(error, timeline) {
    if (timeline == undefined) {
      res.send('');
    }

    res.json(timeline);
  });
})

/**
 * @brief Twitter image proxy
 * @return Twitter target image through nodeJS
 */
app.get('/tweetImage/*', function (req, res) {
   ImageProxy.proxyImage(req, res);
})

Timeline.assertEnvironmentSet();

// Run the server
app.listen(port, function () {
    console.log('Twitter proxy running on ' + port + ' !')
})
<|endoftext|>


<commit_before>var mappings = [
	{
		"id": "Logitech Gamepad F310",
		"userAgent": "Firefox",
		"buttons": [
			"a",
			"b",
			"x",
			"y",
			"left shoulder",
			"right shoulder",
			"back",
			"start",
			"home",
			"left stick",
			"right stick",
		],
		"axes": [
			{
				"name": "left stick x",
				"buttons": [
					"left stick left",
					"left stick right",
				]
			},
			{
				"name": "left stick y",
				"buttons": [
					"left stick up",
					"left stick down",
				]
			},
			{
				"name": "left trigger",
				"buttons": [
					null,
					"left trigger",
				]
			},
			{
				"name": "right stick x",
				"buttons": [
					"right stick left",
					"right stick right",
				]
			},
			{
				"name": "right stick y",
				"buttons": [
					"right stick up",
					"right stick down",
				]
			},
			{
				"name": "right trigger",
				"buttons": [
					null,
					"right trigger",
				]
			},
			{
				"name": "dpad x",
				"buttons": [
					"dpad left",
					"dpad right",
				]
			},
			{
				"name": "dpad y",
				"buttons": [
					"dpad up",
					"dpad down",
				]
			}
		]
	}
];

function getMapping(gamepadId, userAgent) {
	return mappings.filter(function(mapping) {
		return gamepadId.indexOf(mapping.id) !== -1 && userAgent.indexOf(mapping.userAgent) !== -1;
	})[0];
}

function transformButton(mapping, gp, button, i) {
	var name = mapping.buttons[i];
	gp.buttons[name] = button.pressed;
	return gp;
}

function transformAxis(mapping, threshold, gp, axis, i) {
	var ma = mapping.axes[i];
	var name = ma.name;
	gp.axes[name] = axis;
	if (ma.buttons) {
		if (ma.buttons[0] !== null) {
			gp.buttons[ma.buttons[0]] = axis < -threshold;
		}
		if (ma.buttons[1] !== null) {
			gp.buttons[ma.buttons[1]] = axis > threshold;
		}
	}
	return gp;
}

function transformGamepad(threshold, gamepad) {
	var gp = {
		id: gamepad.id,
		buttons: {},
		axes: {}
	};
	var mapping = getMapping(gamepad.id, navigator.userAgent);
	gp = gamepad.buttons.reduce(transformButton.bind(undefined, mapping), gp),
	gp = gamepad.axes.reduce(transformAxis.bind(undefined, mapping, threshold), gp);
	return gp;
}

function Gamepad() {
	this.threshold = 0.001;
	this.gamepads = [];
}
Gamepad.prototype.update = function() {
	this.gamepads = navigator.getGamepads().map(transformGamepad.bind(undefined, this.threshold));
	document.getElementById("content").innerHTML = JSON.stringify(this.gamepads, null, 2);
};
Gamepad.prototype.axis = function(gamepad, axis) {
	if (gamepad >= this.gamepads.length) {
		return 0;
	}
	return this.gamepads[gamepad].axes[axis];
};
Gamepad.prototype.count = function() {
	return this.gamepads.length;
}
Gamepad.prototype.isPressed = function(gamepad, button) {
	if (gamepad >= this.gamepads.length) {
		return false;
	}
	return this.gamepads[gamepad].buttons[button];
};

var g = new Gamepad();

function render() {
	g.update();
	window.requestAnimationFrame(render);
}
window.requestAnimationFrame(render);
<commit_msg>Use first mapping if none are found.<commit_after>var mappings = [
	{
		"id": "Logitech Gamepad F310",
		"userAgent": "Firefox",
		"buttons": [
			"a",
			"b",
			"x",
			"y",
			"left shoulder",
			"right shoulder",
			"back",
			"start",
			"home",
			"left stick",
			"right stick",
		],
		"axes": [
			{
				"name": "left stick x",
				"buttons": [
					"left stick left",
					"left stick right",
				]
			},
			{
				"name": "left stick y",
				"buttons": [
					"left stick up",
					"left stick down",
				]
			},
			{
				"name": "left trigger",
				"buttons": [
					null,
					"left trigger",
				]
			},
			{
				"name": "right stick x",
				"buttons": [
					"right stick left",
					"right stick right",
				]
			},
			{
				"name": "right stick y",
				"buttons": [
					"right stick up",
					"right stick down",
				]
			},
			{
				"name": "right trigger",
				"buttons": [
					null,
					"right trigger",
				]
			},
			{
				"name": "dpad x",
				"buttons": [
					"dpad left",
					"dpad right",
				]
			},
			{
				"name": "dpad y",
				"buttons": [
					"dpad up",
					"dpad down",
				]
			}
		]
	}
];

function getMapping(gamepadId, userAgent) {
	return mappings.filter(function(mapping) {
		return gamepadId.indexOf(mapping.id) !== -1 && userAgent.indexOf(mapping.userAgent) !== -1;
	})[0] || mappings[0];
}

function transformButton(mapping, gp, button, i) {
	var name = mapping.buttons[i];
	gp.buttons[name] = button.pressed;
	return gp;
}

function transformAxis(mapping, threshold, gp, axis, i) {
	var ma = mapping.axes[i];
	var name = ma.name;
	gp.axes[name] = axis;
	if (ma.buttons) {
		if (ma.buttons[0] !== null) {
			gp.buttons[ma.buttons[0]] = axis < -threshold;
		}
		if (ma.buttons[1] !== null) {
			gp.buttons[ma.buttons[1]] = axis > threshold;
		}
	}
	return gp;
}

function transformGamepad(threshold, gamepad) {
	var gp = {
		id: gamepad.id,
		buttons: {},
		axes: {}
	};
	var mapping = getMapping(gamepad.id, navigator.userAgent);
	gp = gamepad.buttons.reduce(transformButton.bind(undefined, mapping), gp),
	gp = gamepad.axes.reduce(transformAxis.bind(undefined, mapping, threshold), gp);
	return gp;
}

function Gamepad() {
	this.threshold = 0.001;
	this.gamepads = [];
}
Gamepad.prototype.update = function() {
	this.gamepads = navigator.getGamepads().map(transformGamepad.bind(undefined, this.threshold));
	document.getElementById("content").innerHTML = JSON.stringify(this.gamepads, null, 2);
};
Gamepad.prototype.axis = function(gamepad, axis) {
	if (gamepad >= this.gamepads.length) {
		return 0;
	}
	return this.gamepads[gamepad].axes[axis];
};
Gamepad.prototype.count = function() {
	return this.gamepads.length;
}
Gamepad.prototype.isPressed = function(gamepad, button) {
	if (gamepad >= this.gamepads.length) {
		return false;
	}
	return this.gamepads[gamepad].buttons[button];
};

var g = new Gamepad();

function render() {
	g.update();
	window.requestAnimationFrame(render);
}
window.requestAnimationFrame(render);
<|endoftext|>


<commit_before>
var bytes = require('bytes');
var getBody = require('raw-body');
var typeis = require('type-is');
var http = require('http');
var qs = require('qs');

var firstcharRegExp = /^\s*(.)/

exports = module.exports = bodyParser;
exports.json = json;
exports.urlencoded = urlencoded;

function bodyParser(options){
  var opts = {}

  options = options || {}

  // exclude type option
  for (var prop in options) {
    if ('type' !== prop) {
      opts[prop] = options[prop]
    }
  }

  var _urlencoded = urlencoded(opts)
  var _json = json(opts)

  return function bodyParser(req, res, next) {
    _json(req, res, function(err){
      if (err) return next(err);
      _urlencoded(req, res, next);
    });
  }
}

function json(options){
  options = options || {};

  var limit = typeof options.limit !== 'number'
    ? bytes(options.limit || '100kb')
    : options.limit;
  var reviver = options.reviver
  var strict = options.strict !== false;
  var type = options.type || 'json';
  var verify = options.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  function parse(str) {
    if (0 === str.length) {
      throw new Error('invalid json, empty body')
    }
    if (strict) {
      var first = firstchar(str)

      if (first !== '{' && first !== '[') {
        throw new Error('invalid json')
      }
    }

    return JSON.parse(str, reviver)
  }

  return function jsonParser(req, res, next) {
    if (req._body) return next();
    req.body = req.body || {} // TODO: move this after type check in next major

    if (!typeis(req, type)) return next();

    // read
    read(req, res, next, parse, {
      limit: limit,
      verify: verify
    })
  }
}

function urlencoded(options){
  options = options || {};

  var limit = typeof options.limit !== 'number'
    ? bytes(options.limit || '100kb')
    : options.limit;
  var type = options.type || 'urlencoded';
  var verify = options.verify || false;

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  function parse(str) {
    return str.length
      ? qs.parse(str)
      : {}
  }

  return function urlencodedParser(req, res, next) {
    if (req._body) return next();
    req.body = req.body || {} // TODO: move this after type check in next major

    if (!typeis(req, type)) return next();

    // read
    read(req, res, next, parse, {
      limit: limit,
      verify: verify
    })
  }
}

function firstchar(str) {
  if (!str) return ''
  var match = firstcharRegExp.exec(str)
  return match ? match[1] : ''
}

function read(req, res, next, parse, options) {
  var length = req.headers['content-length']

  // flag as parsed
  req._body = true

  options = options || {}
  options.length = length

  var encoding = options.encoding || 'utf-8'
  var verify = options.verify

  options.encoding = verify
    ? null
    : encoding

  // read body
  getBody(req, options, function (err, body) {
    if (err) return next(err)
    var str

    // verify
    if (verify) {
      try {
        verify(req, res, body, encoding)
      } catch (err) {
        if (!err.status) err.status = 403
        return next(err)
      }
    }

    // parse
    try {
      str = typeof body !== 'string'
        ? body.toString(encoding)
        : body
      req.body = parse(str)
    } catch (err){
      err.body = str
      err.status = 400
      return next(err)
    }

    next()
  })
}
<commit_msg>remove todo note<commit_after>
var bytes = require('bytes');
var getBody = require('raw-body');
var typeis = require('type-is');
var http = require('http');
var qs = require('qs');

var firstcharRegExp = /^\s*(.)/

exports = module.exports = bodyParser;
exports.json = json;
exports.urlencoded = urlencoded;

function bodyParser(options){
  var opts = {}

  options = options || {}

  // exclude type option
  for (var prop in options) {
    if ('type' !== prop) {
      opts[prop] = options[prop]
    }
  }

  var _urlencoded = urlencoded(opts)
  var _json = json(opts)

  return function bodyParser(req, res, next) {
    _json(req, res, function(err){
      if (err) return next(err);
      _urlencoded(req, res, next);
    });
  }
}

function json(options){
  options = options || {};

  var limit = typeof options.limit !== 'number'
    ? bytes(options.limit || '100kb')
    : options.limit;
  var reviver = options.reviver
  var strict = options.strict !== false;
  var type = options.type || 'json';
  var verify = options.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  function parse(str) {
    if (0 === str.length) {
      throw new Error('invalid json, empty body')
    }
    if (strict) {
      var first = firstchar(str)

      if (first !== '{' && first !== '[') {
        throw new Error('invalid json')
      }
    }

    return JSON.parse(str, reviver)
  }

  return function jsonParser(req, res, next) {
    if (req._body) return next();
    req.body = req.body || {}

    if (!typeis(req, type)) return next();

    // read
    read(req, res, next, parse, {
      limit: limit,
      verify: verify
    })
  }
}

function urlencoded(options){
  options = options || {};

  var limit = typeof options.limit !== 'number'
    ? bytes(options.limit || '100kb')
    : options.limit;
  var type = options.type || 'urlencoded';
  var verify = options.verify || false;

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  function parse(str) {
    return str.length
      ? qs.parse(str)
      : {}
  }

  return function urlencodedParser(req, res, next) {
    if (req._body) return next();
    req.body = req.body || {}

    if (!typeis(req, type)) return next();

    // read
    read(req, res, next, parse, {
      limit: limit,
      verify: verify
    })
  }
}

function firstchar(str) {
  if (!str) return ''
  var match = firstcharRegExp.exec(str)
  return match ? match[1] : ''
}

function read(req, res, next, parse, options) {
  var length = req.headers['content-length']

  // flag as parsed
  req._body = true

  options = options || {}
  options.length = length

  var encoding = options.encoding || 'utf-8'
  var verify = options.verify

  options.encoding = verify
    ? null
    : encoding

  // read body
  getBody(req, options, function (err, body) {
    if (err) return next(err)
    var str

    // verify
    if (verify) {
      try {
        verify(req, res, body, encoding)
      } catch (err) {
        if (!err.status) err.status = 403
        return next(err)
      }
    }

    // parse
    try {
      str = typeof body !== 'string'
        ? body.toString(encoding)
        : body
      req.body = parse(str)
    } catch (err){
      err.body = str
      err.status = 400
      return next(err)
    }

    next()
  })
}
<|endoftext|>


<commit_before>/*jslint indent: 2*/
/*globals require: true*/

var getLines = function (file, cb, async) {
  var fs = require('fs'), splitLines, data;
  splitLines = function (data) {
    data = data.toString();
    var lines;
    if (data.indexOf('\r\n') > -1) {
      lines = data.split('\r\n');
    } else if (data.indexOf('\n') > -1) {
      lines = data.split('\n');
    } else if (data.indexOf('\r') > -1) {
      lines = data.split('\r');
    } else { // mostly it's only one line
      lines = [data];
    }
    return lines.filter(function (line) {
      return line !== '';
    });
  };
  if (async) {
    fs.readFile(file, function (err, data) {
      if (err) {
        throw err;
      }
      cb(splitLines(data));
    });
  } else {
    data = fs.readFileSync(file);
    return splitLines(data);
  }
};

/**
 * If a string is inside quotes, the quotes will be removed
 * Very simple and not foolproof yet. It doesn't care about
 * escaped/not escaped strings. So you can have thing like this;
 * "lorem ipsum" dolor sit"
 * and you will receive:
 * lorem ipsum" dolor sit
 *
 * FIXME
 * is it a bug?
 */
var fixQuoted = function (str) {
  if (
    (str[0] === '"' && str[str.length - 1] === '"') ||
    (str[0] === "'" && str[str.length - 1] === "'")
  ) {

    return str.substr(1, str.length - 2);
  }

  return str;

};

var inheritDefault = function (block, _default) {
  var _inheritDefault, _key;
  _default = typeof _default === 'object' ? _default : {};

  if (typeof block === 'object') {
    for (_key in _default) {
      if (!(_key in block)) {
        block[_key] = _default[_key];
      }
    }
  }

  return block;
};

/**
 * Parses a .ini file and convert's it's content to a JS object
 * Parser regexps are from the Config::Simple Perl module
 * @class IniReader
 * @constructor
 */
var IniReader = function (cfg) {
  // backward compatibility
  // in first versions the first argument was the file name and the second was
  // the async flag
  if (typeof cfg === 'string') {
    cfg = {
      file: cfg
    };
    if (typeof arguments[1] === 'boolean') {
      cfg.async = arguments[1];
    }
  }
  cfg = cfg || {};
  this.async = !!cfg.async;
  this.file = cfg.file || null;
  this.inheritDefault = !!cfg.inheritDefault;
};
require('util').inherits(IniReader, require('events').EventEmitter);
/**
 * Regexp to get the group names
 */
IniReader.prototype.groupRex = /^\s*\[\s*([^\]]+)\s*\]$/;

/**
 * Regexp to get key/value pairs
 */
IniReader.prototype.keyValueRex = /^\s*([^=]*\w)\s*=\s*(.*)\s*$/;

/**
 * @method load
 * @param String file
 * Loads a ini file
 **/
IniReader.prototype.load = IniReader.prototype.init = function (file) {
  if (typeof file === 'string') {
    this.file = file;
  }
  if (!this.file) {
    throw new Error('No file name given');
  }
  if (this.async) {
    getLines(this.file, function (lines) {
      this.lines = lines;
      this.values = this.parseFile();
      this.emit('fileParse');
    }.bind(this), true);
  } else {
    this.lines = getLines(this.file);
    this.values = this.parseFile();
    this.emit('fileParse');
  }
};

/**
  * Tries to find a group name in a line
  * @method parseSectionHead
  * @type {String|False}
  * @returns the group name if found or false
  */
IniReader.prototype.parseSectionHead = function (line) {
  var groupMatch = line.match(this.groupRex);
  return groupMatch ? groupMatch[1] : false;
};

/**
  * Tries to find a key/value pair in a line
  * @method keyValueMatch
  * @type {Object|False}
  * @returns the key value pair in an object ({key: 'key', value;'value'}) if found or false
  */
IniReader.prototype.keyValueMatch = function (line) {
  var keyValMatch = line.match(this.keyValueRex);
  return keyValMatch ? {key: keyValMatch[1], value: keyValMatch[2]} : false;
};

/**
  * Parses an init file, and extracts blocks with keys and values
  * @method parseFile
  * @returns the conf tree
  * @type Object
  */
IniReader.prototype.parseFile = function () {

  var output, lines, groupName, keyVal, line, currentSection, lineNumber;

  // regular expressions to clear, validate and get the values
  var skipLineRex = /^\s*(\n|\#|;)/,
    chompRex = /(?:\n|\r)$/,
    nonWhitespaceRex = /\S/;

  output = {};
  lines = this.lines;

  lineNumber = 0;

  while (line = lines.shift()) {

    lineNumber += 1;
    // skip comments and empty lines
    if (skipLineRex.test(line) || !nonWhitespaceRex.test(line)) {
      continue;
    }

    line = line.replace(chompRex, '');
    line = line.trim();

    // block name
    groupName = this.parseSectionHead(line);
    if (groupName) {
      currentSection = groupName;
      if (!output[currentSection]) {
        output[currentSection] = {};
      }
      continue;
    }

    // key/value pairs
    keyVal = this.keyValueMatch(line);
    if (keyVal) {
      if (currentSection) {
        output[currentSection][keyVal.key] = fixQuoted(keyVal.value);
        continue;
      }
    }

    // if we came this far, the syntax couldn't be validated
    throw new Error("syntax error in line " + lineNumber);

  }

  return output;
};
/**
  * @method getBlock
  * @returns A block of the conf tree
  * @type Object
  * @deprecated
  */
IniReader.prototype.getBlock = function (block) {
  return this.param(block);
};
/**
  * @method getValue
  * @returns the value of the key
  * @param String block The name of the block where the key should be defined
  * @param String key The name of the key which value should be returned
  * @deprecated
  */
IniReader.prototype.getValue = function (block, key) {
  var param = block;
  if (typeof key !== 'undefined') {
    param += '.' + key;
  }
  return this.getParam(param);
};
/**
  * @method getParam
  * @returns the value of the key
  * @param String param The name of the block where the key should be defined
  */
IniReader.prototype.getParam = function (param) {
  var output = this.values,
  block, key, _block;

  if (this.inheritDefault && output.hasOwnProperty('DEFAULT')) {
    for (_block in output) {
      if (output.hasOwnProperty(_block)) {
        output[_block] = inheritDefault(output[_block], output.DEFAULT);
      }
    }
  }

  if (param) {
    param = param.split('.');
    block = param[0];
    key = param[1];

    if (block) {
      output = output[block];

      if (key) {
        output = output[key];
      }
    }
  }

  return output;
};
/**
 * @method setParam
 */
IniReader.prototype.setParam = function (prop, value) {
  if (typeof this.values !== 'object') {
    this.values = {};
  }
  var propKeys = prop.split('.'),
    propKeysLen = propKeys.length,
    ref = this.values;
  if (propKeysLen > 0) {
    propKeys.forEach(function (key, index) {
      if (!ref[key]) {
        ref[key] = {};
      }
      if (index < propKeysLen - 1) {
        ref = ref[key];
      } else {
        ref[key] = value;
      }
    }, this);
  }
};
/**
 * @method param
 * **/
IniReader.prototype.param = function (prop, value) {
  if (typeof value === 'undefined') {
    return this.getParam(prop);
  } else {
    return this.setParam(prop, value);
  }
};

IniReader.prototype.getLe = function (le) {
  return typeof le === 'string' && (le === '\n' || le === '\r\n' || le === '\r') ? le : '\n';
};

IniReader.prototype.serialize = function (le) {
  var output = '',
    group, ws = /\s+/;

  le = this.getLe(le);

  Object.keys(this.values).forEach(function (group) {
    output += le + '[' + group + ']' + le;

    Object.keys(this.values[group]).forEach(function (key) {
      var value = this.values[group][key];
      if (ws.test(value)) {
        if (value.indexOf('"') > -1) {
          value = "'" + value + "'";
        } else {
          value = '"' + value + '"';
        }
      }
      output += key + '=' + value + le;
    }, this);
  }, this);
  return output;
};

IniReader.prototype.write = function (file, le) {
  if (!file) {
    file = this.file;
  }

  le = this.getLe(le);

  var now = new Date(),
    output = '; IniReader' + le + '; ' + now.getFullYear() + '-' +
      (now.getMonth() + 1) + '-' + now.getDate() + le,
    fs = require('fs'),
    group, item, value, ws = /\s+/;

  output += this.serialize(le);

  if (this.async) {
    fs.writeFile(file, output, function (err) {
      if (err) {
        throw err;
      }
      this.emit('fileWritten', file);
    }.bind(this));
  } else {
    fs.writeFileSync(file, output);
    this.emit('fileWritten', file);
  }
};

exports.IniReader = IniReader;
<commit_msg>interpolation of %([BLOCK.]KEY)<commit_after>/*jslint indent: 2*/
/*globals require: true*/

var getLines = function (file, cb, async) {
  var fs = require('fs'), splitLines, data;
  splitLines = function (data) {
    data = data.toString();
    var lines;
    if (data.indexOf('\r\n') > -1) {
      lines = data.split('\r\n');
    } else if (data.indexOf('\n') > -1) {
      lines = data.split('\n');
    } else if (data.indexOf('\r') > -1) {
      lines = data.split('\r');
    } else { // mostly it's only one line
      lines = [data];
    }
    return lines.filter(function (line) {
      return line !== '';
    });
  };
  if (async) {
    fs.readFile(file, function (err, data) {
      if (err) {
        throw err;
      }
      cb(splitLines(data));
    });
  } else {
    data = fs.readFileSync(file);
    return splitLines(data);
  }
};

/**
 * If a string is inside quotes, the quotes will be removed
 * Very simple and not foolproof yet. It doesn't care about
 * escaped/not escaped strings. So you can have thing like this;
 * "lorem ipsum" dolor sit"
 * and you will receive:
 * lorem ipsum" dolor sit
 *
 * FIXME
 * is it a bug?
 */
var fixQuoted = function (str) {
  if (
    (str[0] === '"' && str[str.length - 1] === '"') ||
    (str[0] === "'" && str[str.length - 1] === "'")
  ) {

    return str.substr(1, str.length - 2);
  }

  return str;

};

var inheritDefault = function (block, _default) {
  var _inheritDefault, _key;
  _default = typeof _default === 'object' ? _default : {};

  if (typeof block === 'object') {
    for (_key in _default) {
      if (!(_key in block)) {
        block[_key] = _default[_key];
      }
    }
  }

  return block;
};

/**
 * return a deep copy of the object o
 */
var deepCopy = function (o, c) {
  var out = c || {}, key;
  for (key in o) {
    if (typeof o[key] === 'object') {
      out[key] = (o[key].constructor === Array ? [] : {});
      deepCopy(o[key], out[key]);
    } else {
      out[key] = o[key];
    }
  };
  return out;
};

/**
 * Parses a .ini file and convert's it's content to a JS object
 * Parser regexps are from the Config::Simple Perl module
 * @class IniReader
 * @constructor
 */
var IniReader = function (cfg) {
  // backward compatibility
  // in first versions the first argument was the file name and the second was
  // the async flag
  if (typeof cfg === 'string') {
    cfg = {
      file: cfg
    };
    if (typeof arguments[1] === 'boolean') {
      cfg.async = arguments[1];
    }
  }
  cfg = cfg || {};
  this.async = !!cfg.async;
  this.file = cfg.file || null;
  this.inheritDefault = !!cfg.inheritDefault;
};
require('util').inherits(IniReader, require('events').EventEmitter);
/**
 * Regexp to get the group names
 */
IniReader.prototype.groupRex = /^\s*\[\s*([^\]]+)\s*\]$/;

/**
 * Regexp to get key/value pairs
 */
IniReader.prototype.keyValueRex = /^\s*([^=]*\w)\s*=\s*(.*)\s*$/;

/**
 * @method load
 * @param String file
 * Loads a ini file
 **/
IniReader.prototype.load = IniReader.prototype.init = function (file) {
  if (typeof file === 'string') {
    this.file = file;
  }
  if (!this.file) {
    throw new Error('No file name given');
  }
  if (this.async) {
    getLines(this.file, function (lines) {
      this.lines = lines;
      this.values = this.parseFile();
      this.emit('fileParse');
    }.bind(this), true);
  } else {
    this.lines = getLines(this.file);
    this.values = this.parseFile();
    this.emit('fileParse');
  }
};

/**
  * Tries to find a group name in a line
  * @method parseSectionHead
  * @type {String|False}
  * @returns the group name if found or false
  */
IniReader.prototype.parseSectionHead = function (line) {
  var groupMatch = line.match(this.groupRex);
  return groupMatch ? groupMatch[1] : false;
};

/**
  * Tries to find a key/value pair in a line
  * @method keyValueMatch
  * @type {Object|False}
  * @returns the key value pair in an object ({key: 'key', value;'value'}) if found or false
  */
IniReader.prototype.keyValueMatch = function (line) {
  var keyValMatch = line.match(this.keyValueRex);
  return keyValMatch ? {key: keyValMatch[1], value: keyValMatch[2]} : false;
};

/**
  * Parses an init file, and extracts blocks with keys and values
  * @method parseFile
  * @returns the conf tree
  * @type Object
  */
IniReader.prototype.parseFile = function () {

  var output, lines, groupName, keyVal, line, currentSection, lineNumber;

  // regular expressions to clear, validate and get the values
  var skipLineRex = /^\s*(\n|\#|;)/,
    chompRex = /(?:\n|\r)$/,
    nonWhitespaceRex = /\S/;

  output = {};
  lines = this.lines;

  lineNumber = 0;

  while (line = lines.shift()) {

    lineNumber += 1;
    // skip comments and empty lines
    if (skipLineRex.test(line) || !nonWhitespaceRex.test(line)) {
      continue;
    }

    line = line.replace(chompRex, '');
    line = line.trim();

    // block name
    groupName = this.parseSectionHead(line);
    if (groupName) {
      currentSection = groupName;
      if (!output[currentSection]) {
        output[currentSection] = {};
      }
      continue;
    }

    // key/value pairs
    keyVal = this.keyValueMatch(line);
    if (keyVal) {
      if (currentSection) {
        output[currentSection][keyVal.key] = fixQuoted(keyVal.value);
        continue;
      }
    }

    // if we came this far, the syntax couldn't be validated
    throw new Error("syntax error in line " + lineNumber);

  }

  return output;
};
/**
  * @method getBlock
  * @returns A block of the conf tree
  * @type Object
  * @deprecated
  */
IniReader.prototype.getBlock = function (block) {
  return this.param(block);
};
/**
  * @method getValue
  * @returns the value of the key
  * @param String block The name of the block where the key should be defined
  * @param String key The name of the key which value should be returned
  * @deprecated
  */
IniReader.prototype.getValue = function (block, key) {
  var param = block;
  if (typeof key !== 'undefined') {
    param += '.' + key;
  }
  return this.getParam(param);
};

IniReader.prototype.setDefaultValue = function (currentValue, block, key) {
  var defaultValues = this.values.DEFAULT,
      output = currentValue, _block;
  if (typeof defaultValues !== 'undefined') {
    if (block) {
      if (key) {
        output = typeof currentValue === 'undefined' ? defaultValues[key] : currentValue;
      } else {
        output = inheritDefault(currentValue, defaultValues);
      }
    } else {
      for (_block in currentValue) {
        if (_block !== 'DEFAULT' && currentValue.hasOwnProperty(_block)) {
          output[_block] = inheritDefault(currentValue[_block], defaultValues);
        }
      }
    }
  }
  return output;
};

/**
  * @method getParam
  * @returns the value of the key
  * @param String param The name of the block where the key should be defined
  */
IniReader.prototype.getParam = function (param) {
  var output = this.values,
  block, key, _block;

  if (param) {
    param = param.split('.');
    block = param[0];
    key = param[1];

    if (block) {
      output = output[block];

      if (key) {
        output = output[key];
      }
    }
  }

  if (this.inheritDefault && this.values.hasOwnProperty('DEFAULT')) {
    output = this.setDefaultValue(output, block, key);
  }

  return output;
};
/**
 * @method setParam
 */
IniReader.prototype.setParam = function (prop, value) {
  if (typeof this.values !== 'object') {
    this.values = {};
  }
  var propKeys = prop.split('.'),
    propKeysLen = propKeys.length,
    ref = this.values;
  if (propKeysLen > 0) {
    propKeys.forEach(function (key, index) {
      if (!ref[key]) {
        ref[key] = {};
      }
      if (index < propKeysLen - 1) {
        ref = ref[key];
      } else {
        ref[key] = value;
      }
    }, this);
  }
};
/**
 * @method param
 * **/
IniReader.prototype.param = function (prop, value) {
  if (typeof value === 'undefined') {
    return this.getParam(prop);
  } else {
    return this.setParam(prop, value);
  }
};

IniReader.prototype.getLe = function (le) {
  return typeof le === 'string' && (le === '\n' || le === '\r\n' || le === '\r') ? le : '\n';
};

IniReader.prototype.serialize = function (le) {
  var output = '',
    group, ws = /\s+/;

  le = this.getLe(le);

  Object.keys(this.values).forEach(function (group) {
    output += le + '[' + group + ']' + le;

    Object.keys(this.values[group]).forEach(function (key) {
      var value = this.values[group][key];
      if (ws.test(value)) {
        if (value.indexOf('"') > -1) {
          value = "'" + value + "'";
        } else {
          value = '"' + value + '"';
        }
      }
      output += key + '=' + value + le;
    }, this);
  }, this);
  return output;
};

IniReader.prototype.write = function (file, le) {
  if (!file) {
    file = this.file;
  }

  le = this.getLe(le);

  var now = new Date(),
    output = '; IniReader' + le + '; ' + now.getFullYear() + '-' +
      (now.getMonth() + 1) + '-' + now.getDate() + le,
    fs = require('fs'),
    group, item, value, ws = /\s+/;

  output += this.serialize(le);

  if (this.async) {
    fs.writeFile(file, output, function (err) {
      if (err) {
        throw err;
      }
      this.emit('fileWritten', file);
    }.bind(this));
  } else {
    fs.writeFileSync(file, output);
    this.emit('fileWritten', file);
  }
};

IniReader.prototype.interpolate = function (param) {
  var output = this.getParam(param),
      self = this,
      block, key, refParams, refParam, references,
      _block, _key;

  if (typeof output === 'object') {
    output = deepCopy(output);
  }
  if (param) {
    param = param.split('.');
    block = param[0];
    key = param[1];
  }

  if (typeof key === 'undefined' || !param) {
    for (_block in output) {
      if (output.hasOwnProperty(_block)) {
        for (_key in output[block]) {
          if (output[_block].hasOwnProperty(_key)) {
            output[_block][_key] = this.interpolate(_block + '.' + _key);
          }
        }
      }
    }
  } else {
    if (typeof output === 'string') {
      references = output.match(/%\(.*?\)/g);
      references && references.forEach(
        function(reference) {
          var refKey = reference.replace(/%\((.*?)\)/, '$1');
          refParams = refKey.split('.');
          if (refParams.length < 2) { // interpolation in current block
            refParam = block + '.' + refParams[0];
          } else {
            refParam = refKey;
          }
          output = output.replace(reference, self.interpolate(refParam));
        }
      );
    }
  }

  return output;
};

exports.IniReader = IniReader;
<|endoftext|>


<commit_before>var stream = require('stream')
var util = require('util')
var gen = require('generate-object-property')

var quote = new Buffer('"')[0]
var comma = new Buffer(',')[0]

var Parser = function(opts) {
	if (!opts) opts = {}
	if (Array.isArray(opts)) opts = {headers:opts}

	stream.Transform.call(this, {objectMode:true})

	this.seperator = opts.seperator ? new Buffer(opts.seperator)[0] : comma
	this.headers = opts.headers || null

	this._raw = !!opts.raw
	this._prev = null
	this._prevEnd = 0
	this._nlbyte = 10
	this._first = true
	this._quoting = false
	this._empty = this._raw ? new Buffer(0) : ''
	this._Row = null

	if (this.headers) {
		this._first = false
		this._compile(this.headers)
	}
}

util.inherits(Parser, stream.Transform)

Parser.prototype._write = function(data, enc, cb) {
	var start = 0
	var buf = data

	if (this._prev) {
		start = this._prev.length
		buf = Buffer.concat([this._prev, data])
		this._prev = null
	}

	for (var i = start i < buf.length i++) {
		if (buf[i] === quote) this._quoting = !this._quoting

		if (!this._quoting && buf[i] === this._nlbyte) {
			this._online(buf, this._prevEnd, i+1)
			this._prevEnd = i+1
		}
	}

	if (this._prevEnd === buf.length) {
		this._prevEnd = 0
		return cb()
	}

	if (buf.length - this._prevEnd < data.length) {
		this._prev = data
		this._prevEnd -= (buf.length - data.length)
		return cb()
	}

	this._prev = buf
	cb()
}

Parser.prototype._flush = function(cb) {
	if (this._quoting || !this._prev) return cb()
	this._online(this._prev, this._prevEnd, this._prev.length+1) // plus since online -1s
	cb()
}

Parser.prototype._online = function(buf, start, end) {
	end -- // trim newline
	if (buf.length && buf[end-1] === 13) end--

	var comma = this.seperator
	var cells = []
	var inQuotes = false
	var offset = start

	for (var i = start i < end i++) {
		if (buf[i] === quote) { // "
			if (i < end-1 && buf[i + 1] === quote) { // ""
				i++
			} else {
				inQuotes = !inQuotes
			}
			continue
		}
		if (buf[i] === comma && !inQuotes) {
			cells.push(this._oncell(buf, offset, i))
			offset = i + 1
		}
	}
	if (offset < end) cells.push(this._oncell(buf, offset, end))
	if (buf[end-1] === comma) cells.push(this._empty)

	if (this._first) {
		this._first = false
		this.headers = cells
		this._compile(cells)
		this.emit('headers', this.headers)
		return
	}

	this._emit(this._Row, cells)
}

Parser.prototype._compile = function() {
	if (this._Row) return

	var props = this.headers.map(function(cell, i) {
		return '\t'+gen('this', cell)+' = cells['+i+']'
	}).join('\n')+'\n'

	this._Row = new Function('return function Row(cells) {\n'+props+'}')()
}

Parser.prototype._emit = function(Row, cells) {
	this.push(new Row(cells))
}

Parser.prototype._oncell = function(buf, start, end) {
	if (buf[start] === quote && buf[end - 1] === quote) {
		start++
		end--
	}

	for (var i = start, y = start i < end i++) {
		if (buf[i] === quote && buf[i + 1] === quote) i++
		if (y !== i) buf[y] = buf[i]
		y++
	}

	return this._onvalue(buf, start, y)
}

Parser.prototype._onvalue = function(buf, start, end) {
	if (this._raw) return buf.slice(start, end)
	return buf.toString('utf-8', start, end)
}

module.exports = function(opts) {
	return new Parser(opts)
}
<commit_msg>trying something new<commit_after>var stream = require('stream')
var util = require('util')
var gen = require('generate-object-property')

var quote = new Buffer('"')[0]
var comma = new Buffer(',')[0]

var Parser = function(opts) {
  if (!opts) opts = {}
  if (Array.isArray(opts)) opts = {headers:opts}

  stream.Transform.call(this, {objectMode:true})

  this.seperator = opts.seperator ? new Buffer(opts.seperator)[0] : comma
  this.headers = opts.headers || null

  this._raw = !!opts.raw
  this._prev = null
  this._prevEnd = 0
  this._nlbyte = 10
  this._first = true
  this._quoting = false
  this._empty = this._raw ? new Buffer(0) : ''
  this._Row = null

  if (this.headers) {
    this._first = false
    this._compile(this.headers)
  }
}

util.inherits(Parser, stream.Transform)

Parser.prototype._write = function(data, enc, cb) {
  var start = 0
  var buf = data

  if (this._prev) {
    start = this._prev.length
    buf = Buffer.concat([this._prev, data])
    this._prev = null
  }

  for (var i = start; i < buf.length; i++) {
    if (buf[i] === quote) this._quoting = !this._quoting

    if (!this._quoting && buf[i] === this._nlbyte) {
      this._online(buf, this._prevEnd, i+1)
      this._prevEnd = i+1
    }
  }

  if (this._prevEnd === buf.length) {
    this._prevEnd = 0
    return cb()
  }

  if (buf.length - this._prevEnd < data.length) {
    this._prev = data
    this._prevEnd -= (buf.length - data.length)
    return cb()
  }

  this._prev = buf
  cb()
}

Parser.prototype._flush = function(cb) {
  if (this._quoting || !this._prev) return cb()
  this._online(this._prev, this._prevEnd, this._prev.length+1) // plus since online -1s
  cb()
}

Parser.prototype._online = function(buf, start, end) {
  end -- // trim newline
  if (buf.length && buf[end-1] === 13) end--

  var comma = this.seperator
  var cells = []
  var inQuotes = false
  var offset = start

  for (var i = start; i < end; i++) {
    if (buf[i] === quote) { // "
      if (i < end-1 && buf[i + 1] === quote) { // ""
        i++
      } else {
        inQuotes = !inQuotes
      }
      continue
    }
    if (buf[i] === comma && !inQuotes) {
      cells.push(this._oncell(buf, offset, i))
      offset = i + 1
    }
  }

  if (offset < end) cells.push(this._oncell(buf, offset, end))
  if (buf[end-1] === comma) cells.push(this._empty)

  if (this._first) {
    this._first = false
    this.headers = cells
    this._compile(cells)
    this.emit('headers', this.headers)
    return
  }

  this._emit(this._Row, cells)
}

Parser.prototype._compile = function() {
  if (this._Row) return

  var props = this.headers.map(function(cell, i) {
    return '\t'+gen('this', cell)+' = cells['+i+']'
  }).join('\n')+'\n'

  this._Row = new Function('return function Row(cells) {\n'+props+'}')()
}

Parser.prototype._emit = function(Row, cells) {
  this.push(new Row(cells))
}

Parser.prototype._oncell = function(buf, start, end) {
  if (buf[start] === quote && buf[end - 1] === quote) {
    start++
    end--
  }

  for (var i = start, y = start; i < end; i++) {
    if (buf[i] === quote && buf[i + 1] === quote) i++
    if (y !== i) buf[y] = buf[i]
    y++
  }

  return this._onvalue(buf, start, y)
}

Parser.prototype._onvalue = function(buf, start, end) {
  if (this._raw) return buf.slice(start, end)
  return buf.toString('utf-8', start, end)
}

module.exports = function(opts) {
  return new Parser(opts)
}<|endoftext|>


<commit_before>/**

 Copyright 2015 Covistra Technologies Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

"use strict";
var P = require('bluebird');

exports.register = function (server, options, next) {

    server.dependency(['covistra-socket'], function(plugin, done) {
        plugin.log(['plugin', 'info'], "Registering the messaging plugin");

        var Router = server.plugins['covistra-system'].Router;
        var config = server.plugins['hapi-config'].CurrentConfiguration;
        var systemLog = server.plugins['system'].systemLog;

        // Expose our services
        plugin.expose('channelManager', require('./lib/channel-manager')(config, server, systemLog.child({service:'channel-manager'})));
        plugin.expose('workerService', require('./lib/worker-service')(config, server, systemLog.child({service:'worker-service'})));

        // Register routes
        Router.routes(plugin, __dirname, "./routes");

        done();
    });

    next();
};

exports.register.attributes = {
    pkg: require(__dirname + '/package.json')
};
<commit_msg>Add missing reference to covistra system<commit_after>/**

 Copyright 2015 Covistra Technologies Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

"use strict";
var P = require('bluebird');

exports.register = function (server, options, next) {

    server.dependency(['covistra-socket'], function(plugin, done) {
        plugin.log(['plugin', 'info'], "Registering the messaging plugin");

        var Router = server.plugins['covistra-system'].Router;
        var config = server.plugins['hapi-config'].CurrentConfiguration;
        var systemLog = server.plugins['covistra-system'].systemLog;

        // Expose our services
        plugin.expose('channelManager', require('./lib/channel-manager')(config, server, systemLog.child({service:'channel-manager'})));
        plugin.expose('workerService', require('./lib/worker-service')(config, server, systemLog.child({service:'worker-service'})));

        // Register routes
        Router.routes(plugin, __dirname, "./routes");

        done();
    });

    next();
};

exports.register.attributes = {
    pkg: require(__dirname + '/package.json')
};
<|endoftext|>