<commit_before>/*
 * Copyright (c) 2012 Minori Yamashita <ympbyc@gmail.com>
 * See LICENCE.txt
 */
/*
 * ExpressionParser
 * Little Smalltalk expression to Javascript expression
 */
(function () {
  'use strict';

  var LittleParsers, optimization, ExpressionParser,
  __each = function (obj, fn) {
    for (var key in obj)
      if (obj.hasOwnProperty(key))
        fn(obj[key], key);
    return;
  },
  __template = function (template, hashmap) {
    var dest_str = template;
    __each(hashmap, function (it, key) {
      dest_str = dest_str.replace(new RegExp('%'+key+'%', 'g'), it || "");
    });
    return dest_str;
  };

  try {
    LittleParsers = require('./littleparsers').LittleParsers;
    optimization = require('./optimization');
  } catch (err) {
    if ( ! (LittleParsers = window.LittleParsers)) throw "littleparsers.js is required";
    if ( ! (optimization = window.optimization)) throw "optimization.js is required";
  }

  ExpressionParser = (function () {
    var ExpressionParser;

    ExpressionParser = function (input) {
      this.cache = {};
      this.input = input;
    };
    ExpressionParser.prototype = new LittleParsers("");

    /*                             cascade *
     * variable <-@recur(variable)         */
    ExpressionParser.prototype.expression = function () {
      var assignments,
          cascade,
          _this = this,
          tmpl = "%assignments% %cascade%"; // a = b = A new
      return this.cacheDo("expression", function () {
        assignments = _this.optional(_this.assignments);
        cascade = _this.cascade();
        return __template(tmpl, {assignments:assignments, cascade:cascade});
      });
    };

    ExpressionParser.prototype.assignments = function () {
      var _this = this;
      return this.cacheDo("assignments", function () {
        return _this.many(function () {
          var a = "";
          a += _this.variable();
          _this.skipSpace(),
          _this.assignmentArrow();
          _this.skipSpace();
          a += " = ";
          return a;
        });
      });
    };

    /*
     * obj mes / obj kw: arg - simpleExpression
     * obj mes ; mes2 ; kw: arg - cascade
     */
    ExpressionParser.prototype.cascade = function () {
      var _this = this,
          tmpl = "(function () { var _receiver = %simpleExpression%; %body% return _receiver;  })()";
      return this.cacheDo("cascade", function () {
        var se, conti, brackets;
        se = _this.simpleExpression(); // obj mes / obj sel arg / obj kw: arg kw2: arg
        try {
          _this.notFollowedBy(function () { _this.skipSpace(); _this.semicolon(); });
          brackets = "";
          conti = _this.many(function () {
            var conti = _this.continuation();
            brackets += "(";
            return conti + ")";
          });
          if ( ! conti) return se;
          return brackets + se + conti;
        } catch (e) {}
        conti = _this.optional(function () {
          return _this.many(function () {
            _this.skipSpace();
            _this.semicolon();
            _this.skipSpace();
            return "_receiver" + _this.continuation() + ";";
          });
        });
        return __template(tmpl, {simpleExpression:se, body:conti});
      });
    };

    /*
     * receiver
     * receiver unarySelector
     * receiver keyword: argument ...
     */
    ExpressionParser.prototype.simpleExpression = function () {
      var _this = this;
      return this.cacheDo("simpleExpression", function () {
        return _this.try_(
          _this.keywordExpression,
          _this.binaryExpression,
          _this.unaryExpression,
          _this.primary
        );
      });
    };

    // from | receiver keyword1: aaa keyword2: bbb
    // to   | receiver.keyword1_keyword2_(aaa, bbb)
    ExpressionParser.prototype.keywordExpression = function () {
      var _this = this;
      return this.cacheDo("keywordExpression", function () {
        var receiver,
            methodCall,
            methodName,
            args,
            tmp;
        receiver = _this.primaryReceiver();
        tmp = _this.keywordMessage();
        methodCall = tmp.methodCall;
        methodName = tmp.methodName;
        args = tmp.args;

        //optimize if optimization is available
        if (_this.options.optimization && optimization.optimizationAvailable(methodName))
          return optimization.optimize(receiver, methodName, args);

        return receiver + "." + methodCall;
      });
    };

    // from | sel1: arg1 sel2: arg2
    // to   | sel1_sel2_(arg1, arg2)
    ExpressionParser.prototype.keywordMessage = function () {
      var _this = this;
      return this.cacheDo("keywordMessage", function () {
        var methodName = "",
        args = [];
        _this.many1(function () {
          _this.skipSpace();
          methodName += _this.keywordSelector().replace(':', ''); // "inject:into" becomes "injectinto"
          _this.skipSpace();
          args.push(_this.primary())
          _this.skipSpace();
        });
        return {
          methodCall : methodName + "(" + args.join(", ") + ")",
          methodName : methodName,
          args : args
        };
      });
    };

    ExpressionParser.prototype.binaryExpression = function () {
      var _this = this;
      return this.cacheDo("binaryExpression", function () {
        var receiver,binaryMessage;
        _this.skipSpace();
        receiver = _this.primaryReceiver();
        binaryMessage = _this.binaryMessage();
        return receiver + " " + operator + " " + argument;
      });
    };

    // from | <+> 1
    // to   | + 1
    ExpressionParser.prototype.binaryMessage = function () {
      var _this = this;
      return this.cacheDo("binaryMessage", function () {
        var operator, argument;
        _this.skipSpace();
        operator = _this.operator();
        _this.skipSpace();
        argument = _this.primary();
        return operator + " " + argument;
      });
    };

    // from | receiver selector
    // to   | receiver.selector()
    ExpressionParser.prototype.unaryExpression = function () {
      var _this = this;
      return this.cacheDo("unaryExpression", function () {
        var receiver, unarySelector;
        receiver = _this.primaryReceiver();
        _this.skipSpace();
        unarySelector = _this.unarySelector();

        //optimize if optimization is available
        if (_this.options.optimization && optimization.optimizationAvailable(unarySelector))
          return optimization.optimize(receiver, unarySelector, []);

        return receiver + '.' + unarySelector + '()';
      });
    };

    // from | selector
    // to   | selector()
    ExpressionParser.prototype.unaryMessage = function () {
      var _this = this;
      return this.cacheDo("unaryMessage", function () {
        return _this.unarySelector() + '()';
      });
    };

    ExpressionParser.prototype.continuation = function () {
      var _this = this;
      return this.cacheDo("continuation", function () {
        _this.skipSpace();
        return _this.try_(
          function () { return "." + _this.keywordMessage().methodCall; },
          _this.binaryMessage,
          function () { return "." + _this.unaryMessage(); }
        );
      });
    };

    /*
     * variable, literal, block, primitive, (cascade)
     */
    ExpressionParser.prototype.primary = function () {
      var _this = this;
      return this.cacheDo("primary", function () {
        return _this.try_(
          _this.variable,
          _this.literal,
          _this.block,
          _this.primitive,
          function () {
            var ret;
            _this.chr("(");
            ret = _this.cascade();
            _this.chr(")");
            return ret;
          }
        );
      });
    };

    /*
     * primary used as receiver have following special cases
     * invalid: function(){}() valid: (function () {})()
     * invalid: 1.foo valid: 1 .foo valid: (1).foo
     */
    ExpressionParser.prototype.primaryReceiver = function () {
      var _this = this;
      return this.cacheDo("primaryReceiver", function () {
        return _this.try_(
          function () {
            return _this.numberLiteral() + " ";
          },
          function () {
            return "(" + _this.block() + ")";
          },
          _this.primary
        );
      });
    };

    /*
     * <inline.javascript(code)>
     */
    ExpressionParser.prototype.primitive = function () {
      var _this = this;
      return this.cacheDo("primitive", function () {
        _this.skipSpace();
        return _this.between(
          function () {
            var ret = _this.chr("<");
            _this.notFollowedBy(_this.toParser("-"););
            return ret;
          },
          _this.anyChar,
          _this.toParser(">");
        );
      });
    };

    ExpressionParser.prototype.operator = function () {
      var _this = this;
      return this.cacheDo("operator", function () {
        var op;
        _this.skipSpace();
        op = _this.try_(
          _this.toParser("+"),
          _this.toParser("-"),
          _this.toParser("*"),
          _this.toParser("/"),
          _this.toParser("."),
          _this.toParser("+="),
          _this.toParser("-="),
          _this.toParser("*="),
          _this.toParser("/="),
          _this.toParser("==="),
          _this.toParser("!=="),
          _this.toParser("instanceof"),
          _this.toParser("%"),
          _this.toParser("%="),
          _this.toParser("<"),
          _this.toParser(">"),
          _this.toParser("<="),
          _this.toParser(">="),
          _this.toParser("^"),
          _this.toParser("&&"),
          _this.toParser("||")
        );
        _this.skipSpace();
        return op;
      });
    };

    return ExpressionParser;
  })();

  try {
    exports.ExpressionParser = ExpressionParser;
  } catch (err) {}
  try {
    window.ExpressionParser = ExpressionParser;
  } catch (err) {}

}).call(this);
<commit_msg>bug fix<commit_after>/*
 * Copyright (c) 2012 Minori Yamashita <ympbyc@gmail.com>
 * See LICENCE.txt
 */
/*
 * ExpressionParser
 * Little Smalltalk expression to Javascript expression
 */
