<commit_before>"use strict";

const fs = require("graceful-fs");
const chalk = require("chalk");
const os = require("os");

const OVERWRITE_MODES = {
    NONE: "none",
    ALTER: "alter",
    ADAPT: "adapt"
};

class LoggerRawStream {
    /***
     * Stream class that enables bunyan to write custom fields to the log
     * e.g. switching time to @timestamp
     * will either write to process.stdout or logfile (depending on a given logFile)
     * @constructor
     */
    constructor(logFile, logFieldOptions, dockerMode) {

        this.buffer = [];
        this.bufferFlushSize = 10;
        this.bufferTimeout = 5000;
        this.logFieldOptions = logFieldOptions || null;
        this.logFieldKeys = this.logFieldOptions ? Object.keys(logFieldOptions) : null; //do once only
        this.dockerMode = dockerMode || false;

        this.logStream = null;
        this.outStream = null;

        if (logFile && !dockerMode) {
            this.logStream = fs.createWriteStream(logFile, { "flags": "a" });
        } else {
            this.outStream = process.stdout; //get ref and stop using the getter
        }

        this.dockerMode = dockerMode;
        this.hostName = os.hostname();
        this.pid = process.pid;
        this.serviceColor = process.env.SERVICE_COLOR;
    }

    /**
     * (stream) write method, called by bunyan
     * @param rec
     * @param overwriteMode
     */
    write(rec, overwriteMode) {

        if (typeof rec !== "object") {
            console.log("[log4bro] error: raw stream got a non-object record: %j", rec);
            return;
        }

        overwriteMode = overwriteMode || OVERWRITE_MODES.ALTER;

        switch(overwriteMode){

            case OVERWRITE_MODES.NONE:
                //none..
                break;

            case OVERWRITE_MODES.ADAPT:
                try {
                    rec = this.adaptLogFields(rec);
                } catch(e){
                    process.stdout.write("An exception occured during log field adaption: " +
                        e.message + ", for message: " + JSON.stringify(rec));
                    return;
                }
                break;

            case OVERWRITE_MODES.ALTER:
            default:
                try {
                    rec = this.alterLogFields(rec);
                } catch(e){
                    process.stdout.write("An exception occured during log field alteration: " +
                        e.message + ", for message: " + JSON.stringify(rec));
                    return;
                }
                break;
        }

        this.dockerMode ? this.jsonConsoleOutput(rec) : this.consoleOutput(rec);

        if(this.logStream){
            this.buffer.push(JSON.stringify(rec));
            rec = null;
            this.checkAndFlushBuffer();
        }
    }

    /**
     * alter method were log objects are re-mapped (actually re maps bunyan log output)
     * @returns {*}
     * @param log
     */
    alterLogFields(log) {

        //log will never be a string since it is coming from bunyan => object

        // remove bunyan fields

        if(log.time){
            delete log.time;
        }

        if(log.hostname){
            delete log.hostname;
        }

        if(typeof log.v !== "undefined"){
            delete log.v;
        }

        if(log.name){
            delete log.name;
        }

        // alter bunyan fields

        //level -> loglevel_value(int) + loglevel(string)
        if(log.level !== null){
            log.loglevel = LoggerRawStream.levelToName(log.level);
            log.loglevel_value = log.level;
            delete log.level;
        }

        // alter message payload (make sure only one of them exist)

        const jmsg = LoggerRawStream._isJsonString(log.msg);
        if(jmsg !== null){
            log.msg_json = jmsg;
            delete log.msg;
        }

        // set static log field keys

        if(this.logFieldKeys){
            for(let i = 0; i < this.logFieldKeys.length; i++){
                log[this.logFieldKeys[i]] = this.logFieldOptions[this.logFieldKeys[i]];
            }
        }

        // ensure minimum validity of log object

        return this.adaptLogFields(log);
    }

    /**
     * maps any (plain) object
     * @param log
     */
    adaptLogFields(log) {

        if(!log["@timestamp"]){
            log["@timestamp"] = new Date().toISOString();
        }

        if(!log["host"]){
            log.host = this.hostName;
        }

        if(!log.pid){
            log.pid = this.pid;
        }

        if(!log.loglevel){
            log.loglevel = "INFO";
        }

        if(!log.loglevel_value){
            log.loglevel_value = 30;
        }

        if(!log.log_type){
            log.log_type = "application";
        }

        if(!log.application_type){
            log.application_type = "service";
        }

        if(!log.service && this.logFieldOptions && this.logFieldOptions.service){
            log.service = this.logFieldOptions.service;
        }

        if(!log.current_color){
            log.current_color = this.serviceColor;
        }

        if(typeof log.msg === "undefined" && !log.msg_json){
            log.msg = "[log4bro] empty.";
        }

        if(typeof log.msg !== "undefined" && log.msg_json){
            delete log.msg;
        }

        return log;
    }

    /**
     * parses json if possible
     */
    static _isJsonString(str) {
        let obj = null;
        try {
            obj = JSON.parse(str);
        } catch (e) {
            //empty
        }
        return obj;
    }

    /**
     * writes a text console output if the logstream is not set
     */
    consoleOutput(obj) {

        if (!this.logStream) {
            let msg = LoggerRawStream.levelToName(obj.level ? obj.level : obj.loglevel_value)
                + " @ " + obj["@timestamp"] + " : " + (obj.msg ? obj.msg : JSON.stringify(obj.msg_json)) + "\n";
            msg = LoggerRawStream.levelToColorWrap(msg, obj.level ? obj.level : obj.loglevel_value);
            this.outStream.write(msg);
            msg = null;
        }
    }

    /**
     * writes a json console output if the logstream is not set
     */
    jsonConsoleOutput(obj) {

        if (!this.logStream) {
            let msg = LoggerRawStream.levelToColorWrap(JSON.stringify(obj), obj.level ? obj.level : obj.loglevel_value) + "\n";
            this.outStream.write(msg);
            msg = null;
        }
    }

    /**
     * turns log-level int-value into a read-able string
     * @param num
     * @returns {*}
     */
    static levelToName(num) {
        switch (num){
            case 10: return "TRACE";
            case 20: return "DEBUG";
            case 30: return "INFO";
            case 40: return "WARN";
            case 50: return "ERROR";
            case 60: return "FATAL";
            default: return "UNKNOWN";
        }
    }

    /**
     * turns a string into a colored string, depending on the log-level
     */
    static levelToColorWrap(str, level) {
        switch (level){
            case 10: return chalk.white(str);
            case 20: return chalk.cyan(str);
            case 30: return chalk.green(str);
            case 40: return chalk.yellow(str);
            case 50: return chalk.red(str);
            case 60: return chalk.red(str);
            default: return chalk.blue(str);
        }
    }

    /**
     * checks if the buffer has reached its flushing point, also takes care of the buffer timeout
     */
    checkAndFlushBuffer() {

        if (!this.logStream || !this.buffer.length) {
            return; //will do nothing
        }

        if (this.buffer.length >= this.bufferFlushSize) {
            return this.processBuffer(); //will end with a buffer being send to disk
        }

        clearTimeout(this._timeout); //buffer limit not reached, reset a timer to process buffer after timeout, if no more logs are sent

        const self = this;
        this._timeout = setTimeout(function(){ self.processBuffer(); }, this.bufferTimeout);
    }

    /**
     * writes buffer to file stream
     */
    processBuffer() {

        clearTimeout(this._timeout);

        const content = this.buffer.slice();
        this.buffer = [];

        for (let i = 0; i < content.length; i++) {
            this.logStream.write(content[i] + "\n");
        }
    }
}

LoggerRawStream.OVERWRITE_MODES = OVERWRITE_MODES;

module.exports = LoggerRawStream;
<commit_msg>Fix JsonString detection<commit_after>"use strict";

const fs = require("graceful-fs");
const chalk = require("chalk");
const os = require("os");

const OVERWRITE_MODES = {
    NONE: "none",
    ALTER: "alter",
    ADAPT: "adapt"
};

class LoggerRawStream {
    /***
     * Stream class that enables bunyan to write custom fields to the log
     * e.g. switching time to @timestamp
     * will either write to process.stdout or logfile (depending on a given logFile)
     * @constructor
     */
    constructor(logFile, logFieldOptions, dockerMode) {

        this.buffer = [];
        this.bufferFlushSize = 10;
        this.bufferTimeout = 5000;
        this.logFieldOptions = logFieldOptions || null;
        this.logFieldKeys = this.logFieldOptions ? Object.keys(logFieldOptions) : null; //do once only
        this.dockerMode = dockerMode || false;

        this.logStream = null;
        this.outStream = null;

        if (logFile && !dockerMode) {
            this.logStream = fs.createWriteStream(logFile, { "flags": "a" });
        } else {
            this.outStream = process.stdout; //get ref and stop using the getter
        }

        this.dockerMode = dockerMode;
        this.hostName = os.hostname();
        this.pid = process.pid;
        this.serviceColor = process.env.SERVICE_COLOR;
    }

    /**
     * (stream) write method, called by bunyan
     * @param rec
     * @param overwriteMode
     */
    write(rec, overwriteMode) {

        if (typeof rec !== "object") {
            console.log("[log4bro] error: raw stream got a non-object record: %j", rec);
            return;
        }

        overwriteMode = overwriteMode || OVERWRITE_MODES.ALTER;

        switch(overwriteMode){

            case OVERWRITE_MODES.NONE:
                //none..
                break;

            case OVERWRITE_MODES.ADAPT:
                try {
                    rec = this.adaptLogFields(rec);
                } catch(e){
                    process.stdout.write("An exception occured during log field adaption: " +
                        e.message + ", for message: " + JSON.stringify(rec));
                    return;
                }
                break;

            case OVERWRITE_MODES.ALTER:
            default:
                try {
                    rec = this.alterLogFields(rec);
                } catch(e){
                    process.stdout.write("An exception occured during log field alteration: " +
                        e.message + ", for message: " + JSON.stringify(rec));
                    return;
                }
                break;
        }

        this.dockerMode ? this.jsonConsoleOutput(rec) : this.consoleOutput(rec);

        if(this.logStream){
            this.buffer.push(JSON.stringify(rec));
            rec = null;
            this.checkAndFlushBuffer();
        }
    }

    /**
     * alter method were log objects are re-mapped (actually re maps bunyan log output)
     * @returns {*}
     * @param log
     */
    alterLogFields(log) {

        //log will never be a string since it is coming from bunyan => object

        // remove bunyan fields

        if(log.time){
            delete log.time;
        }

        if(log.hostname){
            delete log.hostname;
        }

        if(typeof log.v !== "undefined"){
            delete log.v;
        }

        if(log.name){
            delete log.name;
        }

        // alter bunyan fields

        //level -> loglevel_value(int) + loglevel(string)
        if(log.level !== null){
            log.loglevel = LoggerRawStream.levelToName(log.level);
            log.loglevel_value = log.level;
            delete log.level;
        }

        // alter message payload (make sure only one of them exist)

        const jmsg = LoggerRawStream._isJsonString(log.msg);
        if(typeof jmsg === "object" && jmsg !== null){
            log.msg_json = jmsg;
            delete log.msg;
        }

        // set static log field keys

        if(this.logFieldKeys){
            for(let i = 0; i < this.logFieldKeys.length; i++){
                log[this.logFieldKeys[i]] = this.logFieldOptions[this.logFieldKeys[i]];
            }
        }

        // ensure minimum validity of log object

        return this.adaptLogFields(log);
    }

