<commit_before>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var util = require('../util');
var common = require('../common');
var css2str = require('../css2str');
var debug = require('debug')('transport:css2js');

function parser(options){
  return common.createStream(options, 'css', transport);
}

function transport(file, options){
  var id = common.transportId(file, options, true);
  var deps = common.transportCssDeps(file, options, true);

  // get code
  var code = '';

  // get code
  deps.forEach(function (id){
    code += "require('" + id + "');\n";
  });

  // push import-style module dependencies
  deps.push('import-style');

  // import import
  code += "require('import-import')('" + css2str(file.contents, options) + "');";

  file.contents = new Buffer(util.wrapModule(id, deps, code));

  // debug
  debug(util.colors.infoBold('transport css2js file ok'));

  return file;
}

module.exports = parser;<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var util = require('../util');
var common = require('../common');
var css2str = require('../css2str');
var debug = require('debug')('transport:css2js');

function parser(options){
  return common.createStream(options, 'css', transport);
}

function transport(file, options){
  var id = common.transportId(file, options, true);
  var deps = common.transportCssDeps(file, options, true);

  // get code
  var code = '';

  // get code
  deps.forEach(function (id){
    code += "require('" + id + "');\n";
  });

  // push import-style module dependencies
  deps.push('import-style');

  // import import
  code += "require('import-import')('" + css2str(file.contents, options) + "');";

  file.contents = new Buffer(util.wrapModule(id, deps, code));

  // debug
  debug(util.colors.infoBold('transport css to js file ok'));

  return file;
}

module.exports = parser;<|endoftext|>


<commit_before>var _ = require('lodash');
var debug = require('debug')('4front:logout');

// Simple middleware that logs the user out by destroying any session cookie
// and redirecting to the index page.
module.exports = function(options) {
  options = _.defaults(options || {}, {
    sessionCookieName: 'sid',
    redirectUrl: '/'
  });

  return function(req, res, next) {
    debug('logging out');
    if (req.session)
      req.session.destroy();

    res.clearCookie(options.sessionCookieName);
    res.redirect(options.redirectUrl);
  };
};
<commit_msg>Get session cookie name from req.session object<commit_after>var _ = require('lodash');
var debug = require('debug')('4front:logout');

// Simple middleware that logs the user out by destroying any session cookie
// and redirecting to the index page.
module.exports = function(options) {
  options = _.defaults(options || {}, {
    redirectUrl: '/'
  });

  return function(req, res, next) {
    debug('logging out');
    if (req.session) {
      req.session.destroy();
      res.clearCookie(req.session.cookie.name);
    }

    res.redirect(options.redirectUrl);
  };
};
<|endoftext|>


<commit_before>// Based on: https://raw.github.com/imathis/octopress/master/plugins/backtick_code_block.rb

var extend = require('../extend'),
  renderer = Object.keys(extend.renderer.list()),
  tag = extend.tag.list(),
  render = require('../render'),
  util = require('../util'),
  file = util.file,
  yfm = util.yfm,
  highlight = util.highlight,
  path = require('path'),
  fs = require('fs'),
  async = require('async'),
  swig = require('swig'),
  _ = require('underscore'),
  config = hexo.config;

swig.init({tags: tag});

var regex = {
  codeBlock: /`{3} *([^\n]+)?\n(.+?)\n`{3}/,
  AllOptions: /([^\s]+)\s+(.+?)(https?:\/\/\S+)\s*(.+)?/i,
  LangCaption: /([^\s]+)\s*(.+)?/i
};

var load = function(source, callback){
  var extname = path.extname(source),
    moment = require('../moment');

  async.waterfall([
    function(next){
      file.read(source, function(err, result){
        if (err) throw err;

        fs.stat(source, function(err, stats){
          if (err) throw err;
          next(null, result, stats);
        });
      });
    },
    function(file, stats, next){
      var meta = yfm(file);

      meta.date = _.isDate(meta.date) ? moment(meta.date) : moment(meta.date, 'YYYY-MM-DD HH:mm:ss');
      meta.stats = stats;
      meta.source = source;

      if (meta.updated) meta.updated = _.isDate(meta.updated) ? moment(meta.date) : moment(meta.date, 'YYYY-MM-DD HH:mm:ss');
      else meta.updated = moment(stats.mtime);

      var compiled = swig.compile(meta._content)().replace(regex.codeBlock, function(match, args, str){
        if (!args) return match;

        var captionPart = args.match(regex.AllOptions);
        if (captionPart){
          var lang = captionPart[1],
            caption = '' + captionPart[2] + '' + (captionPart[4] ? captionPart[4] : 'link') + '';
        } else {
          var captionPart = args.match(regex.LangCaption);

          if (!captionPart[2]) return match;

          if (captionPart){
            var lang = captionPart[1],
              caption = '' + captionPart[2] + '';
          }
        }

        return '<notextile>' + highlight(str, {lang: lang, caption: caption}) + '</notextile>';
      });

      render.render(compiled, extname.substring(1), function(err, result){
        if (err) throw err;

        delete meta._content;
        meta.content = result.replace(/<\/?notextile>/g, '');

        callback(meta);
      });
    }
  ]);
};

var loadPost = function(source, category, callback){
  var extname = path.extname(source),
    filename = path.basename(source, extname);

  load(source, function(meta){
    if (_.isArray(meta.tags)){
      meta.tags = _.map(meta.tags, function(item){
        var tagPath = config.tag_dir + '/' + item + '/';

        return {
          name: item,
          path: tagPath,
          permalink: config.url + '/' + tagPath
        };
      });
    } else if (meta.tags) {
      var postTag = meta.tags.toString();
      meta.tags = [{name: postTag, permalink: config.tag_dir + '/' + postTag + '/'}];
    }

    if (category){
      var categories = category.split(path.sep);

      meta.categories = [];

      _.each(categories, function(item, i){
        var catPath = categories.slice(0, i + 1).join('/') + '/';

        meta.categories.push({
          name: item,
          path: catPath,
          permalink: config.url + '/' + catPath
        });
      });
    }

    var date = meta.date;

    if (meta.permalink){
      var link = meta.permalink;
      if (!path.extname(link) && link.substr(link.length - 1, 1) !== '/') meta.path += '/';
    } else {
      if (config.permalink){
        if (!path.extname(config.permalink) && config.permalink.substr(config.permalink.length - 1, 1) !== '/') config.permalink += '/';

        meta.path = config.permalink
          .replace(/:category/, category ? category : config.category_dir)
          .replace(/:year/, date.format('YYYY'))
          .replace(/:month/, date.format('MM'))
          .replace(/:day/, date.format('DD'))
          .replace(/:title/, filename);
      } else {
        meta.path = date.format('YYYY/MM/DD') + '/' + filename;
      }
    }

    meta.permalink = config.url + '/' + meta.path;

    callback(meta);
  });
};

var loadPage = function(source, category, callback){
  var extname = path.extname(source);

  load(source, function(meta){
    if (meta.permalink){
      var link = meta.permalink;

      if (!path.extname(link)){
        if (link.substr(link.length - 1, 1) === '/'){
          meta.path += 'index.html';
        } else {
          meta.path += '/index.html';
        }
      }
    } else {
      meta.path = category.replace(extname, '.html');
    }

    meta.permalink = config.url + '/' + meta.path;

    callback(meta);
  });
};

extend.processor.register(function(locals, callback){
  var source = hexo.source_dir;

  console.log('Loading source files.');

  file.dir(source, function(files){
    async.forEach(files, function(item, next){
      var extname = path.extname(item),
        dirs = item.split('/');

      if (dirs[0] === '_posts'){
        var category = dirs.slice(1);

        for (var i=0, len=category.length; i<len; i++){
          var front = category[i].substring(0, 1);

          if (front === '_' || front === '.'){
            return next();
          }
        }

        if (_.indexOf(renderer, extname.substring(1)) !== -1){
          loadPost(source + item, category.reverse().slice(1).reverse().join('/'), function(post){
            locals.posts.push(post);
            next();
          });
        } else {
          next();
        }
      } else {
        for (var i=0, len=dirs.length; i<len; i++){
          var front = dirs[i].substring(0, 1);

          if (front === '_' || front === '.'){
            return next();
          }
        }

        if (_.indexOf(renderer, extname.substring(1)) !== -1){
          loadPage(source + item, item, function(page){
            locals.pages.push(page);
            next();
          });
        } else {
          file.copy(source + item, hexo.public_dir + item, next);
        }
      }
    }, function(err){
      callback(err, locals);
    });
  });
});<commit_msg>Fixed "permalink" parameter in article not work<commit_after>// Based on: https://raw.github.com/imathis/octopress/master/plugins/backtick_code_block.rb

var extend = require('../extend'),
  renderer = Object.keys(extend.renderer.list()),
  tag = extend.tag.list(),
  render = require('../render'),
  util = require('../util'),
  file = util.file,
  yfm = util.yfm,
  highlight = util.highlight,
  path = require('path'),
  fs = require('fs'),
  async = require('async'),
  swig = require('swig'),
  _ = require('underscore'),
  config = hexo.config;

swig.init({tags: tag});

var regex = {
  codeBlock: /`{3} *([^\n]+)?\n(.+?)\n`{3}/,
  AllOptions: /([^\s]+)\s+(.+?)(https?:\/\/\S+)\s*(.+)?/i,
  LangCaption: /([^\s]+)\s*(.+)?/i
};

var load = function(source, callback){
  var extname = path.extname(source),
    moment = require('../moment');

  async.waterfall([
    function(next){
      file.read(source, function(err, result){
        if (err) throw err;

        fs.stat(source, function(err, stats){
          if (err) throw err;
          next(null, result, stats);
        });
      });
    },
    function(file, stats, next){
      var meta = yfm(file);

      meta.date = _.isDate(meta.date) ? moment(meta.date) : moment(meta.date, 'YYYY-MM-DD HH:mm:ss');
      meta.stats = stats;
      meta.source = source;

      if (meta.updated) meta.updated = _.isDate(meta.updated) ? moment(meta.date) : moment(meta.date, 'YYYY-MM-DD HH:mm:ss');
      else meta.updated = moment(stats.mtime);

      var compiled = swig.compile(meta._content)().replace(regex.codeBlock, function(match, args, str){
        if (!args) return match;

        var captionPart = args.match(regex.AllOptions);
        if (captionPart){
          var lang = captionPart[1],
            caption = '' + captionPart[2] + '' + (captionPart[4] ? captionPart[4] : 'link') + '';
        } else {
          var captionPart = args.match(regex.LangCaption);

          if (!captionPart[2]) return match;

          if (captionPart){
            var lang = captionPart[1],
              caption = '' + captionPart[2] + '';
          }
        }

        return '<notextile>' + highlight(str, {lang: lang, caption: caption}) + '</notextile>';
      });

      render.render(compiled, extname.substring(1), function(err, result){
        if (err) throw err;

        delete meta._content;
        meta.content = result.replace(/<\/?notextile>/g, '');

        callback(meta);
      });
    }
  ]);
};