(function () {
  'use strict';

  var LittleParsers, optimization, ExpressionParser,
  __each = function (obj, fn) {
    for (var key in obj)
      if (obj.hasOwnProperty(key))
        fn(obj[key], key);
    return;
  },
  __template = function (template, hashmap) {
    var dest_str = template;
    __each(hashmap, function (it, key) {
      dest_str = dest_str.replace(new RegExp('%'+key+'%', 'g'), it || "");
    });
    return dest_str;
  };

  try {
    LittleParsers = require('./littleparsers').LittleParsers;
    optimization = require('./optimization');
  } catch (err) {
    if ( ! (LittleParsers = window.LittleParsers)) throw "littleparsers.js is required";
    if ( ! (optimization = window.optimization)) throw "optimization.js is required";
  }

  ExpressionParser = (function () {
    var ExpressionParser;

    ExpressionParser = function (input) {
      this.cache = {};
      this.input = input;
    };
    ExpressionParser.prototype = new LittleParsers("");

    /*                             cascade *
     * variable <-@recur(variable)         */
    ExpressionParser.prototype.expression = function () {
      var assignments,
          cascade,
          _this = this,
          tmpl = "%assignments% %cascade%"; // a = b = A new
      return this.cacheDo("expression", function () {
        assignments = _this.optional(_this.assignments);
        cascade = _this.cascade();
        return __template(tmpl, {assignments:assignments, cascade:cascade});
      });
    };

    ExpressionParser.prototype.assignments = function () {
      var _this = this;
      return this.cacheDo("assignments", function () {
        return _this.many(function () {
          var a = "";
          a += _this.variable();
          _this.skipSpace(),
          _this.assignmentArrow();
          _this.skipSpace();
          a += " = ";
          return a;
        });
      });
    };

    /*
     * obj mes / obj kw: arg - simpleExpression
     * obj mes ; mes2 ; kw: arg - cascade
     */
    ExpressionParser.prototype.cascade = function () {
      var _this = this,
          tmpl = "(function () { var _receiver = %simpleExpression%; %body% return _receiver;  })()";
      return this.cacheDo("cascade", function () {
        var se, conti, brackets;
        se = _this.simpleExpression(); // obj mes / obj sel arg / obj kw: arg kw2: arg
        try {
          _this.notFollowedBy(function () { _this.skipSpace(); _this.semicolon(); });
          brackets = "";
          conti = _this.many(function () {
            var conti = _this.continuation();
            brackets += "(";
            return conti + ")";
          });
          if ( ! conti) return se;
          return brackets + se + conti;
        } catch (e) {}
        conti = _this.optional(function () {
          return _this.many(function () {
            _this.skipSpace();
            _this.semicolon();
            _this.skipSpace();
            return "_receiver" + _this.continuation() + ";";
          });
        });
        return __template(tmpl, {simpleExpression:se, body:conti});
      });
    };

    /*
     * receiver
     * receiver unarySelector
     * receiver keyword: argument ...
     */
    ExpressionParser.prototype.simpleExpression = function () {
      var _this = this;
      return this.cacheDo("simpleExpression", function () {
        return _this.try_(
          _this.keywordExpression,
          _this.binaryExpression,
          _this.unaryExpression,
          _this.primary
        );
      });
    };

    // from | receiver keyword1: aaa keyword2: bbb
    // to   | receiver.keyword1_keyword2_(aaa, bbb)
    ExpressionParser.prototype.keywordExpression = function () {
      var _this = this;
      return this.cacheDo("keywordExpression", function () {
        var receiver,
            methodCall,
            methodName,
            args,
            tmp;
        receiver = _this.primaryReceiver();
        tmp = _this.keywordMessage();
        methodCall = tmp.methodCall;
        methodName = tmp.methodName;
        args = tmp.args;

        //optimize if optimization is available
        if (_this.options.optimization && optimization.optimizationAvailable(methodName))
          return optimization.optimize(receiver, methodName, args);

        return receiver + "." + methodCall;
      });
    };

    // from | sel1: arg1 sel2: arg2
    // to   | sel1_sel2_(arg1, arg2)
    ExpressionParser.prototype.keywordMessage = function () {
      var _this = this;
      return this.cacheDo("keywordMessage", function () {
        var methodName = "",
        args = [];
        _this.many1(function () {
          _this.skipSpace();
          methodName += _this.keywordSelector().replace(':', ''); // "inject:into" becomes "injectinto"
          _this.skipSpace();
          args.push(_this.primary())
          _this.skipSpace();
        });
        return {
          methodCall : methodName + "(" + args.join(", ") + ")",
          methodName : methodName,
          args : args
        };
      });
    };

    ExpressionParser.prototype.binaryExpression = function () {
      var _this = this;
      return this.cacheDo("binaryExpression", function () {
        var receiver,binaryMessage;
        _this.skipSpace();
        receiver = _this.primaryReceiver();
        binaryMessage = _this.binaryMessage();
        return receiver + " " + operator + " " + argument;
      });
    };

    // from | <+> 1
    // to   | + 1
    ExpressionParser.prototype.binaryMessage = function () {
      var _this = this;
      return this.cacheDo("binaryMessage", function () {
        var operator, argument;
        _this.skipSpace();
        operator = _this.operator();
        _this.skipSpace();
        argument = _this.primary();
        return operator + " " + argument;
      });
    };

    // from | receiver selector
    // to   | receiver.selector()
    ExpressionParser.prototype.unaryExpression = function () {
      var _this = this;
      return this.cacheDo("unaryExpression", function () {
        var receiver, unarySelector;
        receiver = _this.primaryReceiver();
        _this.skipSpace();
        unarySelector = _this.unarySelector();

        //optimize if optimization is available
        if (_this.options.optimization && optimization.optimizationAvailable(unarySelector))
          return optimization.optimize(receiver, unarySelector, []);

        return receiver + '.' + unarySelector + '()';
      });
    };

    // from | selector
    // to   | selector()
    ExpressionParser.prototype.unaryMessage = function () {
      var _this = this;
      return this.cacheDo("unaryMessage", function () {
        return _this.unarySelector() + '()';
      });
    };

    ExpressionParser.prototype.continuation = function () {
      var _this = this;
      return this.cacheDo("continuation", function () {
        _this.skipSpace();
        return _this.try_(
          function () { return "." + _this.keywordMessage().methodCall; },
          _this.binaryMessage,
          function () { return "." + _this.unaryMessage(); }
        );
      });
    };

    /*
     * variable, literal, block, primitive, (cascade)
     */
    ExpressionParser.prototype.primary = function () {
      var _this = this;
      return this.cacheDo("primary", function () {
        return _this.try_(
          _this.variable,
          _this.literal,
          _this.block,
          _this.primitive,
          function () {
            var ret;
            _this.chr("(");
            ret = _this.cascade();
            _this.chr(")");
            return ret;
          }
        );
      });
    };

    /*
     * primary used as receiver have following special cases
     * invalid: function(){}() valid: (function () {})()
     * invalid: 1.foo valid: 1 .foo valid: (1).foo
     */
    ExpressionParser.prototype.primaryReceiver = function () {
      var _this = this;
      return this.cacheDo("primaryReceiver", function () {
        return _this.try_(
          function () {
            return _this.numberLiteral() + " ";
          },
          function () {
            return "(" + _this.block() + ")";
          },
          _this.primary
        );
      });
    };

    /*
     * <inline.javascript(code)>
     */
    ExpressionParser.prototype.primitive = function () {
      var _this = this;
      return this.cacheDo("primitive", function () {
        _this.skipSpace();
        return _this.between(
          function () {
            var ret = _this.chr("<");
            _this.notFollowedBy(_this.toParser("-"));
            return ret;
          },
          _this.anyChar,
          _this.toParser(">");
        );
      });
    };

    ExpressionParser.prototype.operator = function () {
      var _this = this;
      return this.cacheDo("operator", function () {
        var op;
        _this.skipSpace();
        op = _this.try_(
          _this.toParser("+"),
          _this.toParser("-"),
          _this.toParser("*"),
          _this.toParser("/"),
          _this.toParser("."),
          _this.toParser("+="),
          _this.toParser("-="),
          _this.toParser("*="),
          _this.toParser("/="),
          _this.toParser("==="),
          _this.toParser("!=="),
          _this.toParser("instanceof"),
          _this.toParser("%"),
          _this.toParser("%="),
          _this.toParser("<"),
          _this.toParser(">"),
          _this.toParser("<="),
          _this.toParser(">="),
          _this.toParser("^"),
          _this.toParser("&&"),
          _this.toParser("||")
        );
        _this.skipSpace();
        return op;
      });
    };

    return ExpressionParser;
  })();

  try {
    exports.ExpressionParser = ExpressionParser;
  } catch (err) {}
  try {
    window.ExpressionParser = ExpressionParser;
  } catch (err) {}

}).call(this);
<|endoftext|>


