I have this problem all the time that I want to write a docstring like this:
def foo(arg):
'''Add ``arg`` to the list of :class:`foo.bar.baz.Argument`s.'''
pass
However, that doesn't work, Sphinx will warn that
py:class reference target not found: foo.bar.baz.Argument`s
so it's treating the s after the closing backtick as part of the class name. This does not happen with e.g. punctuation marks like the dot ..
Is there anything to be done about this, except adding a space between the class name and the Plural-s (which looks crazy)?
You should be able to use backslash-escaped whitespace.
def foo(arg):
'''Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\ s.'''
pass
Similar to the answer of #mzjn, but in recent versions of Python you have to include two backslashes, e.g.:
def foo(arg):
"""Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\\ s."""
As pointed out before, a raw string ("r-string") also does the job with one backslash:
def foo(arg):
r"""Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\ s."""
Related
Sorry if it was not clear enough.
I have the following groovy snippet (from Jenkins)
def jdk = jobConfig.java
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
jobConfig.env.PATH="${env.JAVA_HOME}/bin:${env.PATH}"
How can I substitute the value of $jdk variable inside the single quotes on this line?
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
For example, this works with no problems. The usage of tools is OK:
jobConfig.env.JAVA_HOME="${tool 'openjdk_11.0.14'}"
But I want to set the hardcoded value of 'openjdk_11.0.14' to the value coming from def jdk = jobConfig.java
I tried a few variations but couldn't find the solution.
Many thanks
How can I reference the $jdk variable inside the single quotes?
It isn't clear what you mean by that but what you have is this:
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
There are a few things wrong with that but to address how to deal with the single quotes, 1 of the issues is you have nested $ which is going to confuse the situation.
if you are trying to surround the value of jdk with single quotes, you can do this:
def someJavaHomeRelatedVariable ="'${jdk}'"
Note that the quotes are outside of the {} expression.
A separate issue is your use of tool in that expression, but the above explains how to deal with surrounding the value of jdk with single quotes.
EDIT
The question isn't clear but maybe you are wanting to do something like this:
def sout = new StringBuilder()
def jdk = jobConfig.java
def proc = ['tool', jdk].execute()
proc.consumeProcessOutput(sout, null)
proc.waitForOrKill(2000)
jobConfig.env.JAVA_HOME = sout.toString()
Hello so i try to scrape off the author image url from the given video link using the urllib3 module, but due to different lengths of the url it causes to join other properties like the width and height
https://yt3.ggpht.com/ytc/AKedOLS-Bwwebj7zfYDDo43sYPxD8LN7q4Lq4EvqfyoDbw=s400-c-k-c0x00ffffff-no-rj","width":400,"height"
instead of this author image link which i want :
https://yt3.ggpht.com/ytc/AKedOLS-Bwwebj7zfYDDo43sYPxD8LN7q4Lq4EvqfyoDbw=s400-c-k-c0x00ffffff-no-rj
the code that i worked
import re
import urllib.request
def get_author(uri):
html = urllib.request.urlopen(uri)
author_image = re.findall(r'yt3.ggpht.com/(\S{99})', html.read().decode())
return f"https://yt3.ggpht.com/{author_image[1]}"
sorry for my bad english, thanks in advance =)
If you are not sure about the length of the match, do not hardcode the amount of chars to be matched. {99} is not going to work with arbitrary strings.
Besides, you want to match the string in a mark-up text and you need to be sure you only match until the delimiting char. If it is a " char, then match until that character.
Also, dots in regex are special and you need to escape them to match literal dots.
Besides, findall is used to match all occurrences, you can use re.search to get the first one to free up some resources.
So, a fix could look like
def get_author(uri):
html = urllib.request.urlopen(uri)
author_image = re.search(r'yt3\.ggpht\.com/[^"]+', html.read().decode())
if author_image:
return f"https://{author_image.group()}"
return None # you will need to handle this condition in your later code
Here, author_image is the regex match data object, and if it matches, you need to prepend the match value (author_image.group()) with https:// and return the value, else, you need to return some default value to check later in the code (here, None).
This problem might be very simple but I find it a bit confusing & that is why I need help.
With relevance to this question I posted that got solved, I got a new issue that I just noticed.
Source code:
from PyQt5 import QtCore,QtWidgets
app=QtWidgets.QApplication([])
def scroll():
#QtCore.QRegularExpression(r'\b'+'cat'+'\b')
item = listWidget.findItems(r'\bcat\b', QtCore.Qt.MatchRegularExpression)
for d in item:
print(d.text())
window = QtWidgets.QDialog()
window.setLayout(QtWidgets.QVBoxLayout())
listWidget = QtWidgets.QListWidget()
window.layout().addWidget(listWidget)
cats = ["love my cat","catirization","cat in the clouds","catść"]
for i,cat in enumerate(cats):
QtWidgets.QListWidgetItem(f"{i} {cat}", listWidget)
btn = QtWidgets.QPushButton('Scroll')
btn.clicked.connect(scroll)
window.layout().addWidget(btn)
window.show()
app.exec_()
Output GUI:
Now as you can see I am just trying to print out the text data based on the regex r"\bcat\b" when I press the "Scroll" button and it works fine!
Output:
0 love my cat
2 cat in the clouds
3 catść
However... as you can see on the #3, it should not be printed out cause it obviously does not match with the mentioned regular expression which is r"\bcat\b". However it does & I am thinking it has something to do with that special foreign character ść that makes it a match & prints it out (which it shouldn't right?).
I'm expecting an output like:
0 love my cat
2 cat in the clouds
Researches I have tried
I found this question and it says something about this \p{L} & based on the answer it means:
If all you want to match is letters (including "international"
letters) you can use \p{L}.
To be honest I'm not so sure how to apply that with PyQT5 also still I've made some tries & and I tried changing the regex to like this r'\b'+r'\p{cat}'+r'\b'. However I got this error.
QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object
Obviously the error says it's not a valid regex. Can someone educate me on how to solve this issue? Thank you!
In general, when you need to make your shorthand character classes and word boundaries Unicode-aware, you need to pass the QRegularExpression.UseUnicodePropertiesOption option to the regex compiler. See the QRegularExpression.UseUnicodePropertiesOption reference:
The meaning of the \w, \d, etc., character classes, as well as the meaning of their counterparts (\W, \D, etc.), is changed from matching ASCII characters only to matching any character with the corresponding Unicode property. For instance, \d is changed to match any character with the Unicode Nd (decimal digit) property; \w to match any character with either the Unicode L (letter) or N (digit) property, plus underscore, and so on. This option corresponds to the /u modifier in Perl regular expressions.
In Python, you could declare it as
rx = QtCore.QRegularExpression(r'\bcat\b', QtCore.QRegularExpression.UseUnicodePropertiesOption)
However, since the QListWidget.findItems does not support a QRegularExpression as argument and only allows the regex as a string object, you can only use the (*UCP) PCRE
verb as an alternative:
r'(*UCP)\bcat\b'
Make sure you define it at the regex beginning.
I am writing detailed information for each function in a class, and hope when others use my python code, they could check the info for each function, by using something like help(function_name)
For example, I have created a python file called text_preprocess.py, in this file I have created a class which includes functions.
class Preprocess():
def str_process(self, row_string):
'''
This Standford CoreNLP package requires the text input as 1 single string.
The input annotators are in you command line input.
:param row_string: The string format input for Standford CoreNLP
:return: Json format output
'''
parsed_json = self.nlp.annotate(row_string, properties={
'annotators': self.standford_annotators,
'outputFormat': 'json'
})
return parsed_json
In this function, as you can see the info is within triple quotes.
But I don't know how could other users see this info without looking into my code.
I have checked many solutions online, people use help(function_name), but it seems that they wrote the code through terminal, and then type help(function_name), many of those examples do not have class either. Using --help through command line only gives them the parameter descriptions I added through argparse....
So, if I hope others could check the info of my function without looking into the code, where and how could they do that?
Either be in the same directory as your script, or make sure your script is in one of the directories listed in sys.path (usually, the first option is easier for simple things, but if you want to do the second, use a virtualenv rather than trying to install the module system-wide).
Run pydoc3 text_preprocess to get documentation for the whole module. This recursively includes all of the items below the module, such as classes, their members, and functions.
Run pydoc3 text_preprocess.Preprocess if you just want the class.
Run pydoc3 text_preprocess.Preprocess.str_process if you just want the method.
Use Sphinx if you want nicely-formatted HTML or other formats such as PDF.
You may also want to remove that empty line at the beginning of your docstring; some docstring-parsing code may misinterpret it.
Putting triple quoted strings just below the declaration of a class or method is called documentation. You can read this using Preprocess.str_process.__doc__.
Trying to print a list of class objects like so:
for order in location_orders:
if (len(location_orders) >= 2):
print("{0}\n".format(order))
else:
print(order)
print("-" * 24)
So basically it's printing out the class objects fine, but I had to add a "\n" to separate them when there are more than one in the list. The problem is this will print a "\n" after the very last object, where I need it to be flush so I can print something else there. Is there a way I can erase the previous empty line only if it exist with the
print("-" * 24)
print statement?
Or alternatively, is there a way I can just separate the orders with a new line?
I can't index into them because they are class objects, therefore I can't use the sep=" " function.
This will print them w/ a space separator:
print " ".join( location_orders )
If you require each to be formatted, then
print " ".join(["{0}".format(order) for order in location_orders])
There's no general way to undo a line that's been printed. Once a line is sent to the terminal, you can only back up to rewrite it using (very involved) platform specific libraries like curses.
But you don't really need that. Since your list is iterable, you can unpack the whole thing into a single print call using the *args syntax. Then you can use the sep argument to put the double newlines in between them:
print(*location_orders, sep='\n\n')
The class instances will be formatted with str, just like they are when you format them one by one (unless you've written an unusual __format__ method for the class).
Another reasonable way to do it (which unlike argument unpacking would also work with Python 2 print statements) would be to use str.join to join individual strings (that you create from each instance in a generator expression) into a single string that you print in the end:
print('\n\n'.join(str(order) for order in location_orders))
Since we're turning the instances into strings more explicitly here, we could use format instead of str if it really made a difference (usually a format call with no special formatting code should be the same as str).