<commit_before>(function ($, undefined) {

    // Contains all the buttons
    var buttons = [
        { label: 'MR' },
        { label: 'MS' },
        { label: 'MC' },
        { label: 'Clear', classname: 'ss-calculator-clear ss-calculator-clearfix', action: 'clear' },
        { label: 'CE', action: 'clearEntry' },
        { label: '*', classname: 'ss-calculator-multiply', action: 'operator' },
        { label: 7, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 8, action: 'number' },
        { label: 9, action: 'number' },
        { label: '+', classname: 'ss-calculator-plus', action: 'operator' },
        { label: 4, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 5, action: 'number' },
        { label: 6, action: 'number' },
        { label: '-', classname: 'ss-calculator-minus', action: 'operator' },
        { label: 1, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 2, action: 'number' },
        { label: 3, action: 'number' },
        { label: '/', classname: 'ss-calculator-divide', action: 'operator' },
        { label: 0, classname: 'ss-calculator-clearfix ss-calculator-wide', action: 'number' },
        { label: '.', classname: 'ss-calculator-dot', action: 'dot' },
        { label: '=', classname: 'ss-calculator-equals', action: 'equals' }
    ];

    // Defines the widget
    $.widget('ss.calculator', {

        version: '0.0.1',

        // configurable options
        options: {
            buttons: buttons,
            show: false,
            hide: false,
            showOnCreate: true
        },

        // Calls at the time of creation
        _create : function() {
            this.element.addClass('ss-calculator');
            this._createWrapper();
            this._createButtons();
            this._renderMarkup();

            this._on({
                'click button': this._clickHandler
            });

            this.currentDisplay = [];
            this.display = [];
            this.numericalInput = false;
        },

        // Creates the wrapper
        _createWrapper: function() {
            var el = $('<div/>'), display;
            this.shell = el.clone().addClass('ss-calculator-shell');
            display = el.clone().addClass('ss-calculator-display').appendTo(this.shell);
            el.clone().text('0').addClass('ss-calculator-calculation').appendTo(display);
            el.clone().addClass('ss-calculator-result').appendTo(display);
            if(!this.options.showOnCreate) {
                this._hide(this.element, this.options.hide)
            }
        },

        // loads the buttons
        _createButtons: function() {
            var el = $('<button/>'), container = $('<div/>').addClass('ui-helper-clearfix'), widget = this, i;

            // iterates on the buttons array
            $.each(this.options.buttons, function(i, button) {
                if(widget._trigger('beforeAddButtons', null, button)) {
                    var btn = el.clone().text(button.label).appendTo(container).button();

                    if(!!button.classname) {
                        btn.addClass(button.classname);
                    }

                    if(typeof button.action === 'string') {
                        btn.data('action', button.action);
                    }
                    else if(typeof button.action === 'function') {
                        var fName = 'custom.ss.' + i;
                        widget['_' + fName] = button.action;
                        button.data('action', fName);
                    }
                }
            });

            // updates shell
            container.appendTo(this.shell);
        },

        // Joins everything together
        _renderMarkup: function() {
            this.shell.appendTo(this.element);
        },

        _setOptions: function(options) {
            this._superApply(arguments);
        },

        _setOption: function(key, val) {
            this._super(key, val);

            if(key === 'buttons') {
                this.shell.find('button').remove();
                this._createButtons;
                this._renderMarkup;
            }
            else if(key === 'disable') {
                this.shell.find('button').button('option', key, val);
            }
        },

        show: function() {
            this._show(this.element, this.options.show);
        },

        _clickHandler: function(e) {
            var btn = $(e.target).closest('button'), fn = btn.data('action');

            this['_' + fn](e, btn);
        },

        _clear: function(e, ui) {
            console.log('clear');
        },

        _clearEntry: function(e, ui) {
            console.log('clearEntry');
        },

        _equals: function(e, ui) {
            console.log('equals');
        },

        _operator: function(e, ui) {
            console.log('operator');
        },

        _number: function(e, ui) {
            this.currentDisplay.push(ui.text());
            this._updateDisplay();
            this.numericalInput = true;
        },

        _dot: function(e, ui) {
            var dot = false, x = this.currentDisplay.length;

            if(!x) {
                this.currentDisplay.push('0');
            }

            while( --x) {
                if(this.currentDisplay[x] === '.') {
                    dot = true;
                    break;
                }
            }

            if(dot) {
                return false;
            }
            else {
                this.currentDisplay.push('.');
                this._updateDisplay();
            }
        },

        _updateDisplay: function() {
            if(this.currentDisplay.length < 18) {
                this.element.find('.ss-calculator-calculation').text(this.currentDisplay.join(''));
            }
        }

    });

}(jQuery));
<commit_msg>displays calculation, operators work, clear works, dot works<commit_after>(function ($, undefined) {

    // Contains all the buttons
    var buttons = [
        { label: 'MR' },
        { label: 'MS' },
        { label: 'MC' },
        { label: 'Clear', classname: 'ss-calculator-clear ss-calculator-clearfix', action: 'clear' },
        { label: 'CE', action: 'clearEntry' },
        { label: '*', classname: 'ss-calculator-multiply', action: 'operator' },
        { label: 7, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 8, action: 'number' },
        { label: 9, action: 'number' },
        { label: '+', classname: 'ss-calculator-plus', action: 'operator' },
        { label: 4, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 5, action: 'number' },
        { label: 6, action: 'number' },
        { label: '-', classname: 'ss-calculator-minus', action: 'operator' },
        { label: 1, classname: 'ss-calculator-clearfix', action: 'number' },
        { label: 2, action: 'number' },
        { label: 3, action: 'number' },
        { label: '/', classname: 'ss-calculator-divide', action: 'operator' },
        { label: 0, classname: 'ss-calculator-clearfix ss-calculator-wide', action: 'number' },
        { label: '.', classname: 'ss-calculator-dot', action: 'dot' },
        { label: '=', classname: 'ss-calculator-equals', action: 'equals' }
    ];

    // Defines the widget
    $.widget('ss.calculator', {

        version: '0.0.1',

        // configurable options
        options: {
            buttons: buttons,
            show: false,
            hide: false,
            showOnCreate: true
        },

        // Calls at the time of creation
        _create : function() {
            this.element.addClass('ss-calculator');
            this._createWrapper();
            this._createButtons();
            this._renderMarkup();

            this._on({
                'click button': this._clickHandler
            });

            this.currentDisplay = [];
            this.display = [];
            this.numericalInput = false;
        },

        // Creates the wrapper
        _createWrapper: function() {
            var el = $('<div/>'), display;
            this.shell = el.clone().addClass('ss-calculator-shell');
            display = el.clone().addClass('ss-calculator-display').appendTo(this.shell);
            el.clone().addClass('ss-calculator-calculation').appendTo(display);
            el.clone().text('0').addClass('ss-calculator-result').appendTo(display);
            if(!this.options.showOnCreate) {
                this._hide(this.element, this.options.hide)
            }
        },

        // loads the buttons
        _createButtons: function() {
            var el = $('<button/>'), container = $('<div/>').addClass('ui-helper-clearfix'), widget = this, i;

            // iterates on the buttons array
            $.each(this.options.buttons, function(i, button) {
                if(widget._trigger('beforeAddButtons', null, button)) {
                    var btn = el.clone().text(button.label).appendTo(container).button();

                    if(!!button.classname) {
                        btn.addClass(button.classname);
                    }

                    if(typeof button.action === 'string') {
                        btn.data('action', button.action);
                    }
                    else if(typeof button.action === 'function') {
                        var fName = 'custom.ss.' + i;
                        widget['_' + fName] = button.action;
                        button.data('action', fName);
                    }
                }
            });

            // updates shell
            container.appendTo(this.shell);
        },

        // Joins everything together
        _renderMarkup: function() {
            this.shell.appendTo(this.element);
        },

        _setOptions: function(options) {
            this._superApply(arguments);
        },

        _setOption: function(key, val) {
            this._super(key, val);

            if(key === 'buttons') {
                this.shell.find('button').remove();
                this._createButtons;
                this._renderMarkup;
            }
            else if(key === 'disable') {
                this.shell.find('button').button('option', key, val);
            }
        },

        show: function() {
            this._show(this.element, this.options.show);
        },

        _clickHandler: function(e) {
            var btn = $(e.target).closest('button'), fn = btn.data('action');

            this['_' + fn](e, btn);
        },

        _clear: function(e, ui) {
            this.currentDisplay = [];
            this.display = [];
            this._updateDisplay();
            this._display();
            this.numericalInput = false;
        },

        _clearEntry: function(e, ui) {
            console.log('clearEntry');
        },

        _equals: function(e, ui) {
            console.log('equals');
        },

        _operator: function(e, ui) {

            if(!this.display.length && !this.currentDisplay.length) {
                this.currentDisplay.push(this.element.find('.ss-calculator-result').text());
            }
            else if(this.currentDisplay.slice(0).reverse()[0] === '.') {
                this.currentDisplay.pop();
            }

            if(!this.display.length || this.numericalInput) {
                this.display.push([this.currentDisplay.join(''), ' ', ui.text(), ' '].join(''))
            }
            else if(!this.numericalInput) {
                var length = this.display.length, str = this.display[length - 1].replace(/[\*\/\+\-]/, ui.text());
                this.display.pop();
                this.display.push(str);
            }

            this._display();
            this.numericalInput = false;
        },

        _number: function(e, ui) {
            this.currentDisplay.push(ui.text());
            this._updateDisplay();
            this.numericalInput = true;
        },

        _dot: function(e, ui) {
            var dot = false, x = this.currentDisplay.length;

            if(!x) {
                this.currentDisplay.push('0');
            }

            while( --x) {
                if(this.currentDisplay[x] === '.') {
                    dot = true;
                    break;
                }
            }

            if(dot) {
                return false;
            }
            else {
                this.currentDisplay.push('.');
                this._updateDisplay();
            }
        },

        _updateDisplay: function() {
            if(!this.currentDisplay.length) {
                this.element.find('.ss-calculator-result').text('0');
            }
            else if(this.currentDisplay.length < 18) {
                this.element.find('.ss-calculator-result').text(this.currentDisplay.join(''));
            }
        },

        _display: function() {
            this.element.find('.ss-calculator-calculation').text(this.display.join(''));
            this.currentDisplay = [];
        }

    });

}(jQuery));
<|endoftext|>