<commit_before>require([
  // Application.
  "app",

  // Main Router.
  "router"
],

function(app, Router) {

  // Define your master router on the application namespace and trigger all
  // navigation from this instance.
  app.router = new Router();
  // Trigger the initial route and enable HTML5 History API support, set the
  // root folder to '/' by default.  Change in app.js.
  Backbone.history.start({ pushState: false, root: app.root });
  // All navigation that is relative should be passed through the navigate
  // method, to be processed by the router. If the link has a `data-bypass`
  // attribute, bypass the delegation completely.
  $(document).on("click", "a:not([data-bypass])", function(evt) {
    // Get the absolute anchor href.
    var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
    // Get the absolute root.
    var root = location.protocol + "//" + location.host + app.root;

    var routeEvent = $(this).attr("route-event");
    if (routeEvent) {
      evt.preventDefault();
      // TODO:: change to false when route events are functional
      Backbone.history.navigate(href.attr, true);
      // Trigger  route events after update of history so that we can get params from url
      app.router.triggerRouteEvent("route:"+routeEvent, href);
    } else {
      // Ensure the root is part of the anchor href, meaning it's relative.
      if (href.prop && href.prop.slice(0, root.length) === root) {
        // Stop the default event to ensure the link will not cause a page
        // refresh.
        evt.preventDefault();

        // `Backbone.history.navigate` is sufficient for all Routers and will
        // trigger the correct events. The Router's internal `navigate` method
        // calls this anyways.  The fragment is sliced from the root.
        Backbone.history.navigate(href.attr, true);
      }
    }
  });
});
<commit_msg>Fauxton: remove route events from main.js<commit_after>require([
        // Application.
        "app",

        // Main Router.
        "router"
],

function(app, Router) {

  // Define your master router on the application namespace and trigger all
  // navigation from this instance.
  app.router = new Router();
  // Trigger the initial route and enable HTML5 History API support, set the
  // root folder to '/' by default.  Change in app.js.
  Backbone.history.start({ pushState: false, root: app.root });
  // All navigation that is relative should be passed through the navigate
  // method, to be processed by the router. If the link has a `data-bypass`
  // attribute, bypass the delegation completely.
  $(document).on("click", "a:not([data-bypass])", function(evt) {
    // Get the absolute anchor href.
    var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
    // Get the absolute root.
    var root = location.protocol + "//" + location.host + app.root;

    // Ensure the root is part of the anchor href, meaning it's relative.
    if (href.prop && href.prop.slice(0, root.length) === root) {
      // Stop the default event to ensure the link will not cause a page
      // refresh.
      evt.preventDefault();

      // `Backbone.history.navigate` is sufficient for all Routers and will
      // trigger the correct events. The Router's internal `navigate` method
      // calls this anyways.  The fragment is sliced from the root.
      Backbone.history.navigate(href.attr, true);
    }
  });
});
<|endoftext|>


<commit_before>/**
 * @file Guild events file.
 * @author Capuccino
 * @author Ovyerus
 */

/* eslint-env node */

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.50) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leave();
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', g => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.50)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            }
            let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.parting.message) {
                return null;
            }
            let msg = res.parting.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });
};
<commit_msg>fix guild leave event more<commit_after>/**
 * @file Guild events file.
 * @author Capuccino
 * @author Ovyerus
 */

/* eslint-env node */

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.50) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leave();
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', g => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.50)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            }
            let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.goodbyes || !res.goodbyes.enabled || !res.goodbyes.channelID || !res.goodbyes.message) {
                return null;
            }
            let msg = res.goodbyes.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });
};
<|endoftext|>


<commit_before>import ReactGA from 'react-ga';
import { setAppName, setVersion, APP_EXPLORER } from './config';
import { setAppColors } from './styles/colors';
import initializeApp from './index';
import routes from './routes/explorerRoutes';

/**
 * This serves as the primary entry point to the Media Cloud Explorer app.
 */
ReactGA.initialize('UA-60744513-11');

setVersion('3.6.1');

setAppName(APP_EXPLORER);

setAppColors({
  light: '#AF53A7',
  dark: '#8F3387', // primary
  darker: '#6F1367',
  main: '#8F3387',
});

initializeApp(routes);
<commit_msg>bump for release<commit_after>import ReactGA from 'react-ga';
import { setAppName, setVersion, APP_EXPLORER } from './config';
import { setAppColors } from './styles/colors';
import initializeApp from './index';
import routes from './routes/explorerRoutes';

/**
 * This serves as the primary entry point to the Media Cloud Explorer app.
 */
ReactGA.initialize('UA-60744513-11');

setVersion('3.6.2');

setAppName(APP_EXPLORER);

setAppColors({
  light: '#AF53A7',
  dark: '#8F3387', // primary
  darker: '#6F1367',
  main: '#8F3387',
});

initializeApp(routes);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**

If you don't know which DAO implementation to choose, EasyDAO is
    ready to help. Simply this.X.EasyDAO.create() and set the flags
    to indicate what behavior you're looking for. Under the hood, EasyDAO
    will create one or more DAO instances to service your requirements.

Since EasyDAO is a proxy, just use it like you would any other
    DAO, without worrying about the internal DAO doing the work.

*/
CLASS({
  package: 'foam.dao',
  name: 'EasyDAO',
  extends: 'foam.dao.ProxyDAO',

  requires: [
    'foam.dao.MDAO',
    'foam.dao.TimestampDAO',
    'foam.dao.JournalDAO',
    'foam.dao.GUIDDAO',
    'foam.dao.IDBDAO',
    //'foam.core.dao.CloningDAO',
    //'foam.core.dao.MergeDAO',
    //'foam.core.dao.MigrationDAO',
    //'foam.core.dao.StorageDAO',
    //'foam.core.dao.SyncDAO',
    //'foam.core.dao.SyncTrait',
    //'foam.core.dao.sync.PollingSyncDAO',
    //'foam.core.dao.sync.SocketSyncDAO',
    //'foam.core.dao.VersionNoDAO',
    //'foam.dao.CachingDAO',
    //'foam.dao.ContextualizingDAO',
    //'foam.dao.DeDupDAO',
    //'foam.dao.EasyClientDAO',
    //'foam.dao.SeqNoDAO',
    //'foam.dao.LoggingDAO',
    //'foam.dao.TimingDAO'
  ],

  help: 'A facade for easy DAO setup.',

  imports: ['document'],

  properties: [
    {
      name: 'name',
      factory: function() { return this.model.id; },
      //documentation: "The developer-friendly name for this $$DOC{ref:'.'}."
    },
    {
      class: 'Boolean',
      name: 'seqNo',
      value: false,
      //documentation: "Have $$DOC{ref:'.'} use a sequence number to index items. Note that $$DOC{ref:'.seqNo'} and $$DOC{ref:'.guid'} features are mutually exclusive."
    },
    {
      class: 'Boolean',
      name: 'guid',
      label: 'GUID',
      value: false,
      //documentation: "Have $$DOC{ref:'.'} generate guids to index items. Note that $$DOC{ref:'.seqNo'} and $$DOC{ref:'.guid'} features are mutually exclusive."
    },
    {
      name: 'seqProperty',
      class: 'Property',
      //documentation: "The property on your items to use to store the sequence number or guid. This is required for $$DOC{ref:'.seqNo'} or $$DOC{ref:'.guid'} mode."
    },
    {
      class: 'Boolean',
      name: 'cache',
      value: false,
      //documentation: "Enable local caching of the $$DOC{ref:'DAO'}."
    },
    {
      class: 'Boolean',
      name: 'dedup',
      value: false,
      //documentation: "Enable value de-duplication to save memory when caching."
    },
    {
      class: 'Boolean',
      name: 'logging',
      value: false,
      //documentation: "Enable logging on the $$DOC{ref:'DAO'}."
    },
    {
      class: 'Boolean',
      name: 'timing',
      value: false,
      //documentation: "Enable time tracking for concurrent $$DOC{ref:'DAO'} operations."
    },
    {
      class: 'Boolean',
      name: 'contextualize',
      value: false,
      //documentation: "Contextualize objects on .find"
    },
    {
      class: 'Boolean',
      name: 'cloning',
      value: false,
      //documentation: "True to clone results on select"
    },
    {
      name: 'daoType',
      value: 'foam.dao.IDBDAO',
      //documentation: function() { /*
//
Selects the basic functionality this $$DOC{ref:'foam.dao.EasyDAO'} should provide.
//           You can specify an instance of a DAO model definition such as
//           $$DOC{ref:'MDAO'}, or a constant indicating your requirements.

//
Choices are:

//

//
$$DOC{ref:'.ALIASES',text:'IDB'}: Use IndexDB for storage.

//
$$DOC{ref:'.ALIASES',text:'LOCAL'}: Use local storage (for Chrome Apps, this will use local, non-synced storage).

//
$$DOC{ref:'.ALIASES',text:'SYNC'}: Use synchronized storage (for Chrome Apps, this will use Chrome Sync storage).

//

//        */}
    },
    {
      class: 'Boolean',
      name: 'autoIndex',
      value: false,
      //documentation: "Automatically generate an index."
    },
    {
      class: 'Array',
      name: 'migrationRules',
      subType: 'foam.core.dao.MigrationRule',
      //documentation: "Creates an internal $$DOC{ref:'MigrationDAO'} and applies the given array of $$DOC{ref:'MigrationRule'}."
    },
    {
      class: 'Boolean',
      name: 'syncWithServer'
    },
    {
      class: 'Boolean',
      name: 'sockets',
      value: false
    },
    {
      class: 'String',
      name: 'serverUri',
      factory: function() {
        return this.document && this.document.location ?
            this.document.location.origin + '/api' :
            '';
      }
    },
    {
      class: 'Boolean',
      name: 'isServer',
      value: false
    },
    {
      name: 'syncProperty'
    },
    {
      name: 'deletedProperty'
    }
  ],

  constants: {
    // Aliases for daoType
    ALIASES: {
      IDB:   'foam.dao.IDBDAO',
      LOCAL: 'foam.dao.LocalStorageDAO',
      //SYNC:  'foam.dao.StorageDAO'
    }
  },

  methods: [
    function init(args) {
      /*

On initialization, the $$DOC{ref:'.'} creates an appropriate chain of
        internal $$DOC{ref:'DAO'} instances based on the $$DOC{ref:'.'}
        property settings.

This process is transparent to the developer, and you can use your
        $$DOC{ref:'.'} like any other $$DOC{ref:'DAO'}.

      */
      this.SUPER(args);

//       if ( window.chrome && chrome.storage ) {
//         this.ALIASES.LOCAL = 'foam.core.dao.ChromeStorageDAO';
//         this.ALIASES.SYNC  = 'foam.core.dao.ChromeSyncStorageDAO';
//       }

      var daoType  = typeof this.daoType === 'string' ? this.ALIASES[this.daoType] || this.daoType : this.daoType;
      var daoModel = typeof daoType === 'string' ? this.X.lookup(daoType) || GLOBAL[daoType] : daoType;
      var params   = { model: this.model, autoIndex: this.autoIndex };

      if ( ! daoModel ) {
        console.warn("EasyDAO: Unknown DAO Type.  Add '" + daoType + "' to requires: list.");
      }

      if ( this.name  ) params.name = this.name;
      if ( this.seqNo || this.guid ) params.property = this.seqProperty;

      var dao = daoModel.create(params, this.Y);

      if ( MDAO.isInstance(dao) ) {
        this.mdao = dao;
        if ( this.dedup ) dao = this.DeDupDAO.create({delegate: dao}, this.Y);
      } else {
        if ( this.migrationRules && this.migrationRules.length ) {
          dao = this.MigrationDAO.create({
            delegate: dao,
            rules: this.migrationRules,
            name: this.model.id + "_" + daoModel.id + "_" + this.name
          }, this.Y);
        }
        if ( this.cache ) {
          this.mdao = this.MDAO.create(params, this.Y);
          dao = this.CachingDAO.create({
            cache: this.dedup ?
              this.mdao :
              this.DeDupDAO.create({delegate: this.mdao}),
            src: dao,
            model: this.model}, this.Y);
        }
      }

      if ( this.seqNo && this.guid ) throw "EasyDAO 'seqNo' and 'guid' features are mutually exclusive.";

      if ( this.seqNo ) {
        var args = {__proto__: params, delegate: dao, model: this.model};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.SeqNoDAO.create(args, this.Y);
      }

      if ( this.guid ) {
        var args = {__proto__: params, delegate: dao, model: this.model};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.GUIDDAO.create(args, this.Y);
      }

      var model = this.model;

      if ( this.syncWithServer && this.isServer ) throw "isServer and syncWithServer are mutually exclusive.";

      if ( this.syncWithServer || this.isServer ) {
        if ( ! this.syncProperty || ! this.deletedProperty ) {
          if ( model.traits.indexOf('foam.core.dao.SyncTrait') != -1 ) {
            // TODO(adamvy): This doesn't work without getPrototype();
            // should models be built such that getPrototype() is unnecessary?
            this.syncProperty = model.getPrototype().SYNC_PROPERTY;
            this.deletedProperty = model.getPrototype().DELETED;
          } else {
            throw "Syncing with server requires the foam.core.dao.SyncTrait be applied to your model, '" + this.model.id + "'.";
          }
        }
      }

      if ( this.syncWithServer ) {
        var syncStrategy = this.sockets ? this.SocketSyncDAO : this.PollingSyncDAO;
        dao = syncStrategy.create({
          remoteDAO: this.EasyClientDAO.create({
            serverUri: this.serverUri,
            model: model,
            sockets: this.sockets,
            reconnectPeriod: 5000
          }, this.Y),
          syncProperty: this.syncProperty,
          deletedProperty: this.deletedProperty,
          delegate: dao,
          period: 1000
        }, this.Y);
        dao.syncRecordDAO = foam.dao.EasyDAO.create({
          model: dao.SyncRecord,
          cache: true,
          daoType: this.daoType,
          name: this.name + '_SyncRecords'
        }, this.Y);
      }

      if ( this.isServer ) {
        dao = this.VersionNoDAO.create({
          delegate: dao,
          property: this.syncProperty,
          version: 2
        }, this.Y);
      }

      if ( this.contextualize ) dao = this.ContextualizingDAO.create({
        delegate: dao
      }, this.Y);

      if ( this.cloning ) dao = this.CloningDAO.create({
        delegate: dao
      }, this.Y);

      if ( this.timing  ) dao = this.TimingDAO.create({ name: this.model.plural + 'DAO', delegate: dao }, this.Y);
      if ( this.logging ) dao = this.LoggingDAO.create({ delegate: dao }, this.Y);

      this.delegate = dao;
    },

    function addIndex() {
      /*
Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'}
         was set to $$DOC{ref:'MDAO'}, but harmless otherwise.

See $$DOC{ref:'MDAO.addIndex', text:'MDAO.addIndex()'}.
 */
      this.mdao && this.mdao.addIndex.apply(this.mdao, arguments);
      return this;
    },

    function addRawIndex() {
      /*
Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'}
         was set to $$DOC{ref:'MDAO'}, but harmless otherwise.

See $$DOC{ref:'MDAO.addRawIndex', text:'MDAO.addRawIndex()'}. */
      this.mdao && this.mdao.addRawIndex.apply(this.mdao, arguments);
      return this;
    }
  ]
});
<commit_msg>Continued EasyDAO porting to FOAM2.<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**