var loadPost = function(source, category, callback){
  var extname = path.extname(source),
    filename = path.basename(source, extname);

  load(source, function(meta){
    if (_.isArray(meta.tags)){
      meta.tags = _.map(meta.tags, function(item){
        var tagPath = config.tag_dir + '/' + item + '/';

        return {
          name: item,
          path: tagPath,
          permalink: config.url + '/' + tagPath
        };
      });
    } else if (meta.tags) {
      var postTag = meta.tags.toString();
      meta.tags = [{name: postTag, permalink: config.tag_dir + '/' + postTag + '/'}];
    }

    if (category){
      var categories = category.split(path.sep);

      meta.categories = [];

      _.each(categories, function(item, i){
        var catPath = categories.slice(0, i + 1).join('/') + '/';

        meta.categories.push({
          name: item,
          path: catPath,
          permalink: config.url + '/' + catPath
        });
      });
    }

    var date = meta.date;

    if (meta.permalink){
      var link = meta.permalink;
      if (!path.extname(link) && link.substr(link.length - 1, 1) !== '/') meta.path = meta.permalink + '/';
    } else {
      if (config.permalink){
        if (!path.extname(config.permalink) && config.permalink.substr(config.permalink.length - 1, 1) !== '/') config.permalink += '/';

        meta.path = config.permalink
          .replace(/:category/, category ? category : config.category_dir)
          .replace(/:year/, date.format('YYYY'))
          .replace(/:month/, date.format('MM'))
          .replace(/:day/, date.format('DD'))
          .replace(/:title/, filename);
      } else {
        meta.path = date.format('YYYY/MM/DD') + '/' + filename;
      }
    }

    meta.permalink = config.url + '/' + meta.path;

    callback(meta);
  });
};

var loadPage = function(source, category, callback){
  var extname = path.extname(source);

  load(source, function(meta){
    if (meta.permalink){
      var link = meta.permalink;

      if (!path.extname(link)){
        if (link.substr(link.length - 1, 1) === '/'){
          meta.path += 'index.html';
        } else {
          meta.path += '/index.html';
        }
      }
    } else {
      meta.path = category.replace(extname, '.html');
    }

    meta.permalink = config.url + '/' + meta.path;

    callback(meta);
  });
};

extend.processor.register(function(locals, callback){
  var source = hexo.source_dir;

  console.log('Loading source files.');

  file.dir(source, function(files){
    async.forEach(files, function(item, next){
      var extname = path.extname(item),
        dirs = item.split('/');

      if (dirs[0] === '_posts'){
        var category = dirs.slice(1);

        for (var i=0, len=category.length; i<len; i++){
          var front = category[i].substring(0, 1);

          if (front === '_' || front === '.'){
            return next();
          }
        }

        if (_.indexOf(renderer, extname.substring(1)) !== -1){
          loadPost(source + item, category.reverse().slice(1).reverse().join('/'), function(post){
            locals.posts.push(post);
            next();
          });
        } else {
          next();
        }
      } else {
        for (var i=0, len=dirs.length; i<len; i++){
          var front = dirs[i].substring(0, 1);

          if (front === '_' || front === '.'){
            return next();
          }
        }

        if (_.indexOf(renderer, extname.substring(1)) !== -1){
          loadPage(source + item, item, function(page){
            locals.pages.push(page);
            next();
          });
        } else {
          file.copy(source + item, hexo.public_dir + item, next);
        }
      }
    }, function(err){
      callback(err, locals);
    });
  });
});<|endoftext|>


<commit_before>'use strict'
var Observable = require('vigour-js/lib/observable')
var ua = require('vigour-ua')
var isNode = require('vigour-js/lib/util/is/node')
var is = require('vigour-js/lib/observable/is')

module.exports = new Observable({
  useVal: true,
  properties: {
    Connection: true,
    ServerConnection: true,
    connections: true,
    internal: true
  },
  connected: {
    val: false,
    inject: is
  },
  reconnecting: {
    val: false,
    inject: is
  },
  on: {
    value: {
      upstream (data, event) {
        if (!this.hasOwnProperty('client')) {
          let upstream = this.val
          if (!upstream) {
            this.emit('error', 'no upstream')
            return
          }

          let hub = this.parent.parent
          let adapter = this.parent
          let id = this.lookUp('id')
          let set = { val: id }
          let connection
          let protocol = this

          if (isNode) {
            set.platform = 'node'
          } else {
            ua(window.navigator.userAgent, set)
          }

          hub.set({ clients: { [id]: set } }, false)
          let client = hub.clients[id]
          this.set({ client: client }, false)
          if (!this.connections) {
            this.connections = {}
          }

          if (!this.connections[upstream]) {
            this.connections[upstream] = connection = new this.Connection({ upstream: this })
          } else {
            connection = this.connections[upstream]
          }

          client.set({ connection: connection }, false)
          // not good for cleaning up make these attach listeners (so they get removed when you remove the protoicol)
          connection
            .on('message', (data) => {
              adapter.receive(data, 'upstream')
            })
            .on('close', (data, event) => {
              this.connected.val = false

              // console.log( this.parent.parent.clients )
              this.parent.parent.clients.each((client, key) => {
                // if (key !== id && c/lient.remove) {
                  // client.remove()
                // }
              })
              // this.parent.parent.clients.clear()

              this.emit('close', data, event)
            })
            .on('reconnect', (data, event) => {
              this.reconnecting.val = true
              this.emit('reconnect', data, event)
            })
            .on('connect', function (data, event) {
              protocol.reconnecting.val = false
              protocol.connected.val = true
              var payload = {
                client: client.serialize(),
                stamp: event.stamp
              }

              if (client.subscriptions) {
                // console.log(client.subscriptions)
                payload.client.subscriptions = client.subscriptions
              }

              if (adapter.scope.val) {
                payload.scope = adapter.scope.val
              }
              this.push(payload)
              // push
              // this.send(payload)
              protocol.emit('connect', data, event)
            })
        } else {
          // console.warn('allready have client this is only a switch', this.path)
          // be extra carefull here when trying to do scope fixes!
        }
      }
    }
  }
}).Constructor
<commit_msg>remove clients when disconnecting<commit_after>'use strict'
var Observable = require('vigour-js/lib/observable')
var ua = require('vigour-ua')
var isNode = require('vigour-js/lib/util/is/node')
var is = require('vigour-js/lib/observable/is')

module.exports = new Observable({
  useVal: true,
  properties: {
    Connection: true,
    ServerConnection: true,
    connections: true,
    internal: true
  },
  connected: {
    val: false,
    inject: is
  },
  reconnecting: {
    val: false,
    inject: is
  },
  on: {
    value: {
      upstream (data, event) {
        if (!this.hasOwnProperty('client')) {
          let upstream = this.val
          if (!upstream) {
            this.emit('error', 'no upstream')
            return
          }

          let hub = this.parent.parent
          let adapter = this.parent
          let id = this.lookUp('id')
          let set = { val: id }
          let connection
          let protocol = this

          if (isNode) {
            set.platform = 'node'
          } else {
            ua(window.navigator.userAgent, set)
          }

          hub.set({ clients: { [id]: set } }, false)
          let client = hub.clients[id]
          this.set({ client: client }, false)
          if (!this.connections) {
            this.connections = {}
          }

          if (!this.connections[upstream]) {
            this.connections[upstream] = connection = new this.Connection({ upstream: this })
          } else {
            connection = this.connections[upstream]
          }

          client.set({ connection: connection }, false)
          // not good for cleaning up make these attach listeners (so they get removed when you remove the protoicol)
          connection
            .on('message', (data) => {
              adapter.receive(data, 'upstream')
            })
            .on('close', (data, event) => {
              this.connected.val = false

              // console.log( this.parent.parent.clients )
              this.parent.parent.clients.each((client, key) => {
                if (key !== id && client.remove) {
                  client.remove()
                }
              })
              // this.parent.parent.clients.clear()

              this.emit('close', data, event)
            })
            .on('reconnect', (data, event) => {
              this.reconnecting.val = true
              this.emit('reconnect', data, event)
            })
            .on('connect', function (data, event) {
              protocol.reconnecting.val = false
              protocol.connected.val = true
              var payload = {
                client: client.serialize(),
                stamp: event.stamp
              }

              if (client.subscriptions) {
                // console.log(client.subscriptions)
                payload.client.subscriptions = client.subscriptions
              }

              if (adapter.scope.val) {
                payload.scope = adapter.scope.val
              }
              this.push(payload)
              // push
              // this.send(payload)
              protocol.emit('connect', data, event)
            })
        } else {
          // console.warn('allready have client this is only a switch', this.path)
          // be extra carefull here when trying to do scope fixes!
        }
      }
    }
  }
}).Constructor
<|endoftext|>


<commit_before>var _modals = {};
ReactiveModal = function(){
  // EV.call(this);
  this.buttons = {};
};
// _.extend(ReactiveModal.prototype, EV.prototype);
Template._reactiveModal.helpers({
  class: function(){
    var att;
    if(this.class){
      att = 'btn ' + this.class;
    }
    return att;
  },
  disabled: function(){
    if (this.button.disabled.get()) {
      return "disabled"
    } else {
      return null;
    }
  },
  dismiss: function(){
    if(this.button.closeModalOnClick){
      return "modal";
    }
  },
  arrayify: function(obj){
    result = [];
    for (var key in obj) result.push({name:key,button:obj[key]});
    return result;
  }
});

Template._reactiveModal.events({
  'click .modal-footer .reactive-modal-btn.btn': function(e){
    this.button.emit('click', this.button);
  }
});

ReactiveModal.initDialog = function (info){
  var key = "rm-"+Meteor.uuid();
  if(!info || !info.template){
    console.error("you must define a template for " , key);
  } else {
    info.key = key;
    _modals[key] = info;

    for(var button in info.buttons){
      var newButton = _.clone(info.buttons[button]);
      _.extend(newButton, new EV());
      info.buttons[button] = newButton;
      newButton.closeModalOnClick = (info.buttons[button].closeModalOnClick === undefined || info.buttons[button].closeModalOnClick === true) ? true : false;
      new ReactiveVar((info.buttons[button].disabled === undefined || info.buttons[button].disabled === false || (info.buttons[button].disabled instanceof ReactiveVar && info.buttons[button].disabled.curValue===false)) ? false : true);
      newButton.disable =  function () {newButton.disabled.set(true);},
      newButton.enable = function () {newButton.disabled.set(false);}
    };

    Blaze.renderWithData(Template._reactiveModal, info, document.body);
  }

  var modalTarget = $('#' + key);
  info.show = function(){
    modalTarget.modal('show');
  }
  info.hide = function(){
    modalTarget.modal('hide');
  }

  if (info.removeOnHide) {
    modalTarget.on('hidden.bs.modal', function() {
      $(this).remove();
    });
  }

  info.modalTarget = modalTarget;
  return info;
};
<commit_msg>fix error introduced in branch related to .disabled<commit_after>var _modals = {};
ReactiveModal = function(){
  // EV.call(this);
  this.buttons = {};
};
// _.extend(ReactiveModal.prototype, EV.prototype);
Template._reactiveModal.helpers({
  class: function(){
    var att;
    if(this.class){
      att = 'btn ' + this.class;
    }
    return att;
  },
  disabled: function(){
    if (this.button.disabled.get()) {
      return "disabled"
    } else {
      return null;
    }
  },
  dismiss: function(){
    if(this.button.closeModalOnClick){
      return "modal";
    }
  },
  arrayify: function(obj){
    result = [];
    for (var key in obj) result.push({name:key,button:obj[key]});
    return result;
  }
});