    /**
     * maps any (plain) object
     * @param log
     */
    adaptLogFields(log) {

        if(!log["@timestamp"]){
            log["@timestamp"] = new Date().toISOString();
        }

        if(!log["host"]){
            log.host = this.hostName;
        }

        if(!log.pid){
            log.pid = this.pid;
        }

        if(!log.loglevel){
            log.loglevel = "INFO";
        }

        if(!log.loglevel_value){
            log.loglevel_value = 30;
        }

        if(!log.log_type){
            log.log_type = "application";
        }

        if(!log.application_type){
            log.application_type = "service";
        }

        if(!log.service && this.logFieldOptions && this.logFieldOptions.service){
            log.service = this.logFieldOptions.service;
        }

        if(!log.current_color){
            log.current_color = this.serviceColor;
        }

        if(typeof log.msg === "undefined" && !log.msg_json){
            log.msg = "[log4bro] empty.";
        }

        if(typeof log.msg !== "undefined" && log.msg_json){
            delete log.msg;
        }

        return log;
    }

    /**
     * parses json if possible
     */
    static _isJsonString(str) {
        let obj = null;
        try {
            obj = JSON.parse(str);
        } catch (e) {
            //empty
        }
        return obj;
    }

    /**
     * writes a text console output if the logstream is not set
     */
    consoleOutput(obj) {

        if (!this.logStream) {
            let msg = LoggerRawStream.levelToName(obj.level ? obj.level : obj.loglevel_value)
                + " @ " + obj["@timestamp"] + " : " + (obj.msg ? obj.msg : JSON.stringify(obj.msg_json)) + "\n";
            msg = LoggerRawStream.levelToColorWrap(msg, obj.level ? obj.level : obj.loglevel_value);
            this.outStream.write(msg);
            msg = null;
        }
    }

    /**
     * writes a json console output if the logstream is not set
     */
    jsonConsoleOutput(obj) {

        if (!this.logStream) {
            let msg = LoggerRawStream.levelToColorWrap(JSON.stringify(obj), obj.level ? obj.level : obj.loglevel_value) + "\n";
            this.outStream.write(msg);
            msg = null;
        }
    }

    /**
     * turns log-level int-value into a read-able string
     * @param num
     * @returns {*}
     */
    static levelToName(num) {
        switch (num){
            case 10: return "TRACE";
            case 20: return "DEBUG";
            case 30: return "INFO";
            case 40: return "WARN";
            case 50: return "ERROR";
            case 60: return "FATAL";
            default: return "UNKNOWN";
        }
    }

    /**
     * turns a string into a colored string, depending on the log-level
     */
    static levelToColorWrap(str, level) {
        switch (level){
            case 10: return chalk.white(str);
            case 20: return chalk.cyan(str);
            case 30: return chalk.green(str);
            case 40: return chalk.yellow(str);
            case 50: return chalk.red(str);
            case 60: return chalk.red(str);
            default: return chalk.blue(str);
        }
    }

    /**
     * checks if the buffer has reached its flushing point, also takes care of the buffer timeout
     */
    checkAndFlushBuffer() {

        if (!this.logStream || !this.buffer.length) {
            return; //will do nothing
        }

        if (this.buffer.length >= this.bufferFlushSize) {
            return this.processBuffer(); //will end with a buffer being send to disk
        }

        clearTimeout(this._timeout); //buffer limit not reached, reset a timer to process buffer after timeout, if no more logs are sent

        const self = this;
        this._timeout = setTimeout(function(){ self.processBuffer(); }, this.bufferTimeout);
    }

    /**
     * writes buffer to file stream
     */
    processBuffer() {

        clearTimeout(this._timeout);

        const content = this.buffer.slice();
        this.buffer = [];

        for (let i = 0; i < content.length; i++) {
            this.logStream.write(content[i] + "\n");
        }
    }
}

LoggerRawStream.OVERWRITE_MODES = OVERWRITE_MODES;

module.exports = LoggerRawStream;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import {MDCComponent} from '../MDCComponent'
import {List} from '../List'
import {MDCSimpleMenu} from '@material/menu/dist/mdc.menu'
import classNames from 'classnames'

class SimpleMenu extends MDCComponent {
  static displayName = 'SimpleMenu'

  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    onCancel: PropTypes.func,
    onChange: PropTypes.func,
    open: PropTypes.bool,
    openFrom: PropTypes.shape({
      horizontal: PropTypes.oneOf(['left', 'right']),
      vertical: PropTypes.oneOf(['top', 'bottom']),
    }),
    tabIndex: PropTypes.number,
  }

  static defaultProps = {
    onCancel: () => {},
    onChange: () => {},
    tabIndex: -1,
  }

  componentDidMount() {
    super.componentDidMount()

    this._setupListeners()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.open !== this.component_.open) {
      this.component_.open = nextProps.open
    }
  }

  componentWillUnmount() {
    this._clearListeners()

    super.componentWillUnmount()
  }

  attachTo(el) {
    return new MDCSimpleMenu(el)
  }

  _setupListeners() {
    this.listen(
      'MDCSimpleMenu:selected',
      this.changeListener_ = e => this.props.onChange(
        e,
        e.detail,
      )
    )
    this.listen(
      'MDCSimpleMenu:cancel',
      this.cancelListener_ = () => this.props.onCancel()
    )
  }

  _clearListeners() {
    this.unlisten(
      'MDCSimpleMenu:selected',
      this.changeListener_
    )
    this.unlisten(
      'MDCSimpleMenu:cancel',
      this.cancelListener_
    )
  }

  render() {
    const {
      children,
      className,
      open,
      openFrom,
      onCancel,
      onChange,
      ...otherProps,
    } = this.props
    const cssClasses = classNames({
      'mdc-simple-menu': true,
      'mdc-simple-menu--open': open,
      [`mdc-simple-menu--open-from-${openFrom && openFrom.vertical}-${openFrom && openFrom.horizontal}`]: openFrom,
    }, className)
    return (
      <div
        {...otherProps}
        className={cssClasses}
        ref={el => this.root_ = el}
      >
        <List
          aria-hidden="true"
          className="mdc-simple-menu__items"
          role="menu"
        >
          {children}
        </List>
      </div>
    )
  }
}

export default SimpleMenu
<commit_msg>fix(components): Prevents FOUC in SimpleMenu<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {MDCComponent} from '../MDCComponent'
import {List} from '../List'
import {MDCSimpleMenu} from '@material/menu/dist/mdc.menu'
import classNames from 'classnames'

class SimpleMenu extends MDCComponent {
  static displayName = 'SimpleMenu'

  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    onCancel: PropTypes.func,
    onChange: PropTypes.func,
    open: PropTypes.bool,
    openFrom: PropTypes.shape({
      horizontal: PropTypes.oneOf(['left', 'right']),
      vertical: PropTypes.oneOf(['top', 'bottom']),
    }),
    style: PropTypes.object, // eslint-disable-line react/forbid-prop-types
    tabIndex: PropTypes.number,
  }

  static defaultProps = {
    onCancel: () => {},
    onChange: () => {},
    tabIndex: -1,
  }

  componentDidMount() {
    super.componentDidMount()

    this._setupListeners()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.open !== this.component_.open) {
      this.component_.open = nextProps.open
    }
  }

  componentWillUnmount() {
    this._clearListeners()

    super.componentWillUnmount()
  }

  attachTo(el) {
    return new MDCSimpleMenu(el)
  }

  _setupListeners() {
    this.listen(
      'MDCSimpleMenu:selected',
      this.changeListener_ = e => this.props.onChange(
        e,
        e.detail,
      )
    )
    this.listen(
      'MDCSimpleMenu:cancel',
      this.cancelListener_ = () => this.props.onCancel()
    )
  }

  _clearListeners() {
    this.unlisten(
      'MDCSimpleMenu:selected',
      this.changeListener_
    )
    this.unlisten(
      'MDCSimpleMenu:cancel',
      this.cancelListener_
    )
  }

  render() {
    const {
      children,
      className,
      open,
      openFrom,
      onCancel,
      onChange,
      style,
      ...otherProps,
    } = this.props
    const cssClasses = classNames({
      'mdc-simple-menu': true,
      'mdc-simple-menu--open': open,
      [`mdc-simple-menu--open-from-${openFrom && openFrom.vertical}-${openFrom && openFrom.horizontal}`]: openFrom,
    }, className)
    return (
      <div
        {...otherProps}
        className={cssClasses}
        ref={el => this.root_ = el}
        style={{transform: 'scale(0)', ...style}}
      >
        <List
          aria-hidden="true"
          className="mdc-simple-menu__items"
          role="menu"
        >
          {children}
        </List>
      </div>
    )
  }
}

export default SimpleMenu
<|endoftext|>


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

function Virus() {
    Cell.apply(this, Array.prototype.slice.call(arguments));
    this.cellType = 2;
    this.isSpiked = true;
    this.isMotherCell = false; // Not to confuse bots
    this.setColor({ r: 0x33, g: 0xff, b: 0x33 });
}

module.exports = Virus;
Virus.prototype = new Cell();

// Main Functions

Virus.prototype.canEat = function (cell) {
    return cell.cellType == 3; // virus can eat ejected mass only
};

Virus.prototype.onEat = function (prey) {
    // Called to eat prey cell
    this.setSize(Math.sqrt(this._sizeSquared + prey._sizeSquared));

    if (this._size >= this.gameServer.config.virusMaxSize) {
        this.setSize(this.gameServer.config.virusMinSize); // Reset mass
        this.gameServer.shootVirus(this, prey.boostDirection.angle);
    }
};

Virus.prototype.onEaten = function (c) {
    if (c.owner == null) return;

    var minSize = this.gameServer.config.playerMinSize,
    min = (minSize == 32) ? 30 : minSize, // minimun size of small splits
    cellsLeft = this.gameServer.config.playerMaxCells - c.owner.cells.length,
    numSplits = cellsLeft < (c._mass / 16) ? cellsLeft : (c._mass / 16),
    splitMass = (c._mass / numSplits) < min ? (c._mass / numSplits) : min;

    // Diverse explosion(s)
    var big = [];
    if (!numSplits) return; // can't split anymore
    if (numSplits == 1) big = [c._mass/2];
    else if (numSplits == 2) big = [c._mass/4,c._mass/4];
    else if (numSplits == 3) big = [c._mass/4,c._mass/4,c._mass/7];
    else if (numSplits == 4) big = [c._mass/5,c._mass/7,c._mass/8,c._mass/10];
    else {
        // ckeck size of exploding
        var threshold = c._mass - numSplits * splitMass;
        // Monotone explosion(s)
        if (threshold > 466) {
            // virus explosion multipliers
            var exp = (Math.random() * (4.5 - 3.33)) + 3.33;
            while (threshold / exp > 24) {
                threshold /= exp;
                exp = 2;
                big.push(threshold >> 0);
            }
        }
    }
    numSplits -= big.length;
    // big splits
    for (var k = 0; k < big.length; k++) {
        var angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(c.owner, c, angle, big[k]);
    }
    // small splits
    for (var k = 0; k < numSplits; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(c.owner, c, angle, min);
    }
};

Virus.prototype.onAdd = function (gameServer) {
    gameServer.nodesVirus.push(this);
};

