I am currently fighting with a javascript problem where I have a 62bit bitmask that should be used as filter.
I used the snippet from here but I cant get it to work for some cases.
How to do bitwise AND in javascript on variables that are longer than 32 bit?
function testBitmask(fd, filterMask){
var a = fd;
var b = filterMask;
var w = 4294967296; // 2^32
var aHI = a / w;
var aLO = a % w;
var bHI = b / w;
var bLO = b % w;
var aAll = (aHI & bHI) * w;
var bAll = (aLO & bLO);
var retVal = (aAll + bAll) == filterMask;
console.log("retVal:",retVal)
return retVal;
}
I dont understand why testBitmask(2147483648,2147483648) returns false, thats for 2^31. 2^32 => true. 2^33 => true.
bAll gets negative here so I assume an overflow of the 32bit int, ideas?
If in javascript all numbers are 64 bit floating point and there are no 64 bit integers, you can't expect to define a and b (or fd and filtermask) with that precision, without rounding errors.
Try to define an object which encapsulates the 64bit integer type.
As an example you can look at the js-ctype implementation made by Mozilla MDN:
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Int64
and in particular
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Working_with_data#64-bit_integers
Theirs Int64 and UInt64 objects don't provide any methods for performing arithmetic, but you can pull out the high and low 32-bit portions and do math on them, then join them back together.
A simple code example, using typed arrays instead:
bitMask = function(high = 0x0,low = 0x0) {
this.bm = new Uint32Array(2);
if (arguments.length === 0 ) {
this.bm[0] = 0x0;
this.bm[1] = 0x0;
} else if (arguments.length === 2 && typeof arguments[0] === "number" && typeof arguments[1] === "number") {
this.bm[0] = arguments[1];
this.bm[1] = arguments[0];
}
this.bwAND = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] & filter.bm[0];
result.bm[1] = this.bm[1] & filter.bm[1];
return result;
}
this.bwOR = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] | filter.bm[0];
result.bm[1] = this.bm[1] | filter.bm[1];
return result;
}
this.bwXOR = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] ^ filter.bm[0];
result.bm[1] = this.bm[1] ^ filter.bm[1];
return result;
}
this.bwNOT = function() {
result = new bitMask();
result.bm[0] = ~this.bm[0];
result.bm[1] = ~this.bm[1];
return result;
}
this.bwEQUALS = function(b){
return (this.bm[0] == b.bm[0]) && (this.bm[1] == b.bm[1]);
}
this.toString = function() {
var zeroes = "00000000000000000000000000000000";
var strH = this.bm[1].toString(2);
var zerH = zeroes.substr(0,32-strH.length);
var strL = this.bm[0].toString(2);
var zerL = zeroes.substr(0,32-strL.length);
return zerH + strH + zerL + strL;
}
}
You can use it like this:
var a = new bitMask(0x0FEDCBA9,0xFF00FF00);
var b = new bitMask(0x12345678,0x0000FFFF);
var c = b.bwAND(a);
var d = b.bwOR(a);
var e = b.bwXOR(a);
var f = b.bwNOT();
var g = b.bwEQUALS(a);
Results:
a = 0000111111101101110010111010100111111111000000001111111100000000
b = 0001001000110100010101100111100000000000000000001111111111111111
a & b = 0000001000100100010000100010100000000000000000001111111100000000
a | b = 0001111111111101110111111111100111111111000000001111111111111111
a ^ b = 0001110111011001100111011101000111111111000000000000000011111111
~b = 1110110111001011101010011000011111111111111111110000000000000000
(a == b)? = false
I try using javascript but the addition is not correct, live code here
function hitung2() {
var a = $(".a2").val();
var b = $(".b2").val();
c = a * b; //a kali b
d = c + a;
$(".c2").val(c);
$(".d2").val(d);
}
function hitung2() {
var a = parseInt($(".a2").val());
var b = parseInt($(".b2").val());
c = a * b; //a kali b
d = c + a;
$(".c2").val(c);
$(".d2").val(d);
}
Or if you going to work with fractions then use parseFloat() function in same way as it described above.
You need to change the string that you get from .val to ints with parseInt()
var a = parseInt($(".a2").val());
var b = parseInt($(".b2").val());
Updated fiddle. http://jsfiddle.net/b39Lz/32/
use parseInt()
var a = $(".a2").val();
var b = $(".b2").val();
temp1=parseInt(a);
temp2=parseInt(b);
c = temp1 * temp2;
d = c + temp1;
Your variables are String, so it uses String + operator, does concatenating the value. Convert string to int using: parseInt("10")
function hitung2() {
var a = $(".a2").val();
var b = $(".b2").val();
c = a * b; //a kali b
d = parseInt(c) + parseInt(a);
$(".c2").val(c);
$(".d2").val(d);
}
Avoid using parseInt() if you dont want to stick to integer calculations only.Try casting to general Number.
function hitung2() {
var a =Number( $(".a2").val());
var b = Number($(".b2").val());
var c = a * b; //a kali b
d =Number(c)+Number(a);
$(".c2").val(c);
$(".d2").val(d);
}
I have the following code in jS :
function stripHTMLWithLinks(c) {
var BodyContents = /([\s\S]*\<body[^\>]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i ;
var h = c.match(BodyContents);
if (h != null && h[2]) {
c = h[2];
}
c = c.replace(/<a\s.*?href\s*=\s*"(.*?)".*?>(.*?)<\/a>/gi, "$2 [$1]");
c = c.replace(/<a\s.*?href\s*=\s*'(.*?)'.*?>(.*?)<\/a>/gi, "$2 [$1]");
c = c.replace(/\/\/--\>/gi, "");
c = c.replace(/(\n)/gi,"");
c = c.replace(/(\r)/gi,"");
c = c.replace(/<title[^\>]*\>[\s\S]*\<\/title\>/gi,"");
c = c.replace(/<br\s*\/\s*>/gi,"\n");
c = c.replace(/(<\/h.>|<\/p>|<\/div>)/gi, "$1\n\n");
c = c.replace(/<[^>]+>/g,"");
c = c.replace(/</g,"<");
c = c.replace(/>/g,">");
c = c.replace(/ /g," ");
return c;
}
I need a function that will extract the body content. All the examples that I saw here were kinda fixed on a particular example , and i need it on dynamic basis. This function can do it for me, I just need it in php.
This should be really easy to transcode to PHP.
Look for preg_match and preg_replace in the PHP Manual.
Try strip_tags.
$html = "<body><a href='http://example.com'>Something</a> <b>big</b> is coming</body>";
echo strip_tags($html); // Something big is coming
$(function() {
var getName = $('#fa_welcome').text();
var myName = getName.replace('Welcome ',"");
var a = $('#recent_topics').find('a[href*="/u"]').filter(':contains("'+myName+'")').length;
var b = $('#recent_topics').find('a[href*="/u"]').length;
var c = a-b;
if(c <= 1) {
$('.topics_name').append('<div title="'+c+' New Post" id="newTops">'+c+'</div>');
}
});
Just for randomness I will give you the lengths of var a and b
a= 15
b= 25
I want to subtract these two as in var c
15-25
Though I get -25 parsed?
Any suggestions
Try with parseInt like
var a = parseInt($('#recent_topics').find('a[href*="/u"]').filter(':contains("'+myName+'")').length);
var b = parseInt($('#recent_topics').find('a[href*="/u"]').length);
If you get these values then, use parseInt to convert it in integer,
var c = parseInt(a)-parseInt(b);
use parseFloat for getting result
$(function() {
var getName = $('#fa_welcome').text();
var myName = getName.replace('Welcome ',"");
var a = parseFloat($('#recent_topics').find('a[href*="/u"]').filter(':contains("'+myName+'")').length);
var b = parseFloat($('#recent_topics').find('a[href*="/u"]').length);
var c = a-b;
if(c <= 1) {
$('.topics_name').append('<div title="'+c+' New Post" id="newTops">'+c+'</div>');
}
});
I want to write a function which will allow me to "solve" an equation in js.
what I want (not in a programming language):
function f(x) { 1 + x * x }
var z = 2
var y = f(z) //y will be 5 as a number
what I have written in JS:
function P(cfg) { ....
this.equation = "1 + x";
....};
P.prototype.eqn = function(x) {
var tmp = eval(this.equation);
return tmp;
};
....
P.prototype.draw = function() {....
for(var i = 0; i < z; i++)
ctx.lineTo(i, this.eqn(i));
....};
also I've read that using eval in a loop is probably not a good idea, but I have not figured out another way (yet) (JS beginner)...
The problem with this code is, that at least in FF the var tmp will STILL contain the string from this.equation instead of the calculated value.
I would appreciate any further insight very much!
Thank you for your time :)
EDIT: because my question was not formulated very well:
after the execution of line
var tmp = eval(this.equation);
the var tmp will hold a STRING which equals the string this.equation, instead of the desired solution y value.
Also I do not mean solve but evaluate, thanks for that tip :)
Based on your example, I'd say that you want to "evaluate an expression", rather than "solve an equation". For evaluating an expression, you can probably find many tutorials. I'll break it down in brief though. You need to do a few steps.
Starting with your string "1 + x * x", you need to break it into tokens. Specifically, break it down into: "1", "+", "x", "*", "x". At this point, you can substitute your variables ("x") for their literal values ("2"), giving you "1", "+", "2", "*", "2"
Now you need to parse the expression. Based on order of operations PEMDAS you need to create a tree data structure, where parenthetical clauses (stuff surrounded by parenthesis) are executed first, multiplication and division next, and then additions and subtraction last. Parsing is often not an easy task, and you may want to put together a simpler BNF grammar (though you can probably find a grammar for simple math expressions with some googling).
Next, walk the tree, depth first, evaluating the operations as you go up the tree. Once you get to the top of the tree, you have your solution.
If instead you want to "solve an equation", you're going to need something much more sophisticated, like Sage
I have used this expression evaluator before. It seemed to work very well. It allows you to pass expressions into a Parser that returns a function object that can then evaluate inputs.
var expr = Parser.parse("2 ^ x");
expr.evaluate({ x: 3 }); // 8
It supports trig functions (sin, cos, ect...) and other handy built in functions such as abs & ciel.
var expr = Parser.parse("sin(x/2) + cos(x/2)")
expr.evaluate({x: Math.PI / 2}); // 1
Examples: http://silentmatt.com/javascript-expression-evaluator/
Code: https://github.com/silentmatt/js-expression-eval
Note that this lib does not use eval().
Not sure I entirely understand your question but how about:
var makeFunctionOfX = function(src) {
return Function('x', 'return ' + src);
};
Then you can say things like:
var g = makeFunctionOfX('2 * x')
var y = g(3); // y contains 6
The great advantage of this over eval is that the Function we create has no magic ability to see variables in the scope (hence the need to explicitly pass it x as a parameter name).
Using eval is safe if you trust the input from the user, and works just fine. (I have no idea what you mean by "the var tmp will still have the string this.equation".)
function FuncCreator(eqn){ this.eqn = eqn }
FuncCreator.prototype.run = function(x,y,z){ return eval(this.eqn) }
var add1 = new FuncCreator('1+x');
var result = add1.run(41); // 42
var complex = new FuncCreator('Math.sin(x*y) / Math.cos(z)');
var result = complex.run(3,4,5); // -1.891591285331882
If you don't trust the user input, you'll need to actually parse the input and process it yourself. This is non-trivial.
You can use the expression parser from the math.js library and do something like this:
var parser = math.parser();
var f = parser.eval('function f(x) = 1 + x * x');
// use the created function f in expressions:
parser.eval('z = 2'); // 2
parser.eval('y = f(z)'); // 5
// or use the created function f in JavaScript:
var z = 2; // 2
var y = f(z); // 5
Creating functions in math.js is quite currently limited, loops and blocks needed to define more extensive functions are not yet supported.
This is an old thread, but I wrote this equation calculator, this doesn't solve algebraic equations though. There is however a function that will allow you to provide an array containing assigned variables. But this doesn't solve for variables that don't have an assigned value.
I probably haven't permuted every test case scenario, but it seems to work pretty decent.
Edit: This would have to be modified to handle negative numbers. Other than that... works fine.
Here is a fiddle
<!doctype html>
<html>
<head>
<title>Javascript Equation Calculator</title>
</head>
<body>
<input type="button" onclick="main()" value="calculate"><br>
<input type="text" id="userinput"><br>
<span id="result">Ready.</span><br>
<script>
function Calculator(){}
String.prototype.replaceLast = function (what, replacement)
{
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
function inS(substr, str){return (str.indexOf(substr) > -1);}
function arrayValueOrToken(arr, key, token)
{
if(key in arr)
{
return arr[key];
}
return token;
}
function reduceEquation(inputStr)
{
console.log("reduceEquation Executed-----");
while(hasNest(inputStr))
{
if(hasNest(inputStr))
{
inputStr = inputStr.replace(")(",')*(');
for(var i=0;i<=9;i++)
{
inputStr = inputStr.replace(i+"(",i+'*(');
inputStr = inputStr.replace(")"+i,')*'+i);
}
var s = inputStr.lastIndexOf("(");
var e = 0;
for(i=s;i,inputStr.length;i++){if(inputStr[i]==")"){e=i+1;break;}}
var eq = inputStr.substring(s,e);
var replace = eq;
eq = eq.replace(/[()]/g, '');
var substitution = solveEquation(eq);
inputStr = inputStr.replaceLast(replace,substitution);
}
}
return inputStr;
}
function solveEquation(eq)
{
console.log("solveEquation Executed-----");
eq = doFirstOrder(eq);
eq = doLastOrder(eq);
return eq;
}
function doFirstOrder(eq)
{
console.log("doFirstOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="*"){eq = solve(eq,"*");return doFirstOrder(eq);}
if(eq[i]=='/'){eq = solve(eq,'/');return doFirstOrder(eq);}
}
return eq;
}
function doLastOrder(eq)
{
console.log("doLastOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="+"){eq = solve(eq,"+");return doLastOrder(eq);}
if(eq[i]=="-"){eq = solve(eq,"-");return doLastOrder(eq);}
}
return eq;
}
function solve(eq, operator)
{
var setOp = operator;
console.log("solve Executed-----");
var buildEq = "",var1 = true,done = false,char="";
var operators = "+-/*";
var ops = operators.replace(operator, '').split('');
var a=ops[0];
var b=ops[1];
var c=ops[2];
for(var i=0;i<eq.length;i++)
{
char = eq[i];
switch(true)
{
case(char==operator):if(var1===true){var1 = false;}else{done = true;}break;
case(char==a):
case(char==b):
case(char==c):if(var1){char = ""; buildEq = "";}else{done = true;}
}
if(done){break;}
buildEq = buildEq + char;
}
var parts = parts = buildEq.split(operator);
var solution = null;
if(operator=="+"){solution = parseFloat(parts[0]) + parseFloat(parts[1]);}
if(operator=="-"){solution = parseFloat(parts[0]) - parseFloat(parts[1]);}
if(operator=="*"){solution = parseFloat(parts[0]) * parseFloat(parts[1]);}
if(operator=="/"){solution = parseFloat(parts[0]) / parseFloat(parts[1]);}
return eq.replace(buildEq, solution);
}
function hasNest(inputStr){return inS("(",inputStr);}
function allNestsComplete(inputStr)
{
var oC = 0, cC = 0,char="";
for(var i=0;i<inputStr.length;i++){char = inputStr[i];if(char=="("){oC+=1;}if(char==")"){cC+=1;}}
return (oC==cC);
}
Calculator.prototype.calc = function(inputStr)
{
console.log("Calc Executed-----");
inputStr = inputStr.replace(/ /g, "");
inputStr = inputStr.replace(/\\/g, '/');
inputStr = inputStr.replace(/x/g, "*")
inputStr = inputStr.replace(/X/g, "*")
if(!allNestsComplete(inputStr)){return "Nested operations not opened/closed properly.";}
inputStr=reduceEquation(inputStr);
inputStr = solveEquation(inputStr);
return inputStr;
};
Calculator.prototype.calcWithVars = function(inputList)
{
if(inputList.length < 2){return "One or more missing arguments!";}
var vars = [];
var assocVars = [];
var lastVarIndex = inputList.length - 2;
var i = 0;
var inputStr = inputList[inputList.length-1];
for(i=0;i<=lastVarIndex;i++)
{
vars.push(inputList[i].replace(/ /g, ""));
}
for(i=0;i<=vars.length-1;i++)
{
var vParts = vars[i].split("=");
var vName = vParts[0];
var vValue = vParts[1];
assocVars[vName] = vValue;
}
inputStr = inputStr.replace(/ /g, "");
var eqVars = inputStr.replace(/\s+/g, ' ').replace(/[^a-zA-Z-]/g, ' ').replace(/\s\s+/g, ' ');
if(inS(" ", eqVars))
{
eqVars = eqVars.split(" ");
}
else{eqVars = [eqVars];}
eqVars.sort(function(a, b){return a.length - a.length;});
var tempTokens = [];
var tempCount = 1;
for(i=0;i<eqVars.length;i++)
{
var eqVname = eqVars[i];
var substitution = arrayValueOrToken(assocVars, eqVname, "<unknown>");
if(substitution != "<unknown>")
{
inputStr = inputStr.replace(eqVname,substitution);
}
else
{
var tempToken = "#______#"+tempCount+"#______#";
tempCount++;
tempTokens.push(tempToken + "?" + eqVname);
inputStr = inputStr.replace(eqVname,tempToken);
}
}
for(i=0;i<tempTokens.length;i++)
{
var tokenSet = tempTokens[i];
var tokenParts = tokenSet.split("?");
var token = tokenParts[0];
var variableName = tokenParts[1];
inputStr = inputStr.replace(token,variableName);
}
var answerName = "<unknown>";
var eq = inputStr;
if(inS("=", inputStr))
{
var eqParts = inputStr.split("=");
answerName = eqParts[0];
eq = eqParts[1];
}
eq = this.calc(eq);
var result = [];
for(i=0;i<eqVars.length;i++)
{
var v = arrayValueOrToken(assocVars, eqVars[i], "<unknown>");
if(v != "<unknown>")
{
result.push(assocVars[eqVars[i]]);
}
}
result.push(eq);
return result;
};
function main()
{
var calculator = new Calculator();
elUserInput = document.getElementById('userinput');
console.log("input: "+ elUserInput.value);
elResult = document.getElementById('result');
equation = elUserInput.value;
result = calculator.calc(equation);
console.log("result: "+ result);
elResult.innerHTML = result;
}
</script>
</body>
</html>