<commit_before>/*
 * This file is part of WebCL – Web Computing Language.
 *
 * This Source Code Form is subject to the terms of the
 * Mozilla Public License, v. 2.0. If a copy of the MPL
 * was not distributed with this file, You can obtain
 * one at http://mozilla.org/MPL/2.0/.
 *
 * The Original Contributor of this Source Code Form is
 * Nokia Research Tampere (http://webcl.nokiaresearch.com).
 *
 * Author: Tomi Aarnio, 2014
 */

describe("Robustness", function() {

  beforeEach(function() {
    try {
      aPlatform = webcl.getPlatforms()[0];
      aDevice = aPlatform.getDevices()[0];
      ctx = createContext();
      preconditions = true;
    } catch (e) {
      ERROR("Robustness -> beforeEach: Caught exception " + e);
      ERROR("Robustness -> beforeEach: Preconditions of the describe() block failed: Skipping all tests.");
      preconditions = false;
    }
  });

  it("must not crash or throw on releaseAll()", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must not crash or throw when calling release() more than once", function()  {
    if (!preconditions) pending();
    ctx.release();
    expect('ctx.release()').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must not crash or throw when manually releasing objects in 'wrong' order", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('program.release()').not.toThrow();
    expect('kernel.release()').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  // Known failures as of 2014-03-25:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //
  it("must not crash or throw when releasing user events", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser on NVIDIA OpenCL. Run anyway?");
    if (r === false) pending();
    expect('userEvent = ctx.createUserEvent()').not.toThrow();
    expect('userEvent.release()').not.toThrow();
    expect('ctx.release()').not.toThrow();
  });

  // Known failures as of 2014-03-05:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //  * Win7 / Intel CPU driver (crashes)
  //
  it("must not crash or throw on build(<callback>)", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    buildCallback = function() {
      DEBUG("WebCLProgram.build() callback invoked!");
      expect('webcl.releaseAll()').not.toThrow();
    }
    src = loadSource('kernels/rng.cl');
    expect('program = ctx.createProgram(src)').not.toThrow();
    try {
      program.build(null, null, buildCallback);
    } catch (e) {
      expect('program.build(null, null, buildCallback)').not.toThrow();
      expect('webcl.releaseAll()').not.toThrow();
    }
  });

  // Known failures as of 2014-03-05:
  //  * Win7 / Firefox 32-bit / NVIDIA GPU driver (crashes)
  //  * Win7 / Firefox 64-bit / Intel CPU driver (crashes randomly)
  //  * Mac OSX 10.9 (crashes)
  //
  it("must not crash on setArg(<invalidArgument>)", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    src = loadSource('kernels/argtypes.cl');
    expect('program = ctx.createProgram(src)').not.toThrow();
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("objects")').not.toThrow();
    expect('kernel.setArg(0, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLBuffer expected
    expect('kernel.setArg(0, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLBuffer expected
    expect('kernel.setArg(1, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(1, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(2, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(2, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(3, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_SAMPLER');     // WebCLSampler expected
    expect('kernel.setArg(3, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_SAMPLER');     // WebCLSampler expected
    expect('webcl.releaseAll()').not.toThrow();
  });

  // Known failures as of 2014-02-12:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //  * Win7 / Intel CPU driver (freezes)
  //
  it("must not crash compiling a kernel that allocates 6 GB of 'local' memory", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    expect('kernels/largeArrayLocal.cl').not.toBuild();
    expect('kernels/largeArrayLocal.cl').not.toBuild();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must throw when trying to use an object that has been released", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
    expect('ctx.getInfo(WebCL.CONTEXT_NUM_DEVICES)').toThrow('WEBCL_IMPLEMENTATION_FAILURE');
    expect('kernel.getInfo(WebCL.PROGRAM_CONTEXT)').toThrow('WEBCL_IMPLEMENTATION_FAILURE');
    expect('webcl.releaseAll()').not.toThrow();
  });

  beforeEach(addCustomMatchers);
});
<commit_msg>New crash test for Apple<commit_after>/*
 * This file is part of WebCL – Web Computing Language.
 *
 * This Source Code Form is subject to the terms of the
 * Mozilla Public License, v. 2.0. If a copy of the MPL
 * was not distributed with this file, You can obtain
 * one at http://mozilla.org/MPL/2.0/.
 *
 * The Original Contributor of this Source Code Form is
 * Nokia Research Tampere (http://webcl.nokiaresearch.com).
 *
 * Author: Tomi Aarnio, 2014
 */

describe("Robustness", function() {

  beforeEach(function() {
    try {
      aPlatform = webcl.getPlatforms()[0];
      aDevice = aPlatform.getDevices()[0];
      ctx = createContext();
      preconditions = true;
    } catch (e) {
      ERROR("Robustness -> beforeEach: Caught exception " + e);
      ERROR("Robustness -> beforeEach: Preconditions of the describe() block failed: Skipping all tests.");
      preconditions = false;
    }
  });

  it("must not crash or throw on releaseAll()", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must not crash or throw when calling release() more than once", function()  {
    if (!preconditions) pending();
    ctx.release();
    expect('ctx.release()').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must not crash or throw when manually releasing objects in 'wrong' order", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('program.release()').not.toThrow();
    expect('kernel.release()').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
  });

  // Known failures as of 2014-03-25:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //
  it("must not crash or throw when releasing user events", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser on NVIDIA OpenCL. Run anyway?");
    if (r === false) pending();
    expect('userEvent = ctx.createUserEvent()').not.toThrow();
    expect('userEvent.release()').not.toThrow();
    expect('ctx.release()').not.toThrow();
  });

  // Known failures as of 2014-03-05:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //  * Win7 / Intel CPU driver (crashes)
  //
  it("must not crash or throw on build(<callback>)", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    buildCallback = function() {
      DEBUG("WebCLProgram.build() callback invoked!");
      expect('webcl.releaseAll()').not.toThrow();
    }
    src = loadSource('kernels/rng.cl');
    expect('program = ctx.createProgram(src)').not.toThrow();
    try {
      program.build(null, null, buildCallback);
    } catch (e) {
      expect('program.build(null, null, buildCallback)').not.toThrow();
      expect('webcl.releaseAll()').not.toThrow();
    }
  });

  // Known failures as of 2014-03-05:
  //  * Win7 / Firefox 32-bit / NVIDIA GPU driver (crashes)
  //  * Win7 / Firefox 64-bit / Intel CPU driver (crashes randomly)
  //  * Mac OSX 10.9 (crashes)
  //
  it("must not crash on setArg(<invalidArgument>)", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    src = loadSource('kernels/argtypes.cl');
    expect('program = ctx.createProgram(src)').not.toThrow();
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("objects")').not.toThrow();
    expect('kernel.setArg(0, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLBuffer expected
    expect('kernel.setArg(0, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLBuffer expected
    expect('kernel.setArg(1, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(1, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(2, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(2, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_MEM_OBJECT');  // WebCLImage expected
    expect('kernel.setArg(3, new Uint32Array( [0xdeadbeef] ))').toThrow('INVALID_SAMPLER');     // WebCLSampler expected
    expect('kernel.setArg(3, new Uint32Array( [-1, -2, -3] ))').toThrow('INVALID_SAMPLER');     // WebCLSampler expected
    expect('webcl.releaseAll()').not.toThrow();
  });

  // Known failures as of 2014-02-12:
  //  * Win7 / NVIDIA GPU driver (crashes)
  //  * Win7 / Intel CPU driver (freezes)
  //
  it("must not crash compiling a kernel that allocates 6 GB of 'local' memory", function() {
    if (!preconditions) pending();
    var r = confirm("This test case may crash your browser. Run anyway?");
    if (r === false) pending();
    expect('kernels/largeArrayLocal.cl').not.toBuild();
    expect('kernels/largeArrayLocal.cl').not.toBuild();
    expect('webcl.releaseAll()').not.toThrow();
  });

  it("must throw when trying to use an object that has been released", function() {
    if (!preconditions) pending();
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[0]=0xdeadbeef; }");
    expect('program.build()').not.toThrow();
    expect('kernel = program.createKernel("dummy")').not.toThrow();
    expect('webcl.releaseAll()').not.toThrow();
    expect('ctx.getInfo(WebCL.CONTEXT_NUM_DEVICES)').toThrow('WEBCL_IMPLEMENTATION_FAILURE');
    expect('kernel.getInfo(WebCL.PROGRAM_CONTEXT)').toThrow('WEBCL_IMPLEMENTATION_FAILURE');
    expect('webcl.releaseAll()').not.toThrow();
  });

  // Known failures as of 2014-02-12:
  //  * Mac OSX 10.9 / CPU driver (crashes)
  //
  it("must not throw on enqueueNDRangeKernel if workDim === 2", function() {
    ctx = createContext();
    queue = ctx.createCommandQueue();
    buffer = ctx.createBuffer(WebCL.MEM_READ_ONLY, 128);
    program = ctx.createProgram("kernel void dummy(global uint* buf) { buf[get_global_id(0)]=0xdeadbeef; }");
    devices = ctx.getInfo(WebCL.CONTEXT_DEVICES);
    program.build(devices);
    kernel = program.createKernelsInProgram()[0];
    kernel.setArg(0, buffer);
    expect('queue.enqueueNDRangeKernel(kernel, 2, null, [8, 2   ]); queue.finish()').not.toThrow();
  });

  beforeEach(addCustomMatchers);
});
<|endoftext|>