Virus.prototype.onRemove = function (gameServer) {
    var index = gameServer.nodesVirus.indexOf(this);
    if (index != -1)
        gameServer.nodesVirus.splice(index, 1);
};
<commit_msg>Update Virus.js<commit_after>var Cell = require('./Cell');

function Virus() {
    Cell.apply(this, Array.prototype.slice.call(arguments));
    this.cellType = 2;
    this.isSpiked = true;
    this.isMotherCell = false; // Not to confuse bots
    this.setColor({ r: 0x33, g: 0xff, b: 0x33 });
}

module.exports = Virus;
Virus.prototype = new Cell();

// Main Functions

Virus.prototype.canEat = function (cell) {
    return cell.cellType == 3; // virus can eat ejected mass only
};

Virus.prototype.onEat = function (prey) {
    // Called to eat prey cell
    this.setSize(Math.sqrt(this._sizeSquared + prey._sizeSquared));

    if (this._size >= this.gameServer.config.virusMaxSize) {
        this.setSize(this.gameServer.config.virusMinSize); // Reset mass
        this.gameServer.shootVirus(this, prey.boostDirection.angle);
    }
};

Virus.prototype.onEaten = function (c) {
    if (c.owner == null) return;

    var minSize = this.gameServer.config.playerMinSize,
    min = (minSize == 32) ? 30 : minSize, // minimun size of small splits
    cellsLeft = this.gameServer.config.playerMaxCells - c.owner.cells.length,
    numSplits = cellsLeft < (c._mass / 16) ? cellsLeft : (c._mass / 16),
    splitMass = (c._mass / numSplits) < min ? (c._mass / numSplits) : min;

    // Diverse explosion(s)
    var big = [];
    if (!numSplits) return; // can't split anymore
    if (numSplits == 1) big = [c._mass/2];
    else if (numSplits == 2) big = [c._mass/4,c._mass/4];
    else if (numSplits == 3) big = [c._mass/4,c._mass/4,c._mass/7];
    else if (numSplits == 4) big = [c._mass/5,c._mass/7,c._mass/8,c._mass/10];
    else {
        // ckeck size of exploding
        var threshold = c._mass - numSplits * splitMass;
        // Monotone explosion(s)
        if (threshold > 466) {
            // virus explosion multipliers
            var v = c.isMoving ? 4 : 4.5;
            var exp = (Math.random() * (v - 3.33)) + 3.33;
            while (threshold / exp > 24) {
                threshold /= exp;
                exp = 2;
                big.push(threshold >> 0);
            }
        }
    }
    numSplits -= big.length;
    // big splits
    for (var k = 0; k < big.length; k++) {
        var angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(c.owner, c, angle, big[k]);
    }
    // small splits
    for (var k = 0; k < numSplits; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(c.owner, c, angle, min);
    }
};

Virus.prototype.onAdd = function (gameServer) {
    gameServer.nodesVirus.push(this);
};

Virus.prototype.onRemove = function (gameServer) {
    var index = gameServer.nodesVirus.indexOf(this);
    if (index != -1)
        gameServer.nodesVirus.splice(index, 1);
};
<|endoftext|>


<commit_before>var Cell = require('./Cell');
var Logger = require('../modules/Logger');

function Virus() {
    Cell.apply(this, Array.prototype.slice.call(arguments));
    this.cellType = 2;
    this.isSpiked = true;
    this.fed = 0;
    this.isMotherCell = false; // Not to confuse bots
    this.setColor({ r: 0x33, g: 0xff, b: 0x33 });
}

module.exports = Virus;
Virus.prototype = new Cell();

// Main Functions

Virus.prototype.canEat = function (cell) {
    return cell.cellType == 3; // virus can eat ejected mass only
};

Virus.prototype.onEat = function (prey) {
    // Called to eat prey cell
    this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared()));

    if (this.getSize() >= this.gameServer.config.virusMaxSize) {
        this.setSize(this.gameServer.config.virusMinSize); // Reset mass
        this.gameServer.shootVirus(this, prey.getAngle());
    }
};

Virus.prototype.onEaten = function (consumer) {
    var client = consumer.owner;
    if (client == null) return;

    var mass = consumer.getMass(),
    maxSplits = ((mass / 16) >> 0) - 1, // maximum amount of splits
    cellsLeft = this.gameServer.config.playerMaxCells - client.cells.length,
    numSplits = Math.min(cellsLeft, maxSplits), // get number of splits
    splitMass = Math.min(consumer.getMass() / numSplits, 24);

    // cannot split any further
    if (numSplits <= 0) return;

    // won't split regular way unless numSplits > 4
    var bigSplits = [];
    if (numSplits == 1) bigSplits = [mass / 2];
    else if (numSplits == 2) bigSplits = [mass / 4, mass / 4];
    else if (numSplits == 3) bigSplits = [mass / 4, mass / 4, mass / 7];
    else if (numSplits == 4) bigSplits = [mass / 5, mass / 7, mass / 8, mass / 10];
    else {
        var m = mass - numSplits * splitMass; // threshold
        var r = Math.random(), mult = 0;      // starting mult
        var mults = {                         // random selection
            v1: ((r * (4 - 3.8)) + 3.8),      // vanilla mult 1
            v2: ((r * (3.8 - 3.7)) + 3.7),    // vanilla mult 2
            v3: ((r * (3.7 - 3.33)) + 3.33),  // vanilla mult 3
            v4: ((r * (2.5 - 2.3)) + 2.3),    // second vanilla mult 1
            v5: ((r * (2.3 - 2.25)) + 2.25),  // second vanilla mult 2
            v6: ((r * (2.25 - 2)) + 2),       // second vanilla mult 3
        };

        // Diverse explosions, 1 of 3 selected randomly
        if (m > 466) {
            if (r * 3 <= 1) mult = mults.v1;
            if (r * 3 <= 2) mult = mults.v2;
            if (r * 3 <= 3) mult = mults.v3;
            while (m / mult > 24) {
                m /= mult;
                if (r * 3 <= 1) mult = mults.v4;
                if (r * 3 <= 2) mult = mults.v5;
                if (r * 3 <= 3) mult = mults.v6;
                bigSplits.push(m >> 0);
            }
        }
    }
    numSplits -= bigSplits.length;

    // big splits
    var angle = 0;
    for (var k = 0; k < bigSplits.length; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(
            client, consumer, angle, bigSplits[k]
        );
    }

    // small splits
    for (var k = 0; k < numSplits; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(
            client, consumer, angle, splitMass
        );
    }
};

Virus.prototype.onAdd = function (gameServer) {
    gameServer.nodesVirus.push(this);
};

Virus.prototype.onRemove = function (gameServer) {
    var index = gameServer.nodesVirus.indexOf(this);
    if (index != -1) {
        gameServer.nodesVirus.splice(index, 1);
    } else {
        Logger.warn("Virus.onRemove: Tried to remove a non existing virus!");
    }
};
<commit_msg>Update Virus.js<commit_after>var Cell = require('./Cell');
var Logger = require('../modules/Logger');

function Virus() {
    Cell.apply(this, Array.prototype.slice.call(arguments));
    this.cellType = 2;
    this.isSpiked = true;
    this.fed = 0;
    this.isMotherCell = false; // Not to confuse bots
    this.setColor({ r: 0x33, g: 0xff, b: 0x33 });
}

module.exports = Virus;
Virus.prototype = new Cell();

// Main Functions

Virus.prototype.canEat = function (cell) {
    return cell.cellType == 3; // virus can eat ejected mass only
};

Virus.prototype.onEat = function (prey) {
    // Called to eat prey cell
    this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared()));

    if (this._size >= this.gameServer.config.virusMaxSize) {
        this.setSize(this.gameServer.config.virusMinSize); // Reset mass
        this.gameServer.shootVirus(this, prey.getAngle());
    }
};

Virus.prototype.onEaten = function (consumer) {
    var client = consumer.owner;
    if (client == null) return;

    var mass = consumer.getMass(),
    maxSplits = ((mass / 16) >> 0) - 1, // maximum amount of splits
    cellsLeft = this.gameServer.config.playerMaxCells - client.cells.length,
    numSplits = Math.min(cellsLeft, maxSplits), // get number of splits
    splitMass = Math.min(consumer.getMass() / numSplits, 24);

    // cannot split any further
    if (numSplits <= 0) return;

    // won't split regular way unless numSplits > 4
    var bigSplits = [];
    if (numSplits == 1) bigSplits = [mass / 2];
    else if (numSplits == 2) bigSplits = [mass / 4, mass / 4];
    else if (numSplits == 3) bigSplits = [mass / 4, mass / 4, mass / 7];
    else if (numSplits == 4) bigSplits = [mass / 5, mass / 7, mass / 8, mass / 10];
    else {
        var m = mass - numSplits * splitMass; // threshold
        var r = Math.random(), mult = 0;      // starting mult
        var mults = {                         // random selection
            v1: ((r * (4 - 3.8)) + 3.8),      // vanilla mult 1
            v2: ((r * (3.8 - 3.7)) + 3.7),    // vanilla mult 2
            v3: ((r * (3.7 - 3.33)) + 3.33),  // vanilla mult 3
            v4: ((r * (2.5 - 2.3)) + 2.3),    // second vanilla mult 1
            v5: ((r * (2.3 - 2.25)) + 2.25),  // second vanilla mult 2
            v6: ((r * (2.25 - 2)) + 2),       // second vanilla mult 3
        };

        // Diverse explosions, 1 of 3 selected randomly
        if (m > 466) {
            if (r * 3 <= 1) mult = mults.v1;
            if (r * 3 <= 2) mult = mults.v2;
            if (r * 3 <= 3) mult = mults.v3;
            while (m / mult > 24) {
                m /= mult;
                if (r * 3 <= 1) mult = mults.v4;
                if (r * 3 <= 2) mult = mults.v5;
                if (r * 3 <= 3) mult = mults.v6;
                bigSplits.push(m >> 0);
            }
        }
    }
    numSplits -= bigSplits.length;

    // big splits
    var angle = 0;
    for (var k = 0; k < bigSplits.length; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(
            client, consumer, angle, bigSplits[k]
        );
    }

    // small splits
    for (var k = 0; k < numSplits; k++) {
        angle = 2 * Math.PI * Math.random(); // random directions
        this.gameServer.splitPlayerCell(
            client, consumer, angle, splitMass
        );
    }
};

Virus.prototype.onAdd = function (gameServer) {
    gameServer.nodesVirus.push(this);
};

Virus.prototype.onRemove = function (gameServer) {
    var index = gameServer.nodesVirus.indexOf(this);
    if (index != -1) {
        gameServer.nodesVirus.splice(index, 1);
    } else {
        Logger.warn("Virus.onRemove: Tried to remove a non existing virus!");
    }
};
<|endoftext|>


