I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow. What am i doing wrong here?
searchPages is an array of 54 numbers corresponding to a URL value for a search page.
casper.each(searchPages,function(casper,index){
loadSearch(casper,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Still doesn't exist...retry");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out.");
},20000);
});
}
And it adds about 3GB per loop.
Well turns out this is a very well-known issue with PhantomJS. 3+ years as an open bug and apparently it has something to do with QT Webkit. Nonetheless, i was able to solve it by closing each page during the loop and re-opening a new Phantom page. It's a bit of a hacky work-around, but the memory consumption is far less. However, after about 200 pages, it still has a pretty high memory usage (1GB+). So, i break up my scripts into blocks of 200 and just start the next one upon completion. Here is the finished product that completes successfully without too much memory usage. It uses less on MacOS than Windows for some reason.
casper.start(url,function(){
this.echo('continuing captures...');
}).each(searchPages,function(casper,index){
loadSearch(this,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 1;
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
var fortnightAway = new Date(+new Date + 12096e5);
var dateEnd = fortnightAway.getMonth() + 1 + "/" + fortnightAway.getDate() + "/" + fortnightAway.getFullYear();
casper.page.close();
casper.page = require('webpage').create();
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Search failed to load. Retrying");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out. Retrying");
loadSearch(casper,index);
},20000);
});
}
There might be a better solution to the original issue, but for a quick fix on running out of memory, try setTimeout to make the recursive call without winding up the stack...
setTimeout(() => loadSearch(casper,index), 0);
(This idea assumes that the memory issue is the result of too much recursive depth over a long wait time).
Related
I was wondering if it was possible to add live time stamps to omegle using greasemonkey.
I did some digging up and found the function to add time but I got no experience with javascript and was not sure where am I supposed to add the code.
This is the code I found: http://stackoverflow.com/questions/10211145/getting-current-date-and-time-in-javascript
function getCurrentTime() {
var currentdate = new Date();
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return datetime;
}
I would appreciate it if someone could point me to the right direction (if this is even possible in the first place)
Here's what I've been using so far. It's terribly hacky but works fine.
if (!window.Timestamp$Element)
Timestamp$Element = Element;
Element = function (a, b) {
let elem = Timestamp$Element(a, b);
if (typeof a == "string" && b && (b["class"] == "youmsg" || b["class"] == "strangermsg")) {
let stamp = new Timestamp$Element("span", {"class": "timestamp"});
stamp.appendText(new Date().toLocaleTimeString() + " ");
elem.grab(stamp);
}
return elem;
};
Object.assign(Element, Timestamp$Element);
Or as a fully-cooked userscript with XrayWrapper handling and such, https://pastebin.com/czc0aLbG
I've been looking for a way to display the date the page last was updated.
Now I've been searching around, and everything points to the document.lastModified function, but however I've tried to fix it, it always shows the current date.
I've tried this example:
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" + modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds(); }
else {
Seconds = modiDate.getSeconds(); }
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime }
document.write("Last updated on ");
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]"); document.write("");
Or a simple one like this:
<SCRIPT LANGUAGE="JavaScript">
var t = new Date(document.lastModified);
document.write("<I>Last Updated: "+document.lastModified+"</I><BR>");
document.write("<I>Last Updated: "+t+"</I><BR>");
</SCRIPT>
Is there any other way to do this?
.. Without taking a 3 years tech-class?
Press here to see the scripts live
Because you are modifying it currently. Check this out for example.
To make this work based on your requirement, checkout this link and this link
check this it will help u
Put this on the page at the bottom:
<script type="text/javascript" src="js_lus.js"></script>
Name the file whatever you want. Example: js_lus.js Make sure src=""
path is correct for all your pages.
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" +
modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
document.write("Last updated on ")
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]")
document.write("");
I'm trying to bring back to life and older script I had used that worked in the past. The script would download comics (that we have the rights to) using autohotkey and curl... Then in InDesign we would run the following from the javascript Scripts panel:
#targetengine "session"
var date, month, year, myDocument;
var curDate = new Date();
var myTemplatePath = "/c/Comic/ComicImport.indd";
var myComicsPath = "/c/Comic/Comics/";
var myTemplate = new File(myTemplatePath);
if (myTemplate.exists) {
try {
myDocument = app.open(myTemplate);
} catch (e) {
alert("Could not open template, exiting\n" + e);
exit();
}
var win = showDialog();
} else {
alert("Could not locate template at:\n" + myTemplatePath + "\nexiting");
}
function showDialog() {
var win = new Window('palette');
with(win){
win.Pnl = add('panel', undefined, 'Date / Month / Year');
win.Pnl.orientation = 'row';
with(win.Pnl) {
win.Pnl.day = add('edittext');
win.Pnl.day.text = curDate.getDate();
win.Pnl.day.preferredSize = [30,20];
win.Pnl.month = add('edittext');
win.Pnl.month.text = curDate.getMonth() + 1;
win.Pnl.month.preferredSize = [30,20];
win.Pnl.year = add('edittext');
win.Pnl.year.text = curDate.getFullYear();
win.Pnl.year.preferredSize = [50,20];
}
win.btnOk = add('button', undefined, 'Import Comic');
win.btnOk.onClick = setDate;
};
win.center();
win.show();
return win;
}
function setDate() {
date = win.Pnl.day.text;
month = win.Pnl.month.text;
year = win.Pnl.year.text;
// OK we close the window and do the import
//win.close();
importComics();
}
function importComics() {
try {
//set comic1 to "macintosh Hd:users:marshall:documents:comics:" & DYear & Dmonth & Dday & "pzjud-a.tif"
var comics = new Array();
// REPLACE with own filepaths, could be
//comics.push(new File("/c/comics/" + year + month + date + "pzjud- a.tif"));
comics.push(new File(myComicsPath + "comic1-" + year + "-" + month + "-" + date + ".tif"));
comics.push(new File(myComicsPath + "comic2-" + year + "-" + month + "-" + date + ".tif"));
comics.push(new File(myComicsPath + "comic3-" + year + "-" + month + "-" + date + ".tif"));
comics.push(new File(myComicsPath + "comic4-" + year + "-" + month + "-" + date + ".tif"));
comics.push(new File(myComicsPath + "comic5-" + year + "-" + month + "-" + date + ".tif"));
} catch (e) {
alert("Error assigning images for import, stopping script\n" + e);
exit();
}
for (i = 1; i <= comics.length; i++) {
// Script label of the rectangles/pageitems to place the graphics into
var myRect = myDocument.pageItems.item("comic" + i);
try {
myRect.place(comics[i-1]);
} catch (e) {
alert(e);
}
myRect.fit(FitOptions.CONTENT_TO_FRAME);
}
}
However as soon as I hit the Import Comic button, I get the "ReferenceError: Object is invalid" error. My directory structures look ok to me. Any ideas?
thanks!
Watch this line:
var myRect = myDocument.pageItems.item("comic" + i);
In newest ID version it is no longer calling "item.label" but "item.name"
(the one shown in Layer Panel)
If inside your doc target rectangles have "label == comic + i" you have to repeat/move this values as rectangle's name as well.
Otherwise - your code needs to create a loop through all pageItems and check particular item.label before placing image.
var dateObj = new Date();
var month = dateObj.getUTCMonth() +1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var nowhour = dateObj.getHours();
var nowday = dateObj.getUTCDate();
var hour = "03";
var min = "00";
var hour2 = "18";
var min2 = "00";
var hour3 = "21";
var min3 = "00";
if(hour == 03)
{
day++;
}
document.write(nowhour);
newdate = year + "/" + month + "/" + day;
hourdate = " " + hour + ":" + min;
hourdate2 = " " + hour2 + ":" + min3;
hourdate3 = " " + hour2 + ":" + min3;
$("#bifrost")
if(nowhour > hour && day > nowday)
{
.countdown(newdate + hourdate, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else if(nowhour > hour2)
{
.countdown(newdate + hourdate2, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else{
.countdown(newdate + hourdate3, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}
Hello, i wanna make a countdown timer for events. I have 3 different event time,i wanna show up coming event here is my javascript code.
can anyone help me ?
ps: sorry for my bad english.
If countdown is a global function, you do not need the period before the call, just
countdown(parameters ... );
If countdown is a jquery plugin you have, and you are trying to call it on the jQuery object you created before the if statements, you must do it like this
$("#bifrost").countdown(parameters ... );
And repeat the jQuery selector in each of your if statements.
There is built in function setTimeout(function,milliseconds,param1,param2,...). Please see for examples in here.
setTimeout(function_to_do, miliseconds to wait) - will be triggered once;
setInterval(function_to_do, miliseconds to wait) - will be triggered periodically.
By the way - function name can't start with dot - and you have three calls to something .countdown(... There is you error.
This code below is for a form that needs to save some values into local storage, I have got it to work in a browser, but when I load this thing up in xcode/cordova, it wont fire the function. I tried debugging, hence the many, many alerts, I tried in DWCS6 with live view, but no avail, I can't seem to get it to run. Can you please find the error?
The function saveSpanning() has an if loop and when it goes out of the if-then-else loop it doesn't continue in xcode simulator. In the browser it does continue.
update: what is does: there's a slider, that produces a value, this value needs to be saved in local storage along with two other values (generated by JavaScript), namely: the date and the record count. So three values in all.
The script runs, using jquery mobile, the button to start this function works, I have use document.ready instead onBodyLoad, it basically works, but the function saveSpanning just does not go further in phonegap/ios/xcode simulator or device.
function saveSpanning() {
alert("saveSpanning gestart!");
var inputSpanning = document.getElementById("valSliderSpanning").value;
alert("input spanning = " + inputSpanning);
//For Time
var mes_time = document.getElementById("tijdSpanning").value;
var mestimearr = mes_time.split(":");
//For Date
var mes_date = document.getElementById("datumSpanning").value;
var mesdatearr = mes_date.split("-");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var curr_hours = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
//newDate = curr_year + "/" + curr_month + "/" + curr_date + " " + curr_hours + ":" + curr_min + ":" + curr_sec
// origienel opmaak datum newDate = mesdatearr[0] + "/" + mesdatearr[1] + "/" + mesdatearr[2] + " " + mestimearr[0] + ":" + mestimearr[1] + ":00";
newDate = mesdatearr[0] + "/" + mesdatearr[1] + "/" + mesdatearr[2];
alert("deze datum wordt opgelsage: " + newDate);
//var itemId = newDate.getTime(); //creates a unique id with the milliseconds since January 1, 1970
var itemId = "spanningKey";
var values = new Array();
values.push(newDate); //push each value into our values array
values.push(inputSpanning); //push each value into our values array
//alert(inputSpanning);
var spanningCountVal = localStorage.getItem('spanning_count');
//alert(spanningCountVal);
if (spanningCountVal == null) {
spanningCountVal = 1;
alert("spanningCountVal was null, en wordt dus nu 1: " + spanningCountVal);
}
else {
spanningCount = parseInt(spanningCountVal) + 1;
alert("zit nu in de else loop: " + spanningCount);
}
alert("uit de ifthenelseloop, spanningCount = " + spanningCount);
itemId = itemId + '-rec-' + spanningCount;
alert("itemid: " + itemId);
alert("spanningCountVal: " + spanningCount);
localStorage.setItem("spanning_count", spanningCount); //store the item in the database
localStorage.setItem(itemId, values.join("|")); //store the item in the database
alert("Successfully Saved.");
}
$(document).ready(function() {
$("#button").click(function() {
alert("hallo functie");
});
$("p").text("The DOM is now loaded and can be manipulated.");
$('#button2').click(function() {
alert('Button has been clicked');
});
$('#knopje').click(function() {
saveSpanning();
});
});
document.ready is called when all the DOM Elements are loaded, and accessible. In a browser this typically is a good time to start executing code that requires the DOM to be ready.
However in Phonegap/Cordova, there are a number of steps that run after the document.ready event is fired, including connecting to the debugging console.
Instead, you'll need to wait for the deviceready event to know when phonegap/cordova is fully loaded and ready to be executed. Inside $(document).on('ready') you'll need to add an event listener for deviceready which should fire your methods.