If you don't know which DAO implementation to choose, EasyDAO is
    ready to help. Simply this.X.EasyDAO.create() and set the flags
    to indicate what behavior you're looking for. Under the hood, EasyDAO
    will create one or more DAO instances to service your requirements.

Since EasyDAO is a proxy, just use it like you would any other
    DAO, without worrying about the internal DAO doing the work.

*/
foam.CLASS({
  package: 'foam.dao',
  name: 'EasyDAO',
  extends: 'foam.dao.ProxyDAO',

  requires: [
    'foam.dao.MDAO',
    'foam.dao.TimestampDAO',
    'foam.dao.JournalDAO',
    'foam.dao.GUIDDAO',
    'foam.dao.IDBDAO',
    'foam.dao.SequenceNumberDAO',
    //'foam.core.dao.CloningDAO',
    //'foam.core.dao.MergeDAO',
    //'foam.core.dao.MigrationDAO',
    //'foam.core.dao.StorageDAO',
    //'foam.core.dao.SyncDAO',
    //'foam.core.dao.SyncTrait',
    //'foam.core.dao.sync.PollingSyncDAO',
    //'foam.core.dao.sync.SocketSyncDAO',
    //'foam.core.dao.VersionNoDAO',
    //'foam.dao.CachingDAO',
    //'foam.dao.ContextualizingDAO',
    //'foam.dao.DeDupDAO',
    //'foam.dao.EasyClientDAO',
    //'foam.dao.LoggingDAO',
    //'foam.dao.TimingDAO'
  ],

  help: 'A facade for easy DAO setup.',

  imports: [ 'document' ],

  properties: [
    {
      name: 'name',
      factory: function() { return this.of.id; },
      //documentation: "The developer-friendly name for this $$DOC{ref:'.'}."
    },
    {
      class: 'Boolean',
      name: 'seqNo',
      value: false,
      //documentation: "Have $$DOC{ref:'.'} use a sequence number to index items. Note that $$DOC{ref:'.seqNo'} and $$DOC{ref:'.guid'} features are mutually exclusive."
    },
    {
      class: 'Boolean',
      name: 'guid',
      label: 'GUID',
      value: false,
      //documentation: "Have $$DOC{ref:'.'} generate guids to index items. Note that $$DOC{ref:'.seqNo'} and $$DOC{ref:'.guid'} features are mutually exclusive."
    },
    {
      name: 'seqProperty',
      class: 'Property',
      //documentation: "The property on your items to use to store the sequence number or guid. This is required for $$DOC{ref:'.seqNo'} or $$DOC{ref:'.guid'} mode."
    },
    {
      class: 'Boolean',
      name: 'cache',
      value: false,
      //documentation: "Enable local caching of the $$DOC{ref:'DAO'}."
    },
    {
      class: 'Boolean',
      name: 'dedup',
      value: false,
      //documentation: "Enable value de-duplication to save memory when caching."
    },
    {
      class: 'Boolean',
      name: 'logging',
      value: false,
      //documentation: "Enable logging on the $$DOC{ref:'DAO'}."
    },
    {
      class: 'Boolean',
      name: 'timing',
      value: false,
      //documentation: "Enable time tracking for concurrent $$DOC{ref:'DAO'} operations."
    },
    {
      class: 'Boolean',
      name: 'contextualize',
      value: false,
      //documentation: "Contextualize objects on .find"
    },
    {
      class: 'Boolean',
      name: 'cloning',
      value: false,
      //documentation: "True to clone results on select"
    },
    {
      name: 'daoType',
      value: 'foam.dao.IDBDAO',
      //documentation: function() { /*
//
Selects the basic functionality this $$DOC{ref:'foam.dao.EasyDAO'} should provide.
//           You can specify an instance of a DAO model definition such as
//           $$DOC{ref:'MDAO'}, or a constant indicating your requirements.

//
Choices are:

//

//
$$DOC{ref:'.ALIASES',text:'IDB'}: Use IndexDB for storage.

//
$$DOC{ref:'.ALIASES',text:'LOCAL'}: Use local storage (for Chrome Apps, this will use local, non-synced storage).

//
$$DOC{ref:'.ALIASES',text:'SYNC'}: Use synchronized storage (for Chrome Apps, this will use Chrome Sync storage).

//

//        */}
    },
    {
      class: 'Boolean',
      name: 'autoIndex',
      value: false,
      //documentation: "Automatically generate an index."
    },
    {
      class: 'FObjectArray',
      name: 'migrationRules',
      of: 'foam.core.dao.MigrationRule',
      //documentation: "Creates an internal $$DOC{ref:'MigrationDAO'} and applies the given array of $$DOC{ref:'MigrationRule'}."
    },
    {
      class: 'Boolean',
      name: 'syncWithServer'
    },
    {
      class: 'Boolean',
      name: 'sockets',
      value: false
    },
    {
      class: 'String',
      name: 'serverUri',
      factory: function() {
        return this.document && this.document.location ?
            this.document.location.origin + '/api' :
            '';
      }
    },
    {
      class: 'Boolean',
      name: 'isServer',
      value: false
    },
    {
      name: 'syncProperty'
    },
    {
      name: 'deletedProperty'
    }
  ],

  constants: {
    // Aliases for daoType
    ALIASES: {
      MDAO:  'foam.dao.MDAO',
      IDB:   'foam.dao.IDBDAO',
      LOCAL: 'foam.dao.LocalStorageDAO',
      //SYNC:  'foam.dao.StorageDAO'
    }
  },

  methods: [
    function init(args) {
      /*

On initialization, the $$DOC{ref:'.'} creates an appropriate chain of
        internal $$DOC{ref:'DAO'} instances based on the $$DOC{ref:'.'}
        property settings.

This process is transparent to the developer, and you can use your
        $$DOC{ref:'.'} like any other $$DOC{ref:'DAO'}.

      */
      this.SUPER(args);

//       if ( window.chrome && chrome.storage ) {
//         this.ALIASES.LOCAL = 'foam.core.dao.ChromeStorageDAO';
//         this.ALIASES.SYNC  = 'foam.core.dao.ChromeSyncStorageDAO';
//       }

      var daoType  = typeof this.daoType === 'string' ? this.ALIASES[this.daoType] || this.daoType : this.daoType;
      var daoModel = typeof daoType === 'string' ? this.lookup(daoType) || global[daoType] : daoType;
      var params   = { of: this.of, autoIndex: this.autoIndex };

      if ( ! daoModel ) {
        console.warn("EasyDAO: Unknown DAO Type.  Add '" + daoType + "' to requires: list.");
      }

      if ( this.name  ) params.name = this.name;
      if ( this.seqNo || this.guid ) params.property = this.seqProperty;

      var dao = daoModel.create(params, this.__subContext__);

      if ( this.MDAO.isInstance(dao) ) {
        this.mdao = dao;
        if ( this.dedup ) dao = this.DeDupDAO.create({delegate: dao});
      } else {
        if ( this.migrationRules && this.migrationRules.length ) {
          dao = this.MigrationDAO.create({
            delegate: dao,
            rules: this.migrationRules,
            name: this.model.id + "_" + daoModel.id + "_" + this.name
          });
        }
        if ( this.cache ) {
          this.mdao = this.MDAO.create(params);
          dao = this.CachingDAO.create({
            cache: this.dedup ?
              this.mdao :
              this.DeDupDAO.create({delegate: this.mdao}),
            src: dao,
            of: this.model});
        }
      }

      if ( this.seqNo && this.guid ) throw "EasyDAO 'seqNo' and 'guid' features are mutually exclusive.";

      if ( this.seqNo ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.SequenceNumberDAO.create(args);
      }

      if ( this.guid ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.GUIDDAO.create(args);
      }

      var model = this.model;

      if ( this.syncWithServer && this.isServer ) throw "isServer and syncWithServer are mutually exclusive.";

      if ( this.syncWithServer || this.isServer ) {
        if ( ! this.syncProperty || ! this.deletedProperty ) {
          if ( model.traits.indexOf('foam.core.dao.SyncTrait') != -1 ) {
            // TODO(adamvy): This doesn't work without getPrototype();
            // should models be built such that getPrototype() is unnecessary?
            this.syncProperty = model.getPrototype().SYNC_PROPERTY;
            this.deletedProperty = model.getPrototype().DELETED;
          } else {
            throw "Syncing with server requires the foam.core.dao.SyncTrait be applied to your model, '" + this.model.id + "'.";
          }
        }
      }

      if ( this.syncWithServer ) {
        var syncStrategy = this.sockets ? this.SocketSyncDAO : this.PollingSyncDAO;
        dao = syncStrategy.create({
          remoteDAO: this.EasyClientDAO.create({
            serverUri: this.serverUri,
            model: model,
            sockets: this.sockets,
            reconnectPeriod: 5000
          }),
          syncProperty: this.syncProperty,
          deletedProperty: this.deletedProperty,
          delegate: dao,
          period: 1000
        });
        dao.syncRecordDAO = foam.dao.EasyDAO.create({
          model: dao.SyncRecord,
          cache: true,
          daoType: this.daoType,
          name: this.name + '_SyncRecords'
        });
      }

      if ( this.isServer ) {
        dao = this.VersionNoDAO.create({
          delegate: dao,
          property: this.syncProperty,
          version: 2
        });
      }

      if ( this.contextualize ) dao = this.ContextualizingDAO.create({
        delegate: dao
      });

      if ( this.cloning ) dao = this.CloningDAO.create({
        delegate: dao
      });

      if ( this.timing  ) dao = this.TimingDAO.create({ name: this.model.plural + 'DAO', delegate: dao });
      if ( this.logging ) dao = this.LoggingDAO.create({ delegate: dao });

      this.delegate = dao;
    },

    function addIndex() {
      /*
Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'}
         was set to $$DOC{ref:'MDAO'}, but harmless otherwise.

See $$DOC{ref:'MDAO.addIndex', text:'MDAO.addIndex()'}.
 */
      this.mdao && this.mdao.addIndex.apply(this.mdao, arguments);
      return this;
    },

    function addRawIndex() {
      /*
Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'}
         was set to $$DOC{ref:'MDAO'}, but harmless otherwise.

See $$DOC{ref:'MDAO.addRawIndex', text:'MDAO.addRawIndex()'}. */
      this.mdao && this.mdao.addRawIndex.apply(this.mdao, arguments);
      return this;
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

FOAM_FILES([
  { name: "foam/nanos/auth/ChangePassword" },
  { name: "foam/nanos/auth/EnabledAware", flags: ['js'] },
  { name: "foam/nanos/auth/EnabledAwareInterface", flags: ['java'] },
  { name: "foam/nanos/auth/Group" },
  { name: "foam/nanos/auth/Language" },
  { name: "foam/nanos/auth/LastModifiedAware", flags: ['js'] },
  { name: "foam/nanos/auth/LastModifiedAwareInterface", flags:['java']  },
  { name: "foam/nanos/auth/LastModifiedByAware", flags: ['js'] },
  { name: "foam/nanos/auth/LastModifiedByAwareInterface", flags: ['java'] },
  { name: "foam/nanos/auth/Login" },
  { name: "foam/nanos/auth/Permission" },
  { name: "foam/nanos/auth/Country" },
  { name: "foam/nanos/auth/Region" },
  { name: "foam/nanos/auth/User" },
  { name: "foam/nanos/boot/NSpec" },
  { name: "foam/nanos/client/Client" },
  { name: "foam/nanos/menu/Menu" },
  { name: "foam/nanos/script/Language" },
  { name: "foam/nanos/script/Script" },
  { name: "foam/nanos/test/Test" },
  { name: "foam/nanos/test/TestBorder" },
  { name: "foam/nanos/cron/Cron" },
  { name: "foam/nanos/export/ExportDriverRegistry"},
  { name: "foam/nanos/export/JSONDriver"},
  { name: "foam/nanos/export/XMLDriver"},
  { name: "foam/nanos/export/CSVDriver"},
  { name: "foam/nanos/auth/Relationships" },
  { name: "foam/nanos/NanoService" },
  { name: "foam/nanos/auth/WebAuthService" },
  { name: "foam/nanos/auth/ClientAuthService" },
  { name: "foam/nanos/pm/PMInfo" },
  { name: "foam/nanos/pm/TemperatureCView" }
]);
<commit_msg>Added PMTableView to nanos.js.<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

FOAM_FILES([
  { name: "foam/nanos/auth/ChangePassword" },
  { name: "foam/nanos/auth/EnabledAware", flags: ['js'] },
  { name: "foam/nanos/auth/EnabledAwareInterface", flags: ['java'] },
  { name: "foam/nanos/auth/Group" },
  { name: "foam/nanos/auth/Language" },
  { name: "foam/nanos/auth/LastModifiedAware", flags: ['js'] },
  { name: "foam/nanos/auth/LastModifiedAwareInterface", flags:['java']  },
  { name: "foam/nanos/auth/LastModifiedByAware", flags: ['js'] },
  { name: "foam/nanos/auth/LastModifiedByAwareInterface", flags: ['java'] },
  { name: "foam/nanos/auth/Login" },
  { name: "foam/nanos/auth/Permission" },
  { name: "foam/nanos/auth/Country" },
  { name: "foam/nanos/auth/Region" },
  { name: "foam/nanos/auth/User" },
  { name: "foam/nanos/boot/NSpec" },
  { name: "foam/nanos/client/Client" },
  { name: "foam/nanos/menu/Menu" },
  { name: "foam/nanos/script/Language" },
  { name: "foam/nanos/script/Script" },
  { name: "foam/nanos/test/Test" },
  { name: "foam/nanos/test/TestBorder" },
  { name: "foam/nanos/cron/Cron" },
  { name: "foam/nanos/export/ExportDriverRegistry"},
  { name: "foam/nanos/export/JSONDriver"},
  { name: "foam/nanos/export/XMLDriver"},
  { name: "foam/nanos/export/CSVDriver"},
  { name: "foam/nanos/auth/Relationships" },
  { name: "foam/nanos/NanoService" },
  { name: "foam/nanos/auth/WebAuthService" },
  { name: "foam/nanos/auth/ClientAuthService" },
  { name: "foam/nanos/pm/PMInfo" },
  { name: "foam/nanos/pm/PMTableView" },
  { name: "foam/nanos/pm/TemperatureCView" }
]);
<|endoftext|>


<commit_before>
import _ from 'lodash';
import express from 'express';
import WebSocket from 'ws';
import bodyParser from 'body-parser';
import superagent from 'superagent';
import mongodb from 'mongodb';
import core from './forest-core';
import auth from './auth';

let serverHost=null;
let serverPort=0;

// --------------------------------

const logRequest = (req, res, next) => {
  console.log('---------------------------->');
  if(req.method==='POST') console.log(req.method, req.originalUrl, req.body && req.body.UID, req.headers.authorization||'');
  else                    console.log(req.method, req.originalUrl,                           req.headers.authorization||'');
  next();
};

const logResponse = (req, res, next) => {
  console.log(res.statusCode);
  console.log('<----------------------------');
  next();
};

const CORS = (req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization'); // Accept, X-Requested-By, Origin, Cache-Control
  next();
};

// ---- HTTP ----------------------

const app = express();

app.use(bodyParser.json());

app.options("/*",
  logRequest,
  CORS,
  (req, res, next) => {
    res.sendStatus(200);
  },
  logResponse,
);

function prefixUIDs(o){
  const s = JSON.stringify(_.omit(o, core.localProps), null, 2);
  return s.replace(/"(uid-[^"]*"[^:])/g, `"http://${serverHost}:${serverPort}/$1`);
}

function checkPKAndReturnObject(Peer, uid, res, r){
  if(!r.pk || r.pk==='FAIL'){
    res.status(404).send('Not found');
  }
  else if(r.pk==='OK' || auth.checkSig(r.pk)){
  // TODO: delete r
    return core.getObject(uid).then(o => {
      res.json(JSON.parse(prefixUIDs(o)));
      if(Peer) core.setNotify(o,Peer);
    });
  }
  else{
    res.status(404).send('Not found');
  }
  // TODO: delete r
}

app.get('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const { Peer, User } = auth.getPeerUser(req);
    const uid = req.originalUrl.substring(1);
    const rc=core.spawnTemporaryObject({
      Evaluator: 'evalRequestChecker',
      is: ['request', 'checker'],
      user: User,
      peer: Peer,
      method: 'GET',
      url: uid,
    });
    core.runEvaluator(rc).then(r => {
      if(r.pk) return checkPKAndReturnObject(Peer, uid, res, r);
      return new Promise(resolve => setTimeout(()=>core.getObject(rc).then(r=>resolve(checkPKAndReturnObject(Peer, uid, res, r))), 500));
    })
    .then(()=>next())
    .catch(e => {
      console.error(e);
      res.status(404).send('Not found');
      next();
    });
  },
  logResponse,
);

function checkPKAndSaveObject(User, Peer, body, setnotify, res, r){
  if(!r.pk || r.pk==='FAIL'){
    res.status(403).send('Forbidden');
  }
  else if(r.pk==='OK' || auth.checkSig(r.pk)){
    core.incomingObject(Object.assign({ User }, Peer && { Peer }, body), setnotify);
    res.json({ });
  }
  else{
    res.status(403).send('Forbidden');
  }
  // TODO: delete r
}

app.post('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const body=req.body;
    if(!body || !body.UID) next();
    const { Peer, User } = auth.getPeerUser(req);
    const path = req.originalUrl.substring(1);
    const setnotify=(path!=='notify' && path);
    const n=(setnotify && [setnotify] || []).concat(body.Notify||[]);
    const notifying=(n.length===1 && n[0]) || n;
    const rc=core.spawnTemporaryObject({
      Evaluator: 'evalRequestChecker',
      is: ['request', 'checker'],
      user: User,
      peer: Peer,
      method: 'POST',
      url: body.UID,
      notifying,
      body,
    });
    core.runEvaluator(rc).then(r => {
      if(r.pk) return checkPKAndSaveObject(User, Peer, body, setnotify, res, r);
      return new Promise(resolve => setTimeout(()=>core.getObject(rc).then(r=>resolve(checkPKAndSaveObject(User, Peer, body, setnotify, res, r))), 500));
    })
    .then(()=>next())
    .catch(e => {
      console.error(e);
      res.status(403).send('Forbidden');
      next();
    });
  },
  logResponse,
);

// --------------------------------

function doGet(url){
  return superagent.get(url)
    .timeout({ response: 9000, deadline: 10000 })
    .set(auth.makeHTTPAuth())
    .then(x => x.body);
}

// ---- WebSockets ----------------

const pendingWSpackets = {};

function doPost(o, u){
  if(core.isURL(u)) return Promise.resolve(false);
  const Peer = core.isNotify(u)? u: o.Peer;
  if(!pendingWSpackets[Peer]) pendingWSpackets[Peer] = [];
  pendingWSpackets[Peer].push(prefixUIDs(o));
  wsFlush(Peer);
  return Promise.resolve(true);
}

const peer2ws = {};

function wsInit(config){
  const wss = new WebSocket.Server(config);
  wss.on('connection', (ws) => {
    ws.on('message', (data) => {
      const body = JSON.parse(data);
      if(body.Peer){
        console.log('ws init:', body);
        peer2ws[body.Peer]=ws;
        ws.send(auth.makeWSAuth());
        wsFlush(body.Peer);
      }
      else{
        console.log('ws incoming:', body);
      }
    });
  });
}

function wsFlush(Peer){
  const ws = peer2ws[Peer];
  if(!ws){
    console.log('websocket not found', Peer);
    return;
  }
  let packet;
  while((packet=(pendingWSpackets[Peer]||[]).shift())){
    try{
      console.log('<<----------ws---------------', Peer);
      if(ws.readyState === ws.OPEN) ws.send(packet);
      else console.log('WebSocket closed sending\n', packet, '\nto', Peer);
    }
    catch(e){
      console.error('error sending\n', packet, '\nto', Peer, '\n', e);
    }
  }
}

// --------------------------------

core.setNetwork({ doGet, doPost });

// ---- Mongo ---------------------

let forestdb;

function persistenceInit(mongoHostPort){
  return mongodb.MongoClient.connect(mongoHostPort)
    .then((client) => {
      forestdb = client.db('forest');
    });
}

function persist(o){
  if(!o.is) return Promise.resolve();
  const collectionName = (o.is.constructor===String)? o.is:
                        ((o.is.constructor===Array)? o.is.join('-'): null);
  if(!collectionName) return Promise.resolve();
  return forestdb.collection(collectionName)
    .update({ UID: o.UID }, o, { upsert: true })
    .then(result => result.result)
    .catch(err => { console.log(err, `Failed to insert ${o.UID} in ${collectionName}`); return err });
}

function fetch(uid){
  return forestdb.collections().then(colls=>findOneFirst(colls, uid));
}

function findOneFirst(colls, uid){
  if(!(colls && colls.length)) return Promise.resolve(null);
  return colls[0].findOne({ UID: uid }, { projection: { _id: 0 }}).then(o => o || findOneFirst(colls.slice(1), uid));
}

function recache(){
  return forestdb.collections()
    .then(colls=>Promise.all(colls.map(coll=>coll.find({ Cache: 'keep-active' }, { projection: { _id: 0 }}).toArray()))
                  .then(actives => [].concat(...actives)));
}

function query(is, scope, query){
  return forestdb.collection(is.join('-'))
    .find(toMongo(scope, query.match), { projection: { _id: 0 }})
    .toArray()
    .then(r => r.map(o => query.inline? getInlineVals(o, query.inline): o.UID))
    .catch(e => console.error(e));
}

function toMongo(scope, match){
  return Object.assign({}, ...Object.keys(match).map(k => ({[k]: toMongoProp(k,match[k])})));
}

function toMongoProp(key, val){
  if(val.length===3 && val[1]==='..'){
    return { $gt: val[0], $lt: val[2] };
  }
  return val;
}

function getInlineVals(o, inline){
  return Object.assign({}, ...inline.map(k => o[k] && { [k]: o[k] }), { More: o.UID });
}

function dropAll(actually){
  return forestdb.collections()
            .then(colls=>Promise.all(colls.map(coll=>coll.stats()
              .then(s=>{
                  if(!/system.indexes/.test(s.ns)){
                    console.log(actually? '*************** dropping': '(not dropping)', s.ns, s.count);
                    return actually && coll.drop();
                  }
              })
            )));
}

core.setPersistence({ persist, fetch, recache, query });

// --------------------------------

function init({httpHost, httpPort, wsPort, mongoHostPort}){
  serverHost=httpHost; serverPort=httpPort;
  return new Promise((resolve, reject) => {
    persistenceInit(mongoHostPort)
      .then(() => {
        app.listen(httpPort, ()=>{
          console.log(`Server started on port ${httpPort}`);
          wsInit({ port: wsPort });
          resolve();
        }).on('error', (err) => reject(err));
      })
      .catch((err) => reject(err));
  });
}

export default {
  init,
  dropAll,
  cacheObjects:        core.cacheObjects,
  reCacheObjects:      core.reCacheObjects,
  setEvaluator:        core.setEvaluator,
  runEvaluator:        core.runEvaluator,
  getObject:           core.getObject,
  spawnObject:         core.spawnObject,
  makeUID:             core.makeUID,
  setLogging:          core.setLogging,
  setPeerIdentityUser: auth.setPeerIdentityUser,
}

<commit_msg>move things around<commit_after>
import _ from 'lodash';
import express from 'express';
import WebSocket from 'ws';
import bodyParser from 'body-parser';
import superagent from 'superagent';
import mongodb from 'mongodb';
import core from './forest-core';
import auth from './auth';

let serverHost=null;
let serverPort=0;

// --------------------------------

const logRequest = (req, res, next) => {
  console.log('---------------------------->');
  if(req.method==='POST') console.log(req.method, req.originalUrl, req.body && req.body.UID, req.headers.authorization||'');
  else                    console.log(req.method, req.originalUrl,                           req.headers.authorization||'');
  next();
};

const logResponse = (req, res, next) => {
  console.log(res.statusCode);
  console.log('<----------------------------');
  next();
};

const CORS = (req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization'); // Accept, X-Requested-By, Origin, Cache-Control
  next();
};

// --------------------------------

function prefixUIDs(o){
  const s = JSON.stringify(_.omit(o, core.localProps), null, 2);
  return s.replace(/"(uid-[^"]*"[^:])/g, `"http://${serverHost}:${serverPort}/$1`);
}

function checkPKAndReturnObject(Peer, uid, res, r){
  if(!r.pk || r.pk==='FAIL'){
    res.status(404).send('Not found');
  }
  else if(r.pk==='OK' || auth.checkSig(r.pk)){
    // TODO: delete r
    return core.getObject(uid).then(o => {
      res.json(JSON.parse(prefixUIDs(o)));
      if(Peer) core.setNotify(o,Peer);
    });
  }
  else{
    res.status(404).send('Not found');
  }
  // TODO: delete r
}

function checkPKAndSaveObject(User, Peer, body, setnotify, res, r){
  if(!r.pk || r.pk==='FAIL'){
    res.status(403).send('Forbidden');
  }
  else if(r.pk==='OK' || auth.checkSig(r.pk)){
    core.incomingObject(Object.assign({ User }, Peer && { Peer }, body), setnotify);
    res.json({ });
  }
  else{
    res.status(403).send('Forbidden');
  }
  // TODO: delete r
}

// ---- HTTP ----------------------

const app = express();

app.use(bodyParser.json());

app.options("/*",
  logRequest,
  CORS,
  (req, res, next) => {
    res.sendStatus(200);
  },
  logResponse,
);

app.get('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const { Peer, User } = auth.getPeerUser(req);
    const uid = req.originalUrl.substring(1);
    const rc=core.spawnTemporaryObject({
      Evaluator: 'evalRequestChecker',
      is: ['request', 'checker'],
      user: User,
      peer: Peer,
      method: 'GET',
      url: uid,
    });
    core.runEvaluator(rc).then(r => {
      if(r.pk) return checkPKAndReturnObject(Peer, uid, res, r);
      return new Promise(resolve => setTimeout(()=>core.getObject(rc).then(r=>resolve(checkPKAndReturnObject(Peer, uid, res, r))), 500));
    })
    .then(()=>next())
    .catch(e => {
      console.error(e);
      res.status(404).send('Not found');
      next();
    });
  },
  logResponse,
);

app.post('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const body=req.body;
    if(!body || !body.UID) next();
    const { Peer, User } = auth.getPeerUser(req);
    const path = req.originalUrl.substring(1);
    const setnotify=(path!=='notify' && path);
    const n=(setnotify && [setnotify] || []).concat(body.Notify||[]);
    const notifying=(n.length===1 && n[0]) || n;
    const rc=core.spawnTemporaryObject({
      Evaluator: 'evalRequestChecker',
      is: ['request', 'checker'],
      user: User,
      peer: Peer,
      method: 'POST',
      url: body.UID,
      notifying,
      body,
    });
    core.runEvaluator(rc).then(r => {
      if(r.pk) return checkPKAndSaveObject(User, Peer, body, setnotify, res, r);
      return new Promise(resolve => setTimeout(()=>core.getObject(rc).then(r=>resolve(checkPKAndSaveObject(User, Peer, body, setnotify, res, r))), 500));
    })
    .then(()=>next())
    .catch(e => {
      console.error(e);
      res.status(403).send('Forbidden');
      next();
    });
  },
  logResponse,
);