<commit_before>
function PsiiiTable(_tableObj,_actionCallback,_parameters,_debugMode)
{

	if(_debugMode)
		this.debugMode=_debugMode;
	else
		this.debugMode=false;

	this._loadingCallback 	= function(){
		_actionCallback();
	};

	this._text_pull 		= _parameters.text_pull;
	this._text_refresh 		= _parameters.text_refresh;
	this._text_last_update 	= _parameters.text_last_update;
	this._text_loading 		= _parameters.text_loading;
	this._text_loading_error= (_parameters.text_loading_error)?_parameters.text_loading_error:"Es ist ein Problem aufgetreten.";

	this._timeout 			= (_parameters._timeout)?_parameters._timeout:8000;

	this._label_color 		= _parameters.labelColor;
	this._background_color	= _parameters.backgroundColor;
	this._background_image	= _parameters.backgroundImage;

	this._arrow_image		= (_parameters.arrowImage)?_parameters.arrowImage:"/libs/arrow.png";

    this._table 				= Titanium.UI.createTableView(_tableObj);
    this._table.headerPullView 	= this.createPullToRefresh();

    this.isAndroid 	= (Titanium.Platform.osname=='android')?true:false;
	this.isIOS 		= (Titanium.Platform.osname=='iphone')?true:false;

    var $this = this;
    this._table.addEventListener("scroll",	function(_e) 	{ $this._scroll(_e); 		});
	this._table.addEventListener("scrollEnd",function(_e) 	{ $this._begin(_e, $this); 	});
	this._table.addEventListener("_end",function(_e) 		{ $this._end(); 			});

}

/*
 * wrappter function for Ti.API.error
 * to enable and disable debug output
 */
PsiiiTable.prototype.log = function(_text)
{
	if(this.debugMode==true)
		Ti.API.error(_text);
}

PsiiiTable.prototype.getTable = function() {
    return this._table;
};

PsiiiTable.prototype.createPullToRefresh = function()
{

	var $_view = Ti.UI.createView({
		backgroundColor:this._background_color,
		width:320,
		height:60
	});

	if(this._background_image)
	{

		$_view.backgroundImage = this._background_image;
		$_view.backgroundRepeat = true;
	}

	var $_arrow = Ti.UI.createView({
		backgroundImage:this._arrow_image,
		width:30,
		height:30,
		bottom:20,
		left:20
	});
	$_view.add($_arrow);

	var $_status = Ti.UI.createLabel({
		text: this._text_pull,
		left:55,
		width:220,
		bottom:35,
		height:"auto",
		color: this._label_color,
		textAlign:"center",
		font:{fontSize:13,fontWeight:"bold"}
	});
	$_view.add($_status);

	var $_lastUpdate = Ti.UI.createLabel({
		text: this._text_last_update+(String.formatTime(new Date())),
		left:55,
		width:220,
		bottom:15,
		height:15,
		height:"auto",
		color:	this._label_color,
		textAlign:"center",
		font:{fontSize:12}
	});
	$_view.add($_lastUpdate);

	var $_activityIndicator = Titanium.UI.createActivityIndicator({
		left:20,
		bottom:13,
		width:30,
		height:30,
	});

	$_view.add($_activityIndicator);

	//make it accessable in obj-scope
	this._activityIndicator = $_activityIndicator;
	this._lastUpdate 		= $_lastUpdate;
	this._status 			= $_status;
	this._arrow 			= $_arrow;

	return $_view;

};

PsiiiTable.prototype._scroll = function(e)
{
	var offset = e.contentOffset.y;
	if (offset <= -65.0 && !this._pulling)
	{
		var t = Ti.UI.create2DMatrix();
		t = t.rotate(-180);
		this._pulling = true;
		this._arrow.animate({transform:t, duration:180});
		this._status.text = this._text_refresh;
	}
	else if (this._pulling && offset > -65.0 && offset < 0)
	{
		this._pulling = false;
		var t = Ti.UI.create2DMatrix();
		this._arrow.animate({transform:t,duration:180});
		this._status.text = this._text_pull;
	}
};

PsiiiTable.prototype._begin = function(e, tableView)
{
	if (this._pulling && !this._reloading && e.contentOffset.y <= -65.0)
	{
		this._reloading 		= true;
		this._pulling 			= false;
		this._arrow.hide();
		this._activityIndicator.show();
		this._status.text 		= this._text_loading;

		this._table.setContentInsets({top:60},{animated:true});

		this._arrow.transform 	= Ti.UI.create2DMatrix();
		this._loadingCallback();

		var $this = this;

		setTimeout(function()
		{
			if($this._reloading)
			{
				$this._end();
				alert($this._text_loading_error);
			}
		},$this._timeout);

	}
};

PsiiiTable.prototype._end= function()
{
	this.log("PsiiiTable.prototype._end "+this.isIOS);

	this._reloading 		= false;
	this._lastUpdate.text 	= this._text_last_update +(String.formatTime(new Date())),
	this._status.text 		= this._text_pull;
	this._activityIndicator.hide();
	this._arrow.show();

	if(this.isIOS)
		this._table.setContentInsets({top:0},{animated:true});

	this.log("PsiiiTable.prototype._end done");
};

module.exports = PsiiiTable;<commit_msg>renamings and added PsiiiTableView.prototype.fillData to fill table data an finish psiiiTable live cycle<commit_after>
function PsiiiTableView(_tableObj,_actionCallback,_parameters,_debugMode)
{

	if(_debugMode)
		this.debugMode=_debugMode;
	else
		this.debugMode=false;

	this._loadingCallback 	= function(_this){
		_actionCallback(_this);
	};

	this._text_pull 		= _parameters.text_pull;
	this._text_refresh 		= _parameters.text_refresh;
	this._text_last_update 	= _parameters.text_last_update;
	this._text_loading 		= _parameters.text_loading;
	this._text_loading_error= (_parameters.text_loading_error)?_parameters.text_loading_error:"Something went wrong.";

	this._timeout 			= (_parameters._timeout)?_parameters._timeout:8000;

	this._label_color 		= _parameters.labelColor;
	this._background_color	= _parameters.backgroundColor;
	this._background_image	= _parameters.backgroundImage;

	this._arrow_image		= (_parameters.arrowImage)?_parameters.arrowImage:"/libs/arrow.png";

    this._table 				= Titanium.UI.createTableView(_tableObj);
    this._table.headerPullView 	= this.createPullToRefresh();

    this.isAndroid 	= (Titanium.Platform.osname=='android')?true:false;
	this.isIOS 		= (Titanium.Platform.osname=='iphone')?true:false;

    var $this = this;
    this._table.addEventListener("scroll",	function(_e) 	{ $this._scroll(_e); 		});
	this._table.addEventListener("scrollEnd",function(_e) 	{ $this._begin(_e, $this); 	});
	this._table.addEventListener("_end",function(_e) 		{ $this._end(); 			});

}

/*
 * sets the table Rows and finishs psiiTableView livecycle
 * cant call it setData couz of appC rules
 */
PsiiiTableView.prototype.fillData = function(_data)
{
	this.getTable().setData(_data);
	this.getTable().fireEvent('_end');
}
/*
 * wrappter function for Ti.API.error
 * to enable and disable debug output
 */
PsiiiTableView.prototype.log = function(_text)
{
	if(this.debugMode==true)
		Ti.API.error(_text);
}

/*
 * returns the extended Table
 * @return Ti.UI.TableView
 */
PsiiiTableView.prototype.getTable = function()
{
    return this._table;
};

/*
 * returns the extended Table
 * @return Ti.UI.TableView
 */
PsiiiTableView.prototype.getUI = function()
{
    return this._table;
};

/*
 * extends the standard Ti.UI.TableView with the push to refresh feature
 */
PsiiiTableView.prototype.createPullToRefresh = function()
{

	var $_view = Ti.UI.createView({
		backgroundColor:this._background_color,
		width:320,
		height:60
	});

	if(this._background_image)
	{

		$_view.backgroundImage = this._background_image;
		$_view.backgroundRepeat = true;
	}

	var $_arrow = Ti.UI.createView({
		backgroundImage:this._arrow_image,
		width:30,
		height:30,
		bottom:20,
		left:20
	});
	$_view.add($_arrow);

	var $_status = Ti.UI.createLabel({
		text: this._text_pull,
		left:55,
		width:220,
		bottom:35,
		height:"auto",
		color: this._label_color,
		textAlign:"center",
		font:{fontSize:13,fontWeight:"bold"}
	});
	$_view.add($_status);

	var $_lastUpdate = Ti.UI.createLabel({
		text: this._text_last_update+(String.formatTime(new Date())),
		left:55,
		width:220,
		bottom:15,
		height:15,
		height:"auto",
		color:	this._label_color,
		textAlign:"center",
		font:{fontSize:12}
	});
	$_view.add($_lastUpdate);

	var $_activityIndicator = Titanium.UI.createActivityIndicator({
		left:20,
		bottom:13,
		width:30,
		height:30,
	});

	$_view.add($_activityIndicator);

	//make it accessable in obj-scope
	this._activityIndicator = $_activityIndicator;
	this._lastUpdate 		= $_lastUpdate;
	this._status 			= $_status;
	this._arrow 			= $_arrow;

	return $_view;

};

/*
 * Function-Event: gets fired when table is scrolling
 */
PsiiiTableView.prototype._scroll = function(e)
{
	var offset = e.contentOffset.y;
	if (offset <= -65.0 && !this._pulling)
	{
		var t = Ti.UI.create2DMatrix();
		t = t.rotate(-180);
		this._pulling = true;
		this._arrow.animate({transform:t, duration:180});
		this._status.text = this._text_refresh;
	}
	else if (this._pulling && offset > -65.0 && offset < 0)
	{
		this._pulling = false;
		var t = Ti.UI.create2DMatrix();
		this._arrow.animate({transform:t,duration:180});
		this._status.text = this._text_pull;
	}
};

/*
 * Function-Event: gets fired when loading starts
 */
PsiiiTableView.prototype._begin = function(e, tableView)
{
	if (this._pulling && !this._reloading && e.contentOffset.y <= -65.0)
	{
		this._reloading 		= true;
		this._pulling 			= false;
		this._arrow.hide();
		this._activityIndicator.show();
		this._status.text 		= this._text_loading;

		this._table.setContentInsets({top:60},{animated:true});

		this._arrow.transform 	= Ti.UI.create2DMatrix();
		this._loadingCallback(this);

		var $this = this;

		setTimeout(function()
		{
			if($this._reloading)
			{
				$this._end();
				alert($this._text_loading_error);
			}
		},$this._timeout);

	}
};

/*
 * Function-Event: gets fired after loading
 */
PsiiiTableView.prototype._end= function()
{
	this.log("PsiiiTableView.prototype._end "+this.isIOS);

	this._reloading 		= false;
	this._lastUpdate.text 	= this._text_last_update +(String.formatTime(new Date())),
	this._status.text 		= this._text_pull;
	this._activityIndicator.hide();
	this._arrow.show();

	if(this.isIOS)
		this._table.setContentInsets({top:0},{animated:true});

	this.log("PsiiiTableView.prototype._end done");
};

module.exports = PsiiiTableView;<|endoftext|>


<commit_before>'use strict';

var orgJGrapesOsgiPortletsBundles = {
    l10n: {
        "bundleCategory": "${_("bundleCategory")}",
        "bundleRefresh": "${_("bundleRefresh")}",
        "bundleStart": "${_("bundleStart")}",
        "bundleState": "${_("bundleState")}",
        "bundleStop": "${_("bundleStop")}",
        "bundleSymbolicName": "${_("bundleSymbolicName")}",
        "bundleUpdate": "${_("bundleUpdate")}",
        "bundleUninstall": "${_("bundleUninstall")}",
        "bundleVersion": "${_("bundleVersion")}",
    }
};

