<commit_before>
var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    yeoman = require('../../../../');

module.exports = AppGenerator;

// this example defines a prompt-app generator for demonstration purpose.
//
// So we need to hook other generators with the appropriate context (stylesheet-engine mainly)

function AppGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.test_framework = options['test-framework'] || 'mocha';

  // cleanup the name property from trailing /, typical usage of directories.
  // update the args object, it's used to initialize js-framework hooks
  if(this.name) this.args[0] = this.args[0].replace(/\/$/, '');

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });
}

util.inherits(AppGenerator, yeoman.generators.NamedBase);

AppGenerator.prototype.askFor = function askFor (argument) {
  var cb = this.async(),
    self = this;

  // a bit verbose prompt configuration, maybe we can improve that
  // demonstration purpose. Also, probably better to have this in other generator, whose responsability is to ask
  // and fetch all realated bootstrap stuff, that we hook from this generator.
  var prompts = [{
    name: 'compassBootstrap',
    message: 'Would you like to include Twitter Bootstrap for Compass?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap files will be placed into the styles directory.'
  },{
    name: 'bootstrap',
    message: 'Would you like to include the Twitter Bootstrap plugins?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap plugins will be placed into the JavaScript vendor directory.'
  },
  {
    name: 'includeRequireJS',
    message: 'Would you like to include RequireJS (for AMD support)?',
    default: 'Y/n',
    warning: 'Yes: RequireJS will be placed into the JavaScript vendor directory.'
  },
  {
    name: 'includeRequireHM',
    message: 'Would you like to support writing ECMAScript 6 modules?',
    default: 'Y/n',
    warning: 'Yes: RequireHM will be placed into the JavaScript vendor directory.'
  }];

  this.prompt(prompts, function(e, props) {
    if(e) { return self.emit('error', e); }

    // manually deal with the response, get back and store the results.
    // We change a bit this way of doing to automatically do this in the self.prompt() method.
    self.bootstrap = (/y/i).test(props.bootstrap);
    self.compassBootstrap = (/y/i).test(props.compassBootstrap);
    self.includeRequireJS = (/y/i).test(props.includeRequireJS);
    self.includeRequireHM = (/y/i).test(props.includeRequireHM);

    // we're done, go through next step
    cb();
  });
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  // this.write('foo.js', '');
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.favicon = function favicon(){
  this.copy('favicon.ico', 'app/favicon.ico');
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet(){
  if ( !this.compassBootstrap ) {
    this.write('app/styles/main.css', "/* Will be compiled down to a single stylesheet with your sass files */");
  }
};

AppGenerator.prototype.fetchH5bp = function fetchH5bp() {
  var cb = this.async();

  // Using sha since the lastest tag is so old
  this.remote('h5bp', 'html5-boilerplate', '456211dc54c7a0328485d73cf25443d210d8e1d8', function(err, remote) {
    if(err) { return cb(err); }

    remote.copy( '.htaccess', 'app/.htaccess' );
    remote.copy( '404.html', 'app/404.html' );
    remote.copy( 'robots.txt', 'app/robots.txt' );
    remote.copy( 'js/vendor/jquery-1.8.0.min.js', 'app/scripts/vendor/jquery.min.js' );
    remote.copy( 'js/vendor/modernizr-2.6.1.min.js', 'app/scripts/vendor/modernizr.min.js' );

    this.indexFile = this.readFileAsString(path.join(remote.cachePath, 'index.html'));

    cb();
  }.bind(this));
};

AppGenerator.prototype.fetchBootstrap = function fetchBootstrap() {
  // prevent the bootstrap fetch is user said NO
  if(!this.bootstrap) { return; }

  var cb = this.async();

  // third optional argument is the branch / sha1. Defaults to master when ommitted.
  this.remote('twitter', 'bootstrap', 'v2.1.0', function(err, remote, files) {
    if(err) { return cb(err); }

    'affix alert button carousel collapse dropdown modal popover scrollspy tab tooltip transition typeahead'.split(' ')
    .forEach(function( el ) {
      var filename = 'bootstrap-' + el + '.js';
      remote.copy( 'js/' + filename, 'app/scripts/vendor/bootstrap/' + filename );
    });

    cb();
  });
};

// Duplicated from the SASS generator, waiting a solution for #138
AppGenerator.prototype.compassBootstrapFiles = function compassBootstrapFiles() {
  if ( this.compassBootstrap ) {
    var cb = this.async();

    this.write('app/styles/main.scss', '@import "compass_twitter_bootstrap";');

    this.remote('kristianmandrup', 'compass-twitter-bootstrap', '19626592c8a2eafa8f52ee0344ef1ac30f74502f', function(err, remote) {
      if(err) { return cb(err); }

      remote.directory('stylesheets', 'app/styles');

      cb();
    });
  } else {
    this.log.writeln('Writing compiled Bootstrap');
    this.copy( 'bootstrap.css', 'app/styles/bootstrap.css' );
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {

  var $;

  // Resolve path to index.html
  var indexOut = path.resolve('app/index.html');

  // Read in as string for further update
  var indexData = this.indexFile;

  // Prepare default content text
  var defaults = ['HTML5 Boilerplate','Twitter Bootstrap'];
  var contentText = [
    '
',
    '
',
    '
Wotcha!
',
    '
You now have
',
    '
'
  ];

  // Strip sections of H5BP we're going to overwrite
  indexData = this.removeScript(indexData, 'plugins.js');
  indexData = this.removeScript(indexData, 'main.js');
  indexData = this.removeStyle(indexData, 'normalize.css');

  indexData = indexData.replace(/js\/vendor\/jquery[^"]+/g, 'scripts/vendor/jquery.min.js');

  $ = require('cheerio').load( indexData );
  $('link[href="css/main.css"]').attr('href', 'styles/main.css');
  $('script[src^="js/vendor/modernizr"]').attr('src', 'scripts/vendor/modernizr.min.js');
  indexData = $.html();

  // Asked for Twitter bootstrap plugins?
  if(this.bootstrap) {

    defaults.push('Twitter Bootstrap plugins');

    // Wire Twitter Bootstrap plugins (usemin: scripts/plugins.js)
    indexData = this.appendScripts(indexData, 'scripts/plugins.js', [
      'scripts/vendor/bootstrap/bootstrap-affix.js',
      'scripts/vendor/bootstrap/bootstrap-alert.js',
      'scripts/vendor/bootstrap/bootstrap-dropdown.js',
      'scripts/vendor/bootstrap/bootstrap-tooltip.js',
      'scripts/vendor/bootstrap/bootstrap-modal.js',
      'scripts/vendor/bootstrap/bootstrap-transition.js',
      'scripts/vendor/bootstrap/bootstrap-button.js',
      'scripts/vendor/bootstrap/bootstrap-popover.js',
      'scripts/vendor/bootstrap/bootstrap-typeahead.js',
      'scripts/vendor/bootstrap/bootstrap-carousel.js',
      'scripts/vendor/bootstrap/bootstrap-scrollspy.js',
      'scripts/vendor/bootstrap/bootstrap-collapse.js',
      'scripts/vendor/bootstrap/bootstrap-tab.js'
     ]);
  }

  if(this.includeRequireJS){
    defaults.push('RequireJS');
  }

  if(this.includeRequireHM){
    defaults.push('Support for ES6 Modules');
  }

  // Iterate over defaults, create content string
  defaults.forEach(function(i,x){
    contentText.push('
' + i  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // Append the default content
  indexData = indexData.replace('', '\n' + contentText.join('\n'));

  // Write out final file
  this.indexFile = indexData;
};

// XXX to be put in a subgenerator like rjs:app, along the fetching or require.js /
// almond lib
AppGenerator.prototype.requirejs = function requirejs(){
  var cb = this.async(),
    self = this;

  if(self.includeRequireJS){

    this.remote('jrburke', 'requirejs', '2.0.5', function(err, remote) {
      if(err) { return cb(err); }
      remote.copy('require.js', 'app/scripts/vendor/require.js');

      // Wire RequireJS/AMD (usemin: js/amd-app.js)
      var body = this.indexFile;
      body = this.appendScripts(body, 'scripts/amd-app.js', ['scripts/vendor/require.js'], {
        'data-main': 'scripts/main'
      });
      this.write('app/index.html', body);

      // add a basic amd module (should be a file in templates/)
      this.write('app/scripts/app.js',[
        "define([], function() {",
        "  return 'Hello from Yeoman!';",
        "});"
      ].join('\n'));

      this.mainJsFile = [
        "require.config({",
        "  shim: {",
        "  },",
        "",
        "  paths: {",
        "    jquery: 'vendor/jquery.min'",
        "  }",
        "});",
        " ",
        "require(['app'], function(app) {",
        "  // use app here",
        "  console.log(app);",
        "});"
      ].join('\n');

      cb();
    }.bind(this));

  } else {
    cb();
  }
};

AppGenerator.prototype.requirehm = function requirehm(){
  var cb = this.async(),
    self = this;

  if(self.includeRequireHM){

    this.remote('jrburke', 'require-hm', '0.2.1', function(err, remote) {
      if(err) { return cb(err); }
      remote.copy('hm.js', 'app/scripts/vendor/hm.js');
      remote.copy('esprima.js', 'app/scripts/vendor/esprima.js');

      // Wire RequireJS/AMD (usemin: js/amd-app.js)
      var mainjs = this.mainJsFile.replace('paths: {', 'paths: {\n    hm: \'vendor/hm\',\n    esprima: \'vendor/esprima\',');
      this.write('app/scripts/main.js', mainjs);

      cb();
    }.bind(this));

  } else {
    cb();
  }
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.mkdir('app/templates');
};

AppGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.mkdir('test/spec');
};
<commit_msg>Update Compass Bootstrap to latest rev<commit_after>
var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    yeoman = require('../../../../');

module.exports = AppGenerator;

// this example defines a prompt-app generator for demonstration purpose.
//
// So we need to hook other generators with the appropriate context (stylesheet-engine mainly)

function AppGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.test_framework = options['test-framework'] || 'mocha';

  // cleanup the name property from trailing /, typical usage of directories.
  // update the args object, it's used to initialize js-framework hooks
  if(this.name) this.args[0] = this.args[0].replace(/\/$/, '');

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });
}

util.inherits(AppGenerator, yeoman.generators.NamedBase);

AppGenerator.prototype.askFor = function askFor (argument) {
  var cb = this.async(),
    self = this;

  // a bit verbose prompt configuration, maybe we can improve that
  // demonstration purpose. Also, probably better to have this in other generator, whose responsability is to ask
  // and fetch all realated bootstrap stuff, that we hook from this generator.
  var prompts = [{
    name: 'compassBootstrap',
    message: 'Would you like to include Twitter Bootstrap for Compass?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap files will be placed into the styles directory.'
  },{
    name: 'bootstrap',
    message: 'Would you like to include the Twitter Bootstrap plugins?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap plugins will be placed into the JavaScript vendor directory.'
  },
  {
    name: 'includeRequireJS',
    message: 'Would you like to include RequireJS (for AMD support)?',
    default: 'Y/n',
    warning: 'Yes: RequireJS will be placed into the JavaScript vendor directory.'
  },
  {
    name: 'includeRequireHM',
    message: 'Would you like to support writing ECMAScript 6 modules?',
    default: 'Y/n',
    warning: 'Yes: RequireHM will be placed into the JavaScript vendor directory.'
  }];

  this.prompt(prompts, function(e, props) {
    if(e) { return self.emit('error', e); }

    // manually deal with the response, get back and store the results.
    // We change a bit this way of doing to automatically do this in the self.prompt() method.
    self.bootstrap = (/y/i).test(props.bootstrap);
    self.compassBootstrap = (/y/i).test(props.compassBootstrap);
    self.includeRequireJS = (/y/i).test(props.includeRequireJS);
    self.includeRequireHM = (/y/i).test(props.includeRequireHM);

    // we're done, go through next step
    cb();
  });
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  // this.write('foo.js', '');
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.favicon = function favicon(){
  this.copy('favicon.ico', 'app/favicon.ico');
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet(){
  if ( !this.compassBootstrap ) {
    this.write('app/styles/main.css', "/* Will be compiled down to a single stylesheet with your sass files */");
  }
};

AppGenerator.prototype.fetchH5bp = function fetchH5bp() {
  var cb = this.async();

  // Using sha since the lastest tag is so old
  this.remote('h5bp', 'html5-boilerplate', '456211dc54c7a0328485d73cf25443d210d8e1d8', function(err, remote) {
    if(err) { return cb(err); }

    remote.copy( '.htaccess', 'app/.htaccess' );
    remote.copy( '404.html', 'app/404.html' );
    remote.copy( 'robots.txt', 'app/robots.txt' );
    remote.copy( 'js/vendor/jquery-1.8.0.min.js', 'app/scripts/vendor/jquery.min.js' );
    remote.copy( 'js/vendor/modernizr-2.6.1.min.js', 'app/scripts/vendor/modernizr.min.js' );

    this.indexFile = this.readFileAsString(path.join(remote.cachePath, 'index.html'));

    cb();
  }.bind(this));
};

AppGenerator.prototype.fetchBootstrap = function fetchBootstrap() {
  // prevent the bootstrap fetch is user said NO
  if(!this.bootstrap) { return; }

  var cb = this.async();

  // third optional argument is the branch / sha1. Defaults to master when ommitted.
  this.remote('twitter', 'bootstrap', 'v2.1.0', function(err, remote, files) {
    if(err) { return cb(err); }

    'affix alert button carousel collapse dropdown modal popover scrollspy tab tooltip transition typeahead'.split(' ')
    .forEach(function( el ) {
      var filename = 'bootstrap-' + el + '.js';
      remote.copy( 'js/' + filename, 'app/scripts/vendor/bootstrap/' + filename );
    });

    cb();
  });
};

// Duplicated from the SASS generator, waiting a solution for #138
AppGenerator.prototype.compassBootstrapFiles = function compassBootstrapFiles() {
  if ( this.compassBootstrap ) {
    var cb = this.async();

    this.write('app/styles/main.scss', '@import "compass_twitter_bootstrap";');

    this.remote('kristianmandrup', 'compass-twitter-bootstrap', 'c3ccce2cca5ec52437925e8feaaa11fead51e132', function(err, remote) {
      if(err) { return cb(err); }

      remote.directory('stylesheets', 'app/styles');

      cb();
    });
  } else {
    this.log.writeln('Writing compiled Bootstrap');
    this.copy( 'bootstrap.css', 'app/styles/bootstrap.css' );
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {

  var $;

  // Resolve path to index.html
  var indexOut = path.resolve('app/index.html');

  // Read in as string for further update
  var indexData = this.indexFile;

  // Prepare default content text
  var defaults = ['HTML5 Boilerplate','Twitter Bootstrap'];
  var contentText = [
    '
',
    '
',
    '
Wotcha!
',
    '
You now have
',
    '
'
  ];

  // Strip sections of H5BP we're going to overwrite
  indexData = this.removeScript(indexData, 'plugins.js');
  indexData = this.removeScript(indexData, 'main.js');
  indexData = this.removeStyle(indexData, 'normalize.css');

  indexData = indexData.replace(/js\/vendor\/jquery[^"]+/g, 'scripts/vendor/jquery.min.js');

  $ = require('cheerio').load( indexData );
  $('link[href="css/main.css"]').attr('href', 'styles/main.css');
  $('script[src^="js/vendor/modernizr"]').attr('src', 'scripts/vendor/modernizr.min.js');
  indexData = $.html();

  // Asked for Twitter bootstrap plugins?
  if(this.bootstrap) {

    defaults.push('Twitter Bootstrap plugins');

    // Wire Twitter Bootstrap plugins (usemin: scripts/plugins.js)
    indexData = this.appendScripts(indexData, 'scripts/plugins.js', [
      'scripts/vendor/bootstrap/bootstrap-affix.js',
      'scripts/vendor/bootstrap/bootstrap-alert.js',
      'scripts/vendor/bootstrap/bootstrap-dropdown.js',
      'scripts/vendor/bootstrap/bootstrap-tooltip.js',
      'scripts/vendor/bootstrap/bootstrap-modal.js',
      'scripts/vendor/bootstrap/bootstrap-transition.js',
      'scripts/vendor/bootstrap/bootstrap-button.js',
      'scripts/vendor/bootstrap/bootstrap-popover.js',
      'scripts/vendor/bootstrap/bootstrap-typeahead.js',
      'scripts/vendor/bootstrap/bootstrap-carousel.js',
      'scripts/vendor/bootstrap/bootstrap-scrollspy.js',
      'scripts/vendor/bootstrap/bootstrap-collapse.js',
      'scripts/vendor/bootstrap/bootstrap-tab.js'
     ]);
  }

  if(this.includeRequireJS){
    defaults.push('RequireJS');
  }

  if(this.includeRequireHM){
    defaults.push('Support for ES6 Modules');
  }

  // Iterate over defaults, create content string
  defaults.forEach(function(i,x){
    contentText.push('
' + i  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // Append the default content
  indexData = indexData.replace('', '\n' + contentText.join('\n'));

  // Write out final file
  this.indexFile = indexData;
};

// XXX to be put in a subgenerator like rjs:app, along the fetching or require.js /
// almond lib
AppGenerator.prototype.requirejs = function requirejs(){
  var cb = this.async(),
    self = this;

  if(self.includeRequireJS){

    this.remote('jrburke', 'requirejs', '2.0.5', function(err, remote) {
      if(err) { return cb(err); }
      remote.copy('require.js', 'app/scripts/vendor/require.js');

      // Wire RequireJS/AMD (usemin: js/amd-app.js)
      var body = this.indexFile;
      body = this.appendScripts(body, 'scripts/amd-app.js', ['scripts/vendor/require.js'], {
        'data-main': 'scripts/main'
      });
      this.write('app/index.html', body);

      // add a basic amd module (should be a file in templates/)
      this.write('app/scripts/app.js',[
        "define([], function() {",
        "  return 'Hello from Yeoman!';",
        "});"
      ].join('\n'));

      this.mainJsFile = [
        "require.config({",
        "  shim: {",
        "  },",
        "",
        "  paths: {",
        "    jquery: 'vendor/jquery.min'",
        "  }",
        "});",
        " ",
        "require(['app'], function(app) {",
        "  // use app here",
        "  console.log(app);",
        "});"
      ].join('\n');

      cb();
    }.bind(this));

  } else {
    cb();
  }
};

AppGenerator.prototype.requirehm = function requirehm(){
  var cb = this.async(),
    self = this;

  if(self.includeRequireHM){

    this.remote('jrburke', 'require-hm', '0.2.1', function(err, remote) {
      if(err) { return cb(err); }
      remote.copy('hm.js', 'app/scripts/vendor/hm.js');
      remote.copy('esprima.js', 'app/scripts/vendor/esprima.js');

      // Wire RequireJS/AMD (usemin: js/amd-app.js)
      var mainjs = this.mainJsFile.replace('paths: {', 'paths: {\n    hm: \'vendor/hm\',\n    esprima: \'vendor/esprima\',');
      this.write('app/scripts/main.js', mainjs);

      cb();
    }.bind(this));

  } else {
    cb();
  }
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.mkdir('app/templates');
};

AppGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.mkdir('test/spec');
};
<|endoftext|>


<commit_before>(function(exports){
  Ace = require('aceserverside-sharelatex')
  Range = Ace.Range

  //look at applyDeltas method
  exports.applyChange = function(aceDoc, change, callback) {
    var r = change.range;
    var range = new Range(r.start.row, r.start.column, r.end.row, r.end.column);
    if('insertText'==change.action){
      aceDoc.insert(change.range.start, change.text);
    }else if('insertLines'==change.action){
      aceDoc.insertLines(change.range.start.row, change.lines);
    }else if('removeText'==change.action){
      aceDoc.remove(range);
    }else if('removeLines'==change.action){
      aceDoc.removeLines(range.start.row, range.end.row-1);
    }

    if(typeof callback === 'function'){
      callback(null, aceDoc);
    };
  }

})(typeof exports === 'undefined'? this['documentUpdater']={}: exports);

<commit_msg>Remove unused DocumentUpdater.js file<commit_after><|endoftext|>


<commit_before>/**
 * @file message trigger handler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

/**
 * Handles triggers in messages and responds with the respective response
 * @param {Message} message Discord.js message object
 * @returns {void}
 */
module.exports = async message => {
  try {
    let triggerModels = await message.client.database.models.trigger.findAll({
      attributes: [ 'trigger', 'responseMessage', 'responseReactions' ],
      where: {
        guildID: message.guild.id
      }
    });

    if (!triggerModels.length) return;

    let trigger = '';
    let response = [];
    for (let i = 0; i < triggerModels.length; i++) {
      if (message.content.toLowerCase() === triggerModels[i].dataValues.trigger.toLowerCase()) {
        trigger = triggerModels[i].dataValues.trigger;
        response.push({
          message: triggerModels[i].dataValues.responseMessage,
          reaction: triggerModels[i].dataValues.responseReactions
        });
      }
    }

    response = response[Math.floor(Math.random() * response.length)];

    if (response && message.content.toLowerCase() === trigger.toLowerCase()) {
      response.message = JSON.stringify(response.message);
      response.message = message.client.methods.replaceVariables(response.message, message);
      response.message = JSON.parse(response.message);

      if (response.reaction) {
        message.react(response.reaction).catch((e) => {
          message.client.log.error(e);
        });
      }

      if (response.message && Object.keys(response.message).length) {
        let text = response.message.text ? response.message.text : null;

        delete response.message.text;
        let embed = Object.keys(response.message).length ? response.message : null;

        message.channel.send(text, { embed: embed }).catch(e => {
          message.client.log.error(e);

          if (e.code === 50035 && response.message.text) {
            message.channel.send(response.message.text).catch(e => {
              message.client.log.error(e);
            });
          }
        });
      }
    }
  }
  catch (e) {
    message.client.log.error(e);
  }
};
<commit_msg>handlers: generate footer for trigger embeds on the go<commit_after>/**
 * @file message trigger handler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

/**
 * Handles triggers in messages and responds with the respective response
 * @param {Message} message Discord.js message object
 * @returns {void}
 */
module.exports = async message => {
  try {
    let triggerModels = await message.client.database.models.trigger.findAll({
      attributes: [ 'trigger', 'responseMessage', 'responseReactions' ],
      where: {
        guildID: message.guild.id
      }
    });

    if (!triggerModels.length) return;

    let trigger = '';
    let response = [];
    for (let i = 0; i < triggerModels.length; i++) {
      if (message.content.toLowerCase() === triggerModels[i].dataValues.trigger.toLowerCase()) {
        trigger = triggerModels[i].dataValues.trigger;
        response.push({
          message: triggerModels[i].dataValues.responseMessage,
          reaction: triggerModels[i].dataValues.responseReactions
        });
      }
    }

    response = response[Math.floor(Math.random() * response.length)];

    if (response && message.content.toLowerCase() === trigger.toLowerCase()) {
      response.message = JSON.stringify(response.message);
      response.message = message.client.methods.replaceVariables(response.message, message);
      response.message = JSON.parse(response.message);

      if (response.reaction) {
        message.react(response.reaction).catch((e) => {
          message.client.log.error(e);
        });
      }

      if (response.message && Object.keys(response.message).length) {
        let text = response.message.text ? response.message.text : null;

        delete response.message.text;
        let embed = Object.keys(response.message).length ? response.message : null;
        embed.footer = {
          text: `${message.client.credentials.ownerId.includes(message.author.id) ? '' : 'This is not an official message from me or my owners.'}`
        };

        message.channel.send(text, { embed: embed }).catch(e => {
          message.client.log.error(e);

          if (e.code === 50035 && response.message.text) {
            message.channel.send(response.message.text).catch(e => {
              message.client.log.error(e);
            });
          }
        });
      }
    }
  }
  catch (e) {
    message.client.log.error(e);
  }
};
<|endoftext|>


<commit_before>"use strict"

var typeindex = 0;
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var typeStack = [];

var ExecutionStack = [];

var lastnode;

var sugg = {}; // suggestions for autocompletion of node names

var ANALYSIS_NODE_START = 'ANALYSIS_NODE_START';
var ANALYSIS_LINK = 'ANALYSIS_LINK';

function autoSuggestAddName(name)
{
    /* note that name can contain spaces - this is ok. We might want to limit this though? */
    if(name.split(" ").length > 1) {
        sugg['"' + name + '"'] = 1;
    } else {
        sugg[name] = 1;
    }
}

function autocompleteCallback(request, response_callback)
{
    var ret = [];
    if (request.term === "" || request.term) {
        for (var name in sugg) {
            if (name.indexOf(request.term) == 0) {
                ret.push(name);
            }
        }
    }
    response_callback(ret);
}

/*
 * TextAnalyser2
 *
 * Input:
 *  @newtext - new sentence
 *  @finalize - is this an intermediate editing state or are we editing the graph
 *
 * Output:
 *  none
 *
 * Side effect:
 *  updating graph (global)
 *
 * Implementation notes:
 *  There is no well defined grammer. The translation goes from obvious to not
 *  so much for more complex sentences involving more then two nodes (two '#'
 *  marks).
 *
 */
function TextAnalyser2(newtext, finalize) {
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    var linkindex = 0;
    var nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";
    var ret = {'nodes': [], 'links': []};

    function addNode(id, type, state) {
        ret.nodes.push({'id':id, 'type':type, 'state':state});
    }
    function addLink(src, dst, name, state) {
        ret.links.push({'sourceId':src, 'targetId':dst, 'name':name, 'state':state});
    }

    //Sentence Sequencing
    //Build the words and cuts the main elements
    segment = newtext.split("#");
    for (var j = 0; j < segment.length; j++) {
        if (j !== 0) sentence.push("#");
        subsegment = segment[j].split(" ");
        if (subsegment.length === 0) {
            sentence.push(" ");
        }
        for (var k = 0; k < subsegment.length; k++) {
            if (subsegment[k] !== " " && subsegment[k] !== "") {
                if (subsegment[k].charAt(0) === '"') {
                    quoteword = "";
                    do {
                        quoteword += subsegment[k] + " ";
                        if(subsegment[k].charAt(subsegment[k].length-1) !== '"')k++;
                    } while (k < subsegment.length && subsegment[k].charAt(subsegment[k].length - 1) !== '"');
                     if(subsegment[k])if(subsegment[k]!==quoteword.replace(/ /g, ""))quoteword += subsegment[k];
                    sentence.push(quoteword.replace(/"/g, ""));
                } else {
                    sentence.push(subsegment[k]);
                }
            }
        }
    }

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (var m = 0; m < sentence.length; m++) {
        switch (sentence[m]) {
        case "#":
            orderStack.push("START");
            break;
        case "and":
        case "+":
        case ",":
        case "&":
            sentence[m]=" and ";
            ANDcount++;
            //orderStack.push("AND");
        default:
            if (orderStack[orderStack.length - 1] === "START") {
                orderStack.push("NODE");
                newnodes.push(sentence[m]);
                linkindex++;
            } else if (orderStack[orderStack.length - 1] === "NODE") {
                orderStack.push("LINK");
                if (!newlinks[linkindex]) {
                    newlinks[linkindex] = sentence[m] + " ";
                } else {
                    newlinks[linkindex] += sentence[m] + " ";
                }
            } else {
                if (!newlinks[linkindex]) {
                    newlinks[linkindex] = sentence[m] + " ";
                } else {
                    newlinks[linkindex] += sentence[m] + " ";
                }
            }
            if (newnodes.length === 0) prefix += sentence[m] + " ";
            break;
        }
    }

    //ATTACH SENTENCE PREFIX
    if (prefix) newlinks[1] += "(" + prefix + ")";

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    var word = "";
    var completeSentence = "";
    for (var m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            if(newnodes[nodeindex].split(" ").length>1){
                completeSentence += '"'+newnodes[nodeindex]+'"' + " ";
            }else{
                completeSentence += newnodes[nodeindex] + " ";
            }
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }

    //REBUILD GRAPH
    linkindex = 0;
    nodeindex = 0;

    //CHANGE TO PERMANENT STATE AND UPDATE SUGGESTIONLIST
    var typesetter = "";
    if (finalize === true) {
        typesetter = "perm";
        for (var n = 0; n < newnodes.length; n++) {
            autoSuggestAddName(newnodes[n]);
        }
    } else {
        typesetter = "temp";
    }

    //ADD SURROUNDING BUBBLE
    if (orderStack.length > 0) {
        addNode("", "bubble","temp");
    }

    var abnormalGraph = (newlinks.length - ANDcount) >= 3;

    //0-N ORDER STACK
    for (var m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if (!typeStack[nodeindex]) {
                    typeStack[nodeindex] = nodetypes[typeindex];
                }
                break;
            case "NODE":
                addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) {
                    addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                }
                nodeindex++;
                break;
            case "LINK":
                linkindex++;
                break;
        }
    }

    //FINAL N ORDER
    switch (orderStack[orderStack.length - 1]) {
        case "START":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}
            ret.state = ANALYSIS_NODE_START;

            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                ANDconnect(newnodes[nodeindex]);
            }
            break;
        case "LINK":
            linkindex++;
            addNode("new node", "empty", "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_LINK;
            break;
    }

    //EXTERNAL AND CONNECTION CHECKING
    var verb = "";
    function ANDconnect(node) {
          for(var x=0;x<newlinks.length;x++){
            if(newlinks[x])if(newlinks[x].replace(/ /g,"")!=="and"){
                verb=newlinks[x];
                for(var y=0; y<x ;y++){
                    addLink(newnodes[y], node, verb, typesetter);
                    for(var z=x; z<newnodes.length ;z++){
                        addLink(newnodes[y], newnodes[z], verb, typesetter);
                    }
                }

            }
        }
    }

    /*console.log(sentence);
    console.log(completeSentence);
    console.log(orderStack);*/

    //STAR CASE
    verb = "";
    if (abnormalGraph) {
        for (var l = 1; l < newlinks.length; l++) {
            if (newlinks[l])
                if (newlinks[l].replace(/ /g, "") !== "and") {
                    verb = newlinks[l];
                }
        }
        addNode(completeSentence, "chainlink", typesetter);
        for (var n = 0; n < newnodes.length; n++) {
            addLink(newnodes[n], completeSentence, "", typesetter);
        }
    }

    ret.drop_conjugator_links = ANDcount < linkindex;

    //FOR THE EXTERNAL ARROW-TYPE CHANGER
    lastnode = newnodes[nodeindex];

    return ret;
}
<commit_msg>Fixes #50: drop parenthesis for prefix including sentences<commit_after>"use strict"

var typeindex = 0;
var nodetypes = ["person", "project", "skill", "deliverable", "objective"];
var suggestionChange=false;
var sentenceStack = [];
var typeStack = [];

var ExecutionStack = [];

var lastnode;

var sugg = {}; // suggestions for autocompletion of node names

var ANALYSIS_NODE_START = 'ANALYSIS_NODE_START';
var ANALYSIS_LINK = 'ANALYSIS_LINK';

function autoSuggestAddName(name)
{
    /* note that name can contain spaces - this is ok. We might want to limit this though? */
    if(name.split(" ").length > 1) {
        sugg['"' + name + '"'] = 1;
    } else {
        sugg[name] = 1;
    }
}

function autocompleteCallback(request, response_callback)
{
    var ret = [];
    if (request.term === "" || request.term) {
        for (var name in sugg) {
            if (name.indexOf(request.term) == 0) {
                ret.push(name);
            }
        }
    }
    response_callback(ret);
}

/*
 * TextAnalyser2
 *
 * Input:
 *  @newtext - new sentence
 *  @finalize - is this an intermediate editing state or are we editing the graph
 *
 * Output:
 *  none
 *
 * Side effect:
 *  updating graph (global)
 *
 * Implementation notes:
 *  There is no well defined grammer. The translation goes from obvious to not
 *  so much for more complex sentences involving more then two nodes (two '#'
 *  marks).
 *
 */
function TextAnalyser2(newtext, finalize) {
    var segment = [],
        subsegment = [],
        sentence = [];
    var newlinks = [];
    var newnodes = [];
    var linkindex = 0;
    var nodeindex = 0;
    var orderStack = [];
    var quoteword = "";
    var ANDcase = false;
    var ANDcount = 0;
    var prefix = "";
    var ret = {'nodes': [], 'links': []};

    function addNode(id, type, state) {
        ret.nodes.push({'id':id, 'type':type, 'state':state});
    }
    function addLink(src, dst, name, state) {
        ret.links.push({'sourceId':src, 'targetId':dst, 'name':name, 'state':state});
    }

    //Sentence Sequencing
    //Build the words and cuts the main elements
    segment = newtext.split("#");
    for (var j = 0; j < segment.length; j++) {
        if (j !== 0) sentence.push("#");
        subsegment = segment[j].split(" ");
        if (subsegment.length === 0) {
            sentence.push(" ");
        }
        for (var k = 0; k < subsegment.length; k++) {
            if (subsegment[k] !== " " && subsegment[k] !== "") {
                if (subsegment[k].charAt(0) === '"') {
                    quoteword = "";
                    do {
                        quoteword += subsegment[k] + " ";
                        if(subsegment[k].charAt(subsegment[k].length-1) !== '"')k++;
                    } while (k < subsegment.length && subsegment[k].charAt(subsegment[k].length - 1) !== '"');
                     if(subsegment[k])if(subsegment[k]!==quoteword.replace(/ /g, ""))quoteword += subsegment[k];
                    sentence.push(quoteword.replace(/"/g, ""));
                } else {
                    sentence.push(subsegment[k]);
                }
            }
        }
    }

    //BUILD NEW NODE AND LINK ARRAYS WITH ORDER OF APPEARENCE
    for (var m = 0; m < sentence.length; m++) {
        switch (sentence[m]) {
        case "#":
            orderStack.push("START");
            break;
        case "and":
        case "+":
        case ",":
        case "&":
            sentence[m]=" and ";
            ANDcount++;
            //orderStack.push("AND");
        default:
            if (orderStack[orderStack.length - 1] === "START") {
                orderStack.push("NODE");
                newnodes.push(sentence[m]);
                linkindex++;
            } else if (orderStack[orderStack.length - 1] === "NODE") {
                orderStack.push("LINK");
                if (!newlinks[linkindex]) {
                    newlinks[linkindex] = sentence[m] + " ";
                } else {
                    newlinks[linkindex] += sentence[m] + " ";
                }
            } else {
                if (!newlinks[linkindex]) {
                    newlinks[linkindex] = sentence[m] + " ";
                } else {
                    newlinks[linkindex] += sentence[m] + " ";
                }
            }
            if (newnodes.length === 0) {
                prefix += sentence[m];
            }
            break;
        }
    }

    //PREFIX not null case - put complete sentence in first link.
    if (prefix) {
        newlinks[1] = prefix + " " + newnodes[0] + " " + newlinks[1] + newnodes[1];
    }

    //WRITE COMPLETE SENTENCE
    linkindex = 0;
    nodeindex = 0;
    var word = "";
    var completeSentence = prefix.length > 0 ? String(prefix) + " " : "";
    for (var m = 0; m < orderStack.length; m++) {
        if (orderStack[m] === "NODE") {
            word += " (" + newnodes[nodeindex] + ") ";
            if(newnodes[nodeindex].split(" ").length>1){
                completeSentence += '"'+newnodes[nodeindex]+'"' + " ";
            }else{
                completeSentence += newnodes[nodeindex] + " ";
            }
            nodeindex++;
        } else if (orderStack[m] === "LINK") {
            linkindex++;
            word += " -->" + newlinks[linkindex] + " --> ";
            completeSentence += newlinks[linkindex];
        }
    }

    //REBUILD GRAPH
    linkindex = 0;
    nodeindex = 0;

    //CHANGE TO PERMANENT STATE AND UPDATE SUGGESTIONLIST
    var typesetter = "";
    if (finalize === true) {
        typesetter = "perm";
        for (var n = 0; n < newnodes.length; n++) {
            autoSuggestAddName(newnodes[n]);
        }
    } else {
        typesetter = "temp";
    }

    //ADD SURROUNDING BUBBLE
    if (orderStack.length > 0) {
        addNode("", "bubble","temp");
    }

    var abnormalGraph = (newlinks.length - ANDcount) >= 3;

    //0-N ORDER STACK
    for (var m = 0; m < orderStack.length - 1; m++) {
        switch (orderStack[m]) {
            case "START":
                if (!typeStack[nodeindex]) {
                    typeStack[nodeindex] = nodetypes[typeindex];
                }
                break;
            case "NODE":
                addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
                if (!abnormalGraph) {
                    addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                }
                nodeindex++;
                break;
            case "LINK":
                linkindex++;
                break;
        }
    }

    //FINAL N ORDER
    switch (orderStack[orderStack.length - 1]) {
        case "START":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode("new node", typeStack[nodeindex], "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
            ANDconnect("new node");}
            ret.state = ANALYSIS_NODE_START;

            break;
        case "NODE":
            typeStack[nodeindex]=nodetypes[typeindex];
            addNode(newnodes[nodeindex], typeStack[nodeindex], typesetter);
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], newnodes[nodeindex], newlinks[linkindex], typesetter);
                ANDconnect(newnodes[nodeindex]);
            }
            break;
        case "LINK":
            linkindex++;
            addNode("new node", "empty", "temp");
            if (!abnormalGraph) {
                addLink(newnodes[nodeindex - 1], "new node", newlinks[linkindex], "temp");
                ANDconnect("new node");
            }
            ret.state = ANALYSIS_LINK;
            break;
    }

    //EXTERNAL AND CONNECTION CHECKING
    var verb = "";
    function ANDconnect(node) {
          for(var x=0;x<newlinks.length;x++){
            if(newlinks[x])if(newlinks[x].replace(/ /g,"")!=="and"){
                verb=newlinks[x];
                for(var y=0; y<x ;y++){
                    addLink(newnodes[y], node, verb, typesetter);
                    for(var z=x; z<newnodes.length ;z++){
                        addLink(newnodes[y], newnodes[z], verb, typesetter);
                    }
                }

            }
        }
    }

    /*console.log(sentence);
    console.log(completeSentence);
    console.log(orderStack);*/

    //STAR CASE
    verb = "";
    if (abnormalGraph) {
        for (var l = 1; l < newlinks.length; l++) {
            if (newlinks[l])
                if (newlinks[l].replace(/ /g, "") !== "and") {
                    verb = newlinks[l];
                }
        }
        addNode(completeSentence, "chainlink", typesetter);
        for (var n = 0; n < newnodes.length; n++) {
            addLink(newnodes[n], completeSentence, "", typesetter);
        }
    }

    ret.drop_conjugator_links = ANDcount < linkindex;

    //FOR THE EXTERNAL ARROW-TYPE CHANGER
    lastnode = newnodes[nodeindex];

    return ret;
}
<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/* eslint-env node */
'use strict';

const execute = require( '../common/execute' );
const gitPull = require( '../common/gitPull' );
const winston = require( 'winston' );
const _ = require( 'lodash' ); // eslint-disable-line

/**
 * pull master for every repo in dependencies.json (plus babel) to make sure everything is up to date
 */
module.exports = async function pullMaster( repos ) {
  // so we don't have to modify the repos object
  const reposCopy = _.clone( repos );

  if ( 'comment' in reposCopy ) {
    delete reposCopy.comment;
  }

  const errors = [];

  // Add babel to list of repos to pull
  reposCopy.babel = true;

  for ( let repoName in reposCopy ) {
    winston.log( 'info', 'pulling from ' + repoName );
    const repoDir = '../' + repoName;

    try {
      await execute( 'git', [ 'checkout master' ], repoDir );
    }
    catch( error ) {
      return Promise.reject( 'git checkout master failed in ' + repoName );
    }

    try {
      await gitPull( repoName );
    }
    catch( error ) {
      errors.push( error );
    }
  }

  if ( errors.length > 0 ) {
    return Promise.reject( 'at least one repository failed to pull master' );
  }
};<commit_msg>updated execute calls<commit_after>// Copyright 2017, University of Colorado Boulder

/* eslint-env node */
'use strict';

const execute = require( '../common/execute' );
const gitPull = require( '../common/gitPull' );
const winston = require( 'winston' );
const _ = require( 'lodash' ); // eslint-disable-line

/**
 * pull master for every repo in dependencies.json (plus babel) to make sure everything is up to date
 */
module.exports = async function pullMaster( repos ) {
  // so we don't have to modify the repos object
  const reposCopy = _.clone( repos );

  if ( 'comment' in reposCopy ) {
    delete reposCopy.comment;
  }

  const errors = [];

  // Add babel to list of repos to pull
  reposCopy.babel = true;

  for ( let repoName in reposCopy ) {
    winston.log( 'info', 'pulling from ' + repoName );
    const repoDir = '../' + repoName;

    try {
      await execute( 'git', [ 'checkout', 'master' ], repoDir );
    }
    catch( error ) {
      return Promise.reject( 'git checkout master failed in ' + repoName );
    }

    try {
      await gitPull( repoName );
    }
    catch( error ) {
      errors.push( error );
    }
  }

  if ( errors.length > 0 ) {
    return Promise.reject( 'at least one repository failed to pull master' );
  }
};<|endoftext|>


<commit_before>var URL = /^((?:(http|udp|ftp)s?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))$/;

/**
 * Returns true if str is a URL.
 *
 * @param {String} str
 * @return {Boolean}
 */
exports.isURL = function(str) {
  return URL.test(str);
};

/**
 * Returns true if n is an integer.
 *
 * @param {Number} n
 * @return {Boolean}
 */
exports.isInteger = function(n) {
  return !isNaN(parseInt(n, 10));
};

var SIZES = /((\d)+(\.\d+)?)(k|m|g|t)?b?/i;
var POWERS = {k: 10, m: 20, g: 30, t: 40};

/**
 * Returns bytes from human readable memory sizes such as `1.5MB`.
 *
 * @param {String|Number} str
 * @return {Number}
 */
exports.toBytes = function(str) {
  var result = SIZES.exec(str)
    , num    = parseFloat(result[1])
    , c      = result[4].toLowerCase()
    ;

  return POWERS[c] ? Math.round(num * (1 << POWERS[c])): num;
};

/**
 * Returns true if rs is a ReadableStream.
 *
 * @param {ReadableStream} rs
 * @return {Boolean}
 */
exports.isReadableStream = function(rs) {
  return typeof rs === 'object' && typeof rs.pipe === 'function'
    && typeof rs.readable === 'boolean' && rs.readable;
};

/**
 * Splits a path into an array, platform safe.
 *
 * @param {String} path
 * @return {Array.<String>}
 */
var isWindows = process.platform === 'win32';
var splitc    = isWindows ? '\\' : '/';
exports.splitPath = function(path) {
  return path.split(splitc);
};

/**
 * Returns true if part of buffer `b` beginning at `start` matches buffer `a`.
 *
 * @param {Buffer} a
 * @param {Buffer} b
 * @param {Number} start
 */
exports.buffersMatch = function(a, b, start) {
  for (var i = 0, l = b.length; i < l; i++) {
    if (a[start + i] !== b[i]) {
      return false;
    }
  }

  return true;
};
<commit_msg>a url ending with whitespace, for example: 'http://www123.foobar.com:6699/announce ' may cause the URL.test hang up, trying update the URL regexp to fix the issue<commit_after>var URL = /^((?:(http|udp|ftp)s?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))$/;

/**
 * Returns true if str is a URL.
 *
 * @param {String} str
 * @return {Boolean}
 */
exports.isURL = function(str) {
  return URL.test(str);
};

/**
 * Returns true if n is an integer.
 *
 * @param {Number} n
 * @return {Boolean}
 */
exports.isInteger = function(n) {
  return !isNaN(parseInt(n, 10));
};

var SIZES = /((\d)+(\.\d+)?)(k|m|g|t)?b?/i;
var POWERS = {k: 10, m: 20, g: 30, t: 40};

/**
 * Returns bytes from human readable memory sizes such as `1.5MB`.
 *
 * @param {String|Number} str
 * @return {Number}
 */
exports.toBytes = function(str) {
  var result = SIZES.exec(str)
    , num    = parseFloat(result[1])
    , c      = result[4].toLowerCase()
    ;

  return POWERS[c] ? Math.round(num * (1 << POWERS[c])): num;
};

/**
 * Returns true if rs is a ReadableStream.
 *
 * @param {ReadableStream} rs
 * @return {Boolean}
 */
exports.isReadableStream = function(rs) {
  return typeof rs === 'object' && typeof rs.pipe === 'function'
    && typeof rs.readable === 'boolean' && rs.readable;
};

/**
 * Splits a path into an array, platform safe.
 *
 * @param {String} path
 * @return {Array.<String>}
 */
var isWindows = process.platform === 'win32';
var splitc    = isWindows ? '\\' : '/';
exports.splitPath = function(path) {
  return path.split(splitc);
};

/**
 * Returns true if part of buffer `b` beginning at `start` matches buffer `a`.
 *
 * @param {Buffer} a
 * @param {Buffer} b
 * @param {Number} start
 */
exports.buffersMatch = function(a, b, start) {
  for (var i = 0, l = b.length; i < l; i++) {
    if (a[start + i] !== b[i]) {
      return false;
    }
  }

  return true;
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    split = require('split'),
    through = require('through')

module.exports = fileStream

function fileStream(options) {
  var tr = through(write, noop),
      file = null,
      files = []

  options = options || {}

  return tr

  function write(buf) {
    files.push(buf.toString())
    if (file != null) return
    file = true
    processFile(files.shift())
  }

  function processFile(filename) {
    var line = 0,
        file = fs.createReadStream(filename).pipe(split())

    file.on('data', onData)
    file.on('end', onEnd)
    file.on('error', noop)

    function onData(data) {
      line++

      if (!data) return

      var fileObject = {
        filename: filename,
        line: line,
        data: data
      }

      tr.queue(fileObject)
    }

    function onEnd() {
      if (files.length) return processFile(files.shift())
      tr.queue(null)
    }
  }
}

function noop() {}
<commit_msg>cleanup<commit_after>var fs = require('fs'),
    split = require('split'),
    through = require('through')

module.exports = fileStream

function fileStream() {
  var tr = through(write, noop),
      file = null,
      files = []

  return tr

  function write(buf) {
    files.push(buf.toString())
    if (file != null) return
    file = true
    processFile(files.shift())
  }

  function processFile(filename) {
    var line = 0,
        file = fs.createReadStream(filename).pipe(split())

    file.on('data', onData)
    file.on('end', onEnd)
    file.on('error', noop)

    function onData(data) {
      line++

      if (!data) return

      var fileObject = {
        filename: filename,
        line: line,
        data: data
      }

      tr.queue(fileObject)
    }
  }

  function onEnd() {
    if (files.length) return processFile(files.shift())
    tr.queue(null)
  }
}

function noop() {}
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var _ = require('lodash');
var chalk = require('chalk');
var mkdirp = require('mkdirp');
var wiring = require('html-wiring');
var FlowXOUtils = require('../utils');
var pjson = require('../package.json');

var SERVICES_ROOT = 'flowxo-services-';

var FlowXOGenerator = module.exports = function FlowXOGenerator() {
  yeoman.generators.Base.apply(this, arguments);

  this.option('debug');

  // Greet the user
  this.log(FlowXOUtils.greeting);

  if(this.options.debug) {
    this.log(chalk.gray('version: ' + pjson.version + '\n'));
  }

  this.argument('service', {
    type: String,
    required: false
  });

  this.pkg = JSON.parse(wiring.readFileAsString(path.join(__dirname, '../package.json')));
  this.on('end', function() {
    this.log(chalk.cyan('\nYour service has been generated in the ' + this.serviceName + ' folder.\n'));
    this.log(chalk.cyan(FlowXOUtils.messages.whatNext[this.auth.type]));
  });

};

util.inherits(FlowXOGenerator, yeoman.generators.Base);

FlowXOGenerator.prototype.prompting = function() {
  var done = this.async();
  var self = this;
  var prompts = FlowXOUtils.prompts.service;
  this.prompt(prompts, function(props) {
    self.name = props.name;
    self.slug = _.snakeCase(self.name);
    self.slugUpperCased = self.slug.toUpperCase();
    self.auth = {
      type: props.auth_type
    };
    self.serviceName = SERVICES_ROOT + _.kebabCase(self.name);
    self.destinationRoot(self.serviceName);
    done();
  });

};

FlowXOGenerator.prototype.authPrompting = function authPrompting() {
  var done = this.async();
  var self = this;

  if(this.auth.type === 'credentials') {
    this.log(chalk.bgGreen('You now need to define the necessary credential fields for the service connection.'));
    FlowXOUtils.promptUtils.repeatedPrompt.call(this, 'field', FlowXOUtils.prompts.credentials, function(fields) {
      self.auth.fields = fields;
      done();
    });
  } else {
    done();
  }
};

FlowXOGenerator.prototype.coreFiles = function coreFiles() {
  // Root Boilerplate
  this.template('_gitignore', '.gitignore');
  this.template('_jshintrc', '.jshintrc');
  this.template('_jsbeautifyrc', '.jsbeautifyrc');
  this.template('_editorconfig', '.editorconfig');
  this.template('_package.json', 'package.json');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('_CHANGELOG.md', 'CHANGELOG.md');
  this.template('_README.md', 'README.md');
  this.template('_env', '.env');

  // Lib
  mkdirp('lib');
  if(this.auth.type === 'credentials') {
    this.template('_ping.js', 'lib/ping.js');
  }

  this.template('_index.js', 'lib/index.js');

  // Methods
  mkdirp('lib/methods');

};

FlowXOGenerator.prototype.installDeps = function installDeps() {
  this.installDependencies({
    bower: false,
    skipInstall: this.options['skip-install'],
    skipMessage: true
  });
};
<commit_msg>Fix slug generation<commit_after>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var _ = require('lodash');
var chalk = require('chalk');
var mkdirp = require('mkdirp');
var wiring = require('html-wiring');
var FlowXOUtils = require('../utils');
var pjson = require('../package.json');

var SERVICES_ROOT = 'flowxo-services-';

var FlowXOGenerator = module.exports = function FlowXOGenerator() {
  yeoman.generators.Base.apply(this, arguments);

  this.option('debug');

  // Greet the user
  this.log(FlowXOUtils.greeting);

  if(this.options.debug) {
    this.log(chalk.gray('version: ' + pjson.version + '\n'));
  }

  this.argument('service', {
    type: String,
    required: false
  });

  this.pkg = JSON.parse(wiring.readFileAsString(path.join(__dirname, '../package.json')));
  this.on('end', function() {
    this.log(chalk.cyan('\nYour service has been generated in the ' + this.serviceName + ' folder.\n'));
    this.log(chalk.cyan(FlowXOUtils.messages.whatNext[this.auth.type]));
  });

};

util.inherits(FlowXOGenerator, yeoman.generators.Base);

FlowXOGenerator.prototype.prompting = function() {
  var done = this.async();
  var self = this;
  var prompts = FlowXOUtils.prompts.service;
  this.prompt(prompts, function(props) {
    self.name = props.name;
    self.slug = _.snakeCase(self.name);
    self.slugUpperCased = self.slug.toUpperCase();
    self.auth = {
      type: props.auth_type
    };
    self.serviceName = SERVICES_ROOT + _.kebabCase(self.name.toLowerCase());
    self.destinationRoot(self.serviceName);
    done();
  });

};

FlowXOGenerator.prototype.authPrompting = function authPrompting() {
  var done = this.async();
  var self = this;

  if(this.auth.type === 'credentials') {
    this.log(chalk.bgGreen('You now need to define the necessary credential fields for the service connection.'));
    FlowXOUtils.promptUtils.repeatedPrompt.call(this, 'field', FlowXOUtils.prompts.credentials, function(fields) {
      self.auth.fields = fields;
      done();
    });
  } else {
    done();
  }
};

FlowXOGenerator.prototype.coreFiles = function coreFiles() {
  // Root Boilerplate
  this.template('_gitignore', '.gitignore');
  this.template('_jshintrc', '.jshintrc');
  this.template('_jsbeautifyrc', '.jsbeautifyrc');
  this.template('_editorconfig', '.editorconfig');
  this.template('_package.json', 'package.json');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('_CHANGELOG.md', 'CHANGELOG.md');
  this.template('_README.md', 'README.md');
  this.template('_env', '.env');

  // Lib
  mkdirp('lib');
  if(this.auth.type === 'credentials') {
    this.template('_ping.js', 'lib/ping.js');
  }

  this.template('_index.js', 'lib/index.js');

  // Methods
  mkdirp('lib/methods');

};

FlowXOGenerator.prototype.installDeps = function installDeps() {
  this.installDependencies({
    bower: false,
    skipInstall: this.options['skip-install'],
    skipMessage: true
  });
};
<|endoftext|>


<commit_before>/* global YASGUI */

const query = `
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
PREFIX uom: <http://www.opengis.net/def/uom/OGC/1.0/>

select * where {
  graph <http://data.pdok.nl/mossel-en-oesterhabitats> {
    ?s geo:hasGeometry/geo:asWKT ?wkt .
    bind(geof:distance(
      ?wkt, "POINT(5 52)"^^geo:wktLiteral, uom:metre) as ?dist_metres
    )
  }
}
order by ?dist_metres
limit 10`;

YASGUI.YASQE.defaults.value = query;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(location => {
    YASGUI.YASQE.defaults.value = query.replace(
      'POINT(5 52)', `POINT(${location.coords.longitude} ${location.coords.latitude})`
    );
    YASGUI.sparqlStories();
  });
}

<commit_msg>Labels<commit_after>/* global YASGUI */

const query = `
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
PREFIX uom: <http://www.opengis.net/def/uom/OGC/1.0/>

select * where {
  graph <http://data.pdok.nl/mossel-en-oesterhabitats> {
    ?s geo:hasGeometry/geo:asWKT ?wkt .
    bind(geof:distance(
      ?wkt, "POINT(5 52)"^^geo:wktLiteral, uom:metre) as ?dist_metres
    )
    bind(
      concat("Op slechts ", str(round(?dist_metres / 1000)), " km. (water)fietsen!" )
      as ?wktLabel)
  }
}
order by ?dist_metres
limit 10`;

YASGUI.YASQE.defaults.value = query;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(location => {
    YASGUI.YASQE.defaults.value = query.replace(
      'POINT(5 52)', `POINT(${location.coords.longitude} ${location.coords.latitude})`
    );
    YASGUI.sparqlStories();
  });
}

<|endoftext|>


<commit_before>/**
 * @flow
 */

import React, {Component} from 'react';
import {
  AppRegistry,
  Text,
} from 'react-native';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { StackNavigator } from 'react-navigation';
import Home from './routes/Home';
import PlayerSelect from './routes/PlayerSelect';
import TeamSelect from './routes/TeamSelect';
import Game from './routes/Game';
import Score from './routes/Score';
import FinalScore from './routes/FinalScore';
import MatchSettings from './routes/MatchSettings'
import ClubScore from './routes/ClubScore'
import { reducer } from './redux'

const AppNavigator = StackNavigator({
  Home: { screen: Home },
  PlayerSelect: { screen: PlayerSelect },
  Team: { screen: TeamSelect },
  Game: { screen: Game },
  Score: { screen: Score },
  FinalScore: { screen: FinalScore },
  MatchSettings: { screen: MatchSettings },
  ClubScore: { screen: ClubScore },
});

const store = createStore(reducer);

class xMobile extends Component{
  render(){
    return(
      <Provider store={store}>
        <AppNavigator />
      </Provider>
    )
  }
}

AppRegistry.registerComponent('xMobile', () => xMobile);
<commit_msg>Persist redux store via AsyncStorage<commit_after>/**
 * @flow
 */

import React, {Component} from 'react';
import {
  AppRegistry,
  Text,
  AsyncStorage,
} from 'react-native';
import { createStore, compose } from 'redux'
import { Provider } from 'react-redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import { reducer } from './redux'
import { StackNavigator } from 'react-navigation';
import Home from './routes/Home';
import PlayerSelect from './routes/PlayerSelect';
import TeamSelect from './routes/TeamSelect';
import Game from './routes/Game';
import Score from './routes/Score';
import FinalScore from './routes/FinalScore';
import MatchSettings from './routes/MatchSettings'
import ClubScore from './routes/ClubScore'

const AppNavigator = StackNavigator({
  Home: { screen: Home },
  PlayerSelect: { screen: PlayerSelect },
  Team: { screen: TeamSelect },
  Game: { screen: Game },
  Score: { screen: Score },
  FinalScore: { screen: FinalScore },
  MatchSettings: { screen: MatchSettings },
  ClubScore: { screen: ClubScore },
});

const store = compose(autoRehydrate())(createStore)(reducer)

persistStore(store, {storage: AsyncStorage}, () => {
  console.log(store.getState())
})

class xMobile extends Component{
  render(){
    return(
      <Provider store={store}>
        <AppNavigator />
      </Provider>
    )
  }
}

AppRegistry.registerComponent('xMobile', () => xMobile);
<|endoftext|>


<commit_before>/*
 * grunt-php-config
 * https://github.com/mothepro/grunt-php-config
 *
 * Copyright (c) 2015 Maurice Prosper
 * Licensed under the MIT license.
 */

'use strict';
Array.prototype.clone = function() {
    return this.slice(0);
};

module.exports = function(grunt) {
    var util = require('util');
    var _ = require('lodash');

    var constants = [];

    function makeConst(consts, parent, raw, allCaps) {
        var k, val, _raw, _allCaps, _parent, kind;

        for(k in consts) {
            if(!consts.hasOwnProperty(k)) continue;

            // props
            val         = consts[k].value || consts[k]; // for shorthand
            _raw        = consts[k].raw || raw; // override
            _allCaps    = consts[k].allCaps || allCaps; // override

            // add the constant if scalar
            kind = grunt.util.kindOf(val);
            if(['string', 'number', 'boolean', 'date', 'null'].indexOf(kind) >= 0) {
                var c = {
                    name: k,
                    value: val,
                    parent: parent,
                    raw: _raw,
                    allCaps: _allCaps,
                    kind: kind
                };
                constants.push(c);

                grunt.log.debug(c);
            }

            // loop through children
            if(grunt.util.kindOf(consts[k]) === 'object')
                if(_.without(Object.keys(consts[k]), 'value', 'raw', 'allCaps').length) {
                    _parent = parent.clone();
                    _parent.push(k);
                    makeConst(consts[k], _parent, _raw, _allCaps);
                }
        }
    }

    function write(type) {
        var data, name, value;

        switch(type) {
            case 'php':
                data = util.format('<?php // Generated on %s\n', grunt.template.today('mmmm dS yyyy @ h:MM:ss TT'));

                constants.forEach(function(v) {
                    name = v.name;
                    value = v.value;

                    // add to prefix first namespace
                    name = util.format('%s%s\\%s', (v.parent.length ? '\\' : ''), v.parent.join('\\'), name);

                    // standardize date string
                    if(v.kind === 'date') {
                        v.kind = 'string';
                        v.value = v.value.toString();
                    }

                    // escape strings
                    if(v.kind === 'string' && !v.raw)
                        value = util.format("'%s'", value.replace(/'/g, "\\'"));

                    if(v.allCaps)
                        name = name.toUpperCase();

                    data += util.format('define(\'%s\', %s);\n', name, value);
                });

                break;

            default:
                grunt.fail.fatal(util.format('Unknown type "%s".', type));
        }

        return data;
    }

    grunt.registerMultiTask('php_config', 'Builds a PHP config and constants file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            type: 'php',
            allCaps: true,
            raw: false,

            constants: {}
        }), out = '';

        // reset array
        constants = [];

        grunt.log.debug(options.constants);

        if (options.constants)
            makeConst(options.constants, [], options.raw, options.allCaps);

        out = write(options.type);

        if (!this.errorCount)
            this.files.forEach(function (f) {
                grunt.file.write(f.dest, out);
                grunt.log.ok(util.format('%d %s saved in %s file "%s"', constants.length, grunt.util.pluralize(constants.length, "constant/constants"), options.type, f.dest));
            });

        return !this.errorCount;
    });
};<commit_msg>Colored Output!<commit_after>/*
 * grunt-php-config
 * https://github.com/mothepro/grunt-php-config
 *
 * Copyright (c) 2015 Maurice Prosper
 * Licensed under the MIT license.
 */

'use strict';
Array.prototype.clone = function() {
    return this.slice(0);
};

module.exports = function(grunt) {
    var util = require('util');
    var _ = require('lodash');

    var constants = [];

    function makeConst(consts, parent, raw, allCaps) {
        var k, val, _raw, _allCaps, _parent, kind;

        for(k in consts) {
            if(!consts.hasOwnProperty(k)) continue;

            // props
            val         = consts[k].value || consts[k]; // for shorthand
            _raw        = consts[k].raw || raw; // override
            _allCaps    = consts[k].allCaps || allCaps; // override

            // add the constant if scalar
            kind = grunt.util.kindOf(val);
            if(['string', 'number', 'boolean', 'date', 'null'].indexOf(kind) >= 0) {
                var c = {
                    name: k,
                    value: val,
                    parent: parent,
                    raw: _raw,
                    allCaps: _allCaps,
                    kind: kind
                };
                constants.push(c);

                grunt.log.debug(c);
            }

            // loop through children
            if(grunt.util.kindOf(consts[k]) === 'object')
                if(_.without(Object.keys(consts[k]), 'value', 'raw', 'allCaps').length) {
                    _parent = parent.clone();
                    _parent.push(k);
                    makeConst(consts[k], _parent, _raw, _allCaps);
                }
        }
    }

    function write(type) {
        var data, name, value;

        switch(type) {
            case 'php':
                data = util.format('<?php // Generated on %s\n', grunt.template.today('mmmm dS yyyy @ h:MM:ss TT'));

                constants.forEach(function(v) {
                    name = v.name;
                    value = v.value;

                    // add to prefix first namespace
                    name = util.format('%s%s\\%s', (v.parent.length ? '\\' : ''), v.parent.join('\\'), name);

                    // standardize date string
                    if(v.kind === 'date') {
                        v.kind = 'string';
                        v.value = v.value.toString();
                    }

                    // escape strings
                    if(v.kind === 'string' && !v.raw)
                        value = util.format("'%s'", value.replace(/'/g, "\\'"));

                    if(v.allCaps)
                        name = name.toUpperCase();

                    data += util.format('define(\'%s\', %s);\n', name, value);
                });

                break;

            default:
                grunt.fail.fatal(util.format('Unknown type "%s".', type));
        }

        return data;
    }

    grunt.registerMultiTask('php_config', 'Builds a PHP config and constants file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            type: 'php',
            allCaps: true,
            raw: false,

            constants: {}
        }), out = '';

        // reset array
        constants = [];

        grunt.log.debug(options.constants);

        if (options.constants)
            makeConst(options.constants, [], options.raw, options.allCaps);

        out = write(options.type);

        if (!this.errorCount)
            this.files.forEach(function (f) {
                grunt.file.write(f.dest, out);
                grunt.log.ok(util.format('%s %s saved in %s file %s.', constants.length.toString().cyan, grunt.util.pluralize(constants.length, "constant/constants"), options.type, f.dest.yellow));
            });

        return !this.errorCount;
    });
};<|endoftext|>


<commit_before>// Copyright 2014-2017, University of Colorado Boulder

/**
 * An interactive round push button.  This is the file in which the appearance and behavior are brought together.
 *
 * This class inherits from RoundButtonView, which contains all of the
 * code that defines the button's appearance, and adds the button's behavior
 * by hooking up a button model.
 *
 * @author John Blanco (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var PushButtonInteractionStateProperty = require( 'SUN/buttons/PushButtonInteractionStateProperty' );
  var PushButtonIO = require( 'SUN/buttons/PushButtonIO' );
  var PushButtonModel = require( 'SUN/buttons/PushButtonModel' );
  var RoundButtonView = require( 'SUN/buttons/RoundButtonView' );
  var sun = require( 'SUN/sun' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function RoundPushButton( options ) {

    options = _.extend( {
      tandem: Tandem.required,
      phetioType: PushButtonIO,

      // a11y
      tagName: 'button',
      accessibleFire: function() {}
    }, options );

    var self = this;

    // If a listener was passed in, save it and add it after creating the button model.  This is done so that
    // the same code path is always used for adding listener, thus guaranteeing a consistent code path if addListener is
    // overridden, see https://github.com/phetsims/sun/issues/284.
    var listener = options.listener;
    options = _.omit( options, [ 'listener' ] );

    // Safe to pass through options to the PushButtonModel like "fireOnDown".  Other scenery options will be safely ignored.
    assert && assert( !options.phetioEventSource, 'phetioEventSource cannot be supplied in options' );
    this.buttonModel = new PushButtonModel( _.extend( { phetioEventSource: this }, options ) ); // @public, listen only
    RoundButtonView.call( this, this.buttonModel, new PushButtonInteractionStateProperty( this.buttonModel ), options );

    // add the listener that was potentially saved above
    listener && this.addListener( listener );

    // a11y - when the button is clicked with assistive technology, fire
    this.clickListener = this.addAccessibleInputListener( {
      click: function() {
        if ( self.enabled ) {
          self.buttonModel.a11yClick( options.accessibleFire );
        }
      },
      focus: function() {
        self.buttonModel.overProperty.value = true;
      },
      blur: function() {
        self.buttonModel.overProperty.value = false;
      }
    } );

    this.disposeRoundPushButton = function() {
      self.removeAccessibleInputListener( this.clickListener );
      self.buttonModel.dispose();
    };
  }

  sun.register( 'RoundPushButton', RoundPushButton );

  return inherit( RoundButtonView, RoundPushButton, {

    // @public
    dispose: function() {
      this.disposeRoundPushButton();
      RoundButtonView.prototype.dispose.call( this );
    },

    // @public
    addListener: function( listener ) {
      this.buttonModel.addListener( listener );
    },

    // @public
    removeListener: function( listener ) {
      this.buttonModel.removeListener( listener );
    }
  } );
} );<commit_msg>update usage of addAccessibleInputListener, see phetsims/scenery#764<commit_after>// Copyright 2014-2017, University of Colorado Boulder

/**
 * An interactive round push button.  This is the file in which the appearance and behavior are brought together.
 *
 * This class inherits from RoundButtonView, which contains all of the
 * code that defines the button's appearance, and adds the button's behavior
 * by hooking up a button model.
 *
 * @author John Blanco (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var PushButtonInteractionStateProperty = require( 'SUN/buttons/PushButtonInteractionStateProperty' );
  var PushButtonIO = require( 'SUN/buttons/PushButtonIO' );
  var PushButtonModel = require( 'SUN/buttons/PushButtonModel' );
  var RoundButtonView = require( 'SUN/buttons/RoundButtonView' );
  var sun = require( 'SUN/sun' );
  var Tandem = require( 'TANDEM/Tandem' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function RoundPushButton( options ) {

    options = _.extend( {
      tandem: Tandem.required,
      phetioType: PushButtonIO,

      // a11y
      tagName: 'button',
      accessibleFire: function() {}
    }, options );

    var self = this;

    // If a listener was passed in, save it and add it after creating the button model.  This is done so that
    // the same code path is always used for adding listener, thus guaranteeing a consistent code path if addListener is
    // overridden, see https://github.com/phetsims/sun/issues/284.
    var listener = options.listener;
    options = _.omit( options, [ 'listener' ] );

    // Safe to pass through options to the PushButtonModel like "fireOnDown".  Other scenery options will be safely ignored.
    assert && assert( !options.phetioEventSource, 'phetioEventSource cannot be supplied in options' );
    this.buttonModel = new PushButtonModel( _.extend( { phetioEventSource: this }, options ) ); // @public, listen only
    RoundButtonView.call( this, this.buttonModel, new PushButtonInteractionStateProperty( this.buttonModel ), options );

    // add the listener that was potentially saved above
    listener && this.addListener( listener );

    // a11y - when the button is clicked with assistive technology, fire
    var clickListener = {
      click: function() {
        if ( self.enabled ) {
          self.buttonModel.a11yClick( options.accessibleFire );
        }
      },
      focus: function() {
        self.buttonModel.overProperty.value = true;
      },
      blur: function() {
        self.buttonModel.overProperty.value = false;
      }
    };
    this.addAccessibleInputListener( clickListener );

    this.disposeRoundPushButton = function() {
      self.removeAccessibleInputListener( clickListener );
      self.buttonModel.dispose();
    };
  }

  sun.register( 'RoundPushButton', RoundPushButton );

  return inherit( RoundButtonView, RoundPushButton, {

    // @public
    dispose: function() {
      this.disposeRoundPushButton();
      RoundButtonView.prototype.dispose.call( this );
    },

    // @public
    addListener: function( listener ) {
      this.buttonModel.addListener( listener );
    },

    // @public
    removeListener: function( listener ) {
      this.buttonModel.removeListener( listener );
    }
  } );
} );<|endoftext|>


<commit_before>'use strict';

angular.module('polls').controller('PollsSearchController', [
  '$location',
  '$scope',
  '$state',
  'Authentication',
  'CategorysService',
  'Action',
  '$stateParams',
  'Storages',
  'Constants',
  'toastr',
  'ngDialog',
  'Profile',
  function ($location, $scope, $state, Authentication, Categorys, Action, $stateParams, Storages, Constants, toast, dialog, Profile) {
    $scope.user = Authentication.user;
    $scope.isLogged = ($scope.user) ? true : false;
    $scope.detailToggle = -1;
    $scope.form = {};
    $scope.categorys = Categorys.query();

    $scope.condition = {};
    $scope.condition.key = $stateParams.key;
    $scope.condition.in = $stateParams.in;
    $scope.condition.status = $stateParams.status;
    $scope.condition.ctgr = $stateParams.ctgr;

    $scope.condition.cmt = $stateParams.cmt;
    $scope.condition.compare = $stateParams.compare;

    $scope.condition.created = $stateParams.created;
    $scope.condition.timing = $stateParams.timing;

    $scope.condition.sort = $stateParams.sort;
    $scope.condition.sortkind = $stateParams.sortkind;

    $scope.condition.by = $stateParams.by;
    if ($scope.condition.by) {
      Profile.get({ userId: $scope.condition.by }, _user => {
        $scope.selectedUser = _user;
      });
    }
    $scope.search = () => {
      $state.go('search', $scope.condition);
    };

    $scope.busy = false;
    $scope.polls = [];
    $scope.sort = '-poll.created';
    excute();
    function excute() {
      if (check_params()) {
        $scope.busy = true;
        Action.search($scope.condition)
          .then(res => {
            $scope.polls = res.data;
            var promise = [];
            $scope.polls.forEach(function (item) {
              promise.push(get_owner_follow(item.poll));
              promise.push(get_reported(item.poll));
              promise.push(get_bookmarked(item.poll));
            }, this);
            return Promise.all(promise);
          })
          .then(res => {
            create_sort();
            $scope.busy = false;
          })
          .catch(err => {
            $scope.busy = false;
            console.log(err);
          });
      } else {
        $scope.condition = JSON.parse(Storages.get_local(Constants.storages.preferences, JSON.stringify({})));
      }
    }
    function check_params() {
      if ($scope.condition.key || $scope.condition.status || $scope.condition.by || $scope.condition.ctgr || $scope.condition.cmt || $scope.condition.created) {
        return true;
      }
      return false;
    }
    function create_sort() {
      if ($scope.condition.sort) {
        var prefix = ($scope.condition.sort === 'created') ? 'poll.' : 'report.';
        var kind = ($scope.condition.sortkind === 'desc') ? '-' : '';
        $scope.sort = kind + prefix + $scope.condition.sort;
      }
    }

    function get_owner_follow(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.follow = {};
          return resolve();
        }
        Action.get_follow(poll._id)
          .then(res => {
            poll.follow = res.data || { poll: poll._id };
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    function get_reported(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.reported = false;
          return resolve();
        }
        Action.get_report(poll._id)
          .then(res => {
            poll.reported = (res.data) ? res.data : false;
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    function get_bookmarked(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.bookmarked = false;
          return resolve();
        }
        Action.get_bookmark(poll._id)
          .then(res => {
            poll.bookmarked = (res.data) ? res.data : false;
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    $scope.selectedUserFn = function (selected) {
      if (selected) {
        $scope.condition.by = selected.originalObject._id;
        $scope.selectedUser = selected.originalObject;
      } else {
        $scope.condition.by = undefined;
        $scope.selectedUser = undefined;
      }
    };
    $scope.clear_preferences = () => {
      $scope.condition = {};
      Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition));
      // $location.url($location.path());
      $state.go('search', {}, {notify: false})
    };
    $scope.save_preferences = () => {
      Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition));
    };
    $scope.delete_poll = (poll) => {
      if (poll.user._id !== $scope.user._id) {
        toast.error('You are not authorized.', 'Error!');
        return;
      }
      $scope.message_title = 'Delete poll!';
      $scope.message_content = 'Are you sure you want to delete this poll?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        $scope.polls = _.reject($scope.polls, function (item) {
          return item.poll._id === poll._id;
        });
        // Action.delete_poll(poll);
      }
    };
    $scope.report_poll = (poll) => {
      if (poll.reported) {
        toast.error('You are already reported ' + poll.title, 'Error!');
        return;
      }
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/report.dialog.template.html'
      }).then(reason => {
        handle_confirm(reason);
      }, reject => {
      });
      function handle_confirm(reason) {
        Action.save_report(poll._id, reason)
          .then(res => {
            poll.reported = (res) ? true : false;
            toast.success('You have successfully reported ' + poll.title, 'Thank you!');
          })
          .catch(err => {
            toast.error(err.message, 'Error!');
          });
      }
    };
    $scope.bookmark_poll = (poll) => {
      if (poll.bookmarked) {
        toast.error('You are already bookmark ' + poll.title, 'Error!');
        return;
      }
      Action.save_bookmark(poll._id)
        .then(res => {
          poll.bookmarked = (res) ? true : false;
          toast.success('Added ' + poll.title + ' to bookmarks.', 'Success!');
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
        });
    };
    $scope.follow_poll = (poll) => {
      if (!$scope.isLogged) {
        toast.error('You must login to follow poll.', 'Error!');
        return;
      }
      Action.save_follow(poll.follow)
        .then(res => {
          poll.follow = res;
          if (poll.follow.following) {
            toast.success('You followed ' + poll.title, 'Success!');
          }
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
        });
    };
  }
]);
<commit_msg>Commited from lenh at Fri, Jul 21, 2017  4:45:52 PM<commit_after>'use strict';

angular.module('polls').controller('PollsSearchController', [
  '$location',
  '$scope',
  '$state',
  'Authentication',
  'CategorysService',
  'Action',
  '$stateParams',
  'Storages',
  'Constants',
  'toastr',
  'ngDialog',
  'Profile',
  function ($location, $scope, $state, Authentication, Categorys, Action, $stateParams, Storages, Constants, toast, dialog, Profile) {
    $scope.user = Authentication.user;
    $scope.isLogged = ($scope.user) ? true : false;
    $scope.detailToggle = -1;
    $scope.form = {};
    $scope.categorys = Categorys.query();

    $scope.condition = {};
    $scope.condition.key = $stateParams.key;
    $scope.condition.in = $stateParams.in;
    $scope.condition.status = $stateParams.status;
    $scope.condition.ctgr = $stateParams.ctgr;

    $scope.condition.cmt = $stateParams.cmt;
    $scope.condition.compare = $stateParams.compare;

    $scope.condition.created = $stateParams.created;
    $scope.condition.timing = $stateParams.timing;

    $scope.condition.sort = $stateParams.sort;
    $scope.condition.sortkind = $stateParams.sortkind;

    $scope.condition.by = $stateParams.by;
    if ($scope.condition.by) {
      Profile.get({ userId: $scope.condition.by }, _user => {
        $scope.selectedUser = _user;
      });
    }
    $scope.search = () => {
      $state.go('search', $scope.condition);
    };

    $scope.busy = false;
    $scope.polls = [];
    $scope.sort = '-poll.created';
    excute();
    function excute() {
      if (check_params()) {
        $scope.busy = true;
        Action.search($scope.condition)
          .then(res => {
            $scope.polls = res.data;
            var promise = [];
            $scope.polls.forEach(function (item) {
              promise.push(get_owner_follow(item.poll));
              promise.push(get_reported(item.poll));
              promise.push(get_bookmarked(item.poll));
            }, this);
            return Promise.all(promise);
          })
          .then(res => {
            create_sort();
            $scope.busy = false;
          })
          .catch(err => {
            $scope.busy = false;
            console.log(err);
          });
      } else {
        $scope.condition = JSON.parse(Storages.get_local(Constants.storages.preferences, JSON.stringify({})));
      }
    }
    function check_params() {
      if ($scope.condition.key || $scope.condition.status || $scope.condition.by || $scope.condition.ctgr || $scope.condition.cmt || $scope.condition.created) {
        return true;
      }
      return false;
    }
    function create_sort() {
      if ($scope.condition.sort) {
        var prefix = ($scope.condition.sort === 'created') ? 'poll.' : 'report.';
        var kind = ($scope.condition.sortkind === 'desc') ? '-' : '';
        $scope.sort = kind + prefix + $scope.condition.sort;
      }
    }

    function get_owner_follow(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.follow = {};
          return resolve();
        }
        Action.get_follow(poll._id)
          .then(res => {
            poll.follow = res.data || { poll: poll._id };
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    function get_reported(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.reported = false;
          return resolve();
        }
        Action.get_report(poll._id)
          .then(res => {
            poll.reported = (res.data) ? res.data : false;
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    function get_bookmarked(poll) {
      return new Promise((resolve, reject) => {
        if (!$scope.isLogged) {
          poll.bookmarked = false;
          return resolve();
        }
        Action.get_bookmark(poll._id)
          .then(res => {
            poll.bookmarked = (res.data) ? res.data : false;
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }
    $scope.selectedUserFn = function (selected) {
      if (selected) {
        $scope.condition.by = selected.originalObject._id;
        $scope.selectedUser = selected.originalObject;
      } else {
        $scope.condition.by = undefined;
        $scope.selectedUser = undefined;
      }
    };
    $scope.clear_preferences = () => {
      $scope.condition = {};
      $scope.selectedUser = undefined;
      Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition));
      // $location.url($location.path());
      $state.go('search', {}, {notify: false})
    };
    $scope.save_preferences = () => {
      Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition));
    };
    $scope.delete_poll = (poll) => {
      if (poll.user._id !== $scope.user._id) {
        toast.error('You are not authorized.', 'Error!');
        return;
      }
      $scope.message_title = 'Delete poll!';
      $scope.message_content = 'Are you sure you want to delete this poll?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        $scope.polls = _.reject($scope.polls, function (item) {
          return item.poll._id === poll._id;
        });
        // Action.delete_poll(poll);
      }
    };
    $scope.report_poll = (poll) => {
      if (poll.reported) {
        toast.error('You are already reported ' + poll.title, 'Error!');
        return;
      }
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/report.dialog.template.html'
      }).then(reason => {
        handle_confirm(reason);
      }, reject => {
      });
      function handle_confirm(reason) {
        Action.save_report(poll._id, reason)
          .then(res => {
            poll.reported = (res) ? true : false;
            toast.success('You have successfully reported ' + poll.title, 'Thank you!');
          })
          .catch(err => {
            toast.error(err.message, 'Error!');
          });
      }
    };
    $scope.bookmark_poll = (poll) => {
      if (poll.bookmarked) {
        toast.error('You are already bookmark ' + poll.title, 'Error!');
        return;
      }
      Action.save_bookmark(poll._id)
        .then(res => {
          poll.bookmarked = (res) ? true : false;
          toast.success('Added ' + poll.title + ' to bookmarks.', 'Success!');
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
        });
    };
    $scope.follow_poll = (poll) => {
      if (!$scope.isLogged) {
        toast.error('You must login to follow poll.', 'Error!');
        return;
      }
      Action.save_follow(poll.follow)
        .then(res => {
          poll.follow = res;
          if (poll.follow.following) {
            toast.success('You followed ' + poll.title, 'Success!');
          }
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
        });
    };
  }
]);
<|endoftext|>


<commit_before>'use strict';

var base = require('xdg-basedir');
var fs = require('fs');
var mount = require('mount-point');
var path = require('path');

/**
 * Get the correct trash path on Linux
 *
 * @param {String} file
 * @param {Function} cb
 * @api public
 */

module.exports = function (file, cb) {
	if (typeof file === 'function' && !cb) {
		cb = file;
		file = undefined;
	}

	if (process.platform !== 'linux') {
		throw new Error('Only Linux systems are supported');
	}

	if (!file) {
		cb(null, path.join(base.data, 'Trash'));
		return;
	}

	mount(file, function (err, res) {
		if (err) {
			cb(err);
			return;
		}

		if (res.mount === '/') {
			cb(null, path.join(base.data, 'Trash'));
			return;
		}

		var top = path.join(res.mount, '.Trash');
		var topuid = top + '-' + process.getuid();
		var stickyBitMode = 17407;

		fs.exists(top, function (exists) {
			if (!exists) {
				cb(null, topuid);
				return;
			}

			fs.lstat(top, function (err, stats) {
				if (err) {
					cb(null, path.join(base.data, 'Trash'));
					return;
				}

				if (stats.isSymbolicLink() || stats.mode !== stickyBitMode) {
					cb(null, topuid);
					return;
				}

				cb(null, path.join(top, String(process.getuid())));
			});
		});
	});
};
<commit_msg>`HOME` could exist on the `/home` partition<commit_after>'use strict';

var base = require('xdg-basedir');
var fs = require('fs');
var mount = require('mount-point');
var path = require('path');

/**
 * Get the correct trash path on Linux
 *
 * @param {String} file
 * @param {Function} cb
 * @api public
 */

module.exports = function (file, cb) {
	if (typeof file === 'function' && !cb) {
		cb = file;
		file = undefined;
	}

	if (process.platform !== 'linux') {
		throw new Error('Only Linux systems are supported');
	}

	if (!file) {
		cb(null, path.join(base.data, 'Trash'));
		return;
	}

	mount(file, function (err, res) {
		if (err) {
			cb(err);
			return;
		}

		if (res.mount === '/' || res.mount === '/home') {
			cb(null, path.join(base.data, 'Trash'));
			return;
		}

		var top = path.join(res.mount, '.Trash');
		var topuid = top + '-' + process.getuid();
		var stickyBitMode = 17407;

		fs.exists(top, function (exists) {
			if (!exists) {
				cb(null, topuid);
				return;
			}

			fs.lstat(top, function (err, stats) {
				if (err) {
					cb(null, path.join(base.data, 'Trash'));
					return;
				}

				if (stats.isSymbolicLink() || stats.mode !== stickyBitMode) {
					cb(null, topuid);
					return;
				}

				cb(null, path.join(top, String(process.getuid())));
			});
		});
	});
};
<|endoftext|>


<commit_before>'use strict';

exports = module.exports = {};

// dependencies
//
exports.inherits = require('util').inherits;

// library dependencies
//
exports.npmize = require('./npmize');

// assorted
//
exports.formatStack = function formatStack(stack){
  return (
    exports.npmize(stack) + '\n--\n' +
    'cwd ' + process.cwd() + '\n' +
    'node-'+ process.version + ' ' + new Date().toISOString()
  );
};
<commit_msg>lint: infix operators and spaces<commit_after>'use strict';

exports = module.exports = {};

// dependencies
//
exports.inherits = require('util').inherits;

// library dependencies
//
exports.npmize = require('./npmize');

// assorted
//
exports.formatStack = function formatStack(stack){
  return (
    exports.npmize(stack) + '\n--\n' +
    'cwd ' + process.cwd() + '\n' +
    'node-' + process.version + ' ' + new Date().toISOString()
  );
};
<|endoftext|>