Call for global variable in JS block of Selenium Webdriver test (Python) - selenium

I have a string of numbers set by user. Defined in the beginning of the Webdriver test:
numbers = input("prompt")
Then I need to enter value of this variable by JS code like this:
driver.execute_script("document.getElementsByName('phone')[0].value=***")
Where instead of *** I need the value of "numbers" variable. How should I properly insert it to make it work?

Here is what you want to do.
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value={}".format(numbers))
The documentation link:
https://docs.python.org/3/library/string.html
And a snip-it from the docs:
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using getitem().
Changed in version 3.1: The positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).
OR
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value=%s" % numbers)
See examples of both here:
https://pyformat.info/

If your python variable's value is simple string without single quotes or special characters, you can simply use:
driver.execute_script("document.getElementsByName('phone')[0].value='" +
python_variable + "'");
If it has quote marks in it, or special characters that need escaping, or if it's not a string at all, you need to obtain JavaScript string representation of your Python variable's value. json.dumps will handle all the necessary formatting and escaping for you, appropriate to the type of your variable:
from json import dumps
driver.execute_script("document.getElementsByName('phone')[0].value=" +
dumps(python_variable))

Related

Can't get key of object that is numeric

I'm working with an API that returns an array of objects. I can get all the keys, but two of those have numbers as keys, and I cannot get it. Give me an error.
I really dont know why I can not get it those keys.
Is there something different due to are numbers?
BTW Im using axios.
If you're using dot notation, you should change to bracket notation to access properties start by a number.
The code below uses dot notation, it throws an error
const test = {"1h" : "test value"};
console.log(test.1h); // error
Why :
In the object.property syntax, the property must be a valid JavaScript
identifier.
An identifier is a sequence of characters in the code that identifies a variable, function, or property.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.
The code below uses bracket notation, works fine
const test = {"1h" : "test value"};
console.log(test["1h"]); // works
Why :
In the object[property_name] syntax, the property_name is just a
string or Symbol. So, it can be any string, including '1foo', '!bar!',
or even ' ' (a space).
Check out the document here

Constants (constant variables) in ALFA

The OASIS Working Draft 01 for ALFA (alfa-for-xacml-v1.0-wd01) of 10 March 2015 says about constant values
3.15 Constant Values
Constant values can appear in the policy expressions. ALFA supports constants of type strings, integers,
doubles and Booleans directly. Strings are quoted with single or
double quotes. Integers consist of a number and optionally a minus
sign. Double consists of a number with a decimal dot and optionally a
minus sign. Booleans consist of the value true and false, without
quotes. Other datatypes are represented using a string followed by a
colon and the name of the datatype..
What that means is, you can use constant values like in that example (while report is the constant value):
target clause requestedType == "report"
But the thing is, once the ALFA files grow and you have written the constant value report all over, you might want to change the constant value into let's say my.company.attributes.medicalReport. In order to do that you have to find and replace all occurrences of the constant value.
Therefore (for the sake of avoiding redundancy) constants have been invented in other languages, where you define smth. like
const string REPORT_TYPE = "my.company.attributes.medicalReport"
or even more performant:
const integer REPORT_TYPE_ID = 3
or even more elegant:
const enum SUBJECT_TYPES { PATIENT, USER, EXAM, REPORT }
With those constants being defined I could write my target like:
target clause requestedType == REPORT_TYPE_ID
Does ALFA support constants or is there a way to "emulate" them (maybe a function that returns the desired value)?
Not yet! It is definitely a feature we want to have. We've had similar requests so stay tuned.

Extract all characters before a period with HiveQL regex?