(function() {

    var l10n = orgJGrapesOsgiPortletsBundles.l10n;

    function createTooltip(bundle) {
        let tooltip = '
';
        tooltip += '

';
        tooltip += '' + l10n.bundleSymbolicName + ':	';
        tooltip += '' + bundle.symbolicName + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleVersion + ':	';
        tooltip += '' + bundle.version + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleCategory + ':	';
        tooltip += '' + bundle.category + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleState + ':	';
        tooltip += '' + bundle.state + '	';
        tooltip += '

';
        return tooltip;
    }

    function registerTooltip(row, bundleInfo) {
        row.data("bundleInfo", bundleInfo);
        row.tooltip({
            items: "[data-bundle-id]",
            content: function() {
                return createTooltip($( this ).data("bundleInfo"));
            },
            classes: {
                "ui-tooltip": "ui-corner-all ui-widget-shadow jgrapes-osgi-bundles-preview-tooltip"
            }
        });
    }

    orgJGrapesOsgiPortletsBundles.initPreviewTable = function(tableSelector) {
        JGPortal.lockMessageQueue();
        let table = tableSelector.DataTable( {
            "initComplete": function( settings, json ) {
                tableSelector.DataTable().processing(true);
                JGPortal.unlockMessageQueue();
            },
            "columns": [
                { "data": "id" },
                { "data": "name"}
            ],
            "searching": false,
            "paging": false,
            "info": false,
            "dom": "t",
            "rowCallback": function( row, data, dataIndex ) {
                $(row).attr("data-bundle-id", data.id);
                registerTooltip($(row), data);
            },
            "processing": true
        } );
        return table;
    }

    // Delay initialization, l10n is not yet initialized when loading this file
    let _buttonsPrototype = null;

    function buttonsPrototype() {
        if (!_buttonsPrototype) {
            _buttonsPrototype = $(
            '<button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleStart + '" data-bundle-action="start">'
            + '' + l10n.bundleStart + '</button>'
            + '<button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleStop + '" data-bundle-action="stop">'
            + '' + l10n.bundleStop + '</button>'
//            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
//            + 'title="' + l10n.bundleRefresh + '" data-bundle-action="refresh">'
//            + '' + l10n.bundleRefresh + '</button>'
            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleUpdate + '" data-bundle-action="update">'
            + '' + l10n.bundleUpdate + '</button>'
            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleUninstall + '" data-bundle-action="uninstall">'
            + '' + l10n.bundleUninstall + '</button>' );
        }
        return _buttonsPrototype;
    }

    orgJGrapesOsgiPortletsBundles.initViewTable = function(tableSelector) {
        JGPortal.lockMessageQueue();
        let table = tableSelector.DataTable( {
            "initComplete": function( settings, json ) {
                tableSelector.DataTable().processing(true);
                JGPortal.unlockMessageQueue();
            },
            "columns": [
                { "data": "id" },
                { "data": "name",
                  "render": function ( data, type, row, meta ) {
                      if (type === "display") {
                          return row.name + " (" + row.symbolicName + ")";
                      }
                      return data;
                  }
                },
                { "data": "version" },
                { "data": "category" },
                { "data": "state" },
                { "data": null,
                  "defaultContent": "",
                  "orderable": false,
                } ],
            "createdRow": function( row, data, dataIndex ) {
                $(row).attr("data-bundle-id", data.id);
                $( $(row).find("td")[5] ).append(buttonsPrototype().clone());
                $( $(row).find("td")[5] ).find("button").button();
            },
            "rowCallback": function( row, data, index ) {
                if ($( $(row).find("td")[5] ).find("button").length === 0) {
                    $( $(row).find("td")[5] ).append(buttonsPrototype().clone());
                    $( $(row).find("td")[5] ).find("button").button();
                }
                let startButton = $( row ).find('button[data-bundle-action="start"]');
                let stopButton = $( row ).find('button[data-bundle-action="stop"]');
                if (data.startable) {
                    startButton.show();
                    stopButton.hide();
                } else {
                    startButton.hide();
                    stopButton.show()
                }
                if (!data.stoppable) {
                    $( row ).find('button[data-bundle-action="stop"]').button("disable");
                }
                if (!data.uninstallable) {
                    $( row ).find('button [data-bundle-action="uninstall"]').button("disable");
                }
            },
            "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, $.fn.dataTable.defaults.oLanguage.sLengthAll] ],
            "pageLength": -1,
            "processing": true
        } );
        return table;
    }

    $("body").on("click", ".jgrapes-osgi-bundles-view table button",
        function(event) {
            let portletId = $(this).closest("[data-portlet-id]").attr("data-portlet-id");
            let bundleId = $(this).closest("[data-bundle-id]").attr("data-bundle-id");
            let action = $(this).attr("data-bundle-action")
            JGPortal.sendToPortlet(portletId, action, [ parseInt(bundleId) ]);
    });

    function updateTable(table, bundleInfos, replace) {
        if (replace) {
            table.clear();
        }
        bundleInfos.forEach(function(bundleInfo) {
            if (!replace) {
                let row = table.row(function ( idx, data, node ) {
                    return data.id === bundleInfo.id;
                });
                if (row.length > 0) {
                    if (bundleInfo.uninstalled) {
                        table.row(row).remove();
                    } else {
                        table.row(row).data(bundleInfo);
                    }
                    return;
                }
            }
            if (!bundleInfo.uninstalled) {
                table.row.add(bundleInfo);
            }
        });
        table.processing(false);
        table.columns.adjust().draw();
    }

    JGPortal.registerPortletMethod(
            "org.jgrapes.osgi.portlets.bundles.BundleListPortlet",
            "bundleUpdates", function(portletId, params) {
                let bundleInfos = params[0];
                // Preview
                if (params[1] === "preview" || params[1] === "*") {
                    let portlet = JGPortal.findPortletPreview(portletId);
                    if (portlet) {
                        let table = portlet.find(".jgrapes-osgi-bundles-preview table.bundles-table").DataTable();
                        updateTable(table, bundleInfos, params[2]);
                    }
                }

                // View
                if (params[1] === "view" || params[1] === "*") {
                    let portlet = JGPortal.findPortletView(portletId);
                    if (portlet) {
                        let table = portlet.find("table").DataTable();
                        updateTable(table, bundleInfos, params[2]);
                    }
                }
            });

})();

<commit_msg>Fixed HTML.<commit_after>'use strict';

var orgJGrapesOsgiPortletsBundles = {
    l10n: {
        "bundleCategory": "${_("bundleCategory")}",
        "bundleRefresh": "${_("bundleRefresh")}",
        "bundleStart": "${_("bundleStart")}",
        "bundleState": "${_("bundleState")}",
        "bundleStop": "${_("bundleStop")}",
        "bundleSymbolicName": "${_("bundleSymbolicName")}",
        "bundleUpdate": "${_("bundleUpdate")}",
        "bundleUninstall": "${_("bundleUninstall")}",
        "bundleVersion": "${_("bundleVersion")}",
    }
};

(function() {

    var l10n = orgJGrapesOsgiPortletsBundles.l10n;

    function createTooltip(bundle) {
        let tooltip = '
';
        tooltip += '

';
        tooltip += '' + l10n.bundleSymbolicName + ':	';
        tooltip += '' + bundle.symbolicName + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleVersion + ':	';
        tooltip += '' + bundle.version + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleCategory + ':	';
        tooltip += '' + bundle.category + '	';
        tooltip += '

';
        tooltip += '' + l10n.bundleState + ':	';
        tooltip += '' + bundle.state + '	';
        tooltip += '

';
        return tooltip;
    }

    function registerTooltip(row, bundleInfo) {
        row.data("bundleInfo", bundleInfo);
        row.tooltip({
            items: "[data-bundle-id]",
            content: function() {
                return createTooltip($( this ).data("bundleInfo"));
            },
            classes: {
                "ui-tooltip": "ui-corner-all ui-widget-shadow jgrapes-osgi-bundles-preview-tooltip"
            }
        });
    }

    orgJGrapesOsgiPortletsBundles.initPreviewTable = function(tableSelector) {
        JGPortal.lockMessageQueue();
        let table = tableSelector.DataTable( {
            "initComplete": function( settings, json ) {
                tableSelector.DataTable().processing(true);
                JGPortal.unlockMessageQueue();
            },
            "columns": [
                { "data": "id" },
                { "data": "name"}
            ],
            "searching": false,
            "paging": false,
            "info": false,
            "dom": "t",
            "rowCallback": function( row, data, dataIndex ) {
                $(row).attr("data-bundle-id", data.id);
                registerTooltip($(row), data);
            },
            "processing": true
        } );
        return table;
    }

    // Delay initialization, l10n is not yet initialized when loading this file
    let _buttonsPrototype = null;

    function buttonsPrototype() {
        if (!_buttonsPrototype) {
            _buttonsPrototype = $(
            '<button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleStart + '" data-bundle-action="start">'
            + '' + l10n.bundleStart + '</button>'
            + '<button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleStop + '" data-bundle-action="stop">'
            + '' + l10n.bundleStop + '</button>'
//            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
//            + 'title="' + l10n.bundleRefresh + '" data-bundle-action="refresh">'
//            + '' + l10n.bundleRefresh + '</button>'
            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleUpdate + '" data-bundle-action="update">'
            + '' + l10n.bundleUpdate + '</button>'
            + ' <button class="ui-button ui-widget ui-corner-all ui-button-icon-only"'
            + 'title="' + l10n.bundleUninstall + '" data-bundle-action="uninstall">'
            + '' + l10n.bundleUninstall + '</button>' );
        }
        return _buttonsPrototype;
    }

    orgJGrapesOsgiPortletsBundles.initViewTable = function(tableSelector) {
        JGPortal.lockMessageQueue();
        let table = tableSelector.DataTable( {
            "initComplete": function( settings, json ) {
                tableSelector.DataTable().processing(true);
                JGPortal.unlockMessageQueue();
            },
            "columns": [
                { "data": "id" },
                { "data": "name",
                  "render": function ( data, type, row, meta ) {
                      if (type === "display") {
                          return row.name + " (" + row.symbolicName + ")";
                      }
                      return data;
                  }
                },
                { "data": "version" },
                { "data": "category" },
                { "data": "state" },
                { "data": null,
                  "defaultContent": "",
                  "orderable": false,
                } ],
            "createdRow": function( row, data, dataIndex ) {
                $(row).attr("data-bundle-id", data.id);
                $( $(row).find("td")[5] ).append(buttonsPrototype().clone());
                $( $(row).find("td")[5] ).find("button").button();
            },
            "rowCallback": function( row, data, index ) {
                if ($( $(row).find("td")[5] ).find("button").length === 0) {
                    $( $(row).find("td")[5] ).append(buttonsPrototype().clone());
                    $( $(row).find("td")[5] ).find("button").button();
                }
                let startButton = $( row ).find('button[data-bundle-action="start"]');
                let stopButton = $( row ).find('button[data-bundle-action="stop"]');
                if (data.startable) {
                    startButton.show();
                    stopButton.hide();
                } else {
                    startButton.hide();
                    stopButton.show()
                }
                if (!data.stoppable) {
                    $( row ).find('button[data-bundle-action="stop"]').button("disable");
                }
                if (!data.uninstallable) {
                    $( row ).find('button [data-bundle-action="uninstall"]').button("disable");
                }
            },
            "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, $.fn.dataTable.defaults.oLanguage.sLengthAll] ],
            "pageLength": -1,
            "processing": true
        } );
        return table;
    }

    $("body").on("click", ".jgrapes-osgi-bundles-view table button",
        function(event) {
            let portletId = $(this).closest("[data-portlet-id]").attr("data-portlet-id");
            let bundleId = $(this).closest("[data-bundle-id]").attr("data-bundle-id");
            let action = $(this).attr("data-bundle-action")
            JGPortal.sendToPortlet(portletId, action, [ parseInt(bundleId) ]);
    });

    function updateTable(table, bundleInfos, replace) {
        if (replace) {
            table.clear();
        }
        bundleInfos.forEach(function(bundleInfo) {
            if (!replace) {
                let row = table.row(function ( idx, data, node ) {
                    return data.id === bundleInfo.id;
                });
                if (row.length > 0) {
                    if (bundleInfo.uninstalled) {
                        table.row(row).remove();
                    } else {
                        table.row(row).data(bundleInfo);
                    }
                    return;
                }
            }
            if (!bundleInfo.uninstalled) {
                table.row.add(bundleInfo);
            }
        });
        table.processing(false);
        table.columns.adjust().draw();
    }

    JGPortal.registerPortletMethod(
            "org.jgrapes.osgi.portlets.bundles.BundleListPortlet",
            "bundleUpdates", function(portletId, params) {
                let bundleInfos = params[0];
                // Preview
                if (params[1] === "preview" || params[1] === "*") {
                    let portlet = JGPortal.findPortletPreview(portletId);
                    if (portlet) {
                        let table = portlet.find(".jgrapes-osgi-bundles-preview table.bundles-table").DataTable();
                        updateTable(table, bundleInfos, params[2]);
                    }
                }

                // View
                if (params[1] === "view" || params[1] === "*") {
                    let portlet = JGPortal.findPortletView(portletId);
                    if (portlet) {
                        let table = portlet.find("table").DataTable();
                        updateTable(table, bundleInfos, params[2]);
                    }
                }
            });

})();

