Ejemplo n.º 1
0
    run(msg, { query }) {
        const num = math.eval(query);
        try {
            if (query.includes('eval')) {
                if (this.client.isOwner(msg.author)) {
                    math.eval(query);
                } else return msg.say('https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Twemoji_2b50.svg/2000px-Twemoji_2b50.svg.png');
            }
            if (query == 'gay') return msg.say(':gay_pride_flag:');

            return msg.say(num);
        } catch (err) {
            Raven.captureException(err);
            msg.say(err.message);
        }
    }
Ejemplo n.º 2
0
 process.nextTick(function(){
     var result = mathops.eval(value1 + value2);
     process.nextTick(function(){
         setTimeout(function() {
             callback(result);
         }, 2000);
     });
 });
Ejemplo n.º 3
0
    request.post(producerApi.produce, function(error, response, body) {
        if (!error && response.statusCode == 201) {
            var json = JSON.parse(body),
                expression = json.expression;

            // check format of expression from producer
            if (utils.checkExpressionFormat(expression)) {

                // safely eval expression
                var solution = math.eval(expression.replace('=', '')),
                    solutionMsg = expression + solution;

                logger.log('info', 'Success: ' + solutionMsg);

                // report solution back to producer
                request.post({
                    url: producerApi.report,
                    formData: {
                        expression: expression,
                        solution: solution
                    }
                }, function(error, response, body) {
                    if (!error && response.statusCode == 201) {
                        logger.log('info', 'Solution: %s reported to producer', solutionMsg);

                        var data = JSON.parse(response.body);
                        data['expression'] = expression;
                        data['solution'] = solution;

                        res.json(200, data);
                    }
                    else {
                        res.json(400, {'error': error});
                    }

                    next();
                });
            }
            else {
                // expression did not pass format check
                var msg = 'Bad expression format: ' + expression;
                logger.log('error', msg);
                res.json(400, {'error': msg});

                next();
            }
        }
        else {
            // handle error
            logger.log('error', 'Error: ' + error);
            res.json(400, {'error': error});

            next();
        }
    });
Ejemplo n.º 4
0
_.each(_defs, function (def, key) {
  try {
    if (def && key !== 'true' && def !== '') {
      let val = math.eval(def, _defs)
      if (val && Number.isInteger(val)) {
        defs[key] = val
      }
    }
  } catch (e) {
  }
})
Ejemplo n.º 5
0
 'click button': function () {
   let string = $('.formula').val()
   , obj = {
     a: $('#a').val(),
     b: $('#b').val(),
     c: $('#c').val()
   }
   string = Roller.diceFormula(string, obj)
   Session.set('formula', string);
   Session.set('counter', math.eval(string));
 }
Ejemplo n.º 6
0
 this.on("text", function (msg, reply){
     
     var match = Util.parseCommand(msg.text,["calc", "math"], {splitBy: ";"});  
     if(match)
     {
         match.splice(0,1);
         results = mathjs.eval(match);
         result = results[results.length-1];
         
         message = "`" + result + "`";
         reply({type:"text", text: message, options: { parse_mode: "Markdown" }});
     }
 });
Ejemplo n.º 7
0
 function search(query, res) {
   try {
     const ans = math.eval(query);
     if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
       res.add({
         title: `${query.trim()} = ${ans.toString()}`,
         group: 'Math',
         payload: ans.toString()
       });
     }
   } catch (e) {
   }
 }
Ejemplo n.º 8
0
    }).catch(() => {
      math.config({
        number: 'BigNumber',
        precision: 64
      })

      const result = math.eval(expr)

      if (!isNaN(result)) {
        resolve(noExponents(result))
      } else {
        reject(new Error(speech.calc.error))
      }
    })
Ejemplo n.º 9
0
    controller.hears(['what is \\d(.*)\\d', 'what\'s \\d(.*)\\d'],'direct_message,direct_mention,mention',function(bot, message) {

        var question = message.text.match(/(\d.*\d)/i)[0];
        console.log('question:', question);
        bot.reply(message, ':thinking_face: thinking mathy thoughts...' + question);
        question = question.replace(/x/i, '*');
        console.log('question:', question);
        var answer = math.eval(question);
        bot.reply(message, 'got it! ' + answer);
        setTimeout(function(){

        }, 3000);

    });
