MathHelper

@package     gina.utils.math
@author      Rhinostone <gina@rhinostone.com>
@api public
343551
function Math() {

    var self = this;

    // /**
    //  * init
    //  * @constructor
    //  * */
    // var init = function() {
    //     if ( typeof(Math.instance) != "undefined" ) {
    //         return Math.instance
    //     } else {
    //         Math.instance = self
    //     }
    // }

    /**
     * Operate from a string value
     *
     * e.g.:
     *
     *  var operate = require("gina").utils.math.operate;
     *  var calculation = "10*2";
     *  var result = operate(calculation);
     *      => 20
     *
     *  @param {string} calcultation
     *
     *  @return {number} result
     * */
    this.operate = function(calculation) {
        return new Function('return ' + calculation)()
    }

    /**
     * Checksum
     * e.g: checksum(data, 'sha1')
     *
     * @param {string} str - Data to analyse
     * @param {string} algorithm
     * @param {string} [ encoding ] - e.g.: hex
     *
     * @return {string} checksum
     * */
    var checkSum = function (str, algorithm, encoding) {
        try {
            return crypto
                .createHash(algorithm || 'md5')
                .update(str, 'utf8')
                .digest(encoding || 'hex')
        } catch (err) {
            return err
        }
    }

    /**
     * Checksum
     *
     * @param {string} filename|data
     * @param {string} algorithm
     * @param {string} encoding
     *
     * @callback cb
     *  @param {object|string} err
     *  @param {string} checksum
     * */
    this.checkSum = function(filename, algorithm, encoding, cb) {
        var err = false, sum = null;

        if ( /\./.test(filename) ) {
            fs.readFile(filename, function (err, data) {
                sum = checkSum(data, algorithm, encoding);
                if( sum instanceof Error) {
                    err = sum;
                    sum = undefined
                }

                cb(err, sum)
            })
        } else {
            sum = checkSum(filename, algorithm, encoding);
            if( sum instanceof Error) {
                err = sum;
                sum = undefined
            }

            cb(err, sum)
        }
    }

    /**
     * Check sum from file or form data
     *
     * @param {string} filename|data
     * @param {string} algorithm
     * @param {string} encoding
     *
     * @return {string} checksum
     * */
    this.checkSumSync = function(filename, algorithm, encoding) {
        var sum = null;
        try {
            if ( /(\.[a-z]{3})$/.test(filename) ) { // must be a string
                // from filename
                sum = checkSum( fs.readFileSync(filename), algorithm, encoding )
            } else {
                // from data
                sum = checkSum( filename, algorithm, encoding )
            }

            if (sum instanceof Error)
                throw sum;
            else
                return sum

        } catch (err) {
            //console.error(err.stack||err.message);
            //return undefined
            throw err
        }
    }

    // for big files only: > 1Mb
    //this.checkSumBig= function(filename, cb) {
    //    var hash = crypto.createHash('md5');
    //    var encryption = encryption || 'sha1';
    //
    //    var stream = fs.createReadStream(filename);
    //    stream.on('data', function (data) {
    //        hash.update(data, 'utf8')
    //    })
    //
    //    stream.on('end', function () {
    //        hash.digest('hex');
    //    })
    //}

    //init();
    return this
}
520061
function() {
    var m = 0, ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j;
    do { i = ki - ni;
      nj = kj;
      do { j = kj - nj;
        if (Math.abs(this.elements[i][j]) > Math.abs(m)) { m = this.elements[i][j]; }
      } while (--nj);
    } while (--ni);
    return m;
  }
620318
function () {
            var val = this.val;

            var a = val[ 0 ], b = val[ 1 ], c = val[ 2 ],
                d = val[ 3 ], e = val[ 4 ], f = val[ 5 ],
                g = val[ 6 ], h = val[ 7 ], i = val[ 8 ];

            var ta = i * e - f * h,
                td = f * g - i * d,
                tg = h * d - e * g;

            var n = a * ta + b * td + c * tg;

            val[ 0 ] = ta / n;
            val[ 1 ] = ( c * h - i * b ) / n;
            val[ 2 ] = ( f * b - c * e ) / n;

            val[ 3 ] = td / n;
            val[ 4 ] = ( i * a - c * g ) / n;
            val[ 5 ] = ( c * d - f * a ) / n;

            val[ 6 ] = tg / n;
            val[ 7 ] = ( b * g - h * a ) / n;
            val[ 8 ] = ( e * a - b * d ) / n;

            return this;
        }