<commit_before>const request = require('request-promise-native');
const Discord = require('discord.js');
const revive = require('revive-stats.js')
const moment = require('moment');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
	if (message.mentions.users.size === 0 && params.length > 0) {
		message.reply("Usage:\n~info - shows your stats" + "\n~info <usermention> - shows stats of the user mentioned\n" + "(the user should have linked his forum account with his discord account)");
		return;
	}
	let user = message.mentions.users.first() || message.author;
	let id = user.id;
	let all = false;
    let atleastOne = false;
	if (id === message.author.id) all = true;
	let arr = [];
	let body = await request("http://revive-bot-discord.revive.systems/v0/discord/userinfo/" + id);
	try {
		body = JSON.parse(body)
	} catch (e) {
		console.log("error: " + body);
	}
	console.log(body);
	if (body.error) {
		if (all) return message.reply("Please link your discord account first using `~link`");
		return message.reply("The requested user has not yet linked his discord account with their revive account");
	}
	if (body.banned ==1){
		if (all) return message.reply("You are global banned");
		return message.reply("The requested user has been global banned.");
	}

	for (let i = 0; i < body.soldiers.length; i++) {
		let soldier = body.soldiers[i];
		if (!all) {
			if (soldier.nickname != body.username) continue;
		}
		let gameob = soldier.game == "stella" ? revive.bf2142 : revive.bf2;
		let g = soldier.game == "stella" ? 'bf2142' : 'bf2';
		let ranklink = soldier.game == 'stella' ? 'https://raw.githubusercontent.com/ReviveNetwork/ReviveBot/master/img/bf2142/rank_' : 'https://battlelog.co/img/ranks/rank_'
		let rank = null;
        try {
            rank = await gameob.getPlayer(soldier.pid);
        }
        catch(err) {
            continue;
        }
		if (rank ===  null) {
			continue;
		}
		let embed = new Discord.RichEmbed()
		try
		{
		    embed.setTitle(soldier.nickname).setThumbnail(ranklink + rank.rank + '.png')
		    .addField("Game: ", (soldier.game == "stella" ? "Battlefield 2142" : "Battlefield 2"), true)
		    .addField("Rank: ", (soldier.game == "stella" ? require('../../data/bf2142rank.json') : require('../../data/bf2rank.json'))[rank.rank], true)
		    .addField("Online: ", (soldier.online == 1 ? "yes" : "no"), true)
		    .addField("Last Active: ", moment(soldier.last_active, "YYYY-MM-DD HH:mm:ss").fromNow(), true)
		    .addField("KDR: ", rank.kdr, true)
		    .addField("Kills per Minute: ", rank.killsPM, true)
		    .addField("Deaths per Minute: ", rank.deathsPM, true)
		    .addField("Kill Streak: ", rank.bestKillStreak, true)
		    .addField("Death Streak: ", rank.worstDeathStreak, true)
		    .addField("Favourite Kit: ", revive.constants[g].kits[rank.favKit], true)
		    .addField("Favourite Vehicle: ", revive.constants[g].vehicles[rank.favVehicle], true)
		    .addField("Heals: ", rank.heals, true)
		    .addField("Revives: ", rank.revives, true);
			if( rank.topOpponentName && rank.topVictimName)
			{
				embed.addField("Top Opponent: ", rank.topOpponentName, true);
				embed.addField("Top Victim: ", rank.topVictimName, true);
			}
		    embed.setURL((soldier.game == "stella" ? "http://bl2142.co/bfhq.php?pid=" : "http://battlelog.co/bfhq.php?pid=") + soldier.pid)
		    .setFooter("Created " + moment(soldier.time_created, "YYYY-MM-DD HH:mm:ss").fromNow())
		    .setColor(soldier.game == "stella" ? "#0000FF" : "#ff0000");
		    await message.channel.send('', { embed: embed});
			atleastOne = true;
		}
		catch(e){
			console.log(e.stack);
			console.log(embed);
		}
	}
    if(!atleastOne)
        message.channel.send(user.toString()+" has no soldiers");
}
/**
 * description of the command
 */
const description = "Shows battlelog.co stats";
/**
 * Define Exports
 */
module.exports = {
	execute: command,
	description: description
};
<commit_msg>add null checks too<commit_after>const request = require('request-promise-native');
const Discord = require('discord.js');
const revive = require('revive-stats.js')
const moment = require('moment');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
	if (message.mentions.users.size === 0 && params.length > 0) {
		message.reply("Usage:\n~info - shows your stats" + "\n~info <usermention> - shows stats of the user mentioned\n" + "(the user should have linked his forum account with his discord account)");
		return;
	}
	let user = message.mentions.users.first() || message.author;
	let id = user.id;
	let all = false;
    let atleastOne = false;
	if (id === message.author.id) all = true;
	let arr = [];
	let body = await request("http://revive-bot-discord.revive.systems/v0/discord/userinfo/" + id);
	try {
		body = JSON.parse(body)
	} catch (e) {
		console.log("error: " + body);
	}
	console.log(body);
	if (body.error) {
		if (all) return message.reply("Please link your discord account first using `~link`");
		return message.reply("The requested user has not yet linked his discord account with their revive account");
	}
	if (body.banned ==1){
		if (all) return message.reply("You are global banned");
		return message.reply("The requested user has been global banned.");
	}

	for (let i = 0; i < body.soldiers.length; i++) {
		let soldier = body.soldiers[i];
		if (!all) {
			if (soldier.nickname != body.username) continue;
		}
		let gameob = soldier.game == "stella" ? revive.bf2142 : revive.bf2;
		let g = soldier.game == "stella" ? 'bf2142' : 'bf2';
		let ranklink = soldier.game == 'stella' ? 'https://raw.githubusercontent.com/ReviveNetwork/ReviveBot/master/img/bf2142/rank_' : 'https://battlelog.co/img/ranks/rank_'
		let rank = null;
        try {
            rank = await gameob.getPlayer(soldier.pid);
        }
        catch(err) {
            continue;
        }
		if (rank ===  null) {
			continue;
		}
		let embed = new Discord.RichEmbed()
		try
		{
		    embed.setTitle(soldier.nickname).setThumbnail(ranklink + rank.rank + '.png')
		    .addField("Game: ", (soldier.game == "stella" ? "Battlefield 2142" : "Battlefield 2"), true)
		    .addField("Rank: ", (soldier.game == "stella" ? require('../../data/bf2142rank.json') : require('../../data/bf2rank.json'))[rank.rank], true)
		    .addField("Online: ", (soldier.online == 1 ? "yes" : "no"), true)
		    .addField("Last Active: ", moment(soldier.last_active, "YYYY-MM-DD HH:mm:ss").fromNow(), true)
		    .addField("KDR: ", rank.kdr, true)
		    .addField("Kills per Minute: ", rank.killsPM, true)
		    .addField("Deaths per Minute: ", rank.deathsPM, true)
		    .addField("Kill Streak: ", rank.bestKillStreak, true)
		    .addField("Death Streak: ", rank.worstDeathStreak, true)
		    .addField("Favourite Kit: ", revive.constants[g].kits[rank.favKit], true)
		    .addField("Favourite Vehicle: ", revive.constants[g].vehicles[rank.favVehicle], true)
		    .addField("Heals: ", rank.heals, true)
		    .addField("Revives: ", rank.revives, true);
			if( rank.topOpponentName && rank.topVictimName && rank.topOpponentName !=null && rank.topVictimName !=null )
			{
				embed.addField("Top Opponent: ", rank.topOpponentName , true);
				embed.addField("Top Victim: ", rank.topVictimName, true);
			}
		    embed.setURL((soldier.game == "stella" ? "http://bl2142.co/bfhq.php?pid=" : "http://battlelog.co/bfhq.php?pid=") + soldier.pid)
		    .setFooter("Created " + moment(soldier.time_created, "YYYY-MM-DD HH:mm:ss").fromNow())
		    .setColor(soldier.game == "stella" ? "#0000FF" : "#ff0000");
		    await message.channel.send('', { embed: embed});
			atleastOne = true;
		}
		catch(e){
			console.log(e.stack);
			console.log(rank.topOpponentName +" "+ rank.topVictimName)
			console.log(embed);
		}
	}
    if(!atleastOne)
        message.channel.send(user.toString()+" has no soldiers");
}
/**
 * description of the command
 */