Template._reactiveModal.events({
  'click .modal-footer .reactive-modal-btn.btn': function(e){
    this.button.emit('click', this.button);
  }
});

ReactiveModal.initDialog = function (info){
  var key = "rm-"+Meteor.uuid();
  if(!info || !info.template){
    console.error("you must define a template for " , key);
  } else {
    info.key = key;
    _modals[key] = info;

    for(var button in info.buttons){
      var newButton = _.clone(info.buttons[button]);
      _.extend(newButton, new EV());
      info.buttons[button] = newButton;
      newButton.closeModalOnClick = (info.buttons[button].closeModalOnClick === undefined || info.buttons[button].closeModalOnClick === true) ? true : false;
      newButton.disabled = new ReactiveVar((info.buttons[button].disabled === undefined || info.buttons[button].disabled === false || (info.buttons[button].disabled instanceof ReactiveVar && info.buttons[button].disabled.curValue===false)) ? false : true);
      newButton.disable =  function () {newButton.disabled.set(true);},
      newButton.enable = function () {newButton.disabled.set(false);}
    };

    Blaze.renderWithData(Template._reactiveModal, info, document.body);
  }

  var modalTarget = $('#' + key);
  info.show = function(){
    modalTarget.modal('show');
  }
  info.hide = function(){
    modalTarget.modal('hide');
  }

  if (info.removeOnHide) {
    modalTarget.on('hidden.bs.modal', function() {
      $(this).remove();
    });
  }

  info.modalTarget = modalTarget;
  return info;
};
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var util = require('util'),
    Base = require('./base'),
    fs = require('fs'),
    path = require('path'),
    sanitizeCaps = require('../helpers/sanitize').caps;

/**
 * Initialize a new `XUnit` reporter.
 *
 * @param {Runner} runner
 * @api public
 */