I have a table that looks like:
bl.ah
foo.bar
bar.fight
And I'd like to use HiveQL's regexp_extract to return
bl
foo
bar
Given the docs data about regexp_extract:
regexp_extract(string subject, string pattern, int index)
Returns the string extracted using the pattern. For example, regexp_extract('foothebar', 'foo(.*?)(bar)', 2) returns 'bar.' Note that some care is necessary in using predefined character classes: using '\s' as the second argument will match the letter s; '\s' is necessary to match whitespace, etc. The 'index' parameter is the Java regex Matcher group() method index. See docs/api/java/util/regex/Matcher.html for more information on the 'index' or Java regex group() method.
So, if you have a table with a single column (let's call it description for our example) you should be able to use regexp_extract as follows to get the data before a period, if one exists, or the entire string in the absence of a period:
regexp_extract(description,'^([^\.]+)\.?',1)
The components of the regex are as follows:
^ start of string
([^\.]+) any non-period character one or more times, in a capture group
\.? a period either once or no times
Because the part of the string we're interested in will be in the first (and only) capture group, we refer to it by passing the index parameter a value of 1.

pyspark.sql data.frame understanding functions

I am taking a mooc.
It has one assignment where a column needs to be converted to the lower case. sentence=lower(column) does the trick. But initially I thought that the syntax should be sentence=column.lower(). I looked at the documentation and I couldnt figure out the problem with my syntax. Would it be possible to explain how I could have figured out that I have a wrong syntax by searching online documentation and function definition?
I am specially confused as This link shows that string.lower() does the trick in case of the regular string python objects
from pyspark.sql.functions import regexp_replace, trim, col, lower
def removePunctuation(column):
"""Removes punctuation, changes to lower case, and strips leading and trailing spaces.
Note:
Only spaces, letters, and numbers should be retained. Other characters should should be
eliminated (e.g. it's becomes its). Leading and trailing spaces should be removed after
punctuation is removed.
Args:
column (Column): A Column containing a sentence.
Returns:
Column: A Column named 'sentence' with clean-up operations applied.
"""
sentence=lower(column)
return sentence
sentenceDF = sqlContext.createDataFrame([('Hi, you!',),
(' No under_score!',),
(' * Remove punctuation then spaces * ',)], ['sentence'])
sentenceDF.show(truncate=False)
(sentenceDF
.select(removePunctuation(col('sentence')))
.show(truncate=False))
You are correct. When you are working with a string, if you want to convert it to lowercase, you should use str.lower().
And if you check the String page in the Python Documentation, you will see it has a lower method that should work as you expect:
a_string = "StringToConvert"
a_string.lower() # "stringtoconvert"
However. in the Spark example you provided, in your function removePunctuation you are NOT working with a singlestring, you are working with a Column. And a Column is a different object than a string, that is way you should use a method that works with a Column.
Specifically, you are working with this pyspark sql method. The next time you are in doubt on which method you need to implement, double check the datatype of your objects. Also, if you check the list of imports, you will see it is calling the lower method from pyspark.sql.functions
This is how i managed to do it:
lowered = lower(column)
np_lowered = regexp_replace(lowered, '[^\w\s]', '')
trimmed_np_lowered = trim(np_lowered)
return trimmed_np_lowered
return trim(lower(regexp_replace(column, "\p{Punct}", ""))).alias('sentence')

How to add text plus the text written from a Parameter type C in ABAP?

I am working in an ABAP program and I have a question.
For example in C# when we have a String variable: string name; , and we want this to be filled with some data from a textbox but also add some ohter text.
For example:
string name = "Hello: " + textBox1.text;,
And I want to ask you how can I do this in ABAP ??? How to add text plus the text written from a Parameter type C?
CONCATENATE and the concatenate operator && will do it as answered by Jagger and vwegert. To do it with string expressions, you use the below where name is the screen field or whatever that has the name in it (it doesn't need to be a field-symbol):
greeting = |Hello: { <name> }|.
String expressions are extremely useful as they can be used to build up complex values without declaring extra variables - e.g. they can passed as directly as function module or method parameters without first assigning to a local variable.
You can either use the CONCATENATE keyword or -- in newer releases -- string expressions. Be sure to check the online documentation and sample programs available using the transaction ABAPDOCU, it will save you a ton of seemingly basic questions.
The equivalent operator is &&.
So in your case it would be:
name = 'Hello: ' && textBox1->text.