Ejemplo n.º 10
0
	,	function tokenize(variable,expression,negate,match){
			var scope = this.markdown.calculus;
			var _var = (variable?variable+' = ':'');
			var expression = _var+expression;
			var props = {class: 'math'};
			var render;
			try{
				render = _var+mathjs.eval(expression,scope);
			}catch(e){
				props.class+=' math-invalid';
				props['data-error'] = e.toString();
				render = expression;
			}
			return negate? '' : ['span',props,render];
		}
Ejemplo n.º 11
0
exports.applyParameter = function(data, face) {
  for ( var i in data.parameters ) {
    var parameter = data.parameters[i];
    if ( face.match(parameter.name) ) {
      data.usedParameters.push(parameter)
      face = face.replace(new RegExp(parameter.name, 'g'), parameter.value)
    }
  }
  try {
    return math.eval(face)
  } catch (e) {
    console.error(e)
    return 1*face;
  }
}
Ejemplo n.º 12
0
			expr: function (block, next) {
				var expr = this.parseExpression(block.rawExpr, function (n) {
					return parseInt(n, 10) || 0;
				});

				var result = "0";
				try {
					result = mathjs.eval(expr).toString();
				} catch (e) {
					result = "[MathError]";
				}

				this.pieces.push(result);
				this.start = block.end + 1;
				next();
			},
Ejemplo n.º 13
0
function genSolutions() {
    var solutions = [];
    solutions.push(currentAnswer);
    // we have 8 false solutions to generate
    // save our fingers
    var a = currentAnswer;

    // (2)
    if(a > 1) {
        solutions.push(a - 1);
        solutions.push(a + 1);
    } else {
        solutions.push(a + (a / 10 ));
        solutions.push(a - (a / 10 ));
    }

    // (3)
    solutions.push(a / 2);

    // (4)
    solutions.push(a * 1.25);

    // (5)
    solutions.push(math.eval("cos("+a+") * "+a));

    // (6)
    solutions.push(a + Math.floor((Math.random() * 4) + 2));

    // (7)
    solutions.push(a - Math.floor((Math.random() * 4) + 2));

    // (8)
    solutions.push(a + a);

    // clean up floats to 3 decimal places
    for(var i = 0; i < solutions.length; i++) {
        var num = solutions[i];
        if(num.toString().indexOf('.') > -1) {
            solutions[i] = num.toFixed(3);
        }
    }

    shuffle(solutions);

    return solutions;
}
Ejemplo n.º 14
0
var mathCommand = function(bot, sender, args, data, client)
{
	try
	{
		var arg = args.join(" ");
		var result = math.eval(arg);

		if(typeof result == 'function')
		{
			bot.sendClient("Cannot output function. Try " + arg + "; " + result.name + "(...)", client);
			return;
		}

		bot.sendAll("Result: " + result.toString(), client);
	}
	catch(e)
	{
		bot.sendClient(e.toString(), client);
	}
};
Ejemplo n.º 15
0
	search: function(query){
		var answer = undefined;
		try{
			answer = math.eval(query);
		} catch(e){
			return Promise.resolve([]);
		}
		if(!answer){
			return Promise.resolve([]);
		}
		if(answer.units){
			return Promise.resolve([]);
		}
		return Promise.resolve([{
			name:"Math",
			content:"math:"+answer,
			title:answer.toString(),
			url:"Selecting this will copy this to your clipboard."
		}]);
	},
Ejemplo n.º 16
0
/**
 * Evaluate an expression
 * @param {{expr: string | string[], precision: number | null}} params
 * @return {string | string[]} result
 */
