Such a low success rate with this script - javascript

The script itself works fine and all; it is errorless. However, out of running 7,500 times, only 35 were successful. How would I improve the success rate of Regex? Because right now, it is not doing the job.
var IDs = [136758649, 116770724, 136171998]//A lot more IDS than this
var PriceWanting = 60
var scanneditems = 0
var itemerror = 0
document.write('<p id = "title">Total number bought: 0 items for a total of 0</p>')
document.write('<p id = "scanned">Items scanned: 0</p>')
document.write('<p id = "itemerrors">Items scanned: 0</p>')
var buys = 0
var totalrobuxspent = 0
console.log("Bot started")
var loop = setInterval(function()
{
for (var i = 0;i<IDs.length;i++) {
$.get(" http://m.roblox.com/items/" + IDs[i] + "/privatesales",function(data) {
var Regex = /\<span class="currency-robux">([\d,]+)\<\/span\>/;
var PriceSelling = data.match(Regex);
scanneditems = scanneditems + 1
document.getElementById("scanned").innerHTML = "Scanned items: " + scanneditems
PriceSelling = PriceSelling ? PriceSelling[1] : '';
if (PriceSelling.length < 1) {
itemerrors = itemerrors + 1
document.getElementById(''itemserror'').innerHTML = ''Total errors: '' + itemerrors
return
}
PriceSelling = Number(PriceSelling.replace(",",""))
PriceSelling = PriceSelling * 1
totalrobuxspent = totalrobuxspent + PriceSelling
var remaining = PriceWanting - PriceSelling
if (remaining >= -0.1)
{
buys = buys + 1
document.getElementById("title").innerHTML = "Total number of items bought: " + buys + " for a total of " + totalrobuxspent + " "
var Regex2 = /<a href="\/Catalog\/VerifyTransfer\DuserAssetOptionId=([\d,]+)\Damp;expectedPrice=([\d,]+)">/
var HatBuyId = data.match(Regex2)[1]
var HatBuyLink = "http://m.roblox.com/Catalog/VerifyPurchase?assetid=" + HatBuyId + " &type=robux&expectedPrice=" + PriceSelling
var Explorer = document.createElement('iframe');
function Buy(){
Explorer.contentDocument.forms[0].submit();
console.log("Item purchase complete, scanning again.")
var inf = document.createElement('div');
inf.style.fontSize = "18px";
inf.style.background = "rgba(0,0,5,0)";
inf.style.position = "absolute";
inf.style.width = "100%";
inf.style.height = "18pt";
inf.innerText = "Bot currently running. Purchases: "+answer;
document.body.appendChild(inf);
};
Explorer.onload = Buy;
Explorer.width = "100%";
Explorer.height = "85%";
Explorer.src = HatBuyLink;
document.body.innerHTML = "";
document.body.appendChild(Explorer);
}
})
}
},500)

.get is asynchronous. This means that the callback function is not executed until the response is returned. By that point, you are no longer in a loop and in fact the loop has already completed.
Though it's about a slightly different problem, this Question is a very good read to understand how asynchronous calls work.
In addition, continue here would still be illegal, even without the asynchronous behavior, because the function has its own context and is not in the same context as the loop. This simple example would also be illegal and may be easier to understand the context issue:
for(var i=0; i<10; i++){
someFunc();
}
function someFunc(){
continue; // illegal
}
Though in your case the function is an anonymous function, the same concept applies.

Please, use semicolons in your code.
continue;
is applicable in loops, not in functions. Use the
return;
keyword to get out of the context of a function.

Related

Javascript in photoshop - Trying to understand a script found here to customize it - Layer hide/display