// --------------------------------

function doGet(url){
  return superagent.get(url)
    .timeout({ response: 9000, deadline: 10000 })
    .set(auth.makeHTTPAuth())
    .then(x => x.body);
}

// ---- WebSockets ----------------

const pendingWSpackets = {};

function doPost(o, u){
  if(core.isURL(u)) return Promise.resolve(false);
  const Peer = core.isNotify(u)? u: o.Peer;
  if(!pendingWSpackets[Peer]) pendingWSpackets[Peer] = [];
  pendingWSpackets[Peer].push(prefixUIDs(o));
  wsFlush(Peer);
  return Promise.resolve(true);
}

const peer2ws = {};

function wsInit(config){
  const wss = new WebSocket.Server(config);
  wss.on('connection', (ws) => {
    ws.on('message', (data) => {
      const body = JSON.parse(data);
      if(body.Peer){
        console.log('ws init:', body);
        peer2ws[body.Peer]=ws;
        ws.send(auth.makeWSAuth());
        wsFlush(body.Peer);
      }
      else{
        console.log('ws incoming:', body);
      }
    });
  });
}

function wsFlush(Peer){
  const ws = peer2ws[Peer];
  if(!ws){
    console.log('websocket not found', Peer);
    return;
  }
  let packet;
  while((packet=(pendingWSpackets[Peer]||[]).shift())){
    try{
      console.log('<<----------ws---------------', Peer);
      if(ws.readyState === ws.OPEN) ws.send(packet);
      else console.log('WebSocket closed sending\n', packet, '\nto', Peer);
    }
    catch(e){
      console.error('error sending\n', packet, '\nto', Peer, '\n', e);
    }
  }
}