function XUnit(options) {
    Base.call(this);

    var tests = this.tests = {},
        runnerData = this.runnerData = {},
        self = this,
        id = 0;

    this.errorLogCharacterLimitation = 10000;
    this.indents = 0;
    this.errors = 0;
    this.options = options;

    /**
     * remember which tests got executed by runner
     */
    this.on('runner:start', function(runner) {
        tests[runner.pid] = [{
            start: new Date(),
            tests: [],
            root: true,
            /**
             * problematic by setting end date when runner started:
             * `<testsuites />` time will include computation time of all before/after hooks, that
             * results in a bigger time value then all time values of its `<testsuite/>` summed
             * together
             */
            end: new Date(),
        }];

        runnerData[runner.pid] = {
            command: [],
            result: [],
            error: []
        };
    });

    this.on('runner:command', function(data) {
        runnerData[data.pid].command.push(data);
    });
    this.on('runner:result', function(data) {
        runnerData[data.pid].result.push(data);
    });
    this.on('runner:error', function(data) {
        self.errors++;
        runnerData[data.pid].error.push(data);
    });

    /**
     * clear runnerData cache
     */
    this.on('test:start', function(test) {
        runnerData[test.pid] = {
            command: [],
            result: [],
            error: []
        };
    });

    this.on('suite:start', function(suite){
        suite.id = ++id;
        suite.tests = [];
        suite.passes = 0;
        suite.pending = 0;
        suite.failures = 0;
        suite.timestamp = new Date();

        /**
         * root suites
         */
        if(suite.parent === '' || !suite.parent) {
            tests[suite.pid][0].tests.push(suite);
            return;
        }

        var parentSuite = this.findParentSuite(suite.parent, this.tests[suite.pid][0]);
        parentSuite.tests.push(suite);
    });

    this.on('test:pending', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.pending++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
        test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('test:pass', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.passes++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
        test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('test:fail', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.failures++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
        test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('end', function() {
        Object.keys(tests).forEach(function(pid) {
            self.genTestsuites(tests[pid], pid);
        });
    });
}

/**
 * Inherit from Base
 */
util.inherits(XUnit, Base);

function escape(html){
  return String(html)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/\r?\n|\r/g, '');
}

XUnit.prototype.findParentSuite = function(title, suite) {
    var _suite = null;

    for(var i = 0; i < suite.tests.length; ++i) {
        if(suite.tests[i].title === title) {
            return suite.tests[i];
        }

        if(suite.tests[i].tests) {
            _suite = _suite || this.findParentSuite(title, suite.tests[i]);
        }
    }

    return _suite;
};

/**
 * generate junit report
 */
XUnit.prototype.genTestsuites = function(tests, pid) {

    var caps = this.stats.runner[pid].capabilities,
        options = this.options.reporterOptions,
        filename = 'WDIO.xunit.' + sanitizeCaps(caps) + '.' + pid + '.xml';

    if (options && typeof options.outputDir === 'string') {
        this.fileStream = fs.createWriteStream(path.join(process.cwd(), options.outputDir, filename));
    }

    /**
     * root testsuites tag
     */
    this.write(tag('testsuites', {
        name: sanitizeCaps(caps),
        tests: this.stats.tests,
        failures: this.stats.failures,
        errors: this.errors,
        disabled: this.stats.pending,
        time: this.stats.duration / 1000
    }));

    this.indents++;
    this.genTestsuite(tests[0].tests);
    this.indents--;

    this.write('</testsuites>');

    if (this.fileStream) {
        this.fileStream.end();
    }
};

function sumTime(suite) {
    var res = 0;

    for(var i = 0; i < suite.tests.length; ++i) {
        if(suite.tests[i].tests) {
            res += sumTime(suite.tests[i]);
        } else {
            res += suite.tests[i].time;
        }
    }

    return res;
}

XUnit.prototype.printLogTags = function(data, tagName, type, iter) {
    var content = '';

    for(var i = 0; i < data.length; ++i) {
        content += iter(data[i]);
    }

    if(content !== '') {
        content = cdata('\n' + content);
        this.indents++;
        this.write(tag(tagName, {
            type: type
        }, false, content));
        this.indents--;
    }
};

/**
 * generate testsuites markup
 */
XUnit.prototype.genTestsuite = function(tests) {

    var self = this;

    tests.forEach(function(test) {

        /**
         * write test suite
         */
        if(test.tests) {
            self.write(tag('testsuite', {
                name: test.title,
                tests: test.pending + test.passes + test.failures,
                failures: test.failures,
                // errors: test.failures,
                skipped: test.pending,
                disabled: test.pending,
                time: sumTime(test) / 1000,
                timestamp: test.timestamp,
                id: test.id,
                file: test.file
            }));

            self.indents++;
            self.genTestsuite(test.tests);
            self.indents--;

            self.write('</testsuite>');
            return;
        }

        /**
         * write testcase
         */
        self.write(tag('testcase', {
            name: test.title,
            disabled: test.pending,
            time: test.time / 1000,
            id: test.id,
            file: test.file,
            status: test.err && Object.getOwnPropertyNames(test.err).length === 0 ? 'passed' : 'failed',
            classname: sanitizeCaps(self.stats.runner[test.pid].capabilities)
        }));

        /**
         * print skipped tags
         */
        if(test.pending) {

            self.indents++;
            self.write(tag('skipped', {}, true));
            self.indents--;

            self.write('</testcase>');
            return;

        /**
         * print failure tags
         */
        } else if(Object.getOwnPropertyNames(test.err).length > 0) {
            var content = cdata((test.err.stack || '').slice(0, self.errorLogCharacterLimitation));

            self.indents++;
            self.write(tag('failure', {
                type: 'testerror',
                message: escape(test.err.message)
            }, false, content));
            self.indents--;

        }

        /**
         * print runner logs
         */
        self.printLogTags(test.runnerData.command, 'system-out', 'command', function(data) {
            return data.method.toUpperCase() + ' ' + data.uri.href + ' - ' + JSON.stringify(data.data) + '\n';
        });
        self.printLogTags(test.runnerData.result, 'system-out', 'result', function(data) {
            return (data.requestOptions.method || 'get').toUpperCase() + ' ' + data.requestOptions.uri.href + ' - ' + JSON.stringify(data.body).slice(0, self.errorLogCharacterLimitation) + '\n';
        });
        self.printLogTags(test.runnerData.error, 'system-err', 'runnererror', function(data) {
            var ret = '';

            if(data.requestOptions) {
                ret += (data.requestOptions.method || 'get').toUpperCase() + ' ' + data.requestOptions.uri.href + '\n';
            }

            ret += 'ERROR:' + data.err + '\n';

            if(data.body) {
                ret += 'BODY:' + (typeof data.body === 'object' ? JSON.stringify(data.body) : data.body).slice(0, self.errorLogCharacterLimitation) + '\n';
            }

            return ret;
        });

        self.write('</testcase>');
    });

};

/**
 * Write out the given line
 */
XUnit.prototype.write = function(line) {
    var indent = Array(this.indents * 2).join('  ');
    if (this.fileStream) {
        this.fileStream.write(indent + line + '\n');
    } else {
        console.log(indent + line);
    }
};

/**
 * HTML tag helper.
 */
function tag(name, attrs, close, content) {
    var end = close ? '/>' : '>',
        pairs = [],
        _tag;

    for (var key in attrs) {
        pairs.push(key + '="' + escape(attrs[key]) + '"');
    }

    _tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
    if (content) _tag += content + '</' + name + end;
    return _tag;
}

/**
 * Return cdata escaped CDATA `str`.
 */

function cdata(str) {
    return '<![CDATA[' + str + ']]>';
}

/**
 * Expose `XUnit`.
 */
exports = module.exports = XUnit;<commit_msg>Updated xUnit test reporter<commit_after>/**
 * Module dependencies.
 */

var util = require('util'),
    Base = require('./base'),
    fs = require('fs'),
    path = require('path'),
    sanitizeCaps = require('../helpers/sanitize').caps;

/**
 * Initialize a new `XUnit` reporter.
 *
 * @param {Runner} runner
 * @api public
 */
function XUnit(options) {
    Base.call(this);

    var tests = this.tests = {},
        runnerData = this.runnerData = {},
        self = this,
        id = 0;

    this.errorLogCharacterLimitation = 10000;
    this.indents = 0;
    this.errors = 0;
    this.options = options;

    /**
     * remember which tests got executed by runner
     */
    this.on('runner:start', function(runner) {
        tests[runner.pid] = [{
            start: new Date(),
            tests: [],
            root: true,
            /**
             * problematic by setting end date when runner started:
             * `<testsuites />` time will include computation time of all before/after hooks, that
             * results in a bigger time value then all time values of its `<testsuite/>` summed
             * together
             */
            end: new Date(),
        }];

        runnerData[runner.pid] = {
            command: [],
            result: [],
            error: []
        };
    });

    this.on('runner:command', function(data) {
        runnerData[data.pid].command.push(data);
    });
    this.on('runner:result', function(data) {
        runnerData[data.pid].result.push(data);
    });
    this.on('runner:error', function(data) {
        self.errors++;
        runnerData[data.pid].error.push(data);
    });

    /**
     * clear runnerData cache
     */
    this.on('test:start', function(test) {
        runnerData[test.pid] = {
            command: [],
            result: [],
            error: []
        };
    });

    this.on('suite:start', function(suite){
        suite.id = ++id;
        suite.tests = [];
        suite.passes = 0;
        suite.pending = 0;
        suite.failures = 0;
        suite.timestamp = new Date();

        /**
         * root suites
         */
        if(suite.parent === '' || !suite.parent) {
            tests[suite.pid][0].tests.push(suite);
            return;
        }

        var parentSuite = this.findParentSuite(suite.parent, this.tests[suite.pid][0]);
        parentSuite.tests.push(suite);
    });

    this.on('test:pending', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.pending++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
            test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('test:pass', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.passes++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
            test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('test:fail', function(test) {
        var parentSuite = this.findParentSuite(test.parent, this.tests[test.pid][0]);
        parentSuite.failures++;
        test.id = ++id;
        test.time = new Date() - tests[test.pid][0].end,
            test.timestamp = tests[test.pid][0].end = new Date();
        test.runnerData = runnerData[test.pid];
        parentSuite.tests.push(test);
    });

    this.on('end', function() {
        Object.keys(tests).forEach(function(pid) {
            self.genTestsuites(tests[pid], pid);
        });
    });
}

/**
 * Inherit from Base
 */
util.inherits(XUnit, Base);

function escape(html){
    return String(html)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/\r?\n|\r/g, '');
}

XUnit.prototype.findParentSuite = function(title, suite) {
    var _suite = null;

    for(var i = 0; i < suite.tests.length; ++i) {
        if(suite.tests[i].title === title) {
            return suite.tests[i];
        }

        if(suite.tests[i].tests) {
            _suite = _suite || this.findParentSuite(title, suite.tests[i]);
        }
    }

    return _suite;
};

/**
 * generate junit report
 */
XUnit.prototype.genTestsuites = function(tests, pid) {

    var caps = this.stats.runner[pid].capabilities,
        options = this.options.reporterOptions,
        filename = 'WDIO.xunit.' + sanitizeCaps(caps) + '.' + pid + '.xml';

    if (options && typeof options.outputDir === 'string') {
        this.fileStream = fs.createWriteStream(path.join(process.cwd(), options.outputDir, filename));
    }

    /**
     * root testsuites tag
     */
    this.write(tag('testsuites', {
        name: sanitizeCaps(caps),
        tests: this.stats.tests,
        failures: this.stats.failures,
        errors: this.errors,
        disabled: this.stats.pending,
        time: this.stats.duration / 1000
    }));

    this.indents++;
    this.genTestsuite(tests[0].tests);
    this.indents--;

    this.write('</testsuites>');

    if (this.fileStream) {
        this.fileStream.end();
    }
};

function sumTime(suite) {
    var res = 0;

    for(var i = 0; i < suite.tests.length; ++i) {
        if(suite.tests[i].tests) {
            res += sumTime(suite.tests[i]);
        } else {
            res += suite.tests[i].time;
        }
    }

    return res;
}

XUnit.prototype.printLogTags = function(data, tagName, type, iter) {
    var content = '';

    for(var i = 0; i < data.length; ++i) {
        content += iter(data[i]);
    }

    if(content !== '') {
        content = cdata('\n' + content);
        this.indents++;
        this.write(tag(tagName, {
            type: type
        }, false, content));
        this.indents--;
    }
};

/**
 * generate testsuites markup
 */
XUnit.prototype.genTestsuite = function(tests) {

    var self = this;

    tests.forEach(function(test) {

        /**
         * write test suite
         */
        if(test.tests) {
            self.write(tag('testsuite', {
                name: test.title,
                tests: test.pending + test.passes + test.failures,
                failures: test.failures,
                // errors: test.failures,
                skipped: test.pending,
                disabled: test.pending,
                time: sumTime(test) / 1000,
                timestamp: test.timestamp,
                id: test.id,
                file: test.file
            }));

            self.indents++;
            self.genTestsuite(test.tests);
            self.indents--;

            self.write('</testsuite>');
            return;
        }

        /**
         * write testcase
         */
        self.write(tag('testcase', {
            name: test.title,
            disabled: test.pending,
            time: test.time / 1000,
            id: test.id,
            file: test.file,
            status: test.err == null ? 'passed' : 'failed',
            classname: sanitizeCaps(self.stats.runner[test.pid].capabilities)
        }));

        /**
         * print skipped tags
         */
        if(test.pending) {

            self.indents++;
            self.write(tag('skipped', {}, true));
            self.indents--;

            self.write('</testcase>');
            return;

            /**
             * print failure tags
             */
        } else if(test.err && Object.getOwnPropertyNames(test.err).length > 0) {
            var content = cdata((test.err.stack || '').slice(0, self.errorLogCharacterLimitation));

            self.indents++;
            self.write(tag('failure', {
                type: 'testerror',
                message: escape(test.err.message)
            }, false, content));
            self.indents--;

        }

        /**
         * print runner logs
         */
        self.printLogTags(test.runnerData.command, 'system-out', 'command', function(data) {
            return data.method.toUpperCase() + ' ' + data.uri.href + ' - ' + JSON.stringify(data.data) + '\n';
        });
        self.printLogTags(test.runnerData.result, 'system-out', 'result', function(data) {
            return (data.requestOptions.method || 'get').toUpperCase() + ' ' + data.requestOptions.uri.href + ' - ' + JSON.stringify(data.body).slice(0, self.errorLogCharacterLimitation) + '\n';
        });
        self.printLogTags(test.runnerData.error, 'system-err', 'runnererror', function(data) {
            var ret = '';

            if(data.requestOptions) {
                ret += (data.requestOptions.method || 'get').toUpperCase() + ' ' + data.requestOptions.uri.href + '\n';
            }

            ret += 'ERROR:' + data.err + '\n';

            if(data.body) {
                ret += 'BODY:' + (typeof data.body === 'object' ? JSON.stringify(data.body) : data.body).slice(0, self.errorLogCharacterLimitation) + '\n';
            }

            return ret;
        });

        self.write('</testcase>');
    });

};

/**
 * Write out the given line
 */
XUnit.prototype.write = function(line) {
    var indent = Array(this.indents * 2).join('  ');
    if (this.fileStream) {
        this.fileStream.write(indent + line + '\n');
    } else {
        console.log(indent + line);
    }
};

/**
 * HTML tag helper.
 */
function tag(name, attrs, close, content) {
    var end = close ? '/>' : '>',
        pairs = [],
        _tag;

    for (var key in attrs) {
        pairs.push(key + '="' + escape(attrs[key]) + '"');
    }

    _tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
    if (content) _tag += content + '</' + name + end;
    return _tag;
}

/**
 * Return cdata escaped CDATA `str`.
 */

function cdata(str) {
    return '<![CDATA[' + str + ']]>';
}

/**
 * Expose `XUnit`.
 */
exports = module.exports = XUnit;<|endoftext|>


<commit_before>/**
 * Controls the communication with the Abiword application
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const spawn = require('child_process').spawn;
const async = require('async');
const settings = require('./Settings');
const os = require('os');

let doConvertTask;

// on windows we have to spawn a process for each convertion, cause the plugin abicommand doesn't exist on this platform
if (os.type().indexOf('Windows') > -1) {
  let stdoutBuffer = '';

  doConvertTask = function (task, callback) {
    // span an abiword process to perform the conversion
    const abiword = spawn(settings.abiword, [`--to=${task.destFile}`, task.srcFile]);

    // delegate the processing of stdout to another function
    abiword.stdout.on('data', (data) => {
      // add data to buffer
      stdoutBuffer += data.toString();
    });

    // append error messages to the buffer
    abiword.stderr.on('data', (data) => {
      stdoutBuffer += data.toString();
    });

    // throw exceptions if abiword is dieing
    abiword.on('exit', (code) => {
      if (code != 0) {
        return callback(`Abiword died with exit code ${code}`);
      }

      if (stdoutBuffer != '') {
        console.log(stdoutBuffer);
      }

      callback();
    });
  };

  exports.convertFile = function (srcFile, destFile, type, callback) {
    doConvertTask({srcFile, destFile, type}, callback);
  };
}
// on unix operating systems, we can start abiword with abicommand and communicate with it via stdin/stdout
// thats much faster, about factor 10
else {
  // spawn the abiword process
  let abiword;
  let stdoutCallback = null;
  var spawnAbiword = function () {
    abiword = spawn(settings.abiword, ['--plugin', 'AbiCommand']);
    let stdoutBuffer = '';
    let firstPrompt = true;

    // append error messages to the buffer
    abiword.stderr.on('data', (data) => {
      stdoutBuffer += data.toString();
    });

    // abiword died, let's restart abiword and return an error with the callback
    abiword.on('exit', (code) => {
      spawnAbiword();
      stdoutCallback(`Abiword died with exit code ${code}`);
    });

    // delegate the processing of stdout to a other function
    abiword.stdout.on('data', (data) => {
      // add data to buffer
      stdoutBuffer += data.toString();

      // we're searching for the prompt, cause this means everything we need is in the buffer
      if (stdoutBuffer.search('AbiWord:>') != -1) {
        // filter the feedback message
        const err = stdoutBuffer.search('OK') != -1 ? null : stdoutBuffer;

        // reset the buffer
        stdoutBuffer = '';

        // call the callback with the error message
        // skip the first prompt
        if (stdoutCallback != null && !firstPrompt) {
          stdoutCallback(err);
          stdoutCallback = null;
        }

        firstPrompt = false;
      }
    });
  };
  spawnAbiword();

  doConvertTask = function (task, callback) {
    abiword.stdin.write(`convert ${task.srcFile} ${task.destFile} ${task.type}\n`);
    // create a callback that calls the task callback and the caller callback
    stdoutCallback = function (err) {
      callback();
      console.log('queue continue');
      try {
        task.callback(err);
      } catch (e) {
        console.error('Abiword File failed to convert', e);
      }
    };
  };

  // Queue with the converts we have to do
  const queue = async.queue(doConvertTask, 1);
  exports.convertFile = function (srcFile, destFile, type, callback) {
    queue.push({srcFile, destFile, type, callback});
  };
}
<commit_msg>lint: src/node/utils/Abiword.js<commit_after>'use strict';
/**
 * Controls the communication with the Abiword application
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const spawn = require('child_process').spawn;
const async = require('async');
const settings = require('./Settings');
const os = require('os');

let doConvertTask;

// on windows we have to spawn a process for each convertion,
// cause the plugin abicommand doesn't exist on this platform
if (os.type().indexOf('Windows') > -1) {
  let stdoutBuffer = '';

  doConvertTask = (task, callback) => {
    // span an abiword process to perform the conversion
    const abiword = spawn(settings.abiword, [`--to=${task.destFile}`, task.srcFile]);

    // delegate the processing of stdout to another function
    abiword.stdout.on('data', (data) => {
      // add data to buffer
      stdoutBuffer += data.toString();
    });

    // append error messages to the buffer
    abiword.stderr.on('data', (data) => {
      stdoutBuffer += data.toString();
    });

    // throw exceptions if abiword is dieing
    abiword.on('exit', (code) => {
      if (code !== 0) {
        return callback(`Abiword died with exit code ${code}`);
      }

      if (stdoutBuffer !== '') {
        console.log(stdoutBuffer);
      }

      callback();
    });
  };

  exports.convertFile = (srcFile, destFile, type, callback) => {
    doConvertTask({srcFile, destFile, type}, callback);
  };
  // on unix operating systems, we can start abiword with abicommand and
  // communicate with it via stdin/stdout
  // thats much faster, about factor 10
} else {
  // spawn the abiword process
  let abiword;
  let stdoutCallback = null;
  const spawnAbiword = () => {
    abiword = spawn(settings.abiword, ['--plugin', 'AbiCommand']);
    let stdoutBuffer = '';
    let firstPrompt = true;

    // append error messages to the buffer
    abiword.stderr.on('data', (data) => {
      stdoutBuffer += data.toString();
    });

    // abiword died, let's restart abiword and return an error with the callback
    abiword.on('exit', (code) => {
      spawnAbiword();
      stdoutCallback(`Abiword died with exit code ${code}`);
    });

    // delegate the processing of stdout to a other function
    abiword.stdout.on('data', (data) => {
      // add data to buffer
      stdoutBuffer += data.toString();

      // we're searching for the prompt, cause this means everything we need is in the buffer
      if (stdoutBuffer.search('AbiWord:>') !== -1) {
        // filter the feedback message
        const err = stdoutBuffer.search('OK') !== -1 ? null : stdoutBuffer;

        // reset the buffer
        stdoutBuffer = '';

        // call the callback with the error message
        // skip the first prompt
        if (stdoutCallback != null && !firstPrompt) {
          stdoutCallback(err);
          stdoutCallback = null;
        }

        firstPrompt = false;
      }
    });
  };
  spawnAbiword();

  doConvertTask = (task, callback) => {
    abiword.stdin.write(`convert ${task.srcFile} ${task.destFile} ${task.type}\n`);
    // create a callback that calls the task callback and the caller callback
    stdoutCallback = (err) => {
      callback();
      console.log('queue continue');
      try {
        task.callback(err);
      } catch (e) {
        console.error('Abiword File failed to convert', e);
      }
    };
  };

  // Queue with the converts we have to do
  const queue = async.queue(doConvertTask, 1);
  exports.convertFile = (srcFile, destFile, type, callback) => {
    queue.push({srcFile, destFile, type, callback});
  };
}
<|endoftext|>


<commit_before>/*
 * This RESTlet will cover the basic operations for interacting with Netsuite data
*/

function loadRecord(recordType, internalId) {
	/*
	 * Description: Performs record loads and handles exceptions in the event of no record found
	 * Params:
	 *              recordType: String matching a record type
	 *              internalId: String matching the internal id of a record
	 *
	 * Return:      Netsuite record with given type and id or null if none found
	*/
	return(nlapiLoadRecord(recordType, internalId));
}

function getRecord(request) {
	/*
	 * Description: Retrieves a single record based on query fields
	 * Params:
	 *              request.record_type: String matching a record type
	 *              request.internal_id: String matching the internal id of a record
	 *
	 * Return:      Record of given type or null if not found
	*/
    var recordType = request.record_type;
    var internalId = request.internal_id;

    return(loadRecord(recordType, internalId));
}

function createRecord(request) {
	/*
	 * Description: Creates a record with given field values, can ignore validations if requested
	 * Params:
	 *              request.record_type:      String matching a record type
	 *              request.record_data:      String/value pairs to populate record field data
	 *              request.do_sourcing:      Boolean value to set sourcing (the hell is this?)
	 *              request.ignore_mandatory: Boolean value to set ignoring of validations for mandatory fields
	 *
	 * Return:      Internal id of comitted record if successful, false if not
	*/
    var recordType      = request.record_type;
    var recordData      = request.record_data;
    var doSourcing      = request.do_sourcing;
    var ignoreMandatory = request.ignore_mandatory;

    var newRecord       = nlapiCreateRecord(recordType, recordData);

    return(nlapiSubmitRecord(newRecord, doSourcing, ignoreMandatory));
}

function updateRecord(request) {
	/*
	 * Description: Updates a record with given field values, can ignore validations if requested
	 * Params:
	 *              request.record_type:      String matching a record type
	 *              request.internal_id:      String matching the internal id of a record
	 *              request.do_sourcing:      Boolean value to set sourcing (the hell is this?)
	 *              request.ignore_mandatory: Boolean value to set ignoring of validations for mandatory fields
	 *
	 * Return:      Internal id of the comitted record if successful, false if not
	*/
    var recordType      = request.record_type;
    var internalId      = request.internal_id;
    var doSourcing      = request.do_sourcing;
    var ignoreMandatory = request.ignoreMandatory;

    var record          = loadRecord(recordType, internalId);

    if(record) {
      return(nlapiSubmitRecord(record, doSourcing, ignoreMandatory));
    }
    return(false);
}

function deleteRecord(request) {
	/*
	 * Description: Deletes a record of given type with given id
	 * Params:
	 *              request.record_type: String matching a record type
	 *              request.internal_id: String matching the internal id of a record
	 *
	 * Return:      True if successful, false if not
	*/
	var recordType = request.record_type;
	var internalId = request.internal_id;

    nlapiDeleteRecord(recordType, internalId);

	if(loadRecord(recordType, internalId) {
		return(false);
	}
	return(true);
}<commit_msg>moved basic operations into methods with exception catching, methods tied to REST requests can now be made to perform operations on record batches rather than single records<commit_after>/*
 * This RESTlet covers the basic operations for interacting with Netsuite data. The basic
 * operations are wrapped in custom methods to perform exception handling and to expose errors
 * and debug information to the client.
 *
 * Params listed as sub-fields of the request argument will be arguments passed to the endpoint URI
*/

function loadRecord(recordType, internalId) {
	/*
	 * Description: Performs record loads and handles exceptions in the event of no record found
	 * Params:
	 *              recordType: String matching a record type
	 *              internalId: String matching the internal id of a record
	 *
	 * Return:      Netsuite record with given type and id or exception
	*/
	try {
      return([nlapiLoadRecord(recordType, internalId)]);
	}
	catch(exception) {
	  return [exception.message];
	}
}

function submitRecord(record, doSourcing, ignoreMandatory) {
    /*
     * Description: Updates a record with given field values, can ignore validations if requested
     * Params:
     *              record:          Netsuite API record object
     *              doSourcing:      Boolean value to set sourcing (the hell is this?)
     *              ignoreMandatory: Boolean value to set ignoring of validations for mandatory fields
     *
     * Return:      Internal id of the comitted record if successful, exception if not
    */
    try {
      return([nlapiSubmitRecord(record, doSourcing, ignoreMandatory)]);
    }
    catch(exception) {
      return [exception.message];
    }
}

function deleteRecord(recordType, internalId) {
  	/*
	 * Description: Deletes a record of given type with given id
	 * Params:
	 *              recordType: String matching a record type
	 *              internalId: String matching the internal id of a record
	 *
	 * Return:      True if successful, exception if not
	*/
	try {
		nlapiDeleteRecord(recordType, internalId);
		return([true]);
	}
	catch(exception) {
		return([exception.message])
	}
}

function getRecord(request) {
	/*
	 * Description: Retrieves a single record based on query fields
	 * Params:
	 *              request.record_type: String matching a record type
	 *              request.internal_id: String matching the internal id of a record
	 *
	 * Return:      Record of given type or null if not found
	*/
    var recordType = request.record_type;
    var internalId = request.internal_id;

    return(loadRecord(recordType, internalId));
}

function createRecord(request) {
	/*
	 * Description: Creates a record with given field values, can ignore validations if requested
	 * Params:
	 *              request.record_type:      String matching a record type
	 *              request.record_data:      String/value pairs to populate record field data
	 *              request.do_sourcing:      Boolean value to set sourcing (the hell is this?)
	 *              request.ignore_mandatory: Boolean value to set ignoring of validations for mandatory fields
	 *
	 * Return:      Internal id of comitted record if successful, exception if not
	*/
    var recordType      = request.record_type;
    var recordData      = request.record_data;
    var doSourcing      = request.do_sourcing;
    var ignoreMandatory = request.ignore_mandatory;

    var newRecord       = nlapiCreateRecord(recordType, recordData);

    return(submitRecord(newRecord, doSourcing, ignoreMandatory));
}

function updateRecord(request) {
	/*
	 * Description: Updates a record with given field values, can ignore validations if requested
	 * Params:
	 *              request.record_type:      String matching a record type
	 *              request.internal_id:      String matching the internal id of a record
	 *              request.do_sourcing:      Boolean value to set sourcing (the hell is this?)
	 *              request.ignore_mandatory: Boolean value to set ignoring of validations for mandatory fields
	 *
	 * Return:      Internal id of the comitted record if successful, false if not
	*/
    var recordType      = request.record_type;
    var internalId      = request.internal_id;
    var doSourcing      = request.do_sourcing;
    var ignoreMandatory = request.ignoreMandatory;

    var record          = loadRecord(recordType, internalId);

    if(record) {
      return(submitRecord(record, doSourcing, ignoreMandatory));
    }
    return(false);
}

function deleteRecord(request) {
	/*
	 * Description: Deletes a record of given type with given id
	 * Params:
	 *              request.record_type: String matching a record type
	 *              request.internal_id: String matching the internal id of a record
	 *
	 * Return:      True if successful, false if not
	*/
	var recordType = request.record_type;
	var internalId = request.internal_id;

    return(deleteRecord(recordType, internalId));
}<|endoftext|>


<commit_before>'use strict';

var through = require('through2');
var extend = require('xtend');
var commons = require('./_common.js');
var OPTIONS_DEFAULTS = {
  slidingWindowSize: 50,
  slidingWindowOverlap: 20
};

function incrementOffset(xProperty, offset, d) {
  d[xProperty] = d[xProperty] + offset;

  return d;
}

function pushToStream(d) {
  this.push(d);

  return d;
}

/**
 * Processes an array of data and calls an `onComplete` callback with `error` and `spikes` parameters.
 *
 * @example
 ```js
 slayer()
 .fromArray(arrayData, function(err, spikes){
    if (err){
      console.error(err);
      return;
    }

    console.log(spikes);   // { x: 4, y: 12, id: '21232f297a57a5a743894a0e4a801fc3' }
  });
 ```
 *
 * @api
 * @name Slayer.prototype.fromArray
 * @this {Slayer}
 * @param data {Array.<Object|Number>}
 * @param onComplete {Function}
 */
function createReadStream(options){
  options = extend({}, OPTIONS_DEFAULTS, options || {});

  var buffer = [];
  var offset = 0;
  var self = this;
  var SLIDING_WINDOW_SIZE = options.slidingWindowSize;
  var SLIDING_WINDOW_OVERLAP = options.slidingWindowOverlap;

  var findSpikes = function findSpikes(items, stream) {
    var spikes = items
      .map(self.getValueY.bind(self))
      .map(self.filterDataItem.bind(self))
      .map(self.algorithm.bind(self, self.config.minPeakDistance))
      .map(commons.objectMapper.bind(self, buffer))
      .filter(commons.cleanEmptyElement.bind(null, self.config.transformedValueProperty))
      .map(incrementOffset.bind(self, 'x', offset))
      .map(pushToStream, stream);
  }

  var flush = function flushBuffer(done) {
    findSpikes(buffer, this);

    done();
  };

  return through.obj(function(chunk, enc, callback){
    buffer.push(chunk);

    if (buffer.length === SLIDING_WINDOW_SIZE+SLIDING_WINDOW_OVERLAP) {
      findSpikes(buffer, this);

      buffer = buffer.slice(SLIDING_WINDOW_SIZE);
      offset += SLIDING_WINDOW_SIZE;
    }

    callback();
  }, flush);
}

module.exports = createReadStream;
<commit_msg>Implement known emitted spikes in streaming mode<commit_after>'use strict';

var through = require('through2');
var extend = require('xtend');
var commons = require('./_common.js');
var OPTIONS_DEFAULTS = {
  bufferingFactor: 4,           // if slayer.config.minPeakDistance equals to 45, we want to buffer and slide by 180 items each time
  lookAheadFactor: 0.33         // if we buffer 180 items, we actually provision an extra 30% (48) to look ahead
};

function incrementOffset(xProperty, offset, d) {
  d[xProperty] = d[xProperty] + offset;

  return d;
}

function pushToStream(d) {
  this.push(d);

  return d;
}

function cleanEmitted(xProperty, cache, d) {
  if (cache.indexOf(d[xProperty]) === -1) {
    cache.push(d[xProperty]);

    return true;
  }
  else {
    return false;
  }
}

/**
 * Processes an array of data and calls an `onComplete` callback with `error` and `spikes` parameters.
 *
 * @example
 ```js
 slayer()
 .fromArray(arrayData, function(err, spikes){
    if (err){
      console.error(err);
      return;
    }

    console.log(spikes);   // { x: 4, y: 12, id: '21232f297a57a5a743894a0e4a801fc3' }
  });
 ```
 *
 * @api
 * @name Slayer.prototype.fromArray
 * @this {Slayer}
 * @param data {Array.<Object|Number>}
 * @param onComplete {Function}
 */
function createReadStream(options){
  options = extend({}, OPTIONS_DEFAULTS, options || {});

  var self = this;
  var buffer = [];
  var emittedCache = [];
  var currentOffset = 0;
  var SLIDING_WINDOW_SIZE = this.config.minPeakDistance * options.bufferingFactor;
  var SLIDING_WINDOW_OVERLAP = SLIDING_WINDOW_SIZE * options.lookAheadFactor;

  var findSpikes = function findSpikes(items, stream) {
    var spikes = items
      .map(self.getValueY.bind(self))
      .map(self.filterDataItem.bind(self))
      .map(self.algorithm.bind(self, self.config.minPeakDistance))
      .map(commons.objectMapper.bind(self, buffer))
      .filter(commons.cleanEmptyElement.bind(null, self.config.transformedValueProperty))
      .map(incrementOffset.bind(self, 'x', currentOffset))
      .filter(cleanEmitted.bind(self, 'x', emittedCache))
      .map(pushToStream, stream);
  }

  var flush = function flushBuffer(done) {
    findSpikes(buffer, this);

    done();
  };

  return through.obj(function(chunk, enc, callback){
    buffer.push(chunk);

    if (buffer.length === SLIDING_WINDOW_SIZE+SLIDING_WINDOW_OVERLAP) {
      findSpikes(buffer, this);

      emittedCache = emittedCache.slice(-SLIDING_WINDOW_SIZE);
      buffer = buffer.slice(SLIDING_WINDOW_SIZE);
      currentOffset += SLIDING_WINDOW_SIZE;
    }

    callback();
  }, flush);
}

module.exports = createReadStream;
<|endoftext|>


<commit_before>cg.Renderer = (function () {

    /**
     * CodeGraph renderer using SnapSvg library.
     * @param paper {Object} The SnagSvg object which hold the svg context
     * @constructor
     */
    function Renderer(paper) {

        this._paper = paper;
        this._paper.background = new cg.BackgroundGrid(paper);

        this._rootElement = paper.g();
        this._zoom = new cg.Zoom(this, paper, this._rootElement);
        this._paperPoint = paper.node.createSVGPoint();
        this._mousePosition = new cg.Vec2();
        this._selectionBox = new cg.Box2();
        this._selectionRectangle = null;
        this._style = {
            "action": {
                "min-width": 250,
                "border-radius": 5,
                "padding": 10,
                "heading": 40
            },
            "point": {
                "height": 20
            }
        };
    }

    /**
     * @param {cg.Node} node
     * @param {Object?} element
     */
    Renderer.prototype.render = function (node, element) {
        return this["_render" + cg.functionName(node.constructor)](node, element || this._rootElement);
    };

    return Renderer;

})();
<commit_msg>Added 4 new layers<commit_after>cg.Renderer = (function () {

    /**
     * CodeGraph renderer using SnapSvg library.
     * @param paper {Object} The SnagSvg object which hold the svg context
     * @constructor
     */
    function Renderer(paper) {
        this._paper = paper;
        this._paper.background = new cg.BackgroundGrid(paper);
        this._rootElement = paper.g();
        this._groupLayer = this._rootElement.g();
        this._connectionLayer = this._rootElement.g();
        this._actionLayer = this._rootElement.g();
        this._selectionLayer = this._rootElement.g();
        this._groupLayer.addClass('group-layer');
        this._connectionLayer.addClass('connection-layer');
        this._actionLayer.addClass('action-layer');
        this._selectionLayer.addClass('selection-layer');
        this._zoom = new cg.Zoom(this, paper, this._rootElement);
        this._paperPoint = paper.node.createSVGPoint();
        this._mousePosition = new cg.Vec2();
        this._selectionBox = new cg.Box2();
        this._selectionRectangle = null;
        this._style = {
            "group": {
                "heading": 20
            },
            "action": {
                "min-width": 250,
                "border-radius": 5,
                "padding": 10,
                "heading": 40
            },
            "point": {
                "height": 20
            }
        };
    }

    /**
     * @param {cg.Node} node
     * @param {Object?} element
     */
    Renderer.prototype.render = function (node, element) {
        return this["_render" + cg.functionName(node.constructor)](node, element || this._rootElement);
    };

    return Renderer;

})();
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var util = require("util");
var _ = require("lodash");

var SELEMIUM_VER_STR_TMPLT = "./node_modules/selenium-server/lib/runner/selenium-server-standalone-%s.jar"
var CHROMEDRIVER_LOCATION = "./node_modules/chromedriver/lib/chromedriver/chromedriver";
var PHANTOMJS_LOCATION = "./node_modules/phantomjs/bin/phantomjs";
// throws file read/write exceptions, JSON parse exceptions
module.exports = function (sourceConfigPath, tempAssetPath, options) {

  var conf = require(path.resolve(sourceConfigPath));

  if (options.localSeleniumPort) {
    // Local-testing selenium port (non-sauce)
    // Tell nightwatch to both start and connect to a selenium server on port {seleniumPort}
    conf.selenium.port = options.localSeleniumPort;
    conf.test_settings.default.selenium_port = options.localSeleniumPort;

    if (options.seleniumServerVersion) {
      conf.selenium.server_path = util.format(SELEMIUM_VER_STR_TMPLT, options.seleniumServerVersion);
    }
  }

  if (options.isChromedriverPresent) {
    // append chrome driver location if user specifies chromedriver in conf to use
    if (!conf.selenium.cli_args) {
      // create structure if not defined
      conf.selenium.cli_args = {};
    }

    if (!conf.selenium.cli_args["webdriver.chrome.driver"]) {
      // don't overwrite user value
      conf.selenium.cli_args["webdriver.chrome.driver"] = CHROMEDRIVER_LOCATION;
    }
  }

  if (options.isPhantomjsPresent) {
    // append phantomjs location if user specifies phantomjs in conf to use
    if (!conf.test_settings.phantomjs) {
      // create structure if not defined
      conf.test_settings.phantomjs = {
        desiredCapabilities: {
          browserName: "phantomjs"
        }
      };
    }
    if (!conf.test_settings.phantomjs.desiredCapabilities["phantomjs.binary.path"]) {
      // don't overwrite user value
      conf.test_settings.phantomjs.desiredCapabilities["phantomjs.binary.path"] = PHANTOMJS_LOCATION;
    }
  }

  // Remote testing (sauce) selenium settings:
  /*
  "username": "",
  "access_key": "",
  "desiredCapabilities": {
    "browserName": "",
    "platform": "",
    "version": "",
    "tunnel-identifier": "
  },
  */
  if (options.sauceSettings) {
    // Auth
    conf.test_settings.sauce.username = options.sauceSettings.username;
    conf.test_settings.sauce.access_key = options.sauceSettings.accessKey;

    if (!options.sauceBrowserSettings) {
      console.error("ERROR: Missing browser settings even though sauce cloud settings are active");
      throw new Error("invalid configuration");
    }

    conf.test_settings.sauce.desiredCapabilities = options.sauceBrowserSettings;

    if (options.sauceSettings.tunnelId) {
      conf.test_settings.sauce.desiredCapabilities["tunnel-identifier"] = options.sauceSettings.tunnelId;
      if (options.sauceSettings.sharedSauceParentAccount) {
        // if tunnel is shared by parent account
        conf.test_settings.sauce.desiredCapabilities["parent-tunnel"] = options.sauceSettings.sharedSauceParentAccount;
      }
    } else {
      // This property may exist, so blow it away
      delete conf.test_settings.sauce.desiredCapabilities["tunnel-identifier"];
    }
  }

  // Write all the above details to a temporary config file, then return the temporary filename
  var tempConfigPath = path.resolve(tempAssetPath + "/nightwatch.json");

  fs.writeFileSync(tempConfigPath, JSON.stringify(conf), "utf8");

  return tempConfigPath;
};
<commit_msg>patch selenium server version while launching up<commit_after>var fs = require("fs");
var path = require("path");
var util = require("util");
var _ = require("lodash");

var SELEMIUM_VER_STR_TMPLT = "./node_modules/selenium-server/lib/runner/selenium-server-standalone-%s.jar"
var CHROMEDRIVER_LOCATION = "./node_modules/chromedriver/lib/chromedriver/chromedriver";
var PHANTOMJS_LOCATION = "./node_modules/phantomjs/bin/phantomjs";
// throws file read/write exceptions, JSON parse exceptions
module.exports = function (sourceConfigPath, tempAssetPath, options) {

  var conf = require(path.resolve(sourceConfigPath));

  if (options.localSeleniumPort) {
    // Local-testing selenium port (non-sauce)
    // Tell nightwatch to both start and connect to a selenium server on port {seleniumPort}
    conf.selenium.port = options.localSeleniumPort;
    conf.test_settings.default.selenium_port = options.localSeleniumPort;

    if (options.localSeleniumVersion) {
      conf.selenium.server_path = util.format(SELEMIUM_VER_STR_TMPLT, options.localSeleniumVersion);
    }
  }

  if (options.isChromedriverPresent) {
    // append chrome driver location if user specifies chromedriver in conf to use
    if (!conf.selenium.cli_args) {
      // create structure if not defined
      conf.selenium.cli_args = {};
    }

    if (!conf.selenium.cli_args["webdriver.chrome.driver"]) {
      // don't overwrite user value
      conf.selenium.cli_args["webdriver.chrome.driver"] = CHROMEDRIVER_LOCATION;
    }
  }

  if (options.isPhantomjsPresent) {
    // append phantomjs location if user specifies phantomjs in conf to use
    if (!conf.test_settings.phantomjs) {
      // create structure if not defined
      conf.test_settings.phantomjs = {
        desiredCapabilities: {
          browserName: "phantomjs"
        }
      };
    }
    if (!conf.test_settings.phantomjs.desiredCapabilities["phantomjs.binary.path"]) {
      // don't overwrite user value
      conf.test_settings.phantomjs.desiredCapabilities["phantomjs.binary.path"] = PHANTOMJS_LOCATION;
    }
  }

  // Remote testing (sauce) selenium settings:
  /*
  "username": "",
  "access_key": "",
  "desiredCapabilities": {
    "browserName": "",
    "platform": "",
    "version": "",
    "tunnel-identifier": "
  },
  */
  if (options.sauceSettings) {
    // Auth
    conf.test_settings.sauce.username = options.sauceSettings.username;
    conf.test_settings.sauce.access_key = options.sauceSettings.accessKey;

    if (!options.sauceBrowserSettings) {
      console.error("ERROR: Missing browser settings even though sauce cloud settings are active");
      throw new Error("invalid configuration");
    }

    conf.test_settings.sauce.desiredCapabilities = options.sauceBrowserSettings;

    if (options.sauceSettings.tunnelId) {
      conf.test_settings.sauce.desiredCapabilities["tunnel-identifier"] = options.sauceSettings.tunnelId;
      if (options.sauceSettings.sharedSauceParentAccount) {
        // if tunnel is shared by parent account
        conf.test_settings.sauce.desiredCapabilities["parent-tunnel"] = options.sauceSettings.sharedSauceParentAccount;
      }
    } else {
      // This property may exist, so blow it away
      delete conf.test_settings.sauce.desiredCapabilities["tunnel-identifier"];
    }
  }

  // Write all the above details to a temporary config file, then return the temporary filename
  var tempConfigPath = path.resolve(tempAssetPath + "/nightwatch.json");

  fs.writeFileSync(tempConfigPath, JSON.stringify(conf), "utf8");

  return tempConfigPath;
};
<|endoftext|>


<commit_before>import Phaser from 'phaser'

export default class extends Phaser.Sprite {
  constructor (game, x, y, options = { canTurn: false, isFalling: true }) {
    super(game, x, y, 'chars_small', 165)

    this.canTurn = options.canTurn
    this.isFalling = options.isFalling

    this.animations.add('explode', ['expl1, expl2'])

    this.anchor.setTo(0.5)

    this.game.physics.arcade.enable(this)

    this.cursors = this.game.input.keyboard.createCursorKeys()

    this.wasd = {
      up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
      down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
      left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
      right: this.game.input.keyboard.addKey(Phaser.Keyboard.D)
    }

    this.game.input.gamepad.start()

    // Add a bitchin trail because we are going supersonic
    this.playerTrail = this.game.add.emitter(this.x, this.y, 15)
    this.playerTrail.makeParticles('chars_small', 165)
    this.playerTrail.setXSpeed(0, 0)
    this.playerTrail.setYSpeed(0, 0)
    this.playerTrail.setAlpha(0.4, 0.01, 150)
    this.playerTrail.setRotation(0)
    this.playerTrail.start(false, 50, 10)

    // Default maxVelocity in 1G, this magic number is used everywhere
    this.body.maxVelocity.x = 500
  }

  say (text, completed) {
    var style = { font: "20px Arial", fill: "#ffffff", wordWrap: true, wordWrapWidth: 300 , align: "center" };
    this.text = this.game.add.text(0, 0, text, style);
    this.text.anchor.set(0.5);

    var context = this

    setTimeout(function() {
      context.text.destroy()
      completed()
    }, 2000)
  }

  resetWithAnimation () {
    var duration = 500

    var x = this.x
    var y = this.y

    this.emitter = this.game.add.emitter(x, y, 4)
    this.emitter.makeParticles(['expl1', 'expl2'], 2)
    this.emitter.width = 24
    this.emitter.height = 24
    this.emitter.minParticleScale = 1
    this.emitter.maxParticleScale = 4
    this.emitter.minParticleSpeed.set(0, 0)
    this.emitter.maxParticleSpeed.set(0, 0)
    this.emitter.gravity = 0
    this.emitter.start(false, duration, 10, 4)

    var player = this
    player.kill()

    setTimeout(function () {
      player.reset(50, 256)
    }, duration)
  }

  update () {

    if (this.text != undefined) {
      this.text.x = Math.floor(this.x - this.width / 2);
      this.text.y = Math.floor(this.y - 1.5 * this.height);
    }

    this.playerTrail.x = this.x
    this.playerTrail.y = this.y

    const accY = 800

    if (this.isMovingUp()) {
      if (this.isFalling || (!this.isFalling && this.body.onFloor())) {
        this.body.velocity.y = -accY
      }
    } else if (this.isMovingDown()) {
      if (this.isFalling) {
        this.body.velocity.y = accY
      }
    } else {
      this.body.velocity.y = 0
    }

    const accX = 150
    if (this.isMovingLeft()) {
      this.body.velocity.x = -3 * accX
      if (this.canTurn) {
        this.scale.setTo(-1, 1)
      }
    } else if (this.isMovingRight()) {
      if (this.body.maxVelocity.x <= 800 * 1.4) {
        this.body.maxVelocity.x += accX
      }
      this.body.velocity.x += accX
      if (this.canTurn) {
        this.scale.setTo(1, 1)
      }
    } else {
      this.body.maxVelocity.x = 800
    }
  }

  isMovingUp () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.up.isDown || this.wasd.up.isDown || pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_UP) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) < -0.1
  }

  isMovingDown () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.down.isDown || this.wasd.down.isDown || pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_DOWN) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) > 0.1
  }

  isMovingLeft () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.left.isDown || this.wasd.left.isDown || pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1
  }

  isMovingRight () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.right.isDown || this.wasd.right.isDown || pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1
  }
}

