Watir-webdriver hangs fro 1-2 minutes for "repeat" scenario - cucumber

I have the next method in my page object:
def open_random_report(count)
opened_reports = 0
rows = self.how_many_reports_present
cells = self.browser.divs(:class=>/x-grid-cell-inner./)
type_position = self.calculate_report_type_position
row_length = 0
self.browser.divs(:class=>"x-column-header-inner").each do |d|
if d.visible?
row_length += 1
end
end
while opened_reports < count.to_i do
$start=Time.now
r = Random.new
row = r.rand(rows - 2)
cell_position = type_position + (row * row_length) - 1
cells[cell_position].a.click
opened_reports += 1
sleep 1
self.close_report
$finish=Time.now
p "#{$finish} Report# #{opened_reports} - #{$finish - $start}"
f = File.new('log.txt', 'a')
f.puts "#{$finish} Report# #{opened_reports} - #{$finish - $start}"
f.close
end
end
This code clicks on random cell in the table(table is represented by the extjs-grid) and it works ok except for one thing: from time to time driver hangs for 1-2 minutes. There is no pattern for hanging, it can happens one time during a run or may happen 10 times during the run.
One more detail: When driver click on cell the app generates pdf report that will be shown to the user in preview window. I don't care about the report my goal is just to open reports so I'm closing preview window despite that fact that pdf has already completely loaded or not.
Any ideas why such hanging may happen? Maybe there is some problem with code?

Related

Reading excel values as seconds and convert to minutes

I am currently writing a lager script to ease my life.
Right now I am reading raw values from cells from an excel.
So far so good.
These numbers need to be interpreted as seconds and then converted into minutes.
I tried my best with datetime but no luck.
Any suggestions?
elif auswahl == '2':
print("Some user friendly-text:")
excel_download = openpyxl.load_workbook(r'/Path/to/excel.xlsx')
sheet = excel_download.active
Grund_1 = sheet['B2'].value
Grund_2 = sheet['B3'].value
Grund_3 = sheet['B4'].value
Grund_4 = sheet['B5'].value
Grund_5 = sheet['B6'].value
Grund_6 = sheet['B7'].value
Zeit_in_Sekunden_1 = sheet['C2'].value
Zeit_in_Sekunden_2 = sheet['C3'].value
Zeit_in_Sekunden_3 = sheet['C4'].value
Zeit_in_Sekunden_4 = sheet['C5'].value
Zeit_in_Sekunden_5 = sheet['C6'].value
Zeit_in_Sekunden_6 = sheet['C7'].value
print("Du warst heute für", Zeit_in_Sekunden_1, Grund_1, "!")
break
My idea:
raw_seconds_from_C2 = sheet['C2'].value
Then somehow convert to minutes from raw_seconds_from_C2
I am really out of ideas as I then need to put the converted minutes into a print().
Divide the value by 60 to obtain minutes from seconds:
c2_minutes = sheet['C2'].value / 60
Thanks to #Alonso's comment on the question.

Why does the code only return the last date to OBS "text"?