const description = "Shows battlelog.co stats";
/**
 * Define Exports
 */
module.exports = {
	execute: command,
	description: description
};
<|endoftext|>


<commit_before>/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
import Ember from 'ember';
import ApplicationSerializer from 'ghost/serializers/application';
import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';

export default ApplicationSerializer.extend(EmbeddedRecordsMixin, {
    // settings for the EmbeddedRecordsMixin.
    attrs: {
        tags: {embedded: 'always'}
    },

    normalizeHash: {
        // this is to enable us to still access the raw authorId
        // without requiring an extra get request (since it is an
        // async relationship).
        posts(hash) {
            hash.author_id = hash.author;
            return hash;
        }
    },

    normalizeSingleResponse(store, primaryModelClass, payload) {
        let root = this.keyForAttribute(primaryModelClass.modelName);
        let pluralizedRoot = Ember.String.pluralize(primaryModelClass.modelName);

        payload[root] = payload[pluralizedRoot][0];
        delete payload[pluralizedRoot];

        return this._super(...arguments);
    },

    normalizeArrayResponse() {
        return this._super(...arguments);
    },

    serializeIntoHash(hash, type, record, options) {
        options = options || {};
        options.includeId = true;

        // We have a plural root in the API
        let root = Ember.String.pluralize(type.modelName);
        let data = this.serialize(record, options);

        // Properties that exist on the model but we don't want sent in the payload

        delete data.uuid;
        delete data.html;
        // Inserted locally as a convenience.
        delete data.author_id;
        // Read-only virtual property.
        delete data.url;

        hash[root] = [data];
    }
});
<commit_msg>Fix redirect to posts list when saving a new post as an author<commit_after>/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
import Ember from 'ember';
import ApplicationSerializer from 'ghost/serializers/application';
import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';

export default ApplicationSerializer.extend(EmbeddedRecordsMixin, {
    // settings for the EmbeddedRecordsMixin.
    attrs: {
        tags: {embedded: 'always'}
    },

    normalize(model, hash, prop) {
        // this is to enable us to still access the raw authorId
        // without requiring an extra get request (since it is an
        // async relationship).
        if ((prop === 'post' || prop === 'posts') && hash.author !== undefined) {
            hash.author_id = hash.author;
        }

        return this._super(...arguments);
    },

    normalizeSingleResponse(store, primaryModelClass, payload) {
        let root = this.keyForAttribute(primaryModelClass.modelName);
        let pluralizedRoot = Ember.String.pluralize(primaryModelClass.modelName);

        payload[root] = payload[pluralizedRoot][0];
        delete payload[pluralizedRoot];

        return this._super(...arguments);
    },

    normalizeArrayResponse() {
        return this._super(...arguments);
    },

    serializeIntoHash(hash, type, record, options) {
        options = options || {};
        options.includeId = true;

        // We have a plural root in the API
        let root = Ember.String.pluralize(type.modelName);
        let data = this.serialize(record, options);

        // Properties that exist on the model but we don't want sent in the payload

        delete data.uuid;
        delete data.html;
        // Inserted locally as a convenience.
        delete data.author_id;
        // Read-only virtual property.
        delete data.url;

        hash[root] = [data];
    }
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'bquarks:aerialjs',
  version: '0.1.4',
  // Brief, one-line summary of the package.
  summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/bquarks/aerialjs.git',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.3.2.4');
  api.use(['ecmascript', 'bquarks:aerial-mongo@0.0.14', 'bquarks:aerial-minimongo@0.0.14',
            'bquarks:aerial-corbel@0.2.1', 'bquarks:aerial-accounts@0.4.0'], {weak: false, unordered:false});

  api.mainModule('aerialjs.js');
});

// Package.onTest(function(api) {
//   api.use('ecmascript');
//   api.use('tinytest');
//   api.use('bquarks:aerialjs');
//   api.mainModule('aerialjs-tests.js');
// });
<commit_msg>Update versions<commit_after>Package.describe({
    name: 'bquarks:aerialjs',
    version: '0.1.5',
    // Brief, one-line summary of the package.
    summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
    // URL to the Git repository containing the source code for this package.
    git: 'https://github.com/bquarks/aerialjs.git',
    // By default, Meteor will default to using README.md for documentation.
    // To avoid submitting documentation, set this field to null.
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('METEOR@1.3.2.4');
    api.use(['ecmascript', 'bquarks:aerial-mongo@0.0.15', 'bquarks:aerial-minimongo@0.0.19',
              'bquarks:aerial-corbel@0.2.11', 'bquarks:aerial-accounts@0.5.0'], { weak: false, unordered:false });

    api.mainModule('aerialjs.js');
});

// Package.onTest(function(api) {
//   api.use('ecmascript');
//   api.use('tinytest');
//   api.use('bquarks:aerialjs');
//   api.mainModule('aerialjs-tests.js');
// });
<|endoftext|>


<commit_before>import expect from 'expect.js';
import React from 'react/addons';
const { TestUtils } = React.addons;
import TreePane from '../src/TreePane';

describe('TreePane', function () {

    const model = {
        name: 'Default',
        children: [
            { name: 'react-tree-pane', children:[
                {name: 'demo', children: [
                    {name: 'bundle.js'},
                    {name: 'Example.js'}
                ]},
                {name: 'src', children: [
                    {name: 'TreePane.js'}
                ]},
                {name: 'test', children: [
                    {name: 'TreePane-test.js'}
                ]},
                {name: 'package.json'}
            ]}
        ]
    };

    const treePane = TestUtils.renderIntoDocument(
        <TreePane model={model} />
    );

    it('should render the tree pane', function () {
        new TreePaneAsserter(treePane);
    });

    it('should render the whole tree expanded', function () {
        new TreePaneAsserter(treePane)
            .findNode().assertValue('Default').assertIsExpanded().assertNumberOfChildren(1)
                .findChildNode('react-tree-pane').assertIsExpanded().assertNumberOfChildren(3)
                    .findChildNode('demo').assertIsExpanded().assertNumberOfChildren(2).end()
                    .findChildNode('src').assertIsExpanded().assertNumberOfChildren(1).end()
                    .findChildNode('test').assertIsExpanded().assertNumberOfChildren(1).end()
        ;
    });
});

class TreePaneAsserter {

    constructor(treePane) {
        this.treePane = treePane;
    }

    findNode() {
        return new NodeAsserter(this);
    }

}

class NodeAsserter {
    constructor(parent) {
        this.parent = parent;
    }

    findCell() {return new CellAsserter(this) }
    assertValue() { return this; }
    assertIsExpanded() { return this; }
    assertIsCollapsed() { return this; }
    assertNumberOfChildren(expected) { return this; }
    findChildNode(value) { return new NodeAsserter(this) }
    end() { return this.parent; }
}

class CellAsserter {
    constructor(parent) {
        this.parent = parent;
    }
    assertValue() { return this; }
    end() { return this.parent; }
}

<commit_msg>test DSL<commit_after>import expect from 'expect.js';
import React from 'react/addons';
const { TestUtils } = React.addons;
import TreePane from '../src/TreePane';

