General solution for ajax request in Protractor - ajax

I want to wait until ajax call complete. Below I wrote general method. But It seems that is not work.
When I ran call function every afterajax request , isLoaded always to be true.
In protractor, Is there any solution? Or where have I made mistake?
Thank you
module.waitUntilJqueryLoad = async function (timeout) {
var isDone = false;
timeout = timeout || 60;
await browser.sleep(1000);
//Wait for jQuery to load
var isLoaded = await browser.driver.executeScript("return jQuery.active == 0;");
if(isLoaded) {
console.log("JQuery is Ready!");
return await browser;
}
//This loop will rotate for 60 times to check If page Is ready after every 1 second.
//You can replace your value with 60 If you wants to Increase or decrease wait time.
for (var i = 0; i < timeout; i++) {
try {
await browser.sleep(1000);
} catch (err) {}
//To check page ready state.
var isLoaded = await browser.driver.executeScript("return jQuery.active == 0;");
console.log(isLoaded);
if(isLoaded) {
console.log("JQuery is Ready");
isDone = true;
} else {
console.log("JQuery is NOT Ready !!");
}
if(isDone)
break;
}
return browser;
};

I have a work around for that. If your loading popup added display style, it will work.
This is not a general solution but other posted solution has not worked even below code.
await browser.wait(until.invisibilityOf(element(by.id('loadingPanel'))), 60000);
Example Usage :
element(by.id('selectPerson')).waitForInvisibilityOf(10000); // wait 10 seconds
Here is my solution;
protractor.ElementFinder.prototype.waitForInvisibilityOf = async function (timeout) {
var _debug = true;
var isDone = false;
timeout = timeout || 60000;
var seconds = timeout / 1000;
if(await !this.isPresent())
return this;
//This loop will rotate for 60 times to check If page Is ready after every 1 second.
//You can replace your value with 60 If you wants to Increase or decrease wait time.
for (var i = 1; i <= seconds; i++) {
await browser.sleep(1000);
var style = await this.getAttribute('style');
var insibilityOf = await style.includes('display: none;');
var visibilityOf = await style.includes('display: block;');
if(insibilityOf) {
if(_debug)
console.log(i + " second: Element invisible!");
isDone = true;
}
else {
if(_debug)
console.log(i + " second: Element NOT invisible!");
}
if(seconds === i)
throw "Element invisibility timed out after "+ timeout +" milliseconds";
if(!insibilityOf && !visibilityOf && i > 10) // break for paging is loaded
break;
if(isDone) // If element is invisible
break;
}
return await this; };

Related

Google appscript - if else statement not working in for loop

Trying to run the else statement in below code but cant make it work.
What am i missing here?
var startTime= (new Date()).getTime(); //code execution start time
function createtrigger() {
var currTime = (new Date()).getTime(); //current time
Logger.log((currTime-startTime)) //show time difference between start time and current time
//check if difference between current time and start time is greater than 0 is greater than starttime
if (currTime-startTime > 0 ) {
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
//check if trigger function name is "createtrigger"
if (triggers[i].getHandlerFunction() == "createtrigger") {
console.log("Trigger already exists. Hence not created");
}
//if trigger function name is not "createtrigger" then create the trigger
else
ScriptApp.newTrigger("createtrigger")
.timeBased()
.everyMinutes(1)
.create();
console.log("Trigger created");
}
}
}
var startTime= (new Date()).getTime(); //code execution start time
function createtrigger() {
var currTime = (new Date()).getTime(); //current time
Logger.log((currTime-startTime)) //show time difference between start time and current time
//check if difference between current time and start time is greater than 0 is greater than starttime
if (currTime-startTime > 0 ) {
var triggers = ScriptApp.getProjectTriggers();
Logger.log(triggers);
if (triggers.length>0){
for (var i = 0; i < triggers.length; i++) {
//check if trigger function name is "createtrigger"
if (triggers[i].getHandlerFunction() == "createtrigger") {
Logger.log("Trigger already exists. Hence not created");
break;
}
//if trigger function name "createtrigger" was not found then create the trigger
if (i==triggers.length) {
ScriptApp.newTrigger("createtrigger")
.timeBased()
.everyMinutes(1)
.create();
Logger.log("Trigger created");
}
}
} else {
ScriptApp.newTrigger("createtrigger")
.timeBased()
.everyMinutes(1)
.create();
Logger.log("Trigger created first time");
}
}
}

How to seek to a position in a song Discord.js?

I am facing some difficulty with seeking to a specified timestamp in the current song. I have separate files for all my commands. I want to create a seek.js file which takes input a specified time and then passes it to the play.js file(it plays the current song in the queue) but the problem is I cant seem to find a way to how do this.
This is my play command.
const { Collector } = require("discord.js");
const ytdlDiscord = require("ytdl-core-discord");
//const play = require("../commands/play");
module.exports = {
async play(song, message){
const queue = message.client.queue.get(message.guild.id);
if(!song){
setTimeout(function(){
if(!queue.connection.dispatcher && message.guild.me.voice.channel){
queue.channel.leave();
queue.textChannel.send(`**Cadenza** left successfully`).catch(console.error);
}
else return;
},120000);
message.client.queue.delete(message.guild.id);
return queue.textChannel.send(`**Music Queue Ended**`);
}
let stream = await ytdlDiscord(song.url,{filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1<<25});
let streamType = song.url.includes("youtube.com") ? "opus" : "ogg/opus";
queue.connection.on("disconnect", () => message.client.queue.delete(message.guild.id));
const dispatcher = queue.connection
.play(stream, {type: streamType, highWaterMark: 1})
.on("finish", () => {
if(queue.loop){
let last = queue.songs.shift();
queue.songs.push(last);
module.exports.play(queue.songs[0], message);
}else{
queue.songs.shift();
module.exports.play(queue.songs[0], message);
}
})
.on("error", (err) => {
console.error(err);
queue.songs.shift();
module.exports.play(queue.songs[0], message);
});
dispatcher.setVolumeLogarithmic(queue.volume / 100);
queue.textChannel.send(`Started Playing **${song.title}**`);
}
};
seek command
const { play } = require("../include/play");
function timeConvert(str){
const t = str.split(':');
let s = 0, m = 1;
while(t.length > 0){
s = +m * parseInt(t.pop(),10);
m = m * 60;
}
return s;
}
module.exports = {
name: 'seek',
description: 'Seeks to a certain point in the current track.',
execute(message,args){
const queue = message.client.queue.get(message.guild.id);
if(!queue) return message.channel.send("There is no song playing.").catch(console.error);
queue.playing = true;
let time = timeConvert(args[0]);
if( time > queue.songs[0].duration)
return message.channel.send(`**Input a valid time**`);
else{
let time = timeConvert(args[0]) * 1000;
#main code here
}
}
}
How can I pass the time variable to play() so that the current song seeks to that amount?

How to run a timer in background in xamarin forms?

In my app I want to set a timer to calculate the working time. My timer is working fine but when I switch to another page then it stops working. How to run the timer and calculate total time run in the background. Here is my code
Stopwatch st = new Stopwatch();
private void WorkClockStart(object sender,EventArgs e)
{
if(LaborClock.Text == "Start Work Clock")
{
LaborClock.Text = "Stop Work Clock";
Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
{
st.Start();
return false;
});
}
else
{
st.Stop();
long elapsed = st.ElapsedMilliseconds;
var sec = elapsed / 1000;
DisplayAlert("Message", "Worked Time(Sec): " + sec, "ok");
LaborClock.Text = "Start Work Clock";
st.Reset();
}
}
How to achieve this in Xamarin.Forms?
Why do you use a timer? Just store the DateTime.Now in a variable when you start your watch and compute the delta with DateTime.Now when you stop it.
Then you can store wherever you want (in a static variable for example or in App.cs if you want depending on your requirement)
I agree with Daniel you can use DateTime and Task.Factory.StartNew, Like the below code.
Task.Factory.StartNew( async() =>
{
var time = DateTime.Now;
var counter = 30;
transactionItem.RetryCount = 30;
do
{
await Task.Delay(1000);
counter = Math.Abs((DateTime.Now - time.AddSeconds(29)).Seconds);
} while (counter != 0 && time.AddSeconds(29) > DateTime.Now);
});

Xamarin-CrossDownloadManager - waiting for download file

I use Xamarin-CrossDownloadManager (https://github.com/SimonSimCity/Xamarin-CrossDownloadManager) and I need waiting for download a file. I have this code:
private static async Task<bool> FileDownloadedTest(string LinkToFile, string PathFile)
{
var downloadManager = CrossDownloadManager.Current;
CrossDownloadManager.Current.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file => {
return PathFile;
});
{
await DeleteFile(PathFile);
var file = downloadManager.CreateDownloadFile(LinkToFile);
await Task.Run(() => downloadManager.Start(file, true)); //why this not wait???
}
bool FileExist = await IsFileExist(PathFile);
return FileExist;
}
Why it not wait for finish download action? How to do it?
On library site they wrote, that I can watch the IDownloadManager.Queue to get information when the file is downloaded. But, I don't know how to use this in my method... Can you help me?
PS: Sorry for my english, I'm still learning it ;)
With that library, there is no callback or event published for when a file is finished downloading, but you can do a simple check and wait some more loop.
await Task.Run(async () =>
{
var downloadManager = CrossDownloadManager.Current;
var file = downloadManager.CreateDownloadFile(someFileBasedUrl);
downloadManager.Start(file);
bool isDownloading = true;
while (isDownloading)
{
await Task.Delay(10 * 1000);
isDownloading = IsDownloading(file);
}
});
The IsDownloading method:
bool IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
Re: https://github.com/SimonSimCity/Xamarin-CrossDownloadManager/blob/develop/Sample/DownloadExample/Downloader.cs#L46
I don't know why IDownloadFile.Status = COMPLETED not working, but i found solve problem:
await Task.Run(() =>
{
var downloadManager = CrossDownloadManager.Current;
var file = downloadManager.CreateDownloadFile(LinkToFile);
downloadManager.Start(file);
while (file.Status == DownloadFileStatus.INITIALIZED)
{
while (file.TotalBytesExpected > file.TotalBytesWritten)
{
Debug.WriteLine(file.Status);
}
}
});
Somebody know why DownloadFileStatus.INITIALIZED working, but DownloadFileStatus.COMPLETED not?
SushiHangover's answer above worked great, and I combined it with ACR User Dialog's package (https://github.com/aritchie/userdialogs) to show a nice loading progress screen to the user while waiting for the download to complete. This works nicely on Android (I couldn't test iOS yet).
...
var downloadManager = CrossDownloadManager.Current;
var fileToDownload = downloadManager.CreateDownloadFile(args.Url);
downloadManager.Start(fileToDownload, true);
args.Cancel = true;
UserDialogs.Instance.Progress("Downloading").Show();
bool isDownloading = true;
while (isDownloading)
{
await Task.Delay(100);
if (fileToDownload.TotalBytesExpected > 0)
{
UserDialogs.Instance.Progress().PercentComplete = (int)(fileToDownload.TotalBytesWritten / fileToDownload.TotalBytesExpected * 100);
Console.WriteLine(("DOWNLOAD PROGRESS: " + fileToDownload.TotalBytesWritten / fileToDownload.TotalBytesExpected * 100).ToString() + "%");
}
isDownloading = IsDownloading(fileToDownload);
}
UserDialogs.Instance.Progress().Hide();
//Below code opens the download location after download has completed.
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
return;
}
}
}
bool IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
throw new ArgumentOutOfRangeException();
}
}

Greasemonkey profanity filter script to work on Youtube comments

I do not know what I am talking about here I go.
On some pages it filters them and others like Youtube comments don't work.
What code needs to change in order for it to work in these sites?
// ==UserScript==
// #name profanity_filter
// #namespace localhost
// #description Profanity filter
// #include *
// #version 1
// #grant none
// ==/UserScript==
function recursiveFindTextNodes(ele) {
var result = [];
result = findTextNodes(ele,result);
return result;
}
function findTextNodes(current,result) {
for(var i = 0; i < current.childNodes.length; i++) {
var child = current.childNodes[i];
if(child.nodeType == 3) {
result.push(child);
}
else {
result = findTextNodes(child,result);
}
}
return result;
}
var l = recursiveFindTextNodes(document.body);
for(var i = 0; i < l.length; i++) {
var t = l[i].nodeValue;
t = t.replace(/badword1|badword2|badword3/gi, "****");
t = t.replace(/badword4/gi, "******");
t = t.replace(/badword5|badword6|badword7/gi, "*****");
t = t.replace(/badword8/gi, "******");
l[i].nodeValue = t;
}
* Replaced profanity in code to badword
Youtube comments are loaded asynchronously, quite a long time after the page has loaded (userscripts by default are executed at DOMContentLoaded event), so you need to wrap your code as a callback function of waitForKeyElements with a selector for the comments container or MutationObserver or setInterval.
replaceNodes(); // process the page
waitForKeyElements('.comment-text-content', replaceNodes);
function replaceNodes() {
..............
..............
}
Using setInterval instead of waitForKeyElements:
replaceNodes(); // process the page
var interval = setInterval(function() {
if (document.querySelector('.comment-text-content')) {
clearInterval(interval);
replaceNodes();
}
}, 100);
function replaceNodes() {
..............
..............
}
P.S. Don't blindly assign the value to the node, check first if it has changed to avoid layout recalculations:
if (l[i].nodeValue != t) {
l[i].nodeValue = t;
}

Resources