I am trying to change the code in a phyton script for OBS studio to show the dates of coming events from a google calendar. But the output to OBS Studio only shows the same (last) date on every event. The script log shows it as it should be thou...
After struggling to find a way to convert the dictionary items to print in a way that I wanted to show it, I finally thought I had made it work the way I wanted.
I am new to python and have basically just searched for answers to how to solve what I needed to change in the code.
It took me days to find out about datetime.datetime and how strftime could work together, and that I needed to upgrade Dateutil to a more recent version to not get some of the errors I got.
Anyway, since I am new to coding and most of this script has been written by someone else it is somewhat hard for me to see where this problem lies.
it works as it should in the script log but the date in "stime" becomes the same for every event when I send it to "text" in OBS Studio.
If anyone could help me with a solution to this, I would be very happy.
# Time objects using datetime
dt_now = dt.utcnow()
now = dt.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
#Timeformat
locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
tmfmt = '%d %B, %H:%M '
# Gets events currently happending by setting bounds to events happening within a second of current datetime
events = service.events().list(calendarId=cal_url, timeMin=now, timeMax=(dt_now+datetime.timedelta(7,1)).isoformat() +'Z',
maxResults=max_events, singleEvents=True, orderBy='startTime').execute()
# Logs the events to console
for event in events['items']:
mystart = (event['start']['dateTime'])
stime = dt.strftime(dtparse(mystart), format=tmfmt)
print(stime)
#print(datetime.datetime.utcnow().date())
#print (event['start']['dateTime'])
print(event['summary'])
#print(dt_now("%d %b, %Y"))
# Updates the text for each event
count = 0
stream_event_happening = False
record_event_happening = False
for event in events['items']:
if(count >= max_events):
break
text = stime + "\n" + event['summary']
settings = obs.obs_data_create()
obs.obs_data_set_string(settings, "text", text)
source = obs.obs_get_source_by_name(source_names[count])
obs.obs_source_update(source, settings)
obs.obs_data_release(settings)
obs.obs_source_release(source)
settings2 = obs.obs_data_create()
obs.obs_data_set_string(settings2, "file", "{}/{}.jpg".format(images_path, text))
source2 = obs.obs_get_source_by_name(image_sources[count])
obs.obs_source_update(source2, settings2)
obs.obs_data_release(settings2)
obs.obs_source_release(source2)
count += 1
text = stime + "\n" + event['summary']
shows only the same date but different events...
Wow, just a few minutes later I found a solution on my own... I added:
mystart = (event['start']['dateTime'])
stime = dt.strftime(dtparse(mystart), format=tmfmt)
just before:
text = stime + "\n" + event['summary']
and now it works as it should :)

Timing issue in windows rather than linux

I have the following function from a colleague who was previously working for the company and the comments are self explanatory, the problem is I'm right now using windows, and there issues with the synchornization with the device.
Would someone address or know a solution in windows for sync with a device ?
def sync_time(self):
"""Sync time on SmartScan."""
# On a SmartScan time can be set only by the precision of seconds
# So we need to wait for the next full second until we can send
# the packet on it's way to the scanner.
# It's not perfect, but the error should be more or less constant.
message = Maint()
message.state = message.OP_NO_CHANGE
now = datetime.datetime.utcnow()
epoch = datetime.datetime(1970, 1, 1)
# int and datetime objects
seconds = int((now - epoch).total_seconds()) + 1 # + sync second
utctime = datetime.datetime.utcfromtimestamp(seconds)
# wait until next full second
# works only on Linux with good accuracy
# Windows needs another approach
time.sleep((utctime - datetime.datetime.utcnow()).total_seconds())
command = MaintRfc()
command.command = command.SET_CLOCK
command.data = (seconds, )
message.add_message(command)
self._handler.sendto(message)
LOG.debug("Time set to: %d = %s", seconds, utctime)

Using ActiveX to Import from Excel to Matlab