// --------------------------------

core.setNetwork({ doGet, doPost });

// ---- Mongo ---------------------

let forestdb;

function persistenceInit(mongoHostPort){
  return mongodb.MongoClient.connect(mongoHostPort)
    .then((client) => {
      forestdb = client.db('forest');
    });
}

function persist(o){
  if(!o.is) return Promise.resolve();
  const collectionName = (o.is.constructor===String)? o.is:
                        ((o.is.constructor===Array)? o.is.join('-'): null);
  if(!collectionName) return Promise.resolve();
  return forestdb.collection(collectionName)
    .update({ UID: o.UID }, o, { upsert: true })
    .then(result => result.result)
    .catch(err => { console.log(err, `Failed to insert ${o.UID} in ${collectionName}`); return err });
}

function fetch(uid){
  return forestdb.collections().then(colls=>findOneFirst(colls, uid));
}

function findOneFirst(colls, uid){
  if(!(colls && colls.length)) return Promise.resolve(null);
  return colls[0].findOne({ UID: uid }, { projection: { _id: 0 }}).then(o => o || findOneFirst(colls.slice(1), uid));
}

function recache(){
  return forestdb.collections()
    .then(colls=>Promise.all(colls.map(coll=>coll.find({ Cache: 'keep-active' }, { projection: { _id: 0 }}).toArray()))
                  .then(actives => [].concat(...actives)));
}