describe('TreePane', function () {

    const model = {
        name: 'Default',
        children: [
            { name: 'react-tree-pane', children:[
                {name: 'demo', children: [
                    {name: 'bundle.js'},
                    {name: 'Example.js'}
                ]},
                {name: 'src', children: [
                    {name: 'TreePane.js'}
                ]},
                {name: 'test', children: [
                    {name: 'TreePane-test.js'}
                ]},
                {name: 'package.json'}
            ]}
        ]
    };

    it('should render the whole tree expanded', function () {

        var element = document.createElement('div');
        React.render(<TreePane model={model} />, element);

        new TreePaneAsserter(element)
            .findNode().assertValue('Default').assertIsExpanded().assertNumberOfChildren(1).assertChildren('react-tree-pane')
                .findChildNode('react-tree-pane').assertIsExpanded().assertNumberOfChildren(4).assertChildren('demo', 'src', 'test')
                    .findChildNode('demo').assertIsExpanded().assertNumberOfChildren(2).end()
                    .findChildNode('src').assertIsExpanded().assertNumberOfChildren(1).end()
                    .findChildNode('test').assertIsExpanded().assertNumberOfChildren(1).end()
                    .findChildNode('package.json').assertNumberOfChildren(0).end() // isLeaf
        ;
    });

    it('should collapse whole tree', function () {

        var element = document.createElement('div');
        React.render(<TreePane model={model} />, element);

        new TreePaneAsserter(element)
            .findNode().assertValue('Default').assertIsExpanded().collapse().end()
            .findNode().assertValue('Default').assertIsCollapsed()
        ;

        console.info('', element.innerHTML);
    });

});

class TreePaneAsserter {

    constructor(element) {
        this.element = element;
        //console.info('element', element.innerHTML);
    }

    findNode() {
        let treePane = this.element.children[0];
        let childNode = treePane.children[0];
        return new NodeAsserter(this, childNode);
    }

}

class NodeAsserter {

    constructor(parent, node) {
        console.info('NodeAsserter', node.dataset.reactid);
        this.parent = parent;
        this.node = node;
        this.toggle = node.children[0];
    }

    findCell() {
        //todo
        return new CellAsserter(this);
    }

    assertValue(expected) {
        expect(this.node.children[0].children[0].innerHTML).to.contain(expected);
        return this;
    }

    expand() {
        this.assertIsCollapsed();
        TestUtils.Simulate.click(this.toggle);
        this.assertIsExpanded();
        return this;
    }

    collapse() {
        this.assertIsExpanded();
        TestUtils.Simulate.click(this.toggle);
        this.assertIsCollapsed();
        return this;
    }

    assertIsExpanded() {
        expect(this.toggle.className).to.contain('collapse');
        return this;
    }

    assertIsCollapsed() {
        expect(this.toggle.className).to.contain('expand');
        return this;
    }

    assertNumberOfChildren(expected) {
        let children = this.findChildren();
        expect(children.length).to.equal(expected);
        return this;
    }

    assertChildren(expected) {
        //todo
        return this;
    }

    findChildNode(value) {
        var children = this.filterChildren((child) => {
            return !!(child.className === 'Node' && child.children[0].children[0].innerHTML === value);
        });
        return new NodeAsserter(this, children[0]);
    }

    findChildren() {
        return this.filterChildren((child) => {
            return child.className === 'Node';
        });
    }

    filterChildren(filter) {
        return [].slice.call(this.node.children).filter(filter);
    }

    end() {
        return this.parent;
    }
}

class CellAsserter {
    constructor(parent) {
        this.parent = parent;
    }

    assertValue() {
        //todo
        return this;
    }

    end() {
        return this.parent;
    }
}

<|endoftext|>


<commit_before>var lf = require('./lfcli.js');
var issue = require('./issue.js');
var userFunc = require('./user.js');
var ejs = require('./ejs.js');
var logger = require('./logger.js');

var getMemberSupport = function(support, issue, ini) {
	for(var a = 0; a < support.length; a++) {
		if(support[a].length > 0 && support[a][0].issue_id == issue) {
			for(var b = 0; b < support[a].length; b++) {
				if(support[a][b].initiative_id == ini) {
					return true;
				}
			}
		}
	}
}

