How to get rid of \r\n from a string? - jython

I recently had to upgrade to Jython 2.7.2. I send in a Java map instance into my python script.
Previously my python script would print out the key, value in the map as in the below format
message: Community: public
This same string now appears as
u'message': u'Community:\t\tpublic\r
I managed to get rid of the u' prefix by doing the following
encode(encoding = 'UTF-8', errors = 'strict')
But am still left with the \t\r in the string
'message': 'Community:\t\tpublic\r
and it feels very clumsy to manually remove these from the string. Is there any good utility method that would help me to preserve the pre 2.7.7 handling of strings?

Normally the character \r comes from a windows' file and the easiest way to get rid of them is just use replace
mystring = u'asd\r'
mystring = mystring.replace("\r", "")
print(repr(mystring))
Gives the output:
u'asd'

Why not use the toString() method and then replace the unwanted characters?
Sample code:
import java.util.HashMap as HashMap
import re
def test_2():
my_map = HashMap()
inner_map = HashMap()
inner_map.put("community", "public")
my_map.put("message", inner_map)
print re.sub(r"[{}]*", "", my_map.toString()).replace("=", ": ")
if __name__ == '__main__':
test_2()
Output:
message: community: public

Related

Kotlin Comparison between BufferedReader::readText and String always false

I read stdin and stderr from the command-line using:
fun runCommand(vararg commands: String): Pair<String, String> {
val proc = Runtime.getRuntime().exec(commands)
val stdIn = BufferedReader(InputStreamReader(proc.inputStream))
val stdErr = BufferedReader(InputStreamReader(proc.errorStream))
val p = Pair(stdIn.use(BufferedReader::readText).trim(), stdErr.use(BufferedReader::readText).trim())
stdIn.close();
stdErr.close();
return p;
}
This gives me a Pair of <String, String> with the output of stdin and stderr.
However, no matter how I try to compare these Strings to another String, the comparison always returns false.
Things I've tried:
runCommand("nordvpn", "account").first.compareTo("You are not logged in.")
runCommand("nordvpn", "account").first == "You are not logged in."
runCommand("nordvpn", "account").first.equals("You are not logged in.")
Might this have something to do with the encoding?
Or am I just reading the output incorrectly?
Any help would be appreciated!
Thanks to #gidds' comment I was able to find that for some reason the output of the command (stdout) had "-CR SP SP CR" (- CarriageReturn Space Space CarriageReturn" prepended, which I removed with a simple String.drop(5).
Edit: After some more thinking, I assume that the aforementioned charts were responsible for making the output of the command in the terminal colored (yellow)

How to open online reference from IPython?

Is there a way to have IPython open a browser pointed at the appropriate online reference?
Especially for numpy,scipy, matplotlib?
For example, the doc for numpy.linalg.cholesky is pretty hard to read in a terminal.
I don't think there is a direct way to make IPython or any shell to open up documentation online, because the primary job of shells is to let you interact with the things they are shells to.
We could however write a script to open a new tab on a browser with the documentation. Like so:
import webbrowser
docsList = {
"numpy" : lambda x: "https://docs.scipy.org/doc/numpy/reference/generated/" + x + ".html",
"scipy" : lambda x: "https://docs.scipy.org/doc/scipy/reference/generated/" + x + ".html",
"matplotlib" : lambda x: "https://matplotlib.org/api/" + x.split('.')[1] + "_api.html",
"default" : lambda x: "https://www.google.com/search?q=documentation+" + x
}
def online(method_name):
"""
Opens up the documentation for method_name on the default browser.
If the package doesn't match any entry in the dictionary, falls back to
Google.
Usage
-------
>>> lookUp.online("numpy.linalg.cholesky")
>>> lookUp.online("matplotlib.contour")
"""
try:
url = make_url(method_name)
except AttributeError:
print("Enter the method name as a string and try again")
return
webbrowser.open(url, new = 2)
return
def make_url(method_name):
package_name = method_name.split('.')[0]
try:
return docsList[package_name](method_name)
except KeyError:
return docsList["default"](method_name)
You could save the above as "lookUp.py" at a location that Python can find it in, and then import it whenever you need to use it.
Caveats:
This method takes strings as input, so if you call it on a function it'll throw an error.
>>> lookUp.online("numpy.linalg.cholesky")
Will work.
>>> lookUp.online(numpy.linalg.cholesky)
Will ask you to give it as a string.
So use autocomplete to get to the function and then wrap it in quotes to get it to work.