251798
function (type, number1, number2) {
      var result;

      number1 = helper.number(number1);
      number2 = helper.number(number2);

      if (isNaN(number1) || isNaN(number2)) {

        if (number1[0] === '=' || number2[0] === '=') {
          throw Error('NEED_UPDATE');
        }

        throw Error('VALUE');
      }

      switch (type) {
        case '+':
          result = number1 + number2;
          break;
        case '-':
          result = number1 - number2;
          break;
        case '/':
          result = number1 / number2;
          if (result == Infinity) {
            throw Error('DIV_ZERO');
          } else if (isNaN(result)) {
            throw Error('VALUE');
          }
          break;
        case '*':
          result = number1 * number2;
          break;
        case '^':
          result = Math.pow(number1, number2);
          break;
      }

      return result;
    }
632676
function RangeIterator(start, end, step) {
    this.start = start;
    this.end = (end !== undefined) ? end : Math.pow(2,32);    // or should this be Number.MAX_VALUE
    this.step = (step !== undefined)
        ? step
        : (this.end >= this.start)
            ? 1
            : -1;
    this.reset();
}
1203869
def +(arg)
      arg =
        case arg
        when Array
          raise ArgumentError, "Must be three numbers contained" unless arg.size==3
          arg
        else
          raise ArgumentError, "Accept only Array of three numbers"
        end
      new_hsb = self.hsb.zip(arg, [360, 101, 101]).map { |x, y, div| (x + y) % div }
      self.class.new *new_hsb
    end
103476
function maxOrMin( args, method ) {
            var m, n,
                i = 0;

            if ( isArray( args[0] ) ) args = args[0];
            m = new BigNumber( args[0] );

            for ( ; ++i < args.length; ) {
                n = new BigNumber( args[i] );

                // If any number is NaN, return NaN.
                if ( !n.s ) {
                    m = n;
                    break;
                } else if ( method.call( m, n ) ) {
                    m = n;
                }
            }

            return m;
        }
827754
function() {

      var a = this['re'];
      var b = this['im'];
      var ret = '';

      if (this['isNaN']()) {
        return 'NaN';
      }

      if (this['isZero']()) {
        return '0';
      }

      if (this['isInfinite']()) {
        return 'Infinity';
      }

      if (a !== 0) {
        ret += a;
      }

      if (b !== 0) {

        if (a !== 0) {
          ret += b < 0 ? ' - ' : ' + ';
        } else if (b < 0) {
          ret += '-';
        }

        b = Math.abs(b);

        if (1 !== b) {
          ret += b;
        }
        ret += 'i';
      }

      if (!ret)
        return '0';

      return ret;
    }
1357039
function outputHelp () {
  console.log('math.js')
  console.log('https://mathjs.org')
  console.log()
  console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ')
  console.log('real and complex numbers, units, matrices, a large set of mathematical')
  console.log('functions, and a flexible expression parser.')
  console.log()
  console.log('Usage:')
  console.log('    mathjs [scriptfile(s)|expression] {OPTIONS}')
  console.log()
  console.log('Options:')
  console.log('    --version, -v       Show application version')
  console.log('    --help,    -h       Show this message')
  console.log('    --tex               Generate LaTeX instead of evaluating')
  console.log('    --string            Generate string instead of evaluating')
  console.log('    --parenthesis=      Set the parenthesis option to')
  console.log('                        either of "keep", "auto" and "all"')
  console.log()
  console.log('Example usage:')
  console.log('    mathjs                                Open a command prompt')
  console.log('    mathjs 1+2                            Evaluate expression')
  console.log('    mathjs script.txt                     Run a script file')
  console.log('    mathjs script.txt script2.txt         Run two script files')
  console.log('    mathjs script.txt > results.txt       Run a script file, output to file')
  console.log('    cat script.txt | mathjs               Run input stream')
  console.log('    cat script.txt | mathjs > results.txt Run input stream, output to file')
  console.log()
  process.exit(0)
}
417428
function (numerator, denominator) {
        if (!common.isNumber(numerator) || !common.isNumber(denominator)) {
            return new Error('numerator or denominator not a number');
        }
        var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
        jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.WORK_STATUS, [this.handle, numerator, denominator]));
    }