<commit_msg>cleanup; basic new text rendering<commit_after>import Phaser from 'phaser'

export default class extends Phaser.Sprite {
  constructor (game, x, y, options = { canTurn: false, isFalling: true }) {
    super(game, x, y, 'chars_small', 165)

    this.canTurn = options.canTurn
    this.isFalling = options.isFalling

    this.animations.add('explode', ['expl1, expl2'])

    this.anchor.setTo(0.5)

    this.game.physics.arcade.enable(this)

    this.cursors = this.game.input.keyboard.createCursorKeys()

    this.wasd = {
      up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
      down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
      left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
      right: this.game.input.keyboard.addKey(Phaser.Keyboard.D)
    }

    this.game.input.gamepad.start()

    // Add a bitchin trail because we are going supersonic
    this.playerTrail = this.game.add.emitter(this.x, this.y, 15)
    this.playerTrail.makeParticles('chars_small', 165)
    this.playerTrail.setXSpeed(0, 0)
    this.playerTrail.setYSpeed(0, 0)
    this.playerTrail.setAlpha(0.4, 0.01, 150)
    this.playerTrail.setRotation(0)
    this.playerTrail.start(false, 50, 10)

    // Default maxVelocity in 1G, this magic number is used everywhere
    this.body.maxVelocity.x = 500
  }