Validation of dynamic text in testing

I am trying to validate a pin code in my application. I am using Katalon and I have not been able to find an answer.
The pin code that I need to validate is the same length but different each time I run the test and looks like this on my page: PIN Code: 4938475948.
How can I account for the number changing each time I run the test?
I have tried the following regular expressions:
assertEquals(
"PIN Code: [^a-z ]*([.0-9])*\\d",
selenium.getText("//*[#id='RegItemContent0']/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td/div[1]/div[3]/ul/li[2]/span")
);
Note: This was coded in Selenium and converted to Katalon.
In Katalon, use a combination of WebUI.getText() and WebUI.verifyMatch() to do the same thing.
E.g.
TestObject object = new TestObject().addProperty('xpath', ConditionType.EQUALS, '//*[#id='RegItemContent0']/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td/div[1]/div[3]/ul/li[2]/span')
def actualText = WebUI.getText(object)
def expectedText = '4938475948'
WebUI.verifyMatch(actualText, expectedText, true)
Use also toInteger() or toString() groovy methods to convert types, if needed.
Editing upper example but to get this working
TestObject object = new TestObject().addProperty('xpath', ConditionType.EQUALS, '//*[#id='RegItemContent0']/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td/div[1]/div[3]/ul/li[2]/span')
def actualText = WebUI.getText(object)
def expectedText = '4938475948'
WebUI.verifyMatch(actualText, expectedText, true)
This can be done as variable but in Your case I recommend using some java
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(9000000000) + 1000000000;
// this will also cover the bad PIN (above limit)
I'd tweak your regex just a little since your pin code is the same length each time: you could limit the number of digits that the regex looks for and make sure the following character is white space (i.e. not a digit, or another stray character). Lastly, use the "true" flag to let the WebUI.verifyMatch() know it should expect a regular expression from the second string (the regex must be the second parameter).
def regexExpectedText = "PIN Code: ([0-9]){10}\\s"
TestObject pinCodeTO = new TestObject().addProperty('xpath', ConditionType.EQUALS, '//*[#id='RegItemContent0']/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td/div[1]/div[3]/ul/li[2]/span')
def actualText = WebUI.getText(pinCodeTO)
WebUI.verifyMatch(actualText, expectedText, true)
Hope that helps!

Why does pxssh .before method return delimiters?

Looking for a way to return just the stdout string when using the sendline method from pxssh module. Here is an example of code.
import pxssh
s = pxssh.pxssh()
s.force_password = True
s.login('host', 'user', 'password')
s.prompt()
print(s.before)
I get a string with delimters returned. Is this avoidable? I'd like to skip the step of cleaning this up to a usable string with regex if possible.
>>> print(s.before)
b'uptime\r\n 11:53:28 up 14 days, 19:13, 1 user, load average: 0.22, 0.19, 0.17\r\n'
I think you just need to modify the string after you retrieve it.
print(s.before.replace("\r\n", ""))

grails internationalization (i18n)

i work on grails project
def result = "customer"
//(this value is according to returned method parameter,
//it may be customer, company,... & so on)
def messages = "${message(code: 'default.result.${result}', default:'${result}')}"
i need to send a variable inside message code as i mention above
problem: this code appears as
default.result.${result}
that there is no code in message.properties refer to these code
there is default.result.customer ....$ so on
Question: how can i send variable inside message Code?
Try omitting the double quotes (GString) and it should work like the following:
def xxx = "bar"
def m = message(code: "foo.${xxx}", args: ['hello world'])
Results in following message-code
foo.bar
Try:
def messages = message(code: 'default.result.' + result, default: result)
If you want to pass in some values, e.g. a string, you can define your message like this:
default.result.success = Action {0} was successfull.
And resolve your code like this:
def m = message(code: 'default.result.' + result, args: ['delete User'])