function evaluate(params) {
  var scope, result;

  // TODO: validate params.expr
  // TODO: validate params.precision

  if (Array.isArray(params.expr)) {
    scope = {};
    result = params.expr.map(function (expr) {
      var r = math.eval(expr, scope);
      return math.format(r, options.filter(params));
    });
  }
  else {
    var r = math.eval(params.expr);
    result = math.format(r, options.filter(params));
  }

  return result;
}
Ejemplo n.º 17
0
				.get() (function(err, resp, body) {
					if(err) {
						res.send("Error: " + err);
					}else if(resp.statusCode != 200) {
						res.send("Invalid Course (Error " + resp.statusCode + ")");
					}else {
						var course = JSON.parse(body);
						var num_of_assessment = course.assessment.length;
						var scores = res.match[3].split(" ");
						if(scores.length != num_of_assessment - 1) {
							res.send("Invalid number of arguments. Course has " + num_of_assessment + " pieces of assessment, you gave " + scores.length + ".\nKeep in mind you need to leave the last piece of assessment out.");
						}else {
							var total = 0;
							var invalid = false;
							for(var i = 0; i < num_of_assessment - 1; i++) {
								try {
									var evaluated = math.eval(scores[i]);
								}catch(err) {
									res.send("Invalid score: " + scores[i] + ". Reason: Unparsable");
									invalid = true;
									break;
								}
								if(evaluated > 0 && evaluated < 1) {
									res.send("_Note: Treating '" + scores[i] + "' (" + evaluated + ") as: " + evaluated*100 + "%_");
									evaluated *= 100;
								}
								if(evaluated < 0 || evaluated > 100) {
									res.send("Invalid score: " + scores[i] + ". Reason: Score is not within 0 and 100");
									invalid = true;
									break;
								}
								total += (evaluated/100) * course.assessment[i].weight;
							}
							if(!invalid) {
								var needed = 50 - total;
								var result = Math.ceil(needed/course.assessment[num_of_assessment - 1].weight * 100);
								res.send("You need to achieve at least " + result + "% on the final exam.\n_Disclaimer: this does not take hurdles into account_\n_Powered by http://uqfinal.com_");
							}
						}
					}
				});
Ejemplo n.º 18
0
function startRound() {
    phase = 2;
    roundWinner = null;
    // generate new problem
    currentProblem = genProblem();

    // generate new answer
    currentAnswer = math.eval(currentProblem);
    console.log("Answer: " + currentAnswer);

    // generate possible solutions
    var solutions = genSolutions();

    io.emit('start-round', { currentProblem: currentProblem, solutions: solutions, round: round, MAX_ROUNDS: MAX_ROUNDS, countdown: START_COUNTDOWN });

    // start countdown if no one answers in time
    startTimer = setTimeout(function() {
        if(roundWinner === null) {
            endRound();
        }
    }, 1000 * START_COUNTDOWN);
}
Ejemplo n.º 19
0
 f.src.filter(function (filepath) {
     // Warn on and remove invalid source files (if nonull was set).
     if (!grunt.file.exists(filepath)) {
         grunt.log.warn('Source file "' + filepath + '" not found.');
         return false;
     } else {
         var id = filepath.split('/').slice(-2, -1);
         var initial = 0;
         var jsonPath = path.resolve(f.jsonPrefix + id + '.json');
         if (!grunt.file.exists(jsonPath)) {
             grunt.log.warn('No corresponding JSON file found. Set initial to 0.');
         } else {
             var jsonData = grunt.file.read(jsonPath);
             var sphere = JSON.parse(jsonData);
             if (sphere.initialView.long !== undefined) {
                 initial = -math.eval(sphere.initialView.long);
             }
         }
         config.previewSizes.forEach(function (res) {
             generatePreview(path.resolve(filepath), path.resolve(f.dest), id, res.size, res.count, initial);
         });
     }
 })
Ejemplo n.º 20
0
    return reduceFunctionCall(value, 'resolve', function(argString) {

        var unit = '';
        if (argString.indexOf('floor(') >= 0
                || argString.indexOf('ceil(') >= 0) {
            // drop unit to apply floor or ceil function
            var start = argString.indexOf('(') + 1;
            var end = argString.indexOf(')');
            var numberWithUnit = argString.substring(start, end);

            var number = numberWithUnit.replace(/([0-9\.]+)([a-zA-Z]+)$/, '$1');
            unit = numberWithUnit.replace(/([0-9]|\.)+([a-zA-Z]+)$/, '$2');

            argString = argString.substring(0, start) + number + ')';
        }

        var res = maths.eval(argString);
        // Add previous splitted unit if any
        var formatted = res.toString() + unit;

        // Math.JS puts a space between numbers and units, drop it.
        formatted = formatted.replace(/(.+) ([a-zA-Z]+)$/, '$1$2');
        return formatted;
    });