  say (text, completed) {
    var style = { font: "20px Arial", fill: "#ffffff", wordWrap: true, wordWrapWidth: 300 , align: "center" };
    this.text = this.game.add.text(0, 0, text, style);
    this.text.anchor.set(0.5);

    // this.renderByLetter(text, function() {
    //   context.text.destroy()
    //   completed()
    // })

    var context = this

    setTimeout(function() {
      context.text.destroy()
      completed()
    }, 2000)

  }

  renderByLetter(text, completed) {

    var current = "";
    var textField = this.text;

    for (var i = 0 + 1; i < text.length 0; i++) {
      current += text[i]
      this.text.setText(current)
    }

  }

  resetWithAnimation () {
    var duration = 500

    var x = this.x
    var y = this.y

    this.emitter = this.game.add.emitter(x, y, 4)
    this.emitter.makeParticles(['expl1', 'expl2'], 2)
    this.emitter.width = 24
    this.emitter.height = 24
    this.emitter.minParticleScale = 1
    this.emitter.maxParticleScale = 4
    this.emitter.minParticleSpeed.set(0, 0)
    this.emitter.maxParticleSpeed.set(0, 0)
    this.emitter.gravity = 0
    this.emitter.start(false, duration, 10, 4)

    var player = this
    player.kill()

    setTimeout(function () {
      player.reset(50, 256)
    }, duration)
  }