<|endoftext|>


<commit_before>const fs = require('fs');

module.exports = bot => {
    bot.on('ready', () => {
        if (bot.loadCommands) {
            let meme;
            require(`${__baseDir}/modules/commandLoader`).init().then(() => {
                logger.info(`Loaded ${bot.commands.length} ${bot.commands.length === 1 ? 'command' : 'commands'}.`);
                return localeManager.loadLocales();
            }).then(() => bot.db.tableList().run()).then(res => {
                meme = res;
                if (res.indexOf('guild_settings') === -1) {
                    logger.info('Setting up "guild_settings" table in database.');
                    return bot.db.tableCreate('guild_settings').run();
                } else {
                    return null;
                }
            }).then(() => {
                if (meme.indexOf('user_settings') === -1) {
                    logger.info('Setting up "user_settings" table in database.');
                    return bot.db.tableCreate('user_settings').run();
                } else {
                    return null;
                }
            }).then(() => {
                bot.loadCommands = false;
                bot.allowCommandUse = true;

                let altPrefixes = JSON.parse(fs.readFileSync(`${__baseDir}/data/prefixes.json`));
                logger.info(`${bot.user.username} is connected to Discord and ready to use.`);
                logger.info(`Main prefix is '${bot.config.mainPrefix}', can also use @mention.`);
                logger.info(`${altPrefixes.length > 0 ? `Alternative prefixes: '${altPrefixes.join("', ")}'` : 'No alternative prefixes.'}`);
            }).catch(err => {
                logger.error(`Experienced error while loading commands:\n${bot.config.debug ? err.stack : err}`);
            });
        } else {
            logger.info('Reconnected to Discord from disconnect.');
        }

        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}`});
    });
};<commit_msg>fuck this grammar<commit_after>const fs = require('fs');

module.exports = bot => {
    bot.on('ready', () => {
        if (bot.loadCommands) {
            let meme;
            require(`${__baseDir}/modules/commandLoader`).init().then(() => {
                logger.info(`Loaded ${bot.commands.length} ${bot.commands.length === 1 ? 'command' : 'commands'}.`);
                return localeManager.loadLocales();
            }).then(() => bot.db.tableList().run()).then(res => {
                meme = res;
                if (res.indexOf('guild_settings') === -1) {
                    logger.info('Setting up "guild_settings" table in database.');
                    return bot.db.tableCreate('guild_settings').run();
                } else {
                    return null;
                }
            }).then(() => {
                if (meme.indexOf('user_settings') === -1) {
                    logger.info('Setting up "user_settings" table in database.');
                    return bot.db.tableCreate('user_settings').run();
                } else {
                    return null;
                }
            }).then(() => {
                bot.loadCommands = false;
                bot.allowCommandUse = true;

                let altPrefixes = JSON.parse(fs.readFileSync(`${__baseDir}/data/prefixes.json`));
                logger.info(`${bot.user.username} is connected to Discord and ready to use.`);
                logger.info(`Main prefix is '${bot.config.mainPrefix}', can also use @mention.`);
                logger.info(`${altPrefixes.length > 0 ? `Alternative prefixes: '${altPrefixes.join("', ")}'` : 'No alternative prefixes.'}`);
            }).catch(err => {
                logger.error(`Experienced error while loading commands:\n${bot.config.debug ? err.stack : err}`);
            });
        } else {
            logger.info('Reconnected to Discord from disconnection.');
        }

        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}`});
    });
};<|endoftext|>


<commit_before>'use strict'
const farmhash = require('farmhash')
const sql = require('./sql')
const Query = require('./query')
const { calculateClassBreaks, calculateUniqueValueBreaks } = require('./generateBreaks/index')
const _ = require('lodash')

function breaksQuery (features, query, options) {
  const queriedData = standardQuery(features, query, options)
  if (queriedData === undefined || queriedData.features === undefined) throw new Error('query response undefined')
  if (queriedData.features.length === 0) throw new Error('need features in order to classify')

  const classification = options.classification
  if (classification.type === 'classes') {
    if (classification.breakCount <= 0) throw new Error('breakCount must be positive: ' + classification.breakCount)
    return calculateClassBreaks(queriedData.features, classification)
  } else if (classification.type === 'unique') {
    const { options, query } = calculateUniqueValueBreaks(queriedData.features, classification)
    return aggregateQuery(queriedData.features, query, options)
  } else throw new Error('unacceptable classification type: ' + classification.type)
}

function aggregateQuery (features, query, options) {
  const params = Query.params(features, options)
  const filtered = sql(query, params)
  return finishQuery(filtered, options)
}

function limitQuery (features, query, options) {
  let filtered = []
  let limitExceeded = false
  if (options.offset) {
    if (options.offset >= features.length) throw new Error('OFFSET >= features length: ' + options)
    options.limit += options.offset
  }
  features.some((feature) => {
    const result = processQuery(feature, query, options)
    if (result) filtered.push(result)
    if (filtered.length === (options.limit + 1)) {
      limitExceeded = true
      return true
    }
  })

  if (limitExceeded) filtered = filtered.slice(0, -1)

  if (options.collection) {
    options.collection.metadata = Object.assign({}, options.collection.metadata, { limitExceeded })
  }

  return finishQuery(filtered, options)
}

function standardQuery (features, query, options) {
  const filtered = features.reduce((filteredFeatures, feature) => {
    const result = processQuery(feature, query, options)
    if (result) filteredFeatures.push(result)
    return filteredFeatures
  }, [])
  return finishQuery(filtered, options)
}

function processQuery (feature, query, options) {
  const params = Query.params([feature], options)
  const result = sql(query, params)[0]

  if (result && options.toEsri) return esriFy(result, feature, options)
  else return result
}

function esriFy (result, feature, options) {
  if (options.dateFields.length) {
    // mutating dates has down stream consequences if the data is reused
    result.attributes = _.cloneDeep(result.attributes)
    options.dateFields.forEach(field => {
      result.attributes[field] = new Date(result.attributes[field]).getTime()
    })
  }

  const idField = _.get(options, 'collection.metadata.idField')

  // If the idField for the model set use its value as OBJECTID
  if (idField) result.attributes.OBJECTID = feature.properties[idField]
  else {
    // Create an OBJECTID by creating a numeric hash from the stringified feature
    // Note possibility of OBJECTID collisions with this method still exists, but should be small
    result.attributes.OBJECTID = createIntHash(JSON.stringify(feature))
  }
  return result
}

function finishQuery (features, options) {
  if (options.offset) {
    if (options.offset >= features.length) throw new Error('OFFSET >= features length: ' + options)
    features = features.slice(options.offset)
  }
  if (options.groupBy) {
    return features
  } else if (options.aggregates) {
    return features[0]
  } else if (options.collection) {
    const collection = options.collection
    collection.features = features
    return collection
  } else {
    return features
  }
}

/**
 * Create integer hash in range of 0 - 2147483647 from string
 * @param {*} inputStr - any string
 */
function createIntHash (inputStr) {
  // Hash to 32 bit unsigned integer
  const hash = farmhash.hash32(inputStr)
  // Normalize to range of postive values of signed integer
  return Math.round((hash / 4294967295) * (2147483647))
}

module.exports = { breaksQuery, aggregateQuery, limitQuery, standardQuery, finishQuery }
<commit_msg>Add warning for non- or out-of-range integers assigned to OBJECTID property.<commit_after>'use strict'
const farmhash = require('farmhash')
const sql = require('./sql')
const Query = require('./query')
const { calculateClassBreaks, calculateUniqueValueBreaks } = require('./generateBreaks/index')
const _ = require('lodash')

function breaksQuery (features, query, options) {
  const queriedData = standardQuery(features, query, options)
  if (queriedData === undefined || queriedData.features === undefined) throw new Error('query response undefined')
  if (queriedData.features.length === 0) throw new Error('need features in order to classify')

  const classification = options.classification
  if (classification.type === 'classes') {
    if (classification.breakCount <= 0) throw new Error('breakCount must be positive: ' + classification.breakCount)
    return calculateClassBreaks(queriedData.features, classification)
  } else if (classification.type === 'unique') {
    const { options, query } = calculateUniqueValueBreaks(queriedData.features, classification)
    return aggregateQuery(queriedData.features, query, options)
  } else throw new Error('unacceptable classification type: ' + classification.type)
}

function aggregateQuery (features, query, options) {
  const params = Query.params(features, options)
  const filtered = sql(query, params)
  return finishQuery(filtered, options)
}

function limitQuery (features, query, options) {
  let filtered = []
  let limitExceeded = false
  if (options.offset) {
    if (options.offset >= features.length) throw new Error('OFFSET >= features length: ' + options)
    options.limit += options.offset
  }
  features.some((feature) => {
    const result = processQuery(feature, query, options)
    if (result) filtered.push(result)
    if (filtered.length === (options.limit + 1)) {
      limitExceeded = true
      return true
    }
  })

  if (limitExceeded) filtered = filtered.slice(0, -1)

  if (options.collection) {
    options.collection.metadata = Object.assign({}, options.collection.metadata, { limitExceeded })
  }

  return finishQuery(filtered, options)
}

function standardQuery (features, query, options) {
  const filtered = features.reduce((filteredFeatures, feature) => {
    const result = processQuery(feature, query, options)
    if (result) filteredFeatures.push(result)
    return filteredFeatures
  }, [])
  return finishQuery(filtered, options)
}

function processQuery (feature, query, options) {
  const params = Query.params([feature], options)
  const result = sql(query, params)[0]

  if (result && options.toEsri) return esriFy(result, feature, options)
  else return result
}