Ejemplo n.º 21
0
  client.addListener('message#', function(from, to, text) {
    if (text.search(trigger) > -1) {
      var expr = text.substring(6);
      try {
        var ans = math.eval(expr);
        client.say(to, math.format(ans));
      } catch (e) {
        console.error(e);
        client.say(to, 'Sorry, that was a bit too hard for me.');
      }
      return;
    }

    // Shortcuts
    for (let i = 0; i < shortcuts.length; i++) {
      let m = text.match(shortcuts[i].trigger);
      if (m !== null) {
        try {
          let ans = math.eval(m[1] + shortcuts[i].evalString);
          client.say(to, math.format(ans));
        } catch(e) {
          console.error(e);
        }
        return;
      }
    }

    let m = text.match(shortcutCM);
    if (m !== null) {
      let feet = m[1];
      let inches = m[2];
      try {
        let ans = math.eval('(' + feet + ' foot + ' + inches + ' inches) in centimeter');
        client.say(to, math.format(ans));
      } catch(e) {
        console.error(e);
      }
      return;
    }

    m = text.match(shortcutFeetInch);
    if (m !== null) {
      try {
        let cm = math.unit(m[1], 'cm');
        let inches = math.mod(cm.toNumber('inch'), 12);
        let feet = math.floor(cm.toNumber('foot'));
        let res = feet + ' foot ' + inches + ' inches';
        client.say(to, res);
      } catch(e) {
        console.error(e);
      }
      return;
    }

    m = text.match(shortcutPace);
    if (m !== null) {
      // Analyse what exactly the input is and calc based on that
      m = m[1].match(/^([0-9]+)(?:[m:]([0-9]?[0-9])s?)?$/i);
      if (m !== null) {
        let minutes = parseInt(m[1]);
        let seconds = 0;
        if (m[2] !== undefined) {
          seconds = parseInt(m[2]);
        }
        let basepace = seconds + minutes * 60;
        let pacepermile = Math.round(basepace * 1.6093);
        let paceperkm = Math.round(basepace / 1.6093);
        let miletokmtext = seconds_to_string(basepace) + "/mile = " + seconds_to_string(paceperkm) + "/km";
        let kmtomiletext = seconds_to_string(basepace) + "/km = " + seconds_to_string(pacepermile) + "/mile";
        client.say(to, miletokmtext + " || " + kmtomiletext);
      }
    }
  });
Ejemplo n.º 22
0
 result = params.expr.map(function (expr) {
   var r = math.eval(expr, scope);
   return math.format(r, options.filter(params));
 });
Ejemplo n.º 23
0
 return string.replace(/(\d+|\(.+\))d(\d+|\(.+\))/g, function(m) {
   let split = m.split('d')
   return Roller.d(math.eval(split[0]), math.eval(split[1]))
 });