  update () {

    if (this.text != undefined) {
      this.text.x = Math.floor(this.x - this.width / 2);
      this.text.y = Math.floor(this.y - 1.5 * this.height);
    }

    this.playerTrail.x = this.x
    this.playerTrail.y = this.y

    const accY = 800

    if (this.isMovingUp()) {
      if (this.isFalling || (!this.isFalling && this.body.onFloor())) {
        this.body.velocity.y = -accY
      }
    } else if (this.isMovingDown()) {
      if (this.isFalling) {
        this.body.velocity.y = accY
      }
    } else {
      this.body.velocity.y = 0
    }

    const accX = 150
    if (this.isMovingLeft()) {
      this.body.velocity.x = -3 * accX
      if (this.canTurn) {
        this.scale.setTo(-1, 1)
      }
    } else if (this.isMovingRight()) {
      if (this.body.maxVelocity.x <= 800 * 1.4) {
        this.body.maxVelocity.x += accX
      }
      this.body.velocity.x += accX
      if (this.canTurn) {
        this.scale.setTo(1, 1)
      }
    } else {
      this.body.maxVelocity.x = 800
    }
  }

  isMovingUp () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.up.isDown || this.wasd.up.isDown ||
    pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_UP) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) < -0.1
  }

  isMovingDown () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.down.isDown || this.wasd.down.isDown ||
    pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_DOWN) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) > 0.1
  }

  isMovingLeft () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.left.isDown || this.wasd.left.isDown ||
    pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1
  }

  isMovingRight () {
    const pad1 = this.game.input.gamepad.pad1
    return this.cursors.right.isDown || this.wasd.right.isDown ||
    pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1
  }

}