function query(is, scope, query){
  return forestdb.collection(is.join('-'))
    .find(toMongo(scope, query.match), { projection: { _id: 0 }})
    .toArray()
    .then(r => r.map(o => query.inline? getInlineVals(o, query.inline): o.UID))
    .catch(e => console.error(e));
}

function toMongo(scope, match){
  return Object.assign({}, ...Object.keys(match).map(k => ({[k]: toMongoProp(k,match[k])})));
}

function toMongoProp(key, val){
  if(val.length===3 && val[1]==='..'){
    return { $gt: val[0], $lt: val[2] };
  }
  return val;
}

function getInlineVals(o, inline){
  return Object.assign({}, ...inline.map(k => o[k] && { [k]: o[k] }), { More: o.UID });
}

function dropAll(actually){
  return forestdb.collections()
            .then(colls=>Promise.all(colls.map(coll=>coll.stats()
              .then(s=>{
                  if(!/system.indexes/.test(s.ns)){
                    console.log(actually? '*************** dropping': '(not dropping)', s.ns, s.count);
                    return actually && coll.drop();
                  }
              })
            )));
}

core.setPersistence({ persist, fetch, recache, query });

// --------------------------------

function init({httpHost, httpPort, wsPort, mongoHostPort}){
  serverHost=httpHost; serverPort=httpPort;
  return new Promise((resolve, reject) => {
    persistenceInit(mongoHostPort)
      .then(() => {
        app.listen(httpPort, ()=>{
          console.log(`Server started on port ${httpPort}`);
          wsInit({ port: wsPort });
          resolve();
        }).on('error', (err) => reject(err));
      })
      .catch((err) => reject(err));
  });
}

export default {
  init,
  dropAll,
  cacheObjects:        core.cacheObjects,
  reCacheObjects:      core.reCacheObjects,
  setEvaluator:        core.setEvaluator,
  runEvaluator:        core.runEvaluator,
  getObject:           core.getObject,
  spawnObject:         core.spawnObject,
  makeUID:             core.makeUID,
  setLogging:          core.setLogging,
  setPeerIdentityUser: auth.setPeerIdentityUser,
}

<|endoftext|>


<commit_before>var Mode = require('./Mode');

function FFA() {
    Mode.apply(this, Array.prototype.slice.call(arguments));

    this.ID = 0;
    this.name = "Free For All";
    this.specByLeaderboard = true;
}

module.exports = FFA;
FFA.prototype = new Mode();

// Gamemode Specific Functions

FFA.prototype.leaderboardAddSort = function(player, leaderboard) {
    // Adds the player and sorts the leaderboard
    var len = leaderboard.length - 1;
    var loop = true;
    while ((len >= 0) && (loop)) {
        // Start from the bottom of the leaderboard
        if (player.getScore(false) <= leaderboard[len].getScore(false)) {
            leaderboard.splice(len + 1, 0, player);
            loop = false; // End the loop if a spot is found
        }
        len--;
    }
    if (loop) {
        // Add to top of the list because no spots were found
        leaderboard.splice(0, 0, player);
    }
};

// Override

FFA.prototype.onPlayerSpawn = function(gameServer, player) {
    // Random color
    player.color = gameServer.getRandomColor();

    // Set up variables
    var pos, startMass;

    // Check if there are ejected mass in the world.
    if (gameServer.nodesEjected.length > 0) {
        var index = Math.floor(Math.random() * 100) + 1;
        if (index <= gameServer.config.ejectSpawnPlayer) {
            // Get ejected cell
            var index = Math.floor(Math.random() * gameServer.nodesEjected.length);
            var e = gameServer.nodesEjected[index];

            // Remove ejected mass
            gameServer.removeNode(e);

            // Inherit
            pos = {
                x: e.position.x,
                y: e.position.y
            };
            startMass = e.mass;

            var color = e.getColor();
            player.setColor({
                'r': color.r,
                'g': color.g,
                'b': color.b
            });
        }
    }

    // Spawn player
    gameServer.spawnPlayer(player, pos, startMass);
};