I'm in need of optimizing import of .xls files to matlab due to xlsread being very time consuming with large amount of files. Current xlsread script as follows:
scriptName = mfilename('fullpath');
[currentpath, filename, fileextension]= fileparts(scriptName);
xlsnames = dir(fullfile(currentpath,'*.xls'));
xlscount = length(xlsnames);
xlsimportdata = zeros(7,6,xlscount);
for k = 1:xlscount
xlsimport = xlsread(xlsnames(k).name,'D31:I37');
xlsimportdata(:,1:size(xlsimport,2),k) = xlsimport;
end
I have close to 10k files per week that needs processing and with approx. 2sec per file processed on my current workstation, it comes in at about 5½ hours.
I have read that ActiveX can be used for this purpose however that is far beyond my current programming skills and have not been able to find a solution elsewhere. Any help on how to make this would be appreciated.
If it is simple to perform with ActiveX (or other proposed method), I would also be interested in data on cells D5 and G3, which I am currently grabbing from 'xlsnames(k,1).name' and 'xlsnames(k,1).date'
EDIT: updated to reflect the solution
% Get path to .m script
scriptName = mfilename('fullpath');
[currentpath, filename, fileextension]= fileparts(scriptName);
% Generate list of .xls file data
xlsnames = dir(fullfile(currentpath,'*.xls'));
xlscount = length(xlsnames);
SampleInfo = cell(xlscount,2);
xlsimportdata = cell(7,6,xlscount);
% Define xls data ranges to import
SampleID = 'G3';
SampleRuntime = 'D5';
data_range = 'D31:I37';
% Initiate progression bar
h = waitbar(0,'Initiating import...');
% Start actxserver
exl = actxserver('excel.application');
exlWkbk = exl.Workbooks;
for k = 1:xlscount
% Restart actxserver every 100 loops due limited system memory
if mod (k,100) == 0
exl.Quit
exl = actxserver('excel.application');
exlWkbk = exl.Workbooks;
end
exlFile = exlWkbk.Open([dname filesep xlsnames(k).name]);
exlSheet1 = exlFile.Sheets.Item('Page 0');
rngObj1 = exlSheet1.Range(SampleID);
xlsimport_ID = rngObj1.Value;
rngObj2 = exlSheet1.Range(SampleRuntime);
xlsimport_Runtime = rngObj2.Value;
rngObj3 = exlSheet1.Range(data_range);
xlsimport_data = rngObj3.Value;
SampleInfo(k,1) = {xlsimport_ID};
SampleInfo(k,2) = {xlsimport_Runtime};
xlsimportdata(:,:,k) = xlsimport_data;
% Progression bar updater
progress = round((k / xlscount) * 100);
importtext = sprintf('Importing %d of %d', k, xlscount);
waitbar(progress/100,h,sprintf(importtext));
disp(['Import progress: ' num2str(k) '/' num2str(xlscount)]);
end
%close actxserver
exl.Quit
% Close progression bar
close(h)
Give this a try. I am not an ActiveX Excel guru by any means. However, this works for me for my small amount of test XLS files (3). I never close the exlWkbk so I don't know if memory usage is building or if it automatically cleaned up when descoped after the next is opened in its place ... so use at your own risk. I am seeing an almost 2.5x speed increase which seems promising.
>> timeit(#getSomeXLS)
ans =
1.8641
>> timeit(#getSomeXLS_old)
ans =
4.6192
Please leave some feedback if this work on large number of Excel sheets because I am curious how it goes.
function xlsimportdata = getSomeXLS()
scriptName = mfilename('fullpath');
[currentpath, filename, fileextension]= fileparts(scriptName);
xlsnames = dir(fullfile(currentpath,'*.xls'));
xlscount = length(xlsnames);
xlsimportdata = zeros(7,6,xlscount);
exl = actxserver('excel.application');
exlWkbk = exl.Workbooks;
dat_range = 'D31:I37';
for k = 1:xlscount
exlFile = exlWkbk.Open([currentpath filesep xlsnames(k).name]);
exlSheet1 = exlFile.Sheets.Item('Sheet1'); %Whatever your sheet is called.
rngObj = exlSheet1.Range(dat_range);
xlsimport = cell2mat(rngObj.Value);
xlsimportdata(:,:,k) = xlsimport;
end
exl.Quit

Trials Timer with Read and Write

I am creating a GUI in Matlab that will read and write data to a text file based on the trial duration. The user will enter the number of trials and trial duration and
then push the "start" button.
For example the user enters 5 trials at 10 seconds duration. While starting the 1st trial, I will need to read/write data continuously for 10 seconds, then stop and save the text file. This process will continue for the next 5 trials. Here is a brief code I tried to implement below.
How can I run both the timer for 10 seconds and simultaneously read/write data with that time limit?
Thanks in advance.
% Get Number of Trials
number_trials = str2double(get(handles.Number_Trials,'String'));
% Get Trial Duration
trial_duration = str2double(get(handles.Trial_Duration,'String'));
% Timer Counter
global timer_cnt
timer_cnt = 0;
global eye_data
eye_data = 0;
for i = 1:number_trials
% Set Current Trial Executing
set(handles.Current_Trial_Text,'String',num2str(i));
% Set Text File Specifications
data_fname = get(handles.Data_Filename_Edit_Text,'String');
file_fname = '.dat';
data_fname_txt = strcat(data_fname,file_fname);
% Timer Object
fprintf('%s\n','Timer Started');
% Pauses 10 Seconds
t = timer('TimerFcn','stat=false','StartDelay',10);
start(t);
stat = true;
while(stat == true)
disp('.');
pause(1)
end
fprintf('%s\n','Timer Ended');
delete(t);
end
In my experience, timers are usually used in the context of "wait this amount of time, then do foo" rather than how you're using it, which is "do foo until you've done it for this amount of time".
The humble tic/toc functions can do this for you.
t_start = tic;
while toc(t_start) < 10
% do data collection
end

Resources