function esriFy (result, feature, options) {
  if (options.dateFields.length) {
    // mutating dates has down stream consequences if the data is reused
    result.attributes = _.cloneDeep(result.attributes)
    options.dateFields.forEach(field => {
      result.attributes[field] = new Date(result.attributes[field]).getTime()
    })
  }

  const idField = _.get(options, 'collection.metadata.idField')

  // If the idField for the model set use its value as OBJECTID
  if (idField) {
    if (!Number.isInteger(feature.properties[idField]) || feature.properties[idField] > 2147483647 ) {
      console.warn(`WARNING: OBJECTIDs created from provider's "idField" are not integers from 0 to 2147483647`)
    }
    result.attributes.OBJECTID = feature.properties[idField]
  }
  else {
    // Create an OBJECTID by creating a numeric hash from the stringified feature
    // Note possibility of OBJECTID collisions with this method still exists, but should be small
    result.attributes.OBJECTID = createIntHash(JSON.stringify(feature))
  }
  return result
}

function finishQuery (features, options) {
  if (options.offset) {
    if (options.offset >= features.length) throw new Error('OFFSET >= features length: ' + options)
    features = features.slice(options.offset)
  }
  if (options.groupBy) {
    return features
  } else if (options.aggregates) {
    return features[0]
  } else if (options.collection) {
    const collection = options.collection
    collection.features = features
    return collection
  } else {
    return features
  }
}

/**
 * Create integer hash in range of 0 - 2147483647 from string
 * @param {*} inputStr - any string
 */
function createIntHash (inputStr) {
  // Hash to 32 bit unsigned integer
  const hash = farmhash.hash32(inputStr)
  // Normalize to range of postive values of signed integer
  return Math.round((hash / 4294967295) * (2147483647))
}

module.exports = { breaksQuery, aggregateQuery, limitQuery, standardQuery, finishQuery }
<|endoftext|>


<commit_before>const data = require('../../data/hacker.json');

function parse(hacker, format) {
  return format
    .replace(/\{abbreviation\}/g, hacker.abbreviation())
    .replace(/\{adjective\}/g, hacker.adjective())
    .replace(/\{noun\}/g, hacker.noun())
    .replace(/\{verb\}/g, hacker.verb())
    .replace(/\{ingverb\}/g, hacker.ingverb())
    .replace(/^(\w)/, m => m[0].toUpperCase());
}

export default class Hacker {
  constructor(faker) {
    this.faker = faker;
  }

  saySomethingSmart() {
    return parse(this, this.faker.Random.element(data['phrases']));
  }

  abbreviation() {
    return this.faker.Random.element(data['abbreviations']);
  }

  adjective() {
    return this.faker.Random.element(data['adjectives']);
  }

  noun() {
    return this.faker.Random.element(data['nouns']);
  }

  verb() {
    return this.faker.Random.element(data['verbs']);
  }

  ingverb() {
    return this.faker.Random.element(data['ingverbs']);
  }
}
<commit_msg>Using the Fake faker to parse placeholders.<commit_after>const data = require('../../data/hacker.json');

function parse(faker, format) {
  const text = format.replace(/\{(\w+)\}/g, m => `{Hacker.${m.substring(1)}`);
  return faker.Fake.f(text).replace(/^(\w)/, m => m[0].toUpperCase());
}

export default class Hacker {
  constructor(faker) {
    this.faker = faker;
  }

  saySomethingSmart() {
    return parse(this.faker, this.faker.Random.element(data['phrases']));
  }

  abbreviation() {
    return this.faker.Random.element(data['abbreviations']);
  }

  adjective() {
    return this.faker.Random.element(data['adjectives']);
  }

  noun() {
    return this.faker.Random.element(data['nouns']);
  }

  verb() {
    return this.faker.Random.element(data['verbs']);
  }

  ingverb() {
    return this.faker.Random.element(data['ingverbs']);
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.common.gadgets.ExpandedPositions',
    dependencies: [],
    obj: function () {
        var prefix = 'og_expanded_positions_gadget_', counter = 1;
        return function (config) {
            var gadget = this, alive = prefix + counter++;
            gadget.alive = function () {return $('.' + alive).length ? true : false;};
            gadget.resize = function () {gadget.load();};
            gadget.load = function () {
                var selector_position = config.selector + ' .og-js-gadgets-positions',
                    selector_trades = config.selector + ' .og-js-trades-table';
                $.when(og.api.text({module: 'og.views.gadgets.expanded_positions'})).pipe(function (template) {
                    $(config.selector).addClass(alive).html(template);
                    og.common.gadgets.positions($.extend({}, config, {selector: selector_position}));
                    og.common.gadgets.trades($.extend({}, config, {selector: selector_trades}));
                    if (!config.child) og.common.gadgets.manager.register(gadget);
                });
            };
            gadget.load();
        }
    }
});<commit_msg>adding loader to expanded_positions gadget<commit_after>/*
 * Copyright 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.common.gadgets.ExpandedPositions',
    dependencies: [],
    obj: function () {
        var prefix = 'og_expanded_positions_gadget_', counter = 1, loading_template;
        return function (config) {
            var gadget = this, alive = prefix + counter++;
            gadget.alive = function () {return $('.' + alive).length ? true : false;};
            gadget.resize = function () {gadget.load();};
            gadget.load = function () {
                var selector_position = config.selector + ' .og-js-gadgets-positions',
                    selector_trades = config.selector + ' .og-js-trades-table';
                $(config.selector).addClass(alive).html(loading_template({text: 'loading...'}));
                $.when(og.api.text({module: 'og.views.gadgets.expanded_positions'})).pipe(function (template) {
                    $(config.selector).html(template);
                    og.common.gadgets.positions($.extend({}, config, {selector: selector_position}));
                    og.common.gadgets.trades($.extend({}, config, {selector: selector_trades}));
                });
            };
            if (!config.child) og.common.gadgets.manager.register(gadget);
            if (loading_template) gadget.load(); else og.api.text({module: 'og.analytics.loading_tash'})
                .pipe(function (template) {loading_template = Handlebars.compile(template); gadget.load();});
        }
    }
});<|endoftext|>


<commit_before>ManageIQ.angular.app.controller('cloudVolumeBackupFormController', ['miqService', 'cloudVolumeBackupFormId', '$http', function(miqService, cloudVolumeBackupFormId, $http) {
  var vm = this;

  var init = function() {
    vm.afterGet = false;

    vm.cloudVolumeBackupModel = {
      volume_id: '',
    };

    vm.formId = cloudVolumeBackupFormId;
    vm.model = "cloudVolumeBackupModel";

    ManageIQ.angular.scope = vm;
    vm.saveable = function(form) {
      return form.$valid;
    };

    vm.newRecord = false;

    $http.get('/cloud_volume_backup/volume_form_choices')
      .then(getVolumeFormDataComplete)
      .catch(miqService.handleFailure);
  };

  vm.saveClicked = function() {
    var restoreUrl = '/cloud_volume_backup/backup_restore/';
    var buttonUrl = '?button=restore';
    miqService.miqAjaxButton(restoreUrl + cloudVolumeBackupFormId + buttonUrl, vm.cloudVolumeBackupModel, { complete: false });
  };

  vm.cancelClicked = function() {
    var cancelUrl = '/cloud_volume_backup/backup_restore/';
    var buttonUrl = '?button=cancel';
    miqService.miqAjaxButton(cancelUrl + cloudVolumeBackupFormId + buttonUrl);
  };

  vm.resetClicked = function(angularForm) {
    resetModel();
    angularForm.$setPristine(true);
    miqService.miqFlash("warn", "All changes have been reset");
  };

  function getVolumeFormDataComplete(response) {
    vm.volume_choices = response.data.volume_choices;
    if (foundVolumes()) {
      vm.cloudVolumeBackupModel.volume = vm.volume_choices[0];
    }
  }

  function resetModel() {
    vm.cloudVolumeBackupModel = angular.copy(vm.modelCopy);
  }

  function foundVolumes() {
    return vm.volume_choices.length > 0;
  }

  init();
}]);
<commit_msg>Add missing gettext into cloudVolumeBackupFormController<commit_after>ManageIQ.angular.app.controller('cloudVolumeBackupFormController', ['miqService', 'cloudVolumeBackupFormId', '$http', function(miqService, cloudVolumeBackupFormId, $http) {
  var vm = this;

  var init = function() {
    vm.afterGet = false;

    vm.cloudVolumeBackupModel = {
      volume_id: '',
    };

    vm.formId = cloudVolumeBackupFormId;
    vm.model = "cloudVolumeBackupModel";

    ManageIQ.angular.scope = vm;
    vm.saveable = function(form) {
      return form.$valid;
    };

    vm.newRecord = false;

    $http.get('/cloud_volume_backup/volume_form_choices')
      .then(getVolumeFormDataComplete)
      .catch(miqService.handleFailure);
  };

  vm.saveClicked = function() {
    var restoreUrl = '/cloud_volume_backup/backup_restore/';
    var buttonUrl = '?button=restore';
    miqService.miqAjaxButton(restoreUrl + cloudVolumeBackupFormId + buttonUrl, vm.cloudVolumeBackupModel, { complete: false });
  };

  vm.cancelClicked = function() {
    var cancelUrl = '/cloud_volume_backup/backup_restore/';
    var buttonUrl = '?button=cancel';
    miqService.miqAjaxButton(cancelUrl + cloudVolumeBackupFormId + buttonUrl);
  };

  vm.resetClicked = function(angularForm) {
    resetModel();
    angularForm.$setPristine(true);
    miqService.miqFlash("warn", __("All changes have been reset"));
  };

  function getVolumeFormDataComplete(response) {
    vm.volume_choices = response.data.volume_choices;
    if (foundVolumes()) {
      vm.cloudVolumeBackupModel.volume = vm.volume_choices[0];
    }
  }

  function resetModel() {
    vm.cloudVolumeBackupModel = angular.copy(vm.modelCopy);
  }

  function foundVolumes() {
    return vm.volume_choices.length > 0;
  }

  init();
}]);
<|endoftext|>


<commit_before>const GlobalMethodsPlugin = {
	install(Vue) {
		Vue.prototype.$dialogs = {};

		Vue.prototype.$dialogs.success = function(context) {
			context.$swal({
				title: context.$i18n.t('alerts.success.title'),
				text: context.$i18n.t('alerts.success.text'),
				type: 'success',
				toast: true,
				position: 'bottom-end',
				timer: 3000,
				showConfirmButton: false
			});
		};

		Vue.prototype.$dialogs.deleteElement = function(context, workFunction) {
			context.$swal({
				title: context.$i18n.t('alerts.delete.title'),
				text: context.$i18n.t('alerts.delete.text'),
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: context.$i18n.t('general.yes'),
				cancelButtonText: context.$i18n.t('general.abort')
			}).then(result => {
				if (result.value) workFunction();
			});
		};

		Vue.prototype.$dialogs.ajaxError = function(context, err) {
			if (err.status === 0) {
				// no connection
				context.$swal({
					title: context.$i18n.t('rest.errors.no-connection'),
					html: context.$i18n.t('rest.errors.api-unreachable'),
					type: 'error'
				});
			} else if (err.status === 400) {
				// constraint violation
				let errorText = err.body.message + ':
';
				if (err.body.code === 4001) {
					let jsonErrors = '
';
					err.body.violations.forEach(violation => {
						jsonErrors += '
' + violation.field + ' ' + violation.message + ' (' + violation.code + ' - ' + violation.constraint + ')
';
					});
					errorText += '

' + jsonErrors;
				}

				context.$swal({
					title: err.body.name + ' (' + err.body.code + ')',
					html: errorText,
					type: 'error'
				});
			} else if (err.status === 403) {
				// forbidden
				context.$swal({
					title: context.$i18n.t('rest.errors.403.title'),
					html: context.$i18n.t('rest.errors.403.text'),
					type: 'error'
				});
			} else if (err.status === 404) {
				// not found
				context.$swal({
					title: context.$i18n.t('rest.errors.404.title'),
					html: context.$i18n.t('rest.errors.404.text'),
					type: 'error'
				});
			} else {
				// general error
				context.$swal({
					title: context.$i18n.t('rest.errors.title'),
					html: context.$i18n.t('rest.errors.http-error', { status: err.status }),
					type: 'error'
				});
			}
		};

		Vue.prototype.$helpers = {};

		Vue.prototype.$helpers.getAjaxErrorMessage = function(context, response) {
			if (response.status === 0) {
				return context.$i18n.t('rest.errors.api-unreachable');
			} else if (response.status === 401 || response.status === 403) {
				return context.$i18n.t('rest.errors.permissions');
			} else {
				return context.$i18n.t('rest.errors.http-error', { status: response.status });
			}
		};

		Vue.prototype.$helpers.checkForInput = function(context, form) {
			for (let key in form) {
				if (form.hasOwnProperty(key)) {
					if (form[key].length === 0 || form[key] === '') {
						context.$swal({
							title: context.$i18n.t('alerts.input.title'),
							html: context.$i18n.t('alerts.input.text'),
							type: 'error'
						});
						return false;
					}
				}
			}
			return true;
		};

		Vue.prototype.$helpers.zeroPad = function(number, size) {
			let s = String(number);
			while (s.length < (size || 2)) {
				s = '0' + s;
			}
			return s;
		};

		Vue.prototype.$helpers.stringToColor = function(string) {
			let hash = 0;
			for (let i = 0; i < string.length; i++) {
				hash = string.charCodeAt(i) + ((hash << 5) - hash);
				hash = hash & hash;
			}

			return 'hsl(' + hash % 360 + ', 100%, 30%)';
		};

		Vue.prototype.$helpers.getDistributedColors = function(amount) {
			let ret = [];
			let steps = Math.floor(360 / amount);
			for (let i = 1; i <= amount; i++) {
				ret.push('hsl(' + (i * steps) + ', 100%, 30%)');
			}

			return ret;
		};
	}
};

export default GlobalMethodsPlugin;
<commit_msg>Added error-message for overwriting data (#153)<commit_after>const GlobalMethodsPlugin = {
	install(Vue) {
		Vue.prototype.$dialogs = {};

		Vue.prototype.$dialogs.success = function(context) {
			context.$swal({
				title: context.$i18n.t('alerts.success.title'),
				text: context.$i18n.t('alerts.success.text'),
				type: 'success',
				toast: true,
				position: 'bottom-end',
				timer: 3000,
				showConfirmButton: false
			});
		};

		Vue.prototype.$dialogs.deleteElement = function(context, workFunction) {
			context.$swal({
				title: context.$i18n.t('alerts.delete.title'),
				text: context.$i18n.t('alerts.delete.text'),
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: context.$i18n.t('general.yes'),
				cancelButtonText: context.$i18n.t('general.abort')
			}).then(result => {
				if (result.value) workFunction();
			});
		};

		Vue.prototype.$dialogs.ajaxError = function(context, err) {
			if (err.status === 0) {
				// no connection
				context.$swal({
					title: context.$i18n.t('rest.errors.no-connection'),
					html: context.$i18n.t('rest.errors.api-unreachable'),
					type: 'error'
				});
			} else if (err.status === 400) {
				// constraint violation
				let errorText = err.body.message + ':
';
				if (err.body.code === 4001) {
					let jsonErrors = '
';
					err.body.violations.forEach(violation => {
						jsonErrors += '
' + violation.field + ' ' + violation.message + ' (' + violation.code + ' - ' + violation.constraint + ')
';
					});
					errorText += '

' + jsonErrors;
				}

				context.$swal({
					title: err.body.name + ' (' + err.body.code + ')',
					html: errorText,
					type: 'error'
				});
			} else if (err.status === 403) {
				// forbidden
				context.$swal({
					title: context.$i18n.t('rest.errors.403.title'),
					html: context.$i18n.t('rest.errors.403.text'),
					type: 'error'
				});
			} else if (err.status === 404) {
				// not found
				context.$swal({
					title: context.$i18n.t('rest.errors.404.title'),
					html: context.$i18n.t('rest.errors.404.text'),
					type: 'error'
				});
			} else {
				// general error
				context.$swal({
					title: context.$i18n.t('rest.errors.title'),
					html: context.$i18n.t('rest.errors.http-error', { status: err.status }),
					type: 'error'
				});
			}
		};

		Vue.prototype.$dialogs.overwriteError = function(context) {
			context.$swal({
				title: context.$i18n.t('alerts.overwrite.title'),
				html: context.$i18n.t('alerts.overwrite.text'),
				type: 'error'
			});
		};

		Vue.prototype.$helpers = {};

		Vue.prototype.$helpers.getAjaxErrorMessage = function(context, response) {
			if (response.status === 0) {
				return context.$i18n.t('rest.errors.api-unreachable');
			} else if (response.status === 401 || response.status === 403) {
				return context.$i18n.t('rest.errors.permissions');
			} else {
				return context.$i18n.t('rest.errors.http-error', { status: response.status });
			}
		};

		Vue.prototype.$helpers.checkForInput = function(context, form) {
			for (let key in form) {
				if (form.hasOwnProperty(key)) {
					if (form[key].length === 0 || form[key] === '') {
						context.$swal({
							title: context.$i18n.t('alerts.input.title'),
							html: context.$i18n.t('alerts.input.text'),
							type: 'error'
						});
						return false;
					}
				}
			}
			return true;
		};

		Vue.prototype.$helpers.zeroPad = function(number, size) {
			let s = String(number);
			while (s.length < (size || 2)) {
				s = '0' + s;
			}
			return s;
		};

		Vue.prototype.$helpers.stringToColor = function(string) {
			let hash = 0;
			for (let i = 0; i < string.length; i++) {
				hash = string.charCodeAt(i) + ((hash << 5) - hash);
				hash = hash & hash;
			}

			return 'hsl(' + hash % 360 + ', 100%, 30%)';
		};

		Vue.prototype.$helpers.getDistributedColors = function(amount) {
			let ret = [];
			let steps = Math.floor(360 / amount);
			for (let i = 1; i <= amount; i++) {
				ret.push('hsl(' + (i * steps) + ', 100%, 30%)');
			}

			return ret;
		};
	}
};

export default GlobalMethodsPlugin;
<|endoftext|>


<commit_before>/**
 * ReminderBanner Component Stories.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * Internal dependencies
 */