FFA.prototype.updateLB = function(gameServer) {
    var lb = gameServer.leaderboard;
    // Loop through all clients
    for (var i = 0; i < gameServer.clients.length; i++) {
        if (typeof gameServer.clients[i] == "undefined") {
            continue;
        }

        var player = gameServer.clients[i].playerTracker;
        var playerScore = player.getScore(true);
        if (player.cells.length <= 0) {
            continue;
        }

        if (lb.length == 0) {
            // Initial player
            lb.push(player);
            continue;
        } else if (lb.length < 10) {
            this.leaderboardAddSort(player, lb);
        } else {
            // 10 in leaderboard already
            if (playerScore > lb[9].getScore(false)) {
                lb.pop();
                this.leaderboardAddSort(player, lb);
            }
        }
    }

    this.rankOne = lb[0];
};
<commit_msg>ready ffa for the leaderboard control.<commit_after>var Mode = require('./Mode');

function FFA() {
    Mode.apply(this, Array.prototype.slice.call(arguments));

    this.ID = 0;
    this.name = "Free For All";
    this.specByLeaderboard = true;
}

module.exports = FFA;
FFA.prototype = new Mode();

// Gamemode Specific Functions

FFA.prototype.leaderboardAddSort = function(player, leaderboard) {
    // Adds the player and sorts the leaderboard
    var len = leaderboard.length - 1;
    var loop = true;
    while ((len >= 0) && (loop)) {
        // Start from the bottom of the leaderboard
        if (player.getScore(false) <= leaderboard[len].getScore(false)) {
            leaderboard.splice(len + 1, 0, player);
            loop = false; // End the loop if a spot is found
        }
        len--;
    }
    if (loop) {
        // Add to top of the list because no spots were found
        leaderboard.splice(0, 0, player);
    }
};

// Override

FFA.prototype.onPlayerSpawn = function(gameServer, player) {
    // Random color
    player.color = gameServer.getRandomColor();

    // Set up variables
    var pos, startMass;

    // Check if there are ejected mass in the world.
    if (gameServer.nodesEjected.length > 0) {
        var index = Math.floor(Math.random() * 100) + 1;
        if (index <= gameServer.config.ejectSpawnPlayer) {
            // Get ejected cell
            var index = Math.floor(Math.random() * gameServer.nodesEjected.length);
            var e = gameServer.nodesEjected[index];

            // Remove ejected mass
            gameServer.removeNode(e);

            // Inherit
            pos = {
                x: e.position.x,
                y: e.position.y
            };
            startMass = e.mass;

            var color = e.getColor();
            player.setColor({
                'r': color.r,
                'g': color.g,
                'b': color.b
            });
        }
    }

    // Spawn player
    gameServer.spawnPlayer(player, pos, startMass);
};

FFA.prototype.updateLB = function(gameServer) {
    var lb = gameServer.leaderboard;
    // Loop through all clients
    for (var i = 0; i < gameServer.clients.length; i++) {
        if (typeof gameServer.clients[i] == "undefined") {
            continue;
        }

        var player = gameServer.clients[i].playerTracker;
        var playerScore = player.getScore(true);
        if (player.cells.length <= 0) {
            continue;
        }

        if (lb.length == 0) {
            // Initial player
            lb.push(player);
            continue;
        } else if (lb.length < gameServer.config.serverMaxLB) {
            this.leaderboardAddSort(player, lb);
        } else {
            // 10 in leaderboard already
            if (playerScore > lb[gameServer.config.serverMaxLB - 1].getScore(false)) {
                lb.pop();
                this.leaderboardAddSort(player, lb);
            }
        }
    }

    this.rankOne = lb[0];
};
<|endoftext|>


<commit_before>var taskPlatformAdapterPlatform = {
    validate: function(mode, success, error) {
        $('#validateOk').show();
    },
    getTaskParams: function(key, defaultValue, success, error) {
        var res = {'minScore': 0, 'maxScore': 100, 'noScore': 0, 'readOnly': true, 'randomSeed': "0", 'options': {}}; // TODO :: randomSeed
        if(key && key in res) {
            res = res[key];
        } else if(key) {
            res = defaultValue;
        }
        if(success) {
            success(res);
        } else {
            return res;
        }},
    askHint: function(hint, success, error) {
        success();
    },
    updateDisplay: function(params, success, error) {
        success();
    }
};

platform.setPlatform(taskPlatformAdapterPlatform);
$(function () {
    task.load(null, function () {
        var source = window.parent.adapterApi.getSource();
        task.reloadAnswerObject({'easy': [{'blockly': source.sourceCode}]});

        setTimeout(function() {
            $('.contentCentered').hide();
            $('#submitBtn').hide();
            $('#displayHelperAnswering').hide();
            }, 0);
        });

        var updateHeight = null;
        updateHeight = function() {
            window.parent.adapterApi.setHeight($('body').outerHeight(true));
            setTimeout(updateHeight, 1000);
        };
        updateHeight();
        setTimeout(function() {
            task.displayedSubTask.run(function() {
                if(task.displayedSubTask.context.success) {
                    $('#validateOk').show();
                }
                });
        }, 1000);
});

if(window.Blockly) {
  Blockly.JavaScript['input_num'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'parseInt(readStdin())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_next'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'parseInt(input_word())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_char'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_char'] = "function input_char() {\n"
                                                  + "    var buf = readStdin();\n";
                                                  + "    stdinBuffer = buf.substr(1);\n";
                                                  + "    return buf.substr(0, 1);\n";
                                                  + "};\n";
    var code = 'input_char()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_word'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'input_word()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_line'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'readStdin()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_list'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_num_list'] = "function input_num_list() {\n"
                                                      + "    var parts = readStdin().split(/\\s+/);\n"
                                                      + "    for(var i=0; i<parts.length; i++) {\n"
                                                      + "        parts[i] = parseInt(parts[i]);\n"
                                                      + "    }\n"
                                                      + "    return parts;\n"
                                                      + "};";
    var code = 'input_num_list()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['text_print'] = function(block) {
    return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ");\n";
  };
  Blockly.JavaScript['text_print_noend'] = Blockly.JavaScript['text_print'];
}
<commit_msg>quickAlgo: Fix text_print_noend<commit_after>var taskPlatformAdapterPlatform = {
    validate: function(mode, success, error) {
        $('#validateOk').show();
    },
    getTaskParams: function(key, defaultValue, success, error) {
        var res = {'minScore': 0, 'maxScore': 100, 'noScore': 0, 'readOnly': true, 'randomSeed': "0", 'options': {}}; // TODO :: randomSeed
        if(key && key in res) {
            res = res[key];
        } else if(key) {
            res = defaultValue;
        }
        if(success) {
            success(res);
        } else {
            return res;
        }},
    askHint: function(hint, success, error) {
        success();
    },
    updateDisplay: function(params, success, error) {
        success();
    }
};

platform.setPlatform(taskPlatformAdapterPlatform);
$(function () {
    task.load(null, function () {
        var source = window.parent.adapterApi.getSource();
        task.reloadAnswerObject({'easy': [{'blockly': source.sourceCode}]});

        setTimeout(function() {
            $('.contentCentered').hide();
            $('#submitBtn').hide();
            $('#displayHelperAnswering').hide();
            }, 0);
        });

        var updateHeight = null;
        updateHeight = function() {
            window.parent.adapterApi.setHeight($('body').outerHeight(true));
            setTimeout(updateHeight, 1000);
        };
        updateHeight();
        setTimeout(function() {
            task.displayedSubTask.run(function() {
                if(task.displayedSubTask.context.success) {
                    $('#validateOk').show();
                }
                });
        }, 1000);
});

if(window.Blockly) {
  Blockly.JavaScript['input_num'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'parseInt(readStdin())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_next'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'parseInt(input_word())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_char'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_char'] = "function input_char() {\n"
                                                  + "    var buf = readStdin();\n";
                                                  + "    stdinBuffer = buf.substr(1);\n";
                                                  + "    return buf.substr(0, 1);\n";
                                                  + "};\n";
    var code = 'input_char()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_word'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'input_word()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_line'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'readStdin()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_list'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_num_list'] = "function input_num_list() {\n"
                                                      + "    var parts = readStdin().split(/\\s+/);\n"
                                                      + "    for(var i=0; i<parts.length; i++) {\n"
                                                      + "        parts[i] = parseInt(parts[i]);\n"
                                                      + "    }\n"
                                                      + "    return parts;\n"
                                                      + "};";
    var code = 'input_num_list()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['text_print'] = function(block) {
    return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ");\n";
  };
  Blockly.JavaScript['text_print_noend'] = function(block) {
    return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ", '');\n";
  };
}
<|endoftext|>


<commit_before>export const geckoProfiler = {
  stop: jest.fn(() => Promise.resolve()),
  start: jest.fn(() => Promise.resolve()),
  pause: jest.fn(() => Promise.resolve()),
  resume: jest.fn(() => Promise.resolve()),
  getProfile: jest.fn(() => Promise.resolve()),
  getProfileAsArrayBuffer: jest.fn(() => Promise.resolve()),
  getSymbols: jest.fn(function(debugName, breakpadId) {
    return Promise.resolve();
  }),
  onRunning: {
    addListener: jest.fn(),
  },
};
<commit_msg>Cleanup getSymbols mock<commit_after>export const geckoProfiler = {
  stop: jest.fn(() => Promise.resolve()),
  start: jest.fn(() => Promise.resolve()),
  pause: jest.fn(() => Promise.resolve()),
  resume: jest.fn(() => Promise.resolve()),
  getProfile: jest.fn(() => Promise.resolve()),
  getProfileAsArrayBuffer: jest.fn(() => Promise.resolve()),
  getSymbols: jest.fn((debugName, breakpadId) => Promise.resolve()),
  onRunning: {
    addListener: jest.fn(),
  },
};
<|endoftext|>