I'm trying to modify a script I found here so it would randomly display 1 layer per group in some but not all of the groups, with some condition. I have roughly 1hr into Javascript and do not understand 1 thing in the script I found before delving deeper in the modification. Operator for means it'll execute the code multiple times, in this case once for each group of layer. The function Save() is called within this "for" operator.
At the same time, the Visible() function is called multiple time already, once for each pattern you asked for in the initial prompt.
function Visible() {
var Grps = app.activeDocument.layerSets; // loops through all groups
for(var i = 0; i < Grps.length; i++){
var tmp = app.activeDocument.layerSets[i].layers.length;
app.activeDocument.layerSets[i].visible=true;
var groupChildArr = app.activeDocument.layerSets[i].layers;
var randLays = Math.floor(Math.random() * tmp);
groupChildArr[randLays].visible = true;
Save();
}
Revert();
}
function Save() {
var outFolder = app.activeDocument; // psd name
var outPath = outFolder.path;
var fName = "PNG"; // define folder name
var f = new Folder(outPath + "/" + fName);
if ( ! f.exists ) {
f.create()
}
var saveFile = new File(outPath + "/" + fName +"/" + "Pattern_" + num + ".png");
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.interlaced = false;
app.activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function Revert(){
var idRvrt = charIDToTypeID( "Rvrt" );
executeAction( idRvrt, undefined, DialogModes.NO );
}
var count = prompt("How many patterns you want","");
for (var x=0 ; x<count;x++){
var num = x+1;
Visible();
}
From my basic understanding, it means that the file will be saved and overwritten for each new group of layer found and used in the Visible() function? Therefor, if I have 5 group of layers, it'll be saved 5 time before the final version of the image is completed and should instead be moved outside of the "for" operator, if I understood correctly. Would it be better if instead written this way?
function Visible() {
var Grps = app.activeDocument.layerSets; // loops through all groups
for(var i = 0; i < Grps.length; i++){
var tmp = app.activeDocument.layerSets[i].layers.length;
app.activeDocument.layerSets[i].visible=true;
var groupChildArr = app.activeDocument.layerSets[i].layers;
var randLays = Math.floor(Math.random() * tmp);
groupChildArr[randLays].visible = true;
}
Save();
Revert();
}

2D Battleship game demo. Suggestions and logic corrections welcome

I am a novice programmer. I used a Random number generator to place ships. Placing ships needs few tweaks. Will use loops to make use of all the available space and also incorporate vertical placement.
Please review my code below and suggests any tweaks or logic corrections.
Thank you.
var rn = 0;
var bx = by = cx = cy = 0;
var guess;
var guesses
var fsunk;
var bhit;
var c1hit;
var userchoices = [];
var battleship = []; //ship position stored in array
var cruiser1 = [];
var sunk = []; //ship status array 0 = floating, 1 = sunk
//var cruiser2 = [];
//var destroyer1 = [];
//var destroyer2 = [];
//var destroyer3 = [];
//var submarine1 = [];
//var submarine2 = [];
//var submarine3 = [];
//var submarine4 = [];
function rng() //Generates Random Numbers
{
rn = Math.floor(Math.random() * 5);
console.log("rn = " + rn);
return rn;
}
function spawn() //uses rng() to get x and y coordinates
{
bx = rng();
by = rng();
cx = rng();
cy = rng();
position();
}
function position() // ship positon generated
{
battleship[0] = ("" + bx + by);
battleship[1] = ("" + bx + (by + 1));
battleship[2] = ("" + bx + (by + 2));
battleship[3] = ("" + bx + (by + 3));
cruiser1[0] = ("" + cx + cy);
cruiser1[1] = ("" + cx + (cy + 1));
cruiser1[2] = ("" + cx + (cy +2));
}
function play() // onclick function
{
console.log("game start");
sunk[0] = 0; //battleship status flag
sunk[1] = 0; //cruiser1 status flag
bhit = 0; //battleship hit counter set to zero
c1hit = 0; //cruiser hit counter set to zero
console.log("sunk array = " + sunk[0] + " " + sunk[1]);
fsunk = 0; //fleet status
spawn();
position();
console.log("battleship coordinates" + battleship);
console.log("cruiser coordinates" + cruiser1);
game();
}
function game()
{
while(fsunk == 0)
{
if(sunk[0] && sunk[1] == 1) //check if fleet is sunk
{
alert("enemy fleet sunk");
fsunk = 1;
}
else
{
userinput(); //calls function to get users input
if(battleship.includes(guess)) //checks if users guess is in battleship array
{
console.log("game.if") //just to see which clause is executing
bhit++; //no of hits on battleship incremented
if(bhit == 4)
{
sunk[0] = 1; //battleship status set to sunk
console.log("battleship sunk");
}
}
else if (cruiser1.includes(guess))
{
console.log("game.elseif")
c1hit++; //no of hits in cruiser1 incemented
if(c1hit == 3)
{
sunk[1] = 1; //cruiser1 status set to sunk
console.log("cruiser1 sunk");
}
}
}
}
}
function userinput()
{
guess = prompt("Enter the grid coordinates. Do not use space. X-coordinates
0-6, Y-coordinates 0-6.");
console.log("users input = " + guess);
while(guess < 0 || guess > 66 || userchoices.includes(guess)) //checks user input for repeated strikes or out of range. Suggest better way if possible. this is just bad code
{
alert("You have entered an invalid coordinate.");
guess = prompt("Try Again!");
}
guesses++; //increments no of guessess
userchoices.push(guess); //add users guess to array
return guess;
}
I have added comments to better explain each line of code. But feel free to ask for any explanations and do correct my logic wherever required.
Thank you
Edit: I am currently working on incorporating more ships and vertical positioning. I am aware that requires major changes to spawn() and position(). I am also extending the board to the standard 10 X 10 grid and that also makes validating users input way easier.

Change innertext of element dynamically inside for loop of a function

Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.
The increment function is called when an onchange event happens after sending a number as a input to the input element.
JAVASCRIPT :
function increment() {
var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
var stat = document.createElement("p");
stat.id = "current_status";
stat.innerText = "";
document.body.appendChild(stat);
stat.style.display = "block";
for (g = 1; g < count; g++) {
stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
}
}
The DOM doesn't redraw until the executing thread is free. You need to introduce async delays to your code to see a progressive update.
function increment() {
var count = document.getElementById('ac_count').value;
var stat = document.createElement("p");
stat.id = "current_status";
document.body.appendChild(stat);
var g = 1
var itvl = setInterval(function() {
update(g);
g += Math.floor(Math.random() * 20) + 1
if (g >= count) {
clearInterval(itvl);
update(count);
}
}, 10)
function update(g) {
stat.textContent = g + " out of " + count + " records have been processed";
}
}
<input type=number value=10000 id=ac_count>
<button onclick="increment()">CLICK ME</button>
I'm not suggesting that this is a good solution, but this should achieve the effect you're looking for
function increment() {
var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
var stat = document.createElement("p");
stat.id = "current_status";
stat.innerText = "";
document.body.appendChild(stat);
stat.style.display = "block";
updateInnerText(0, count);
}
function updateInnerText(number, max){
if(number < max){
stat.innerText = Number(number + 1) + " out of " + count + " records have been processed";
setTimeout(function(){
updateInnerText(number+1, max);
}, 500);
}
}

Javascript clientHeight returns NaN in certain contexts

Interesting issue arising for me.
I am working on an infinite scroll thing in javascript that requires getting clientHeight of a div at some point:
here is the code:
document.addEventListener('DOMContentLoaded', init, false);
function init(){
var j = 0;
var inner1 = document.getElementById("innerDiv1");
inner1.addEventListener("scroll", function(event){ window.j = 2; checkForLoad();});
var inner2 = document.getElementById("innerDiv2");
inner2.addEventListener("scroll", function(event){ window.j = 1; checkForLoad();});
}
var i = 0;
var checkForLoad = function() {
var bottomDiv;
var bottomDivChild;
var offsetOfDiv;
var offsetOfPage;
if(window.j === 2){
bottomDiv = document.getElementById("innerDiv1");
bottomDivChild = bottomDiv.lastElementChild;
offsetOfDiv = bottomDivChild.offsetTop + bottomDivChild.clientHeight; //WORKS FINE
offsetOfPage = (document.getElementById("innerDiv1").pageYOffset) + (document.getElementById("innerDiv1").clientHeight); //THIS IS WHERE THE ISSUE IS
}
else if(window.j === 1){
bottomDiv = document.querySelector("innerDiv2 > div:last-child");
offsetOfDiv = bottomDiv.offsetTop + bottomDiv.clientHeight;
offsetOfPage = inner1.pageYOffset + inner1.innerHeight;
}
if(offsetOfPage > offsetOfDiv - 10) {
alert("time to add");
//eventually will be AJAX with XSL
if (i % 5 !== 0) {
i++;
alert("into the append part");
var newResults = document.createElement("div");
newDiv.innerHtml = "testing " + i;
if(window.j === 2){
document.getElementById("innerDiv1").appendChild(newResults);
}
else if(window.j === 1){
document.getElementById("innerDiv2").appendChild(newResults);
}
checkForLoad();
} else if (i%5 === 0) {
newDiv = document.createElement("div");
newDiv.innerHTML = "Show more Results! " + i;
document.getElementById("scrollingDiv").appendChild(newDiv);
newDiv.setAttribute("ID", "showResults");
newDiv.setAttribute("onClick", "showMore()");
}
}
};
I realize that there are some inconsistencies here, but they are in parts of the script i am not using. Here is the issue though, in the if(window.j === 2) statement, you can see that I use client height in a couple places. In the first one, it returns a number perfectly and life goes on as planned, but when I use it in the line where I get the "offSerOfPage", the sum becomes NaN. I am using firebug to debug it and when I add document.getElementById("innerDiv1").clientHeight to the watch list, it shows that it has a number attatched to it. Yet the sum is returned as NaN. I think my wording is a bit confusing here so if you need clarification, please ask! Thanks!

Javascript Regex optimization

I have two JQuery/Javascript functions that highlights all string occurences in a web page, and then narrows these occurences one by one when clicking on the next/prev buttons.
Here is the current JS code for the next and previous buttons:
var outputHtmlContent;
var posScroll = 0;
// Trigger on search next occurence's button
$('#nextSearchOutputButton').on("click", function (e) {
e.preventDefault();
var searchString = "Command Name";
$("body").highlight(searchString);
$(".highlight").css({ backgroundColor: "#E0FFFF" });
var regex = /Command Name/g, result, indices = [];
var i = 0;
outputHtmlContent = $("#output").html();
if (posScroll == outputHtmlContent.match(/Command Name/g).length - 1) posScroll = 0;
else
posScroll++;
while ((result = regex.exec(outputHtmlContent))) {
if (posScroll == i) {
var index = result.index;
outputHtmlContent = outputHtmlContent.substring(0, index) + "<span class='highlight'>" + outputHtmlContent.substring(index, index + searchString.length) + "</span>" + outputHtmlContent.substring(index + searchString.length);
$("#output").html(outputHtmlContent);
document.getElementById("commandNumber" + posScroll).scrollIntoView();
return;
}
i++;
}
})
// Trigger on search previous occurence's button
$('#prevSearchOutputButton').on("click", function (e) {
e.preventDefault();
var searchString = "Command Name";
$("body").highlight(searchString);
$(".highlight").css({ backgroundColor: "#E0FFFF" });
var regex = /Command Name/g, result, indices = [];
var i = 0;
outputHtmlContent = $("#output").html();
if (posScroll == 0) posScroll = outputHtmlContent.match(/Command Name/g).length - 1;
else
posScroll--;
while ((result = regex.exec(outputHtmlContent)) && i <= posScroll) {
if (posScroll == i) {
var index = result.index;
outputHtmlContent = outputHtmlContent.substring(0, index) + "<span class='highlight'>" + outputHtmlContent.substring(index, index + searchString.length) + "</span>" + outputHtmlContent.substring(index + searchString.length);
$("#output").html(outputHtmlContent);
document.getElementById("commandNumber" + posScroll).scrollIntoView();
return;
}
i++;
}
})
The two functions work well, but I have a very critical issue concerning the time spent when executing the two functions, this time estimated to 10 seconds for IE when moving from one occurence to an other and is estimated to 4 seconds for FF and chrome.
I googled and found that the Regex performance issue is a classic topic. I found this nice atricle http://infrequently.org/2007/02/regexs-are-slow/.
I would rather remove completely this feature than offering it with such a low quality issue. Yet, I want to stick on it because it is very helpful for my user. Can anyone help improve the Regex performance for my functions ?

Categories

Resources