Ejemplo n.º 24
0
 calculate: function(req, res) {
   var expr = req.vars.expr.replace(/√(\d+)/g, function(s, m) { return `sqrt(${m})`; }).replace(/√\(/g, 'sqrt('),
       start = process.hrtime();   
   return res({ result: math.eval(expr), elapsed: elapsed_time(start)});    
 }
Ejemplo n.º 25
0
slack.on('message', function(message) {
	var channel = slack.getChannelGroupOrDMByID(message.channel);
	var slackUserId = message.user;
	var slackUser = slack.getUserByID(slackUserId);
	TOTController.setChannel(channel);

	//console.log(message.type);

	if (message.type === 'message' && (message.text != null) && (channel != null)){
		var msgArray = TOTController.parseMessage(message.text);
		if(msgArray[0] !== '!trt'){return false;}

		if(playerWarnings[slackUserId] != null && playerWarnings[slackUserId] >= warningsTillIgnore){return false;}

		//check if they are sending too many commands
		if(playerLastCommandCache[slackUserId] == null){
			playerLastCommandCache[slackUserId] = new Date();
		}else{
			//less than 3 seconds between commands? send a warning.
			if(new Date() - playerLastCommandCache[slackUserId] < 3000){ //less than 3 seconds.
				if(playerWarnings[slackUserId] == null){
					playerWarnings[slackUserId] = 1;
				}else{
					playerWarnings[slackUserId] += 1;
				}
				if(playerWarnings[slackUserId] == warningsTillIgnore){
					channel.send(slackUser.name+", I warned you!\nI'm ignoring you now.");
					return false;
				}
				channel.send(slackUser.name+", Please slow down with the commands!!\n*+1 warning!* (currently "+playerWarnings[slackUserId]+")\nIf you get "+warningsTillIgnore+", I'll ignore you till tomorrow.");
				//return false;
			}
		}

		//update when they last sent a command.
		playerLastCommandCache[slackUserId] = new Date();

		switch(msgArray[1]){
			case undefined: //play the game
				TOTController.trickortreat(slackUserId,slackUser.name);
				break;
			case 'register':
				TOTController.register(slackUserId,slackUser.name);
				break;
			case 'help':
				//if(msgArray[2])
				var helpStr = "";
				for(var topic in help){
					helpStr+="*"+topic+"*: "+help[topic].short+"\n";
				}
				channel.send(helpStr);
				break;
			case 'debug':
				if(slackUser.name !== 'sirtopeia'){ return false; }
				var paramStr = "";
				for(var i = 2;i<msgArray.length;i++){
					paramStr += msgArray[i]+"\n";
				}
				if(paramStr !== ""){
					channel.send("These are the parameters I saw:\n"+paramStr);
				}
				break;
			case 'resetday':
				if(slackUser.name !== 'sirtopeia' && slackUser.name !== 'void'){return false;}
				TOTController.resetCooldowns();
				channel.send(slackUser.name+" reset the game day!");
				break;
			case 'loadcandy':
				if(slackUser.name !== 'sirtopeia'){channel.send("Only sirtopeia can add candy!"); return false; }
				TOTController.addCandy();
				break;
			case 'give':
				var response = TOTController.giveCandy(msgArray[2],msgArray[3],msgArray[4])
				if(response.success){

				}else{
					channel.send(response.error);					
				}
				break;
			case 'solve':
				//if(slackUser.name !== 'sirtopeia'){return false;}
				try{
					channel.send(""+math.eval(msgArray[2]));
				}catch(e){
					channel.send("Failed to solve!");
				}
				break;
			case 'count':
				TOTController.candyCount(slackUserId,slackUser.name);
				break;
			default:
				channel.send("Unknown command (try using !trt help)");
				break;

		}
		/*
		if(message.text.indexOf("!trickortreat") == 0 || message.text.indexOf("!trt") == 0 || message.text.indexOf("!tot") == 0){
			trickortreat(channel,user);
		}

		if(message.text.indexOf("!candytotal") == 0 || message.text.indexOf("!ct") == 0){
			if(players[slackUserId] != null){
				channel.send(slackUser.name+", you have "+players[slackUserId]+" candies!");
			}else{
				channel.send("You havn't started playing yet!");
			}
		}
		*/
	}
});
Ejemplo n.º 26
0
/**
 * Evaluate an expression
 * @param {string} expr
 * @return {string} result
 */
function evaluate (expr) {
  var ans = math.eval(expr);
  return math.format(ans);
}
Ejemplo n.º 27
0
exports.post = function(req, res) {

	var m = +req.body.m;
	var n = +req.body.n;

	if (m > n) {
		res.end('m must be less or equal n');
		return;
	}

	var elements = [];

	for (var element in req.body) {
		elements.push( req.body[element] );
	}

	var offset = 0;

	var arrayA = [];
	for (var i = 0; i < m; i++) {
		arrayA[i] = [];
		for (var j = 0; j < n; j++) {
			arrayA[i].push( mathjs.eval(elements[n * i + j ]) );
			offset++;
		}
	}


	var arrayB = [];
	for (var i = 0; i < m; i++) {
		arrayB[i] = [];
		arrayB[i].push( mathjs.eval(elements[ offset ]) );
		offset++;
	}

	var arrayC = [];
	for (var i = 0; i < n; i++) {
		arrayC.push( mathjs.eval(elements[ offset ]) );
		offset++;
	}

	var x = [];
	for (var i = 0; i < n; i++) {
		x.push( mathjs.eval(elements[ offset ]) );
		offset++;
	}


	var b = new Matrix(m, 1, arrayB);
	var A = new Matrix(m, n, arrayA);
	var c = new Matrix(1, n, [arrayC]);

	var output = '';

	output += '<h2>Input:</h2>';
	output += '<div class="alpha"><span class="imp">A = </span>';
	output += helper.outputMatrix(A);
	output += '</div>';

	output += '<div class="alpha"><span class="imp">b = </span>';
	output += helper.outputMatrix(b);
	output += '</div>';

	output += '<div class="alpha"><span class="imp">c = </span>';
	output += helper.outputMatrix(c);
	output += '</div>';
	output += '<span class="basis">X (Initial Basis Plan): ' + roundArray(x)  + '</span>';
	output += '<hr>';

	output += '<h2>Begin!</h2>';
	output += '<hr>';

	//second phase
	var Ai = getMatrixColumns(A);
	var Js = getJs(x, b);
	var Jb = Js.Jb;
	var Jn = Js.Jn;
	var J = Js.J;
	var Ab = getBasisMatrix(A, Jb);
	var B = Ab.inverse();


	var count = 0;

	while (true && count < MAX_NUMBER_OF_ITERATIONS) {
		count++;
		output += '<span class="basis">Jb: ' + Jb  + '</span>';
		output += '<span class="basis">X: ' + roundArray(x)  + '</span>';

		if (!B) {				//!!
			Ab = Ab.getIdentityMatrix(Ab.rowsNumber);
			B = Ab;
		}

		output += '<div class="alpha"><span class="imp">Ab = </span>';
		output += helper.outputMatrix(Ab);
		output += '</div>';

		output += '<div class="alpha"><span class="imp">B = </span>';
		output += helper.outputMatrix(B);
		output += '</div>';

		var cb = getCb(c, Jb);
		console.log(Jb);
		var u = cb.multiply(B);
		output += '<div class="alpha"><span class="imp">u = </span>';
		output += helper.outputMatrix(u);
		output += '</div>';
		var deltas = getDeltas(u, A, c, Jn);
		output += '<span class="basis">Deltas: ' + roundArray(deltas)  + '</span>';
		var stop = true;
		var minDelta;
		var j0;
		for (var i = 0; i < deltas.length; i++) {
			if (deltas[i] < 0 && minDelta == undefined) {
				stop = false;
				minDelta = deltas[i];
				j0 = Jn[i];
			}
			else if (deltas[i] < 0 && deltas[i] < minDelta) {
				minDelta = deltas[i];
				j0 = Jn[i];
			}
		}

		minDelta = undefined;

		if (stop) {		//STOP
			console.log('Optimum has been found: ' + x);
			output += '<h4>STOP</h4>'
			output += '<p class="result">Optimum has been found!</p>';
			output += '<p class="result">X = ' + roundArray(x) + '</p>';

			var xColumn = Matrix.createMatrixFromVectors([x], false);
			var optimum = c.multiply(xColumn).getValue(1, 1);
			output += '<p class="result">Optimum = ' + optimum + '</p>';

			break;
		}

		//step 3
		var z  = B.multiply(A.getCol(j0));
		output += '<div class="alpha"><span class="imp">z = </span>';
		output += helper.outputMatrix(z);
		output += '</div>';
		var hasSolution = false;
		for (var i = 1; i <= z.rowsNumber; i++) {
			if (z.getValue(i, 1) > 0) {
				hasSolution = true;
				break;
			}
		}


		if (!hasSolution) {		//STOP
			console.log('No solution');
			output += '<h4>STOP</h4>'
			output += '<p class="result">No solution</p>';
			break;
		}

		//step 4
		var Q;
		var s;
		for (var i = 1; i <= m; i++) {
			if (z.getValue(i, 1) > 0) {
				var temp = x[Jb[i - 1] - 1] / z.getValue(i, 1);
				if (Q == undefined) {
					Q = temp;
					s = i;
				}
				else if (temp < Q) {
					Q = temp;
					s = i;
				}
			}
		}



		var Js = Jb[s - 1];


		//step 5
		var JnIndex = 0;
		for (var i = 1; i <= n; i++) {
			if (i == Jn[JnIndex]) {
				x[i - 1] = 0;
				JnIndex++;
			}
		}
		x[j0 - 1] = Q;
		for (var i = 0; i < Jb.length; i++) {
			x[Jb[i] - 1] = x[Jb[i] - 1] - Q * z.getValue(i + 1, 1);
		}

		var JsIndex = Jb.indexOf(Js);
		Jb[JsIndex] = j0;

		//Jb.sort(compareNumbers);

		Jn = getNewJn(J, Jb);

		//step 6
		Ab = getBasisMatrix(A, Jb);
		B = Ab.inverse();

		Q = undefined;
		s = undefined;
		j0 - undefined;

		output += '<hr>'
		output += '<p class="next">next iteration</p>'
		output += '<hr>'
	}		//end while


	res.render('simplexMethodCalculate', {output: output});
}
Ejemplo n.º 28
0
/**
 * Calculate the target image size based on the size ratio
 * from the original input image size or base image size.
 *
 * @param  {object} options An object with the following properties:
 *                          - originalSize
 *                          - ratio
 * @return {[type]}         [description]
 */
function getSizeFromRatio(options) {
  var ratio = math.eval(options.ratio);
  return Math.floor(options.size * ratio);
}
Ejemplo n.º 29
0
 process: function(bot, msg, suffix) {
     var answer = math.eval(suffix);
     bot.createMessage(msg.channel.id, "**" + msg.author.username + "** here is the answer to that calculation: ```xl\n" + answer + "```");
 }
Ejemplo n.º 30
0
var query = function() {
    var input = $('#input').val();
    var result;

    var encodedQuery = encodeURIComponent(input);
    var queryURL = util.format(URL, encodedQuery);

    window.links = {
        wolfram: "http://www.wolframalpha.com/input/?i=" + encodedQuery
    };

    // in this try block, we try mathjs
    try {
        if (window.options.mathjs === true) {
            result = math.eval(input);
            if (math.typeof(result) === "Function") {
                throw(new Error("Math.js is sending us a function again..."));
            } else {
                result = result.toString();
            }
        } else if (window.options.mathjs === false) {
            throw(new Error("Math.js has been disabled by the user."))
        }

        $("#output").html(result);
        $(".interpret, #wolfram-credit").css("display", "none");
        backdoor.resizeWindow();

        // speak result if speech is on
        if(window.options.speech === true) {
            backdoor.speak($('#output').text())
        }
    } catch (e) {
        // if input isn't math throw error and use wolfram code
        window.log("Input is not math. Using Wolfram|Alpha. If you'd like, the error message given by MathJS is as follows:\n" + e);
        var encodedQuery = encodeURIComponent(input);
        var queryURL = util.format(URL, encodedQuery);

        window.links = {
            // google: "https://www.google.ca/#q=" + encodedQuery,
            wolfram: "http://www.wolframalpha.com/input/?i=" + encodedQuery
        };

        // loader
        loader(true);

        wolfram.query(input, function(err, queryResult) {
            try {
                window.json = queryResult;

                var inputInterpretation = backdoor.unicodeRegex(window.json.shift().subpods[0].text)[0];
                
                $(".interpret, #wolfram-credit").css("display", "block");
                $("#wolframlink").attr("onclick", "Shell.openExternal(\"" + window.links.wolfram + "\");");
                $("#queryInterpretation").html(inputInterpretation);

                var output = "";

                // look through each pod
                for (i = 0; i !== window.json.length; i++) {
                    // title each pod
                    output += "<h3>" + window.json[i].title + "</h3>"

                    // look through the subpods of each pod
                    for (j = 0; j !== window.json[i].subpods.length; j++) {
                        // add each subpod
                        // sidenote: the onmouseover thing is a hacky solution
                        //           that tells the copy plaintext function what 
                        //           subpod's text to copy based on what you're hovering over

                        output += "<img onmouseover='window.imgHover = [" + i + "," + j + "]' alt=\"" + window.json[i].subpods[j].text + "\" class=\"image-output\" src=\"" + window.json[i].subpods[j].image + "\">";

                        // if the for loop hasn't reached it's last subpod, 
                        // remember to put in a line break because the images would just be on one line

                        if (j !== window.json[i].subpods.length - 1) {
                            output += "<br>";
                        }
                    }
                }

                // set the output to inline block because whenever the error shows up it switches to block
                // hacky solutions!!! yay!
                $(".output").css("display", "inline-block");
                $("#output").html(output)

                // when all images are loaded, remember to resize the window and turn off the loader
                $("#output").imagesLoaded(function() {
                    window.log("Images are ready, resizing window.");
                    loader(false);
                    backdoor.resizeWindow();
                });
            } catch (e) {
                window.log(e.toString())

                // try again if error
                retry(input)
            }

            if (err) {
                window.log(err.toString())

                // try again
                retry(input);
            }
        });

        window.log('Queried with: ' + queryURL);
    }
}