var area = function(state, render, page, memberpage, issue_sort_criteria) {
	var area_id = state.url.query.area_id;
	var builtArea = {};
	var issues = [];
	var policies = [];
	var interest = [];
	var inis = [];
	var inis_by_issueid = {};
	var members = [];
	var users = [];
	var support = [];
	var membershipDone = false;
	var issueDone = false;

	function max_total_supporters(issueid) {
		var inis = inis_by_issueid[issueid];
		var i;
		var max = 0;
		if(inis) {
			for(i = 0; i < inis.length; i++) {
				if(inis[i].supporter_count > max) {
					max = inis[i].supporter_count;
				}
			}
		}
		logger(4, 'Max total supporters for ' + issueid + ': ' + max);
		return max;
	}

	var finish = function() {
		if(builtArea.name && builtArea.unit
			&& membershipDone == true && issueDone == true
			&& interest.length == issues.length
			&& inis.length == issues.length
			&& members.length == users.length
			&& support.length == issues.length ) {

			builtArea.issues = [];
			builtArea.delegations = [];
			builtArea.members = [];
			builtArea.delegationnumber = 0;

			var builtIssue = {};
			var quorum_num, quorum_den;

			var start_issue = 0;
			var end_issue = 6;
			if(page > 1) {
				start_issue = (page - 1) * 6;
				end_issue = page * 6;
			}

			var pages = Math.ceil(issues.length / 6);
			if(pages == 0) {
				pages = 1;
			}

			builtArea.issuespage = page;
			builtArea.issuespages = pages;

			var start_member = 0;
			var end_member = 24;
			if(memberpage > 1) {
				start_member = (memberpage - 1) * 24;
				end_member = memberpage * 24;
			}

			var memberpages = Math.ceil(members.length / 24);
			if(memberpages == 0) {
				memberpages = 1;
			}

			builtArea.memberspage = memberpage;
			builtArea.memberspages = memberpages;

			// sort issues by given criteria
			var issue_sort_function;
			logger(2, 'issue sort criteria is ' + issue_sort_criteria);
			switch(issue_sort_criteria) {
				case '1':
					logger(2, 'sort by max potential supporters (includes actual)');
					issue_sort_function = function(a,b) {
						return max_total_supporters(b.id) - max_total_supporters(a.id);
					}
					break;
				case '3':
					logger(2, 'sorting highes population first');
					issue_sort_function = function(a,b) {
						return b.population - a.polulation;
					};
					break;
				case '4':
					logger(2, 'sorting newest issues first');
					issue_sort_function = function(a,b) {
						if (a.created < b.created)
							return 1;
						else if (a.created > b.created)
							return -1;
						else
							return 0;
					};
					break;
				case '5':
					logger(2, 'sorting oldest issues first');
					issue_sort_function = function(a,b) {
						if (a.created < b.created)
							return -1;
						else if (a.created > b.created)
							return 1;
						else
							return 0;
					};
			};
			if(issue_sort_function) {
				issues.sort(issue_sort_function);
			}
			state.context.selected_issue_sort_criteria = issue_sort_criteria;

			// only the first 6 issues
			for(var i = start_issue; i < issues.length && i < end_issue; i++) {

				builtIssue = {};
				builtIssue.id = issues[i].id;

				builtIssue.status = issue.getIssueStateText(issues[i].state);

				for(var a = 0; a < interest.length; a++) {
					if(interest[a].issue_id == builtIssue.id && interest[a].iwatchissue == true) {
						builtIssue.iwatchissue = true;
					}
				}

				for(var a = 0; a < policies.length; a++) {
					if(policies[a].id == issues[i].policy_id) {
						quorum_num = policies[a].issue_quorum_num;
						quorum_den = policies[a].issue_quorum_den;
					}
				}

				inis_of_issue = inis_by_issueid[builtIssue.id];

				if(issues[i].ranks_available) {
					// only keep admitted inis
					admitted_inis = [];
					for(var b = 0; b < inis_of_issue.length; b++) {
						if(inis_of_issue[b].admitted) {
							admitted_inis.push(inis_of_issue[b])
						}
					}
					inis_of_issue = admitted_inis;

					// sort inis by rank
					Array.prototype.sort.call(inis_of_issue, function(a,b) {
						if (a.rank < b.rank)
							return -1;
						else if (a.rank > b.rank)
							return 1;
						else
							return 0;
					});
				}
				else {
					// sort inis by supporter
					Array.prototype.sort.call(inis_of_issue, function(a,b) {
						if (a.satisfied_supporter_count > b.satisfied_supporter_count)
							return -1;
						else if (a.satisfied_supporter_count < b.satisfied_supporter_count)
							return 1;
						else
							return 0;
					});
				}

				// TODO do something if no ini is admitted..
				if(inis_of_issue[0] == undefined) {
					inis_of_issue = inis_by_issueid[builtIssue.id];
				}

				builtIssue.initiative_id = inis_of_issue[0].id;
				builtIssue.title = inis_of_issue[0].name;
				builtIssue.supporter = inis_of_issue[0].satisfied_supporter_count;
				builtIssue.potsupporter = inis_of_issue[0].supporter_count - inis_of_issue[0].satisfied_supporter_count;
				builtIssue.uninterested = ( builtArea.membernumber - builtIssue.supporter ) - builtIssue.potsupporter;
				if(builtIssue.uninterested < 0) {
					builtIssue.uninterested = 0;
				}

				var total = builtIssue.supporter + builtIssue.potsupporter + builtIssue.uninterested;
				builtIssue.support = Math.floor(( builtIssue.supporter / total ) * 100);
				builtIssue.potential = Math.floor(( builtIssue.potsupporter / total ) * 100);
				builtIssue.uninvolved = Math.floor(( builtIssue.uninterested / total ) * 100);
				builtIssue.quorum = Math.floor(100 * quorum_num / quorum_den);

				// check if member supports ini
				if(getMemberSupport(support, builtIssue.id, inis_of_issue[0].id)) {
					builtIssue.isupportini = true;
				}

				builtIssue.alternativeinis = [];

				for(var b = 1; b < inis_of_issue.length; b++) {
					alternativeIni = {};

					alternativeIni.id = inis_of_issue[b].id;
					alternativeIni.title = inis_of_issue[b].name;
					alternativeIni.supporter = inis_of_issue[b].satisfied_supporter_count;
					alternativeIni.potsupporter = inis_of_issue[b].supporter_count - inis_of_issue[b].satisfied_supporter_count;
					alternativeIni.uninterested = ( builtArea.membernumber - alternativeIni.supporter ) - alternativeIni.potsupporter;
					if(alternativeIni.uninterested < 0) {
						alternativeIni.uninterested = 0;
					}

					var total = alternativeIni.supporter + alternativeIni.potsupporter + alternativeIni.uninterested;
					alternativeIni.support = Math.floor(( alternativeIni.supporter / total ) * 100);
					alternativeIni.potential = Math.floor(( alternativeIni.potsupporter / total ) * 100);
					alternativeIni.uninvolved = Math.floor(( alternativeIni.uninterested / total ) * 100);

					// check if member supports ini
					if(getMemberSupport(support, builtIssue.id, inis_of_issue[b].id)) {
						alternativeIni.isupportini = true;
					}

					builtIssue.alternativeinis.push(alternativeIni);
				}

				builtArea.issues.push(builtIssue);
			}

			// get members
			for(var i = start_member; i < members.length && i < end_member; i++) {
				var builtMember = {};
				for(var a = 0; a < users.length; a++) {
					if(users[a].id == members[i].member_id) {
						builtMember = userFunc.getUserBasic(users[a]);
					}
				}
				builtArea.members.push(builtMember);
			}

			state.context.area = builtArea;
			render();
		}
	}

	var issue_id;

	// get the area
	lf.query('/area', { 'area_id': area_id, 'include_units': 1 }, state, function(res) {
		builtArea.name = res.result[0].name;
		builtArea.unit = res.units[res.result[0].unit_id].name;
		builtArea.id = res.result[0].id;
		builtArea.membernumber = res.result[0].member_weight;

		var issue_params = { 'area_id': area_id, 'include_policies': 1 };
		var issue_state = state.url.query.issue_state;
		if(issue_state && issue_state) {
			issue_params.issue_state = map_issue_states_to_lf(issue_state);
		}
		state.context.selected_issue_state = issue_state || '8';
		lf.query('/issue', issue_params, state, function(issue_res) {
			for(var i = 0; i < issue_res.result.length; i++) {
				issues.push(issue_res.result[i]);

				issue_id = issue_res.result[i].id;
				lf.query('/interest', { 'issue_id': issue_id, 'snapshot': 'latest', 'member_id': state.user_id() }, state, function(interest_res) {
					if(interest_res.result.length > 0) {
						interest.push({ 'issue_id': interest_res.result[0].issue_id, 'iwatchissue': true});
					}
					else {
						interest.push({ 'issue_id': 0, 'iwatchissue': false});
					}
					finish();
				});

				lf.query('/initiative', { 'issue_id': issue_id }, state, function(ini_res) {
					inis.push(ini_res.result);
					if(ini_res.result.length > 0) {
						inis_by_issueid[ini_res.result[0].issue_id] = ini_res.result;
					}
					finish();
				});

				lf.query('/supporter', { 'issue_id': issue_id, 'snapshot': 'latest', 'member_id': state.user_id() }, state, function(support_res) {
					support.push(support_res.result);
					finish();
				});

				policies.push(issue_res.policies[issue_res.result[i].policy_id]);
			}

			issueDone = true;
			finish();
		});

		lf.query('/membership', { 'area_id': area_id }, state, function(member_res) {
			for(var i = 0; i < member_res.result.length; i++) {
				members.push(member_res.result[i]);

				lf.query('/member', { 'member_id': member_res.result[i].member_id }, state, function(user_res) {
					users.push(user_res.result[0]);
					finish();
				});

				if(member_res.result[i].member_id == state.user_id()) {
					builtArea.member = true;
					break;
				}
			}
			membershipDone = true;
			finish();
		});

		finish();
	});

}

exports.show = area;

function map_issue_states_to_lf(bc_state) {
	switch('' + bc_state) {
		case '1':
			return 'open';
		case '2':
			return 'admission';
		case '3':
			return 'discussion';
		case '4':
			return 'verification';
		case '5':
			return 'voting';
		case '6':
			return 'finished_without_winner,finished_with_winner'
		case '7':
			return 'canceled_revoked_before_accepted,canceled_issue_not_accepted,canceled_after_revocation_during_discussion,canceled_after_revocation_during_verification,canceled_no_initiative_admitted';
		case '8':
			return '';
		default:
			return 'open';
	}
}

exports.update_issues_table = function(state) {
	// we need an area id
	if(!state.url.query.area_id) {
		logger(1, 'Please provide area_id parameter');
		invalidURL(state);
		return;
	}

	// get page numbers
	var page = 1;
	var memberpage = 1;
	var issue_sort_criteria = 1;
	if(state.url.query.page) {
		page = state.url.query.page;
	}
	if(state.url.query.memberpage) {
		memberpage = state.url.query.memberpage;
	}
	if(state.url.query.issue_sort_criteria) {
		issue_sort_criteria = state.url.query.issue_sort_criteria;
	}

	var finish = function() {
		var ctx = state.context;
		if(ctx.area !== undefined) {
			ejs.render(state, '/area_issues_table.tpl', true);
		}
	}

	// TODO refactor to avoid querying members
	exports.show(state, finish, page, memberpage, issue_sort_criteria);
};

<commit_msg>Enable sorting of issues by satisfied supporters on area page.<commit_after>var lf = require('./lfcli.js');
var issue = require('./issue.js');
var userFunc = require('./user.js');
var ejs = require('./ejs.js');
var logger = require('./logger.js');

var getMemberSupport = function(support, issue, ini) {
	for(var a = 0; a < support.length; a++) {
		if(support[a].length > 0 && support[a][0].issue_id == issue) {
			for(var b = 0; b < support[a].length; b++) {
				if(support[a][b].initiative_id == ini) {
					return true;
				}
			}
		}
	}
}

