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
Related
When I have been attempting to implement this function tf.train.stg(learningRate).minimize(loss)into my code in order to conduct back-propagation. I have been getting multiple errors such The f passed in variableGrads(f) must be a function. How would I implement the function above into the code bellow successfully? and Why does this error even occur?
Neural Network:
var X = tf.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
var Y = tf.tensor([[0,0,0],[0,0,0], [1,1,1]])
var m = X.shape[0]
var a0 = tf.zeros([1,3])
var y_hat = tf.zeros([1,3])
var parameters = {
"Wax": tf.randomUniform([1,3]),
"Waa": tf.randomUniform([3,3]),
"ba": tf.zeros([1,3]),
"Wya": tf.randomUniform([3,3]),
"by": tf.zeros([1,3])
}
function RNN_cell_Foward(xt, a_prev, parameters){
var Wax = parameters["Wax"]
var Waa = parameters["Waa"]
var ba = parameters["ba"]
var a_next = tf.sigmoid(tf.add(tf.add(tf.matMul(xt, Wax), tf.matMul(a_prev , Waa)),ba))
return a_next
}
function RNN_FowardProp(X, a0, parameters){
var T_x = X.shape[0]
var a_next = a0
var i = 1
var Wya = parameters["Wya"]
var by = parameters["by"]
var l = 1
for(; i <= T_x; i++){
var X_i = X.slice([i-1,0],[1,-1])
for(; l <= X.shape[1]; l++){
var xt = X_i.slice([0,l-1],[1,1])
var a_next = RNN_cell_Foward(xt, a_next, parameters)
}
var y_pred = tf.sigmoid((tf.add(tf.matMul(a_next, Wya), by)))
l = 1
if (i == 1){
var y_pred1 = y_pred
} else if (i == 2) {
var y_pred2 = y_pred
} else if (i == 3) {
var y_pred3 = y_pred
}
}
var y_predx = tf.concat([y_pred1, y_pred2, y_pred3])
return y_predx
}
const learningRate = 0.01;
var optimizer = tf.train.sgd(learningRate);
var model = RNN_FowardProp(X, a0, parameters)
var loss = tf.losses.meanSquaredError(Y, model)
for (let f = 0; f < 10; f++) {
optimizer.minimize(loss)
}
This is a neural network for sentiment classification which has a many to one structure.
The error says it all:
The f passed in variableGrads(f) must be a function
optimizer.minimize is expecting a function as parameter and not a tensor. Since the code is trying to minimize the meanSquaredError, the argument of minimize can be a function that computes the meanSquaredError between the predicted value and the expected one.
const loss = (pred, label) => pred.sub(label).square().mean();
for (let f = 0; f < 10; f++) {
optimizer.minimize(() => tf.losses.meanSquaredError(Y, model))
}
Does it solve the issue, not completely yet ? The error will change for something like:
variableGrads() expects at least one of the input variables to be trainable
What does it mean ? When the optimizer is used, it expects the function passed as argument to contains variables whose values will be updated to minimize the function output.
Here is the changes to be made:
var Y = tf.tensor([[0,0,0],[0,0,0], [1,1,1]]).variable() // a variable instead
// var loss = tf.losses.meanSquaredError(Y, model)
// computed below in the minimize function
const learningRate = 0.01;
var optimizer = tf.train.sgd(learningRate);
var model = RNN_FowardProp(X, a0, parameters);
const loss = (pred, label) => pred.sub(label).square().mean();
for (let f = 0; f < 10; f++) {
optimizer.minimize(() => tf.losses.meanSquaredError(Y, model))
}
I have very long code and want to simplify it. I don't think so we can use string concatination to create different variable name. Is there any other way.
If(Something){
var a = some.Test1.x;
var b = some.Test1.y;
var c = some.Test1.z;
var d = some.Test1.p;
}
If(SomethingElse){
var a = some.Test2.x;
var b = some.Test2.y;
var c = some.Test2.z;
var d = some.Test2.p;
}
If(OneMore){
var a = some.Test3.x;
var b = some.Test3.y;
var c = some.Test3.z;
var d = some.Test3.p;
}
May be create some function like this, i know this is not right but anything similar to that.
function test(s){
a = some.s.x;
b = some.s.y;
c = some.s.z;
d = some.s.p;
}
You can use array-like syntax
function test(s) {
var a,b,c,d;
if (s === Something) {
test = "Test1";
}
if (s === SomethingElse) {
test = "Test2";
}
if (s === OneMore) {
test = "Test3";
}
a = some[test].x;
b = some[test].y;
c = some[test].z;
d = some[test].p;
}
This is a much improved version of the functionally equivalent, but never-to-be-used, eval syntax:
eval("a = some."+test+".x");
function test(index){
t = some["Test" + index];
a = t.x;
b = t.y;
c = t.z;
d = t.p;
}
and the execution:
test(1); test(2); test(3)
I am trying to use crypto module of nodejs and added all required modules into my cloud folder and changed all require('..') methods as require('cloud/..) but getting error while deploying to cloud :
Update failed with Could not load triggers. The error was Error: Module cloud/stream.js is already being loaded
at _stream_readable.js:26:14
at stream.js:28:19
at crypto.js:40:14
at main.js:3:14
Because stream_readable.js requires stream.js and there is a circular dependency between stream.js and stream_readable.js.
Is there any solution or workaround for this circular dependencies?
As show in the Documentation
https://www.parse.com/docs/cloud_code_guide#modules
you need to use exports when using your own modules
var coolNames = ['Ralph', 'Skippy', 'Chip', 'Ned', 'Scooter'];
exports.isACoolName = function(name) {
return coolNames.indexOf(name) !== -1;
}
var name = require('cloud/name.js');
name.isACoolName('Fred'); // returns false
name.isACoolName('Skippy'); // returns true;
name.coolNames; // undefined.
I was stuck on this for a couple weeks as well. Turns out NodeJS isn't the best option (yet, anyways) for Parse Cloud Code signature signing/verification but I did find a solution.
According to Chris Stewart's response here, you can use the jsrsasign library instead.
Here's some cloud code of a working example:
Parse.Cloud.define("verifySignature", function(request, response) {
var KJUR = require('cloud/jsrsasign/npm/lib/jsrsasign.js');
var strPubKey = '-----BEGIN PUBLIC KEY-----(snip)';
// initialize
var pubKey = KJUR.KEYUTIL.getKey(strPubKey);
var data = request.params.data;
var signature = request.params.signature;
var verifier = new KJUR.Signature({"alg": "SHA1withRSA", "prov": "cryptojs/jsrsa"});
// initialize for signature validation
verifier.initVerifyByPublicKey(pubKey);
// update data
verifier.updateString(data);
// verify signature
if (verifier.verify(base64ToHex(signature))
response.success("Signature verified");
else
response.error("Signature could not be verified");
}
function base64ToHex(str) {
for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
var tmp = bin.charCodeAt(i).toString(16);
if (tmp.length === 1) tmp = "0" + tmp;
hex[hex.length] = tmp;
}
return hex.join(" ");
}
function atob(base64) {
var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var table = tableStr.split("");
if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
base64 = base64.replace(/=/g, "");
var n = base64.length & 3;
if (n === 1) throw new Error("String contains an invalid character");
for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
var a = tableStr.indexOf(base64[j++] || "A"), b = tableStr.indexOf(base64[j++] || "A");
var c = tableStr.indexOf(base64[j++] || "A"), d = tableStr.indexOf(base64[j++] || "A");
if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
bin[bin.length] = ((c << 6) | d) & 255;
};
return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
}
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>
Javascript:
var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d {1,2})? )% $ != null;
var str = value.match(/\/\/%//g);
if(converted==NaN){
alert('Input was not a number');
}
else if(converted != null) {
var fracToDecimal = eval (value);
alert(fracToDecimal);
}
else if(converted = str) {
var percToDecimal = value/100;
alert(percToDecimal);
} }
So you have a string like: 50%? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
If you use parseFloat, it will read the string up until the first non-number character (the %)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN, and convert it.
if(!isNaN(y)){
y /= 100; // .201
}
Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).
UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
http://jsfiddle.net/TrCYX/1/
I'm very late, but keeping it as itself if it is a decimal goes like this
let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
if (!Number.isNaN(parsed[i])) {
let newval = parseFloat(percent[i]) / 100;
//return newval;
newarr.push(newval)
} else {
return 0;
}
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))