<|endoftext|>


<commit_before>class ResController {
    constructor() {
        this.userResponses = {};
    }

    addUserRequest(params) {
        params = Object.assign({}, params);

        if (this.userResponses[params.ip] === undefined) this.userResponses[params.ip] = [];

        this.userResponses[params.ip].push(params);
    }

    respondToUser(ip, params, res_response, status_code) {
        if (this.userResponses[ip] === undefined) return;

        for (let response in this.userResponses[ip]) {
            let this_response = this.userResponses[ip][response];

            // check if each param is the same
            for (let param in params) {
                if (params[param] != this_response[param]) continue;
            }

            // Send back the data
            if (params.type == 'http') {
                if (!status_code) this.userResponses[ip][response]['res'].json(res_response);
                else this.userResponses[ip][response]['res'].status(status_code).json(res_response);
            }
            else if (params.type == 'ws') {
                this.userResponses[ip][response]['res'].emit('floatmessage', res_response);
            }

            // Remove the request
            this.userResponses[ip].splice(response, 1);

            break;
        }
    }

    isUserInQueue(ip) {
        if (this.userResponses[ip] === undefined || this.userResponses[ip].length == 0) return false;
        else return true;
    }
}

module.exports = ResController;
<commit_msg>Refactors ResController.respondToUser<commit_after>class ResController {
    constructor() {
        this.userResponses = {};
    }

    addUserRequest(params) {
        params = Object.assign({}, params);

        if (this.userResponses[params.ip] === undefined) this.userResponses[params.ip] = [];

        this.userResponses[params.ip].push(params);
    }

    respondToUser(ip, params, res_response, status_code) {
        if (this.userResponses[ip] === undefined) return;

        // Find the request in our array
        let responseIndex = this.userResponses[ip].findIndex((item) => {
            for (let param in params) {
                if (params[param] != item[param]) return false;
            }

            return true;
        });

        // If we didn't find the request, return
        if (responseIndex === -1) return;

        // Get the response object
        let res = this.userResponses[ip][responseIndex]['res'];

        // Send back the data
        if (params.type == 'http') {
            if (!status_code) res.json(res_response);
            else res.status(status_code).json(res_response);
        }
        else if (params.type == 'ws') {
            res.emit('floatmessage', res_response);
        }

        // Remove the request
        this.userResponses[ip].splice(responseIndex, 1);
    }

    isUserInQueue(ip) {
        if (this.userResponses[ip] === undefined || this.userResponses[ip].length == 0) return false;
        else return true;
    }
}

module.exports = ResController;
<|endoftext|>


<commit_before>/* @flow */
import { observable, computed, action, toJS } from 'mobx';
import systems from './systems.json';
import factions from './factions.json';

import { voronoi as d3voronoi } from 'd3-voronoi';
import Graph from 'node-dijkstra';

import concaveman from 'concaveman';
import greinerHormann from 'greiner-hormann';
import Offset from 'polygon-offset';

const voronoi = d3voronoi().x(d => d.x).y(d => d.y);
const route = new Graph();
const offset = new Offset();

class Universe {

	@observable
	factions: Map<string, Faction> = observable.map({});

	@observable
	path: Array<System> = [];

	@observable
	systemProperties: Map<string, System> = observable.map({});

	constructor() {
		factions.forEach(faction => this.factions.set(faction.name, faction));
		systems
			.map((system, key) => Object.assign({}, system, { id: `${key}` }))
			.filter(system => system.x != null && system.y != null)
			.filter(system => {
				const faction = this.factions.get(system.affiliation);
				return faction && faction.world
			})
			.forEach(system => this.systemProperties.set(system.id, system));

		Array.from(this.systemProperties.values()).forEach(system => {
			var nodes = {};
			system.neighbors.forEach(neighbor => nodes[`${neighbor}`] = 1);
			if(Object.keys(nodes).length)
				route.addNode(system.id, nodes);
		});
	}

	@computed
	get factionMapping(): Map<string, Array<System>> {
		const mapping = observable.map({});
		this.systems.forEach(system => {
			(mapping[system.affiliation] = mapping[system.affiliation] || []).push(system);
		});
		return mapping;
	}

	@computed
	get systems(): Array<System> {
		return Array.from(this.systemProperties.values())
			.map(system => {
				const faction = this.factions.get(system.affiliation);
				return Object.assign({}, system, { color: faction ? faction.color : '#ffffff' });
			});
	}

	@computed
	get spheres(): Array<SystemSphere> {
		const hulls: Map<string, PolygonCoordinates> = new Map();
		const mapping = {};
		this.systems.forEach(system => {
			if(system.x && system.y)
				(mapping[system.affiliation] = mapping[system.affiliation] || []).push(system);
		});

		Object.keys(mapping).forEach(id => {
				hulls.set(id, offset.data(concaveman(mapping[id].map(system => [ system.x, system.y ]), Infinity)).offsetLine(50)[0]);
		});

		voronoi.extent([[-3000,-3000], [3000, 3000]]);
		const systems = toJS(this.systems, false);
		const voronoiPolygons = voronoi(systems).polygons();
		return voronoiPolygons.map(coordinates => {
			const properties = coordinates.data;
			const polygon = coordinates.slice();
			if(properties.x && properties.y) {
				let intersection = greinerHormann.intersection(hulls.get(properties.affiliation), polygon);
				if(intersection) {
				    intersection = intersection[0];
						return {
							sphere: intersection,
							properties: properties
						};
				}
			} else {
				return {
					sphere: polygon,
					properties: properties
				};
			}
		});
	}

	@action
	addStop = (system: System) => {
		const path = toJS(this.path, false);
		if(path.length === 0) {
			path.push(system);
		} else {
			const stops = route.path(path[path.length - 1].id, system.id);
			if(stops)
				stops
					.slice(1)
					.map(stop =>  this.systemProperties.get(stop))
					.forEach(system => path.push(system));
		}
		this.path = path;

	};

}

export default new Universe();
<commit_msg>tweaked values for faction hulls (concave hull)<commit_after>/* @flow */
import { observable, computed, action, toJS } from 'mobx';
import systems from './systems.json';
import factions from './factions.json';

import { voronoi as d3voronoi } from 'd3-voronoi';
import Graph from 'node-dijkstra';

import concaveman from 'concaveman';
import greinerHormann from 'greiner-hormann';
import Offset from 'polygon-offset';

const voronoi = d3voronoi().x(d => d.x).y(d => d.y);
const route = new Graph();
const offset = new Offset();

class Universe {

	@observable
	factions: Map<string, Faction> = observable.map({});

	@observable
	path: Array<System> = [];

	@observable
	systemProperties: Map<string, System> = observable.map({});

	constructor() {
		factions.forEach(faction => this.factions.set(faction.name, faction));
		systems
			.map((system, key) => Object.assign({}, system, { id: `${key}` }))
			.filter(system => system.x != null && system.y != null)
			.filter(system => {
				const faction = this.factions.get(system.affiliation);
				return faction && faction.world
			})
			.forEach(system => this.systemProperties.set(system.id, system));

		Array.from(this.systemProperties.values()).forEach(system => {
			var nodes = {};
			system.neighbors.forEach(neighbor => nodes[`${neighbor}`] = 1);
			if(Object.keys(nodes).length)
				route.addNode(system.id, nodes);
		});
	}

	@computed
	get factionMapping(): Map<string, Array<System>> {
		const mapping = observable.map({});
		this.systems.forEach(system => {
			(mapping[system.affiliation] = mapping[system.affiliation] || []).push(system);
		});
		return mapping;
	}

	@computed
	get systems(): Array<System> {
		return Array.from(this.systemProperties.values())
			.map(system => {
				const faction = this.factions.get(system.affiliation);
				return Object.assign({}, system, { color: faction ? faction.color : '#ffffff' });
			});
	}

	@computed
	get spheres(): Array<SystemSphere> {
		const hulls: Map<string, PolygonCoordinates> = new Map();
		const mapping = {};
		this.systems.forEach(system => {
			if(system.x && system.y)  // filter Terra
				(mapping[system.affiliation] = mapping[system.affiliation] || []).push(system);
		});

		Object.keys(mapping).forEach(id => {
				hulls.set(id, offset.data(concaveman(mapping[id].map(system => [ system.x, system.y ]), 1.5)).offsetLine(20)[0]);
		});

		voronoi.extent([[-3000,-3000], [3000, 3000]]);
		const systems = toJS(this.systems, false);
		const voronoiPolygons = voronoi(systems).polygons();
		return voronoiPolygons.map(coordinates => {
			const properties = coordinates.data;
			const polygon = coordinates.slice();
			if(properties.x && properties.y) {
				let intersection = greinerHormann.intersection(hulls.get(properties.affiliation), polygon);
				if(intersection) {
				    intersection = intersection[0];
						return {
							sphere: intersection,
							properties: properties
						};
				}
			} else {
				// Terra
				return {
					sphere: polygon,
					properties: properties
				};
			}
		});
	}

	@action
	addStop = (system: System) => {
		const path = toJS(this.path, false);
		if(path.length === 0) {
			path.push(system);
		} else {
			const stops = route.path(path[path.length - 1].id, system.id);
			if(stops)
				stops
					.slice(1)
					.map(stop =>  this.systemProperties.get(stop))
					.forEach(system => path.push(system));
		}
		this.path = path;

	};

}

export default new Universe();
<|endoftext|>