var area = function(state, render, page, memberpage, issue_sort_criteria) {
	var area_id = state.url.query.area_id;
	var builtArea = {};
	var issues = [];
	var policies = [];
	var interest = [];
	var inis = [];
	var inis_by_issueid = {};
	var members = [];
	var users = [];
	var support = [];
	var membershipDone = false;
	var issueDone = false;

	function max_total_supporters(issueid) {
		var inis = inis_by_issueid[issueid];
		var i;
		var max = 0;
		if(inis) {
			for(i = 0; i < inis.length; i++) {
				if(inis[i].supporter_count > max) {
					max = inis[i].supporter_count;
				}
			}
		}
		logger(4, 'Max total supporters for ' + issueid + ': ' + max);
		return max;
	}

	function max_supporters(issueid) {
		var inis = inis_by_issueid[issueid];
		var i;
		var max = 0;
		if(inis) {
			for(i = 0; i < inis.length; i++) {
				if(inis[i].supporter_count > max) {
					max = inis[i].satisfied_supporter_count;
				}
			}
		}
		logger(4, 'Max supporters for ' + issueid + ': ' + max);
		return max;
	}

	var finish = function() {
		if(builtArea.name && builtArea.unit
			&& membershipDone == true && issueDone == true
			&& interest.length == issues.length
			&& inis.length == issues.length
			&& members.length == users.length
			&& support.length == issues.length ) {

			builtArea.issues = [];
			builtArea.delegations = [];
			builtArea.members = [];
			builtArea.delegationnumber = 0;

			var builtIssue = {};
			var quorum_num, quorum_den;

			var start_issue = 0;
			var end_issue = 6;
			if(page > 1) {
				start_issue = (page - 1) * 6;
				end_issue = page * 6;
			}

			var pages = Math.ceil(issues.length / 6);
			if(pages == 0) {
				pages = 1;
			}

			builtArea.issuespage = page;
			builtArea.issuespages = pages;

			var start_member = 0;
			var end_member = 24;
			if(memberpage > 1) {
				start_member = (memberpage - 1) * 24;
				end_member = memberpage * 24;
			}

			var memberpages = Math.ceil(members.length / 24);
			if(memberpages == 0) {
				memberpages = 1;
			}

			builtArea.memberspage = memberpage;
			builtArea.memberspages = memberpages;

			// sort issues by given criteria
			var issue_sort_function;
			logger(2, 'issue sort criteria is ' + issue_sort_criteria);
			switch(issue_sort_criteria) {
				case '1':
					logger(2, 'sort by max potential supporters (includes actual)');
					issue_sort_function = function(a,b) {
						return max_total_supporters(b.id) - max_total_supporters(a.id);
					}
					break;
				case '2':
					logger(2, 'sort by satisfied supporters');
					issue_sort_function = function(a,b) {
						return max_supporters(b.id) - max_supporters(a.id);
					}
					break;
				case '3':
					logger(2, 'sorting highes population first');
					issue_sort_function = function(a,b) {
						return b.population - a.polulation;
					};
					break;
				case '4':
					logger(2, 'sorting newest issues first');
					issue_sort_function = function(a,b) {
						if (a.created < b.created)
							return 1;
						else if (a.created > b.created)
							return -1;
						else
							return 0;
					};
					break;
				case '5':
					logger(2, 'sorting oldest issues first');
					issue_sort_function = function(a,b) {
						if (a.created < b.created)
							return -1;
						else if (a.created > b.created)
							return 1;
						else
							return 0;
					};
			};
			if(issue_sort_function) {
				issues.sort(issue_sort_function);
			}
			state.context.selected_issue_sort_criteria = issue_sort_criteria;

			// only the first 6 issues
			for(var i = start_issue; i < issues.length && i < end_issue; i++) {

				builtIssue = {};
				builtIssue.id = issues[i].id;

				builtIssue.status = issue.getIssueStateText(issues[i].state);

				for(var a = 0; a < interest.length; a++) {
					if(interest[a].issue_id == builtIssue.id && interest[a].iwatchissue == true) {
						builtIssue.iwatchissue = true;
					}
				}

				for(var a = 0; a < policies.length; a++) {
					if(policies[a].id == issues[i].policy_id) {
						quorum_num = policies[a].issue_quorum_num;
						quorum_den = policies[a].issue_quorum_den;
					}
				}

				inis_of_issue = inis_by_issueid[builtIssue.id];

				if(issues[i].ranks_available) {
					// only keep admitted inis
					admitted_inis = [];
					for(var b = 0; b < inis_of_issue.length; b++) {
						if(inis_of_issue[b].admitted) {
							admitted_inis.push(inis_of_issue[b])
						}
					}
					inis_of_issue = admitted_inis;

					// sort inis by rank
					Array.prototype.sort.call(inis_of_issue, function(a,b) {
						if (a.rank < b.rank)
							return -1;
						else if (a.rank > b.rank)
							return 1;
						else
							return 0;
					});
				}
				else {
					// sort inis by supporter
					Array.prototype.sort.call(inis_of_issue, function(a,b) {
						if (a.satisfied_supporter_count > b.satisfied_supporter_count)
							return -1;
						else if (a.satisfied_supporter_count < b.satisfied_supporter_count)
							return 1;
						else
							return 0;
					});
				}

				// TODO do something if no ini is admitted..
				if(inis_of_issue[0] == undefined) {
					inis_of_issue = inis_by_issueid[builtIssue.id];
				}

				builtIssue.initiative_id = inis_of_issue[0].id;
				builtIssue.title = inis_of_issue[0].name;
				builtIssue.supporter = inis_of_issue[0].satisfied_supporter_count;
				builtIssue.potsupporter = inis_of_issue[0].supporter_count - inis_of_issue[0].satisfied_supporter_count;
				builtIssue.uninterested = ( builtArea.membernumber - builtIssue.supporter ) - builtIssue.potsupporter;
				if(builtIssue.uninterested < 0) {
					builtIssue.uninterested = 0;
				}

				var total = builtIssue.supporter + builtIssue.potsupporter + builtIssue.uninterested;
				builtIssue.support = Math.floor(( builtIssue.supporter / total ) * 100);
				builtIssue.potential = Math.floor(( builtIssue.potsupporter / total ) * 100);
				builtIssue.uninvolved = Math.floor(( builtIssue.uninterested / total ) * 100);
				builtIssue.quorum = Math.floor(100 * quorum_num / quorum_den);

				// check if member supports ini
				if(getMemberSupport(support, builtIssue.id, inis_of_issue[0].id)) {
					builtIssue.isupportini = true;
				}

				builtIssue.alternativeinis = [];

				for(var b = 1; b < inis_of_issue.length; b++) {
					alternativeIni = {};

					alternativeIni.id = inis_of_issue[b].id;
					alternativeIni.title = inis_of_issue[b].name;
					alternativeIni.supporter = inis_of_issue[b].satisfied_supporter_count;
					alternativeIni.potsupporter = inis_of_issue[b].supporter_count - inis_of_issue[b].satisfied_supporter_count;
					alternativeIni.uninterested = ( builtArea.membernumber - alternativeIni.supporter ) - alternativeIni.potsupporter;
					if(alternativeIni.uninterested < 0) {
						alternativeIni.uninterested = 0;
					}

					var total = alternativeIni.supporter + alternativeIni.potsupporter + alternativeIni.uninterested;
					alternativeIni.support = Math.floor(( alternativeIni.supporter / total ) * 100);
					alternativeIni.potential = Math.floor(( alternativeIni.potsupporter / total ) * 100);
					alternativeIni.uninvolved = Math.floor(( alternativeIni.uninterested / total ) * 100);

					// check if member supports ini
					if(getMemberSupport(support, builtIssue.id, inis_of_issue[b].id)) {
						alternativeIni.isupportini = true;
					}

					builtIssue.alternativeinis.push(alternativeIni);
				}

				builtArea.issues.push(builtIssue);
			}

			// get members
			for(var i = start_member; i < members.length && i < end_member; i++) {
				var builtMember = {};
				for(var a = 0; a < users.length; a++) {
					if(users[a].id == members[i].member_id) {
						builtMember = userFunc.getUserBasic(users[a]);
					}
				}
				builtArea.members.push(builtMember);
			}

			state.context.area = builtArea;
			render();
		}
	}

	var issue_id;

	// get the area
	lf.query('/area', { 'area_id': area_id, 'include_units': 1 }, state, function(res) {
		builtArea.name = res.result[0].name;
		builtArea.unit = res.units[res.result[0].unit_id].name;
		builtArea.id = res.result[0].id;
		builtArea.membernumber = res.result[0].member_weight;

		var issue_params = { 'area_id': area_id, 'include_policies': 1 };
		var issue_state = state.url.query.issue_state;
		if(issue_state && issue_state) {
			issue_params.issue_state = map_issue_states_to_lf(issue_state);
		}
		state.context.selected_issue_state = issue_state || '8';
		lf.query('/issue', issue_params, state, function(issue_res) {
			for(var i = 0; i < issue_res.result.length; i++) {
				issues.push(issue_res.result[i]);

				issue_id = issue_res.result[i].id;
				lf.query('/interest', { 'issue_id': issue_id, 'snapshot': 'latest', 'member_id': state.user_id() }, state, function(interest_res) {
					if(interest_res.result.length > 0) {
						interest.push({ 'issue_id': interest_res.result[0].issue_id, 'iwatchissue': true});
					}
					else {
						interest.push({ 'issue_id': 0, 'iwatchissue': false});
					}
					finish();
				});

				lf.query('/initiative', { 'issue_id': issue_id }, state, function(ini_res) {
					inis.push(ini_res.result);
					if(ini_res.result.length > 0) {
						inis_by_issueid[ini_res.result[0].issue_id] = ini_res.result;
					}
					finish();
				});

				lf.query('/supporter', { 'issue_id': issue_id, 'snapshot': 'latest', 'member_id': state.user_id() }, state, function(support_res) {
					support.push(support_res.result);
					finish();
				});

				policies.push(issue_res.policies[issue_res.result[i].policy_id]);
			}

			issueDone = true;
			finish();
		});

		lf.query('/membership', { 'area_id': area_id }, state, function(member_res) {
			for(var i = 0; i < member_res.result.length; i++) {
				members.push(member_res.result[i]);

				lf.query('/member', { 'member_id': member_res.result[i].member_id }, state, function(user_res) {
					users.push(user_res.result[0]);
					finish();
				});

				if(member_res.result[i].member_id == state.user_id()) {
					builtArea.member = true;
					break;
				}
			}
			membershipDone = true;
			finish();
		});

		finish();
	});

}