1257338
function (n) {
            return n.every(function (a, i, args) {
                if (a === args[0]) {
                    return true;
                } else if (typeof a === 'number' && typeof args[0] === 'number') {
                    return Math.abs(a - args[0]) <= 3e-15;
                } else if (typeof a === 'object') {
                    return a.isEqual(args[0]);
                } else if (typeof args[0] === 'object') {
                    return args[0].isEqual(a);
                }
                return false;
            });
        }
623004
function () {
                var e, t, c, v;

                c = $(this.combinator);

                e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
                    $('*') || $('&') || $(this.attribute) || $(/^\([^)@]+\)/) || $(/^[\.#](?=@)/) || $(this.entities.variableCurly);

                if (! e) {
                    if ($('(') && (v = ($(this.entities.variableCurly) || $(this.entities.variable))) && $(')')) {
                        e = new(tree.Paren)(v);
                    }
                }

                if (e) { return new(tree.Element)(c, e, i) }
            }
794497
function StartMathJax() {
  serverState = STATE.STARTED;
  var script = document.createElement("script");
  script.src = MathJaxPath;
  script.onerror = function () {AddError("Can't load MathJax.js from "+MathJaxPath)};
  document.head.appendChild(script);
}
1101950
function (coordsArr) {
      function mapProp(func, array, prop) {
        function getProp(el) {
          return el[prop];
        }

        if (Array.prototype.map) {
          return func.apply(Math, array.map(getProp));
        }
        return func.apply(Math, $.map(array, getProp));
      }

      return {
        TL: {
          row: mapProp(Math.min, coordsArr, "row"),
          col: mapProp(Math.min, coordsArr, "col")
        },
        BR: {
          row: mapProp(Math.max, coordsArr, "row"),
          col: mapProp(Math.max, coordsArr, "col")
        }
      };
    }
778678
function() {

      var t;
      var a = this['n'];
      var b = this['d'];
      var res = [];

      if (isNaN(this['n']) || isNaN(this['d'])) {
        return res;
      }

      do {
        res.push(Math.floor(a / b));
        t = a % b;
        a = b;
        b = t;
      } while (a !== 1);

      return res;
    }
505702
function multiply(arr, arg) {
    var row, col, nrescols, sum, nrow, ncol, res, rescols;
    // eg: arr = 2 arg = 3 -> 6 for res[0][0] statement closure
    if (arr.length === undefined && arg.length === undefined) {
      return arr * arg;
    }
    nrow = arr.length,
    ncol = arr[0].length,
    res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol),
    rescols = 0;
    if (isUsable(arg)) {
      for (; rescols < nrescols; rescols++) {
        for (row = 0; row < nrow; row++) {
          sum = 0;
          for (col = 0; col < ncol; col++)
          sum += arr[row][col] * arg[col][rescols];
          res[row][rescols] = sum;
        }
      }
      return (nrow === 1 && rescols === 1) ? res[0][0] : res;
    }
    return jStat.map(arr, function(value) { return value * arg; });
  }
944317
function (hash) {
		var wrapper = this;

		each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR'], function (key) {
			wrapper[key] = pick(hash[key], wrapper[key]);
		});

		wrapper.attr({
			d: wrapper.renderer.symbols[wrapper.symbolName](
					mathRound(wrapper.x * 2) / 2, // Round to halves. Issue #274.
					mathRound(wrapper.y * 2) / 2,
					wrapper.r,
					{
						start: wrapper.start,
						end: wrapper.end,
						width: wrapper.width,
						height: wrapper.height,
						innerR: wrapper.innerR
					}
			)
		});
	}