I want to get a text from an element and then I want to write that text into another element which is available in another window when window switch.
Selenium::WebDriver::Chrome.driver_path="C:/chromedriver.exe"
browser = Selenium::WebDriver.for :chrome
browser.get 'https://docs.google.com/spreadsheets/d/1BJMqNGK1e2j4VjS8K2kS5wloKpEaHu_GTxMl2KueUCM/edit?usp=sharing'
sleep 8
browser.action.send_keys(:arrow_down).perform
browser.action.send_keys(:left_control, 'c').perform
sleep 1
browser.execute_script("window.open('http://10.19.252.220:25780/PortalCDT/')")
browser.window_handles.each do |handle|
browser.switch_to.window handle
end
sleep 5
browser.find_element(:id, "IdClient").click
browser.find_element(:id, "IdClient").send_keys(:left_control, 'v')
browser.find_element(:id, "ConfirmButton").click
puts "Disp. Cash: " + browser.find_element(:id, "ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispCash").text
column4 = browser.find_element(:id, "ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispCash").text
puts "-------------------------------------"
sleep 1
browser.window_handles.each do |handle|
browser.switch_to.window handle
sleep 1
browser.action.send_keys(:arrow_right).perform
browser.action.send_keys("Id Here").perform
browser.action.send_keys(:arrow_right).perform
browser.action.send_keys(:colunmn4).text
browser.window_handles.each do |handle|
browser.switch_to.window handle
sleep 1
browser.action.send_keys(:arrow_down).perform
browser.action.send_keys(:left_control, 'c').perform
end
browser.window_handles.each do |handle|
browser.switch_to.window handle
end
tried to save the text into column4 variable and then I want to write it into a text field which is another window.
Html code to copy text
<span id="ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispRotativo">2870,14</span>
Thanks!
There are plenty of mistake in your program.
1)To pass,control+c, you should pass[:control,"c"], not like (:control, 'c'), The difference here is, your code would pass control and c sequentially but code [:control,'c'] would hold the control key while it presses c. Do you see the difference?
2)Why are you opening a new tab while you intend to open another url? Open another Browser, that would not need your shift in Window.
Since I can't open your second URL, I copy your intended cell from spreadsheet and paste it in Google search textfield.
require 'selenium-webdriver'
driver=Selenium::WebDriver.for :chrome
driver.navigate.to 'https://docs.google.com/spreadsheets/d/1FMOaVoDF3PsXCgqiEQgYWe8CCO7PcDwsqHpEGT2no3I/edit?usp=sharing'
driver.action.send_keys(:arrow_down).perform
driver.action.send_keys([:control, 'c']).perform
driver1=Selenium::WebDriver.for :chrome
driver1.navigate.to("https://www.google.com/")
driver1.action.send_keys([:control, 'v']).perform
Correct answer:
value = browser.find_element('span#ctl00_ContentPlaceHolder1_ucInfoClient_lblDispCash')
value_text = value.text
text_area = browser.find_element('textbox#whatver_id')
text_area.send_keys(value_text, :enter).perform
Is there any way to code in Ruby so that the terminal presents two options among which the user is required to select using the arrow keys and confirm using Enter?
Pseudo code:
p "What is the capital of Scotland?
user_select = gets.chomp
p "Edinburgh"
p "Glasgow"
if user_select == "Edinburgh" etc etc
I want to know if this can be achieved without the user having to type in their answer. Can the terminal behave like a GUI?
Alternatively, you could use TTY::Prompt. It will let you use the arrow keys.
Code sample
require 'tty-prompt'
prompt = TTY::Prompt.new
greeting = 'What is the capital of Scotland?'
choices = %w(Edinburgh Glasgow)
answer = prompt.select(greeting, choices)
'do something' if answer == choices[0]
Result
$ ruby quiz.rb
What is the capital of Scotland? (Use arrow keys, press Enter to select)
‣ Edinburgh
Glasgow
You could use something like Highline, though that will not let you use arrow keys:
→ ruby test.rb
1. Edinburgh
2. Glasgow
What is the capital of Scotland?
→ 1
Correct!
Code (just to get an idea):
require 'highline'
cli = HighLine.new
cli.choose do |menu|
menu.prompt = "What is the capital of Scotland?"
menu.choice("Edinburgh") { cli.say "Correct!" }
menu.choice("Glasgow") { cli.say "Wrong!" }
end
For more of a GUI, try using something like MRDialog.
Example:
require 'mrdialog'
dialog = MRDialog.new
dialog.clear = true
dialog.title = "Quiz"
question = "What is the capital of Scotland?"
answers = [['E', 'Edinburg'], ['G', 'Glasgow']]
height = 0
width = 0
menu_height = 2
selected_item = dialog.menu(question, answers, height, width, menu_height)
puts "Selected item: #{selected_item}"
Result:
I am struggling to find a text comparison tool or algorithm that can compare an expected text against the current state of the text being typed.
I will have an experimentee typewrite a text that he has in front of his eyes. My idea is to compare the current state of the text against the expected text whenever something is typed. That way I want to find out when and what the subject does wrong (I also want to find errors that are not in the resulting text but were in the intermediate text for some time).
Can someone point me in a direction?
Update #1
I have access to the typing data in a csv format:
This is example output data of me typing "foOBar". Every line has the form (timestamp, Key, Press/Release)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
In Python
Given your input csv file (I called it keyboard_records.csv)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
The following code does the following:
Read its content and store it in a list named steps
For each step in steps recognizes what happened and
If it was a shift press or release sets a flag (shift_on) accordingly
If it was an arrow pressed moves the cursor (index of current where we insert characters) – if it the cursor is at the start or at the end of the string it shouldn't move, that's why those min() and max()
If it was a letter/number/symbol it adds it in curret at cursor position and increments cursor
Here you have it
import csv
steps = [] # list of all actions performed by user
expected = "Hello"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
current = [] # text written by the user
shift_on = False # is shift pressed
cursor = 0 # where is the cursor in the current text
for step in steps:
time, key, action = step
if key == 'LeftShift':
if action == 'P':
shift_on = True
else:
shift_on = False
continue
if key == 'LeftArrow' and action == 'P':
cursor = max(0, cursor-1)
continue
if key == 'RightArrow' and action == 'P':
cursor = min(len(current), cursor+1)
continue
if action == 'P':
if shift_on is True:
current.insert(cursor, key.upper())
else:
current.insert(cursor, key.lower())
cursor += 1
# Now you can join current into a string
# and compare current with expected
print(''.join(current)) # printing current (just to see what's happening)
else:
# What to do when a key is released?
# Depends on your needs...
continue
To compare current and expected have a look here.
Note: by playing around with the code above and a few more flags you can make it recognize also symbols. This will depend on your keyboard. In mine Shift + 6 = &, AltGr + E = € and Ctrl + Shift + AltGr + è = {. I think this is a good point to start.
Update
Comparing 2 texts isn't a difficult task and you can find tons of pages on the web about it.
Anyway I wanted to present you an object oriented approach to the problem, so I added the compare part that I previously omitted in the first solution.
This is still a rough code, without primary controls over the input. But, as you asked, this is pointing you in a direction.
class UserText:
# Initialize UserText:
# - empty text
# - cursor at beginning
# - shift off
def __init__(self, expected):
self.expected = expected
self.letters = []
self.cursor = 0
self.shift = False
# compares a and b and returns a
# list containing the indices of
# mismatches between a and b
def compare(a, b):
err = []
for i in range(min(len(a), len(b))):
if a[i] != b[i]:
err.append(i)
return err
# Parse a command given in the
# form (time, key, action)
def parse(self, command):
time, key, action = command
output = ""
if action == 'P':
if key == 'LeftShift':
self.shift = True
elif key == 'LeftArrow':
self.cursor = max(0, self.cursor - 1)
elif key == 'RightArrow':
self.cursor = min(len(self.letters), self.cursor + 1)
else:
# Else, a letter/number was pressed. Let's
# add it to self.letters in cursor position
if self.shift is True:
self.letters.insert(self.cursor, key.upper())
else:
self.letters.insert(self.cursor, key.lower())
self.cursor += 1
########## COMPARE WITH EXPECTED ##########
output += "Expected: \t" + self.expected + "\n"
output += "Current: \t" + str(self) + "\n"
errors = UserText.compare(str(self), self.expected[:len(str(self))])
output += "\t\t"
i = 0
for e in errors:
while i != e:
output += " "
i += 1
output += "^"
i += 1
output += "\n[{} errors at time {}]".format(len(errors), time)
return output
else:
if key == 'LeftShift':
self.shift = False
return output
def __str__(self):
return "".join(self.letters)
import csv
steps = [] # list of all actions performed by user
expected = "foobar"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
ut = UserText(expected)
for step in steps:
print(ut.parse(step))
The output for the csv file above was:
Expected: foobar
Current: f
[0 errors at time 17293398.576653]
Expected: foobar
Current: fo
[0 errors at time 17293401.313254]
Expected: foobar
Current: foO
^
[1 errors at time 17293402.073046]
Expected: foobar
Current: foOB
^^
[2 errors at time 17293403.178612]
Expected: foobar
Current: foOBa
^^
[2 errors at time 17293404.966193]
Expected: foobar
Current: foOBar
^^
[2 errors at time 17293405.725405]
I found the solution to my own question around a year ago. Now i have time to share it with you:
In their 2003 paper 'Metrics for text entry research: An evaluation of MSD and KSPC, and a new unified error metric', R. William Soukoreff and I. Scott MacKenzie propose three major new metrics: 'total error rate', 'corrected error rate' and 'not corrected error rate'. These metrics have become well established since the publication of this paper. These are exaclty the metrics i was looking for.
If you are trying to do something similiar to what i did, e.g. compare the writing performance on different input devices this is the way to go.
I am designing a user interface for a menu project. I tried using a for-loop such as:
for i in 0..8
i=i
end
for k in 0..7
k=k
end
if #selection==i && #unlock==k && $switches[(what do I do here?)]==?????
do thing
Whenever the user presses the Y key, it will turn off a function; if #selection==1 is highlighted and the user presses the "Y" key, the corresponding switch at that specific location should be turned off. #unlock is just used as a way of saying that, unless this global boolean is set to true, the user can press "Y" and turn this switch on or off.
First thing, you could change each if else to something like this:
BITMAP_PATH = "Graphics/Pictures/Input Map/switch"
if #selection==1 && #unlock1
pbSEPlay("BW2MenuChoose",65)
bitmap_switch = $switches[310] ? 'off' : 'on' # sets path to off/on
#graphics["switch"].setBitmap(BITMAP_PATH + bitmap_switch)
!$switches[310] # it changes value of boolean to opposite value
end
And the selections that only have one condition could be written like this:
if #selection==0 && #unlock0
pbSEPlay("buzzer",65)
end
You could also try writing a case expression for #selection. Probably you could dry it even more, but I do not really understand what each #unlock is used for.
Edit:
BITMAP_PATH = "Graphics/Pictures/Input/switch"
SELECTION_SWITCHES = [nil, 310, 300, 339, 338, 330, 318]
def pbChangeSwitch
case
when 0
case #selection
when 0,7
pbSEPlay("buzzer",65) if instance_variable_get("#unlock#{#selection}")
when 1..6
if instance_variable_get("#unlock#{#selection}")
pbSEPlay("BW2MenuChoose",65)
bitmap_switch = $switches[SELECTION_SWITCHES[#selection]] ? 'off' : 'on'
#sprites["switch"].setBitmap(BITMAP_PATH + bitmap_switch)
index = SELECTION_SWITCHES[#selection]
$switches[index] = !$switches[index]
end
end
Graphics.update
Please add $ to the last line. bitmap_switch can not be true or false, because you add it to BITMAP_PATH, so it has to be 'off' or 'on'.
I'm building a curses module and using KEY_DOWN to check if a arrow down key is pressed.
But, I get a Name error saying KEY_DOWN is not defined.
if value == KEY_DOWN:
NameError: global name 'KEY_DOWN' is not defined
Good day!
You have to do:
if value == curses.KEY_DOWN:
for it to work.
Hope this works!!!
But if this doesn't work show us your code (so we can analyze it)
To follow up to mvndaai's answer, if you want to detect arrow keys in Python, you have to AND together the three different ASCII values. For example:
key = getch()
if key == (27 and 91 and 65): #27 is ESC, 91 is [, and 65 is A
print("Up key pressed!")
if key == (27 and 91 and 66):
print("Down key pressed!")
if key == (27 and 91 and 67):
print("Right key pressed!")
if key == (27 and 91 and 68):
print("Left key pressed!")
I am not sure why the yave a gloabl named KEY_DOWN, but if you want a key down, you need to do 3 getchs. Warning, the first getch is the same as an ESC. That means you either make sure it doesn't close on ESC or do a work around like I did below. I also included a chart of what you will get as a getch for each key.
KeyESCUPDOWNRIGHTLEFT
getch2727272727
getch [[[[
getch ABCD
Which means that when you hit any Arrow key and you are triggering a ESC.
In ruby I tried a work around of checking for 27, then doing a quick timeout on another getch. If that gets a [ it is an arrow or something else, otherwise it is the escape key. Here is my ruby code:
def read_key
ch = getch
return check_escape_chars if ch == 27
ch
end
def check_escape_chars
require 'timeout'
begin
Timeout.timeout(0.0001) {getch}
case getch
when "A"; return "UP"
when "B"; return "DOWN"
when "C"; return "RIGHT"
when "D"; return "LEFT"
end
rescue Timeout::Error
return "ESC"
end
end