import ReminderBanner from './ReminderBanner';
import { CORE_USER } from '../../../../../googlesitekit/datastore/user/constants';
import WithRegistrySetup from '../../../../../../../tests/js/WithRegistrySetup';
import { MODULES_ANALYTICS } from '../../../../analytics/datastore/constants';
import { provideUserInfo } from '../../../../../../../tests/js/utils';

const Template = () => <ReminderBanner onSubmitSuccess={ () => {} } />;

export const InitialNotice = Template.bind( {} );
InitialNotice.storyName = 'Before 1 June 2023';
InitialNotice.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-05-31' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const InitialNoticeWithoutAccess = Template.bind( {} );
InitialNoticeWithoutAccess.storyName = 'Before 1 June 2023 - Without Access';
InitialNoticeWithoutAccess.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-05-31' );
			provideUserInfo( registry, { id: 2 } );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const LastMonth = Template.bind( {} );
LastMonth.storyName = 'During June 2023';
LastMonth.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-06-01' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const PostCutoff = Template.bind( {} );
PostCutoff.storyName = 'After 30 June 2023';
PostCutoff.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-07-01' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export default {
	title: 'Modules/Analytics4/ReminderBanner',
	decorators: [
		( Story ) => {
			const setupRegistry = ( registry ) => {
				registry
					.dispatch( MODULES_ANALYTICS )
					.receiveGetSettings( { ownerID: 1 } );
				provideUserInfo( registry );
			};

			return (
				<WithRegistrySetup func={ setupRegistry }>
					<Story />
				</WithRegistrySetup>
			);
		},
	],
};
<commit_msg>Update storybook for check module access updates.<commit_after>/**
 * ReminderBanner Component Stories.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import fetchMock from 'fetch-mock';

/**
 * Internal dependencies
 */
import ReminderBanner from './ReminderBanner';
import { CORE_USER } from '../../../../../googlesitekit/datastore/user/constants';
import WithRegistrySetup from '../../../../../../../tests/js/WithRegistrySetup';
import { MODULES_ANALYTICS } from '../../../../analytics/datastore/constants';
import {
	provideModuleRegistrations,
	provideModules,
	provideUserInfo,
} from '../../../../../../../tests/js/utils';

const Template = () => <ReminderBanner onSubmitSuccess={ () => {} } />;

export const InitialNotice = Template.bind( {} );
InitialNotice.storyName = 'Before 1 June 2023';
InitialNotice.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-05-31' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const InitialNoticeWithoutAccess = Template.bind( {} );
InitialNoticeWithoutAccess.storyName = 'Before 1 June 2023 - Without Access';
InitialNoticeWithoutAccess.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-05-31' );
			provideUserInfo( registry, { id: 2 } );
			fetchMock.postOnce(
				/^\/google-site-kit\/v1\/core\/modules\/data\/check-access/,
				{ body: { access: false } }
			);
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const LastMonth = Template.bind( {} );
LastMonth.storyName = 'During June 2023';
LastMonth.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-06-01' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export const PostCutoff = Template.bind( {} );
PostCutoff.storyName = 'After 30 June 2023';
PostCutoff.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( CORE_USER ).setReferenceDate( '2023-07-01' );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export default {
	title: 'Modules/Analytics4/ReminderBanner',
	decorators: [
		( Story ) => {
			const setupRegistry = ( registry ) => {
				provideModules( registry );
				provideModuleRegistrations( registry );
				registry
					.dispatch( MODULES_ANALYTICS )
					.receiveGetSettings( { ownerID: 1 } );
			};

			return (
				<WithRegistrySetup func={ setupRegistry }>
					<Story />
				</WithRegistrySetup>
			);
		},
	],
};
<|endoftext|>


<commit_before>import React from 'react'
import classNames from 'classnames'

import {iconify} from '../lib/str'
import styles from './styles'

export const Link = ({name, href}) => (

)

export const Header = () => (

Langri-Sha

      {[
        ['Stack Overflow', 'https://stackoverflow.com/users/story/44041'],
        ['Keybase', 'https://github.com/langri-sha'],
        ['GitHub', 'https://github.com/langri-sha'],
      ].map(([name, href]) => (
        <Link key={name} name={name} href={href} />
      ))}

)
<commit_msg>style(src): Improve<commit_after>import React from 'react'

import {iconify} from '../lib/str'
import styles from './styles'

export const Link = ({name, href}) => (

)

export const Header = () => (

Langri-Sha

      {[
        ['Stack Overflow', 'https://stackoverflow.com/users/story/44041'],
        ['Keybase', 'https://github.com/langri-sha'],
        ['GitHub', 'https://github.com/langri-sha']
      ].map(([name, href]) => (
        <Link key={name} name={name} href={href} />
      ))}

)
<|endoftext|>