exports.show = area;

function map_issue_states_to_lf(bc_state) {
	switch('' + bc_state) {
		case '1':
			return 'open';
		case '2':
			return 'admission';
		case '3':
			return 'discussion';
		case '4':
			return 'verification';
		case '5':
			return 'voting';
		case '6':
			return 'finished_without_winner,finished_with_winner'
		case '7':
			return 'canceled_revoked_before_accepted,canceled_issue_not_accepted,canceled_after_revocation_during_discussion,canceled_after_revocation_during_verification,canceled_no_initiative_admitted';
		case '8':
			return '';
		default:
			return 'open';
	}
}

exports.update_issues_table = function(state) {
	// we need an area id
	if(!state.url.query.area_id) {
		logger(1, 'Please provide area_id parameter');
		invalidURL(state);
		return;
	}

	// get page numbers
	var page = 1;
	var memberpage = 1;
	var issue_sort_criteria = 1;
	if(state.url.query.page) {
		page = state.url.query.page;
	}
	if(state.url.query.memberpage) {
		memberpage = state.url.query.memberpage;
	}
	if(state.url.query.issue_sort_criteria) {
		issue_sort_criteria = state.url.query.issue_sort_criteria;
	}

	var finish = function() {
		var ctx = state.context;
		if(ctx.area !== undefined) {
			ejs.render(state, '/area_issues_table.tpl', true);
		}
	}

	// TODO refactor to avoid querying members
	exports.show(state, finish, page, memberpage, issue_sort_criteria);
};

<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "proc", "c9", "pubsub", "auth"
    ];
    main.provides = ["plugin.installer"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var c9 = imports.c9;
        var proc = imports.proc;
        var auth = imports.auth;
        var pubsub = imports.pubsub;

        var updates = options.updates;
        var architect;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var HASSDK = c9.location.indexOf("sdk=1") > -1;

        var queue = [];
        var installing;

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            if (!HASSDK) return;

            pubsub.on("message", function(message) {
                if (message.type != "package")
                    return;

                console.log("PubSub package API message", message);
                var action = message.action;
                var body = message.body;

                // Only accept packages that are installed for this project
                if (body.pid && body.pid != c9.projectId)
                    return;

                // Only accept packages that are installed for this user
                if (body.uid && body.uid != c9.uid)
                    return;

                if (action == "install") {
                    installPlugins([body.config], function(){});
                }
                else if (action == "uninstall") {
                    uninstallPlugin(body.name, function(){});
                }
            });

            installPlugins(updates);
        }

        /***** Methods *****/

        function installPlugins(config, callback){
            // if (!vfs.connected) {
            //     vfs.once("connect", loadPackages.bind(this, config));
            //     return;
            // }

            if (!config.length) return;

            var found = {};
            config.forEach(function(item){
                if (!found[item.packageName])
                    found[item.packageName] = true;
                else return;

                queue.push({ name: item.packageName, version: item.version });

                if (installing)
                    installing.push(item);
            });

            if (installing) return;
            installing = config;

            var i = 0;
            function next(err){
                if (err) console.log(err);

                if (!queue[i]) {
                    installing = false; queue = [];
                    architect.loadAdditionalPlugins(config, callback);
                    return;
                }

                installPlugin(queue[i].name, queue[i].version, next);
                i++;
            }

            next();
        }

        function installPlugin(name, version, callback){
            proc.spawn("c9", {
                args: ["install", "--local", "--force", "--accessToken=" + auth.accessToken, name + "@" + version]
            }, function(err, process){
                if (err) return callback(err);

                process.stdout.on("data", function(c){
                    console.log(c);
                });
                process.stderr.on("data", function(c){
                    console.error(c);
                });

                process.on("exit", function(code){
                    if (code) {
                        var error = new Error(err);
                        error.code = code;
                        return callback(error);
                    }
                    callback();
                });
            });
        }

        function uninstallPlugin(name, callback){
            proc.spawn("c9", {
                args: ["remove", "--local", "--force", "--accessToken=" + auth.accessToken, name]
            }, function(err, process){
                if (err) return callback(err);

                var res = null;
                process.stdout.on("data", function(c){
                    res = c.toString("utf8");
                });
                process.stderr.on("data", function(c){
                    err = c.toString("utf8");
                });

                process.on("exit", function(code){
                    if (code) {
                        var error = new Error(err);
                        error.code = code;
                        return callback(error);
                    }
                    callback(null, res);
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            installing = false;
            queue = [];
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            /**
             *
             */
            get architect(){ throw new Error(); },
            set architect(v){ architect = v; },

            /**
             *
             */
            installPlugins: installPlugins,

            /**
             *
             */
            uninstallPlugin: uninstallPlugin
        });

        register(null, {
            "plugin.installer": plugin
        });
    }
});<commit_msg>Patch the installer to circumvent +6151<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "proc", "c9", "pubsub", "auth"
    ];
    main.provides = ["plugin.installer"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var c9 = imports.c9;
        var proc = imports.proc;
        var auth = imports.auth;
        var pubsub = imports.pubsub;

        var updates = options.updates;
        var architect;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var HASSDK = c9.location.indexOf("sdk=1") > -1;

        var queue = [];
        var installing;

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            if (!HASSDK) return;

            pubsub.on("message", function(message) {
                if (message.type != "package")
                    return;

                console.log("PubSub package API message", message);
                var action = message.action;
                var body = message.body;

                // Only accept packages that are installed for this project
                if (body.pid && body.pid != c9.projectId)
                    return;

                // Only accept packages that are installed for this user
                if (body.uid && body.uid != c9.uid)
                    return;

                if (action == "install") {
                    installPlugins([body.config], function(){});
                }
                else if (action == "uninstall") {
                    uninstallPlugin(body.name, function(){});
                }
            });

            installPlugins(updates);
        }

        /***** Methods *****/

        function installPlugins(config, callback){
            // if (!vfs.connected) {
            //     vfs.once("connect", loadPackages.bind(this, config));
            //     return;
            // }

            if (!config.length) return;

            var found = {};
            config.forEach(function(item){
                if (!found[item.packageName])
                    found[item.packageName] = true;
                else return;

                queue.push({ name: item.packageName, version: item.version });

                if (installing)
                    installing.push(item);
            });

            if (installing) return;
            installing = config;

            var i = 0;
            function next(err){
                if (err) console.log(err);

                if (!queue[i]) {
                    installing = false; queue = [];
                    architect.loadAdditionalPlugins(config, callback);
                    return;
                }

                installPlugin(queue[i].name, queue[i].version, next);
                i++;
            }

            next();
        }

        function installPlugin(name, version, callback){
            // proc.spawn("c9", {
            //     args: ["install", "--local", "--force", "--accessToken=" + auth.accessToken, name + "@" + version]
            proc.spawn("/home/ubuntu/.nvm/v0.10.28/bin/node", {
                args: ["/mnt/shared/bin/c9", "install", "--local", "--force", "--accessToken=" + auth.accessToken, name + "@" + version]
            }, function(err, process){
                if (err) return callback(err);

                process.stdout.on("data", function(c){
                    console.log(c);
                });
                process.stderr.on("data", function(c){
                    console.error(c);
                });

                process.on("exit", function(code){
                    if (code) {
                        var error = new Error(err);
                        error.code = code;
                        return callback(error);
                    }
                    callback();
                });
            });
        }

        function uninstallPlugin(name, callback){
            proc.spawn("c9", {
                args: ["remove", "--local", "--force", "--accessToken=" + auth.accessToken, name]
            }, function(err, process){
                if (err) return callback(err);

                var res = null;
                process.stdout.on("data", function(c){
                    res = c.toString("utf8");
                });
                process.stderr.on("data", function(c){
                    err = c.toString("utf8");
                });

                process.on("exit", function(code){
                    if (code) {
                        var error = new Error(err);
                        error.code = code;
                        return callback(error);
                    }
                    callback(null, res);
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            installing = false;
            queue = [];
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            /**
             *
             */
            get architect(){ throw new Error(); },
            set architect(v){ architect = v; },

            /**
             *
             */
            installPlugins: installPlugins,

            /**
             *
             */
            uninstallPlugin: uninstallPlugin
        });

        register(null, {
            "plugin.installer": plugin
        });
    }
});<|endoftext|>