Finding out loading time of webelements in a webpage using selenium webdriver - html

I have a webpage(HTML 5) in which there are 4 charts, each of which taking different time to load once the static content in the page comes up. The Loading is shown in the webpage using a 'rendering' circle image for all the 4 charts. I want to find out how much time each of the charts were showing the 'rendering' circle. Please help me in getting a solution using selenium webdriver.

It is the crude way but it must work.
Create a infinite loop with 1 second wait and in each iteration check if the chart is loaded or not. Once all four charts are loaded or if you have timeout value come out of loop.
In this case there is possibility of error of 1 sec. If your chart is loading fast or want to reduce the margin of error reduce the wait from 1 sec to 100msec.
Pseudo code :[May use this to write better code]
boolean[] chartLoaded = {false,false,false,false};
int[] chartLoadTime = {0,0,0,0};
int counter = 0;
while(counter < 100)
{
counter++;
if(isLoaded(chart1))
{
chartLoaded[0] = true;
chartLoadTime[0]++;
}
//Do this for other three charts also
if(chartLoaded[0] && chartLoaded[1] && chartLoaded[2] && chartLoaded[3])
break;
}

Related

C# - Can not access File which is already being used - Iron OCR

I am using "Iron OCR", something like "Tesseract" to detect and scan certain Text from Screenshots.
Now I have the following error. Every time Iron OCR is used to scan an image for text it tries to access the Iron OCR log file which is somehow still used by the process before. So every time I get the error message that it can't access the log file because it is already in use. Nevertheless the Scan still works and I get a valid result even tho it gives me an exception because of that error.
My program works like this:
it takes a screenshots of certain areas of my screen.
it analyzes that image with Iron OCR and looks for text.
this process repeats itself infinitely.
I have following code:
//------------------------- # Capture Screenshot of specific Area # -------------------------\\
Rectangle bounds3;
Rect rect3 = new Rect();
bounds3 = new Rectangle(rect3.Left + 198, rect3.Top + 36, rect3.Right + 75 - rect3.Left - 10, rect3.Bottom + 30 - rect3.Top - 10);
CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);
Bitmap result3 = new Bitmap(40, 14);
using (Graphics g = Graphics.FromImage(result3))
{
g.CopyFromScreen(new Point(bounds3.Left, bounds3.Top), Point.Empty, bounds3.Size);
}
//------------------------- # Analyze Image for Text # -------------------------\\
var Ocr = new IronTesseract();
using (var Input = new OcrInput(result))
{
Input.Contrast();
Input.EnhanceResolution(300);
Input.Invert();
Input.Sharpen();
Input.ToGrayScale();
try
{
//------------------- # This causes the Error - Using Try Catch to Ignore it # -------------------\\
var Result = Ocr.Read(Input);
text = Result.Text;
}
catch
{
}
}
Also removing all the above only using their "1 Line Code" gives the same error message:
var Result = new IronTesseract().Read(#"images\image.png").Text;
I hope someone can help me to figure out what exactly causes that issue.

How to wait, then do something, in the GameScene

SKAction has waiting for duration abilities, for a period of time on a node. And seems to perform actions on nodes. Like moveTo, etc.
If I don't want that, rather I'd prefer to call functions within GameScene after a period of time, how do I do that with SpriteKit in the GameScene, not on a Sprite or other Node?
Are SKActions the way to do this? The only way to do this?
Yes. This question IS that ridiculously simple. I lack the heuristics and terminology to find an answer. Just keep looping around on how SKAction waits are calls on SKSprites for things like scale, rotation, etc, after time. Which isn't want I want/need.
Update:
Desired outcome, inside GameScene
doSetupStuff() // does some stuff...
waitForAWhile() // somehow wait, perhaps do somethings in here, while waiting
doSomethingElse() // does this after the waitForAWhile has waited
UPDATE 2:
What I think happens, again, inside didMove(to view...)
func wait(){
let timeToPause = SKAction.wait(forDuration: 3)
run(timeToPause)
}
let wontwait = SKAction.wait(forDuration: 3)
run(wontwait)
thisFunction(willnot: WAIT"it starts immediately")
wait()
thisFunction(forcedToWait: "for wait()'s nested action to complete")
UPDATE 3:
Found a way to get the delay without using SKActions. It's a little crude and brutal, but makes more sense to me than SKActions, so far:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
print("I waited ten seconds before printing this!")
}
An option, as you cited, is to manage this externally. The way I typically manage this sort of thing is to have an externally run update cycle. One that
To drive this updater, you could use either CADisplayLink (which is what I use right now with my OpenGL renderer) or a dispatch source timer (which I have used with my SpriteKit engine). When you use an updated, you want to calculate the delta time. The tick handler could look something like:
func tickHandler() {
let currTime = NSDate().timeIntervalSince1970
let dt = lastTime - currTime // lastTime is a data member of the class
// Call all updaters here, pretend "updater" is a known updater class
updater.update(dt)
}
And updater's update method would look something like:
func update(deltaTime:NSTimeInterval) {
// Do your magic
}
I typically have a main overall updater running independent of what people are calling scenes. Example usage would be something like having an attract mode like in old school arcade games. There they show title screen, sample game play, high scores, rinse and repeat. Scenes would be title, game play, high score. Here you can your main updater manage the time and coordinate the construction/destruction/switching of the scenes. Note this implies having an overall scene manager (which is actually quite handy to have).
For your case, you could use this updater to drive the GameScene updater. It's updater could look something like:
func update(deltaTime:NSTimeInterval) {
switch state {
case .SetupState:
// noop?
println("I'm in setup") // Shown just so you can see there is a setup state
case .WaitState:
waitTime += deltaTime
if waitTime >= kWaitTime {
// Do whats you gots to do
doSomethingElse()
state = .NextState
}
case .NextState:
// blah blah blah blah
}
}
So the flow to do this call path from your driver (CADisplayLink or dispatch source) would be something like:
tickHandler -> master updater -> game scene updater
Some will def find this is perhaps a little heavy handed. I, on the other hand, find this very helpful. While there is obviously some time management and the loss of being able to fire and forget, it can help provide more control for orchestrating pieces, as well as arbitrarily changing state without having to worry about killing already queued actions. There is also nothing that says you still cannot mix SKAction. When I did use SpriteKit, I did all my updating this way along with some dispatched items. I only used SKAction to update hierarchy. Keep in mind that I used my own animation and physics system. So at least for me I had a lot less dependency on SpriteKit (it effectively was just a renderer for me).
Note you have to have your own means to handle pause and coming to foreground where your timer will need to be resynced (you only need to worry about tickHandler). Breakpoints also will cause time jumps.
You can use below function
#define ANIM_TIME 2
SKAction *customACtion = [SKAction customActionWithDuration: ANIM_TIME actionBlock:^(SKNode *node, CGFloat elapsedTime) {
// Do Something Here
}];
Another way to make something happen after a certain period of time is to make use of the 'current time' parm passed to update(). The following code will spawn a boss at intervals ranging from 20 to 30 seconds.
In your property definitions:
var timeOfLastBoss: CFTimeInterval = -1 //Indicate no boss yet
var timePerBoss = CFTimeInterval()
.
.
.
didMoveToView() {
...
timePerBoss = CFTimeInterval(Int.random(20...30))
'''
}
.
.
.
func update(currentTime: CFTimeInterval) {
...
spawnBossForUpdate(currentTime)
...
}
'
'
'
func spawnBossForUpdate(currentTime : CFTimeInterval) {
if ( timeOfLastBoss == -1 ) {timeOfLastBoss = currentTime}
if (currentTime - timeOfLastBoss < timePerBoss) {return}
// Rest of 'spawnBoss code
self.timePerBoss = CFTimeInterval(Int.random(20...30))
self.timeOfLastBoss = currentTime
}
One way, using SKActions, in Swift 3.0, looks like this:
DEFINE: aPatientlyWaitingFunction() at the top level of
GameScene class.
To cause a delay to happen before calling the above function, inside
didMove(to view...)
three ways I've found to do this using Actions:
All three ways seem to accomplish the exact same thing:
let timeToWait: TimeInterval = 3 // is seconds in SKAction thinking time
let waitSomeTime = SKAction.wait(forDuration: timeToWait)
// 1st way __________________________________________
// with a completion handler, the function can be called after Action
run(waitSomeTime) {self.aPatientlyWaitingFunction()}
// 2nd way __________________________________________
// as a completion to be done after action, in the run invocation:
run(waitSomeTime, completion: aPatientlyWaitingFunction)
// 3rd way __________________________________________
// alternatively, as part of a sequence of actions...
// Create a sequence, by making a run action from waitSomeTime and...
let thenDoThis = SKAction.run(aPatientlyWaitingFunction)
// then activate sequence, which does one action, then the next
run(SKAction.sequence([waitSomeTime, thenDoThis]))
// OR... for something different ____________________
////////////////////////////////////////////////////////
DispatchQueue.main.asyncAfter(deadline: .now() + timeToWait) {
self.aPatientlyWaitingFunction()
print("DispatchQueue waited for 3 seconds")
}

LayoutCycleDetection - Observablecollection insert twice

I have a strange exception. I get a "LayoutCycleException" when inserting an item into a ObservableCollection two times with a specific index.
Details: I created a Paging-Class, which handles a big ObservableCollection (up to 2000 items) into a single page (200 items). The user can then go to another page. This event causes the Pager to set the page items new. All works fine except one situation: Inserting new items into the page with specific index (0, 1, 2, ..) fires the exception after the second insert.
Anyone an idee why?
Code:
// Calculate the index for this page
var cp = (CurrentPage == 0) ? 1 : CurrentPage;
int pindex = index - ((cp - 1) * PageItemCount);
if (pindex >= 0 && pindex < PageItemCount)
{
// An item is inserted after the list is already loaded
if (pindex == 0)
{
// Check if the page has mor items than it should
if (_pagedItems.Count >= PageItemCount)
{
// Remove last item from page
_pagedItems.RemoveAt(_pagedItems.Count - 1);
}
_pagedItems.Insert(pindex, item);
}
else if (_pagedItems.Count < PageItemCount)
{
// --> EXCEPTION at third insert
_pagedItems.Insert(pindex, item);
}
}
EDIT (solution)
I found the bug in my code. The Problem was, that the UI had no time to update the collection-changed (UI was not responsive). Very strange bug, took me long time to find it...
A simple Thread.Sleep(10) changed the whole thing =) in this time the ui can change the collection and everything works fine.
The exception is not coming from ObservableCollection, but from an event generated when the layout is updated after InsertItem.
LayoutCycleDetection is typically generated when using the LayoutUpdated event handler. You can unintentionally create an infinite loop. In this case _pagedItems.Insert creates a LayoutUpdate event which may be calling _pagedItems to insert again.
If it's not found there, you may have a custom control calling LayoutUpdated and causing the exception.

Game Simulator Times Out

This is my first post on here. Thank you in advance for taking the time to read my question.
I am a novice coder. I have a minor in Computer Science that I got a decade ago. I had an urge to do some simple coding, and an opportunity came up, so I did!
In developing a game, I wanted to run a program to determine the chances of given outcomes with given parameters. I excitedly reached the point where it was a go, but Google Scripts couldn't handle running the 60,000,000 possible scenarios in order to compute a win%.
I got, "error: Exceeded maximum execution time."
I'm just trying to find the shortest path between me and running this program. Ideas:
1) Is there a way to remove the maximum execution time and let it just take all day? Is there some other way I can get it to run in Google Scripts?
2) Perhaps I can run a smaller number of trials by inputing random numbers. Is there a way to generate random numbers in Google Scripts?
3) Should I be doing this kind of thing in something besides Google Scripts? If so, is there a free/affordable compiler for Mac I should look into? I tried importing it into Xcode, but I'm bewildered and can't seem to get to a simple place to compile. Also, importing it to "C" is creating some compatibility issues; though I may just have to suck it up and retool it here.
For reference, here's the function that's timing it out:
function dieFeeder(winCount, fSkill, fMagnitude, fHeart, fDie1, fDie2, fDie3, fDie4, fDie5, cSkill, cMagnitude, cHeart, cDie1, cDie2, cDie3, cDie4, cDie5){
// a parent function to function questionMatrix, feeds the changing dice into it
var matrixWinner;
//This 'for' clause keeps going until all dice permutations have been tried out
for (var i=0; i<60466176; i++){
//This part changes the dice to go through all combiations in a way similar to counting in base 6
if (cDie5 == 7){
cDie5 = 1;
cDie4 = cDie4+1;
}
if (cDie4 == 7){
cDie4 = 1;
cDie3 = cDie3 +1;
}
if (cDie3 == 7){
cDie3 = 1;
cDie2 = cDie2 +1;
}
if (cDie2 == 7){
cDie2 = 1;
cDie1 = cDie1 +1;
}
if (cDie1 == 7){
cDie1 = 1;
fDie5 = fDie5 +1;
}
if (fDie5 == 7){
fDie5 = 1;
fDie4 = fDie4 +1;
}
if (fDie4 == 7){
fDie4 = 1;
fDie3 = fDie3 +1;
}
if (fDie3 == 7){
fDie3 = 1;
fDie2 = fDie2 +1;
}
if (fDie2 == 7){
fDie2 = 1;
fDie1 = fDie1 +1;
}
cDie5 = cDie5 + 1;
//This part checks to see who wins and increases the winCount if it was the Favorite
matrixWinner = questionMatrix(fSkill, fMagnitude, fHeart, fDie1, fDie2, fDie3, fDie4, fDie5, cSkill, cMagnitude, cHeart, cDie1, cDie2, cDie3, cDie4, cDie5);
if (matrixWinner == 'favorite'){
winCount = winCount +1;
}
}
return winCount;
}
There is no way to lift the maximum execution time. The limit is there so that other users (like me) can have time to run our scripts too! The solution to this problem is to break up your problem into many subproblems.
One solution would be to continue executing your script while your running time is under some threshold (say, 3 minutes) (i.e. keep track of how long your script has been running). Then save all state relating to your script (variables, etc.). Save these to ScriptDb. Then have your script run on a 5-minute trigger. When your script runs again, it reads the values from ScriptDb and picks up where it left off.
If you're looking for random numbers, use Math.random(). Google Apps Scripts is built off of javascript, so basic javascript functions are available.
Relating to my answer to #2, what you have shown is entirely javascript, so you can just copy your code over to some webpage to run it. (For testing, you can use jsfiddle).
Also you need to define if (cDie5 == 7){

Methods for deleting blank (or nearly blank) pages from TIFF files

I have something like 40 million TIFF documents, all 1-bit single page duplex. In about 40% of cases, the back image of these TIFFs is 'blank' and I'd like to remove them before I do a load to a CMS to reduce space requirements.
Is there a simple method to look at the data content of each page and delete it if it falls under a preset threshold, say 2% 'black'?
I'm technology agnostic on this one, but a C# solution would probably be the easiest to support. Problem is, I've no image manipulation experience so don't really know where to start.
Edit to add: The images are old scans and so are 'dirty', so this is not expected to be an exact science. The threshold would need to be set to avoid the chance of false positives.
You probably should:
open each image
iterate through its pages (using Bitmap.GetFrameCount / Bitmap.SelectActiveFrame methods)
access bits of each page (using Bitmap.LockBits method)
analyze contents of each page (simple loop)
if contents is worthwhile then copy data to another image (Bitmap.LockBits and a loop)
This task isn't particularly complex but will require some code to be written. This site contains some samples that you may search for using method names as keywords).
P.S. I assume that all of images can be successfully loaded into a System.Drawing.Bitmap.
You can do something like that with DotImage (disclaimer, I work for Atalasoft and have written most of the underlying classes that you'd be using). The code to do it will look something like this:
public void RemoveBlankPages(Stream source stm)
{
List<int> blanks = new List<int>();
if (GetBlankPages(stm, blanks)) {
// all pages blank - delete file? Skip? Your choice.
}
else {
// memory stream is convenient - maybe a temp file instead?
using (MemoryStream ostm = new MemoryStream()) {
// pulls out all the blanks and writes to the temp stream
stm.Seek(0, SeekOrigin.Begin);
RemoveBlanks(blanks, stm, ostm);
CopyStream(ostm, stm); // copies first stm to second, truncating at end
}
}
}
private bool GetBlankPages(Stream stm, List<int> blanks)
{
TiffDecoder decoder = new TiffDecoder();
ImageInfo info = decoder.GetImageInfo(stm);
for (int i=0; i < info.FrameCount; i++) {
try {
stm.Seek(0, SeekOrigin.Begin);
using (AtalaImage image = decoder.Read(stm, i, null)) {
if (IsBlankPage(image)) blanks.Add(i);
}
}
catch {
// bad file - skip? could also try to remove the bad page:
blanks.Add(i);
}
}
return blanks.Count == info.FrameCount;
}
private bool IsBlankPage(AtalaImage image)
{
// you might want to configure the command to do noise removal and black border
// removal (or not) first.
BlankPageDetectionCommand command = new BlankPageDetectionCommand();
BlankPageDetectionResults results = command.Apply(image) as BlankPageDetectionResults;
return results.IsImageBlank;
}
private void RemoveBlanks(List<int> blanks, Stream source, Stream dest)
{
// blanks needs to be sorted low to high, which it will be if generated from
// above
TiffDocument doc = new TiffDocument(source);
int totalRemoved = 0;
foreach (int page in blanks) {
doc.Pages.RemoveAt(page - totalRemoved);
totalRemoved++;
}
doc.Save(dest);
}
You should note that blank page detection is not as simple as "are all the pixels white(-ish)?" since scanning introduces all kinds of interesting artifacts. To get the BlankPageDetectionCommand, you would need the Document Imaging package.
Are you interested in shrinking the files or just want to avoid people wasting their time viewing blank pages? You can do a quick and dirty edit of the files to rid yourself of known blank pages by just patching the second IFD to be 0x00000000. Here's what I mean - TIFF files have a simple layout if you're just navigating through the pages:
TIFF Header (4 bytes)
First IFD offset (4 bytes - typically points to 0x00000008)
IFD:
Number of tags (2-bytes)
{individual TIFF tags} (12-bytes each)
Next IFD offset (4 bytes)
Just patch the "next IFD offset" to a value of 0x00000000 to "unlink" pages beyond the current one.