neulab/docprompting-conala huggingface dataset:
# round number 3.0005 up to 3 decimal places
round(3.0005, 3)
# round number 4.0005 up to 3 decimal places
round(4.0005, 3)
# round number 8.005 up to 2 decimal places
round(8.005, 2)
# round number 7.005 up to 2 decimal places
round(7.005, 2)
# round number 6.005 up to 2 decimal places
round(6.005, 2)
# round number 1.005 up to 2 decimal places
round(1.005, 2)
# Divide elements in list `a` from elements at the same index in list `b`
[(x / y) for x, y in zip(a, b)]
# Unpack each value in list `x` to its placeholder '%' in string '%.2f'
""", """.join(['%.2f'] * len(x))
# delete all columns in  DataFrame `df` that do not hold a non-zero value in its records
df.loc[:, ((df != 0).any(axis=0))]
# Delete an element 0 from a dictionary `a`
{i: a[i] for i in a if (i != 0)}
# Delete an element "hello" from a dictionary `lol`
lol.pop('hello')
# python pandas: apply a function with arguments to a series
my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)
# find element by css selector "input[onclick*='1 Bedroom Deluxe']"
driver.find_element_by_css_selector("input[onclick*='1 Bedroom Deluxe']")
# get  value at index `[2, 0]` in dataframe `df`
df.iloc[2, 0]
# check if the third element of all the lists in a list "items" is equal to zero.
any(item[2] == 0 for item in items)
# Find all the lists from a lists of list 'items' if third element in all sub-lists is '0'
[x for x in items if x[2] == 0]
# find all substrings in `mystring` beginning and ending with square brackets
re.findall('\\[(.*?)\\]', mystring)
# Delete third row in a numpy array `x`
x = numpy.delete(x, 2, axis=1)
# delete first row of array `x`
x = numpy.delete(x, 0, axis=0)
# request URL `url` using http header `{'referer': my_referer}`
requests.get(url, headers={'referer': my_referer})
# get the widget which has currently the focus in tkinter instance `window2`
print(('focus object class:', window2.focus_get().__class__))
# What is the best way to sort list with custom sorting parameters in Python?
li1.sort(key=lambda x: not x.startswith('b.'))
# get user input using message 'Enter name here: ' and insert it to the first placeholder in string 'Hello, {0}, how do you do?'
print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))
# Get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml
print(etree.tostring(some_tag.find('strong')))
# get modified time of file `file`
time.ctime(os.path.getmtime(file))
# get creation time of file `file`
time.ctime(os.path.getctime(file))
# get modification time of file `filename`
t = os.path.getmtime(filename)
# get modified time of file `file`
print(('last modified: %s' % time.ctime(os.path.getmtime(file))))
# get the creation time of file `file`
print(('created: %s' % time.ctime(os.path.getctime(file))))
# get the creation time of file `path_to_file`
return os.path.getctime(path_to_file)
# generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.
""",""".join(str(i) for i in range(100) if i % 4 in (1, 2))
# remove first directory from path '/First/Second/Third/Fourth/Fifth'
os.path.join(*x.split(os.path.sep)[2:])
# convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples
list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))
# print a digit `your_number` with exactly 2 digits after decimal
print('{0:.2f}'.format(your_number))
# get biggest 3 values from each column of the pandas dataframe `data`
data.apply(lambda x: sorted(x, 3))
# replace periods `.` that are not followed by periods or spaces with a period and a space `. `
re.sub('\\.(?=[^ .])', '. ', para)
# append values `[3, 4]` to a set `a`
a.update([3, 4])
# convert hex string "FFFF" to decimal
int('FFFF', 16)
# convert hex string '0xdeadbeef' to decimal
ast.literal_eval('0xdeadbeef')
# convert hex string 'deadbeef' to decimal
int('deadbeef', 16)
# Strip all non-ASCII characters from a unicode string, `\xa3\u20ac\xa3\u20ac`
print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))
# Get all non-ascii characters in a unicode string `\xa3100 is worth more than \u20ac100`
print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))
# removing duplicate characters from a string variable "foo"
"""""".join(set(foo))
# convert a list of characters `['a', 'b', 'c', 'd']` into a string
"""""".join(['a', 'b', 'c', 'd'])
# join elements of each tuple in list `a` into one string
[''.join(x) for x in a]
# join items of each tuple in list of tuples `a` into a list of strings
list(map(''.join, a))
# split string "jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false," on the first occurrence of delimiter '='
"""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,""".split('=', 1)
# get the middle two characters of a string 'state' in a pandas dataframe `df`
df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])
# join multiple dataframes `d1`, `d2`, and `d3` on column 'name'
df1.merge(df2, on='name').merge(df3, on='name')
# How to sort a dictionary in python by value when the value is a list and I want to sort it by the first index of that list
sorted(list(data.items()), key=lambda x: x[1][0])
# sort query set by number of characters in a field `length` in django model `MyModel`
MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
# sort column `m` in panda dataframe `df`
df.sort('m')
# read a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pandas
pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))
# Concatenating two one-dimensional NumPy arrays 'a' and 'b'.
numpy.concatenate([a, b])
# assign float 9.8 to variable `GRAVITY`
GRAVITY = 9.8
# create a regular expression object with the pattern '\xe2\x80\x93'
re.compile('\xe2\x80\x93')
# SQLAlchemy select records of columns of table `my_table` in addition to current date column
print(select([my_table, func.current_date()]).execute())
# change NaN values in dataframe `df` using preceding values in the frame
df.fillna(method='ffill', inplace=True)
# counting the number of true booleans in a python list `[True, True, False, False, False, True]`
sum([True, True, False, False, False, True])
# replacing  '\u200b' with '*' in a string  using regular expressions
'used\u200b'.replace('\u200b', '*')
# display a grayscale image from array of pixels `imageArray`
imshow(imageArray, cmap='Greys_r')
# unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`
pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')
# add unicode string '1' to UTF-8 decoded string '\xc2\xa3'
print('\xc2\xa3'.decode('utf8') + '1')
# convert unicode string `s` into string literals
print(s.encode('unicode_escape'))
# Initialize a list of empty lists `x` of size 3
x = [[] for i in range(3)]
# count the number of items in a generator/iterator `it`
sum(1 for i in it)
# convert nested list 'Cards' into a flat list
[a for c in Cards for b in c for a in b]
# get a list of all items in list `j` with values greater than `5`
[x for x in j if x >= 5]
# merge dictionaries form array `dicts` in a single expression
dict((k, v) for d in dicts for k, v in list(d.items()))
# decode url-encoded string `some_string` to its character equivalents
urllib.parse.unquote(urllib.parse.unquote(some_string))
# decode a double URL encoded string 
'FireShot3%2B%25282%2529.png' to
'FireShot3+(2).png'
urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))
# join list of numbers `[1,2,3,4] ` to string of numbers.
"""""".join([1, 2, 3, 4])
# start a new thread for `myfunction` with parameters 'MyStringHere' and 1
thread.start_new_thread(myfunction, ('MyStringHere', 1))
# python sum of ascii values of all characters in a string `string`
sum(map(ord, string))
# create variable key/value pairs with argparse
parser.add_argument('--conf', nargs=2, action='append')
# convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary
dict(zip(list(range(1, 5)), list(range(7, 11))))
# create a list of integers between 2 values `11` and `17`
list(range(11, 17))
# argparse associate zero or more arguments with flag 'file'
parser.add_argument('file', nargs='*')
# print a character that has unicode value `\u25b2`
print('\u25b2'.encode('utf-8'))
# set every two-stride far element to -1 starting from second element in array `a`
a[1::2] = -1
# Get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda function
max(lst, key=lambda x: x['score'])
# SQLAlchemy count the number of rows with distinct values in column `name` of table `Tag`
session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
# get a list of items form nested list `li` where third element of each item contains string 'ar'
[x for x in li if 'ar' in x[2]]
# get index of character 'b' in list '['a', 'b']'
['a', 'b'].index('b')
# remove null columns in a dataframe `df`
df = df.dropna(axis=1, how='all')
# Log info message 'Log message' with attributes `{'app_name': 'myapp'}`
logging.info('Log message', extra={'app_name': 'myapp'})
# Merge column  'word' in dataframe `df2` with column 'word' on dataframe `df1`
df1.merge(df2, how='left', on='word')
# get the maximum of 'salary' and 'bonus' values in a dictionary
print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))
# match blank lines in `s` with regular expressions
re.split('\n\\s*\n', s)
# replace carriage return in string `somestring` with empty string ''
somestring.replace('\\r', '')
# sort a list `L` by number after second '.'
print(sorted(L, key=lambda x: int(x.split('.')[2])))
# Filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'L'
list(dict((x['id'], x) for x in L).values())
# create list of 'size' empty strings
strs = ['' for x in range(size)]
# Copy list `old_list` and name it `new_list`
new_list = [x[:] for x in old_list]
# append string 'str' at the beginning of each value in column 'col' of dataframe `df`
df['col'] = 'str' + df['col'].astype(str)
# BeautifulSoup find a tag whose id ends with string 'para'
soup.findAll(id=re.compile('para$'))
# select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`
soup.select('div[id^="value_xxx_c_1_f_8_a_"]')
# match string 'this is my string' with regex '\\b(this|string)\\b'
then replace it with regex '<markup>\\1</markup>'
re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')
# replace backslashes in string `result` with empty string ''
result = result.replace('\\', '')
# separate each character in string `s` by '-'
re.sub('(.)(?=.)', '\\1-', s)
# concatenate '-' in between characters of string `str`
re.sub('(?<=.)(?=.)', '-', str)
# cartesian product of `x` and `y` array points into single array of 2d points
numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)
# truncate string `s` up to character ':'
s.split(':', 1)[1]
# remove index 2 element from a list `my_list`
my_list.pop(2)
# Encode each value to 'UTF8' in the list `EmployeeList`
[x.encode('UTF8') for x in EmployeeList]
# get the sum of each second value from a list of tuple `structure`
sum(x[1] for x in structure)
# send data 'HTTP/1.0 200 OK\r\n\r\n' to socket `connection`
connection.send('HTTP/1.0 200 established\r\n\r\n')
# send data 'HTTP/1.0 200 OK\r\n\r\n' to socket `connection`
connection.send('HTTP/1.0 200 OK\r\n\r\n')
# create a slice object using string `string_slice`
slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
# append a pandas series `b` to the series `a` and get a continuous index
a.append(b).reset_index(drop=True)
# simple way to append a pandas series `a` and `b` with same index
pd.concat([a, b], ignore_index=True)
# split unicode string "раз два три" into words
'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split()
# change flask security register url to `/create_account`
app.config['SECURITY_REGISTER_URL'] = '/create_account'
# open the login site 'http://somesite.com/adminpanel/index.php' in the browser
webbrowser.open('http://somesite.com/adminpanel/index.php')
# insert row into mysql database with column 'column1' set to the value `value`
cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))
# check if any item from list `b` is in list `a`
print(any(x in a for x in b))
# un-escape a backslash-escaped string in `Hello,\\nworld!`
print('"Hello,\\nworld!"'.decode('string_escape'))
# round 1123.456789 to be an integer
print(round(1123.456789, -1))
# substitute two or more whitespace characters with character '|' in string `line`
re.sub('\\s{2,}', '|', line.strip())
# create a list containing elements from list `list` that are predicate to function `f`
[f(x) for x in list]
# Make a scatter plot using unpacked values of list `li`
plt.scatter(*zip(*li))
# make a list of integers from 0 to `5` where each second element is a duplicate of the previous element
print([u for v in [[i, i] for i in range(5)] for u in v])
# create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
# create a list of integers from 1 to 5 with each value duplicated
[(i // 2) for i in range(10)]
# calculate the mean of columns with same name in dataframe `df`
df.groupby(by=df.columns, axis=1).mean()
# create a list where each element is a dictionary with keys 'key1' and 'key2' and values corresponding to each value in the lists referenced by keys 'key1' and 'key2' in dictionary `d`
[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]
# Split dictionary of lists into list of dictionaries
map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))
# build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`
ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
# combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary
dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
# pandas: change all the values of a column 'Date' into "int(str(x)[-4:])"
df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
# format number 1000000000.0 using latex notation
print('\\num{{{0:.2g}}}'.format(1000000000.0))
# randomly switch letters' cases in string `s`
"""""".join(x.upper() if random.randint(0, 1) else x for x in s)
# convert the argument `date` with string formatting in logging
logging.info('date=%s', date)
# Log message of level 'info' with value of `date` in the message
logging.info('date={}'.format(date))
# Do group by on `cluster` column in `df` and get its mean
df.groupby(['cluster']).mean()
# sort list `strings` in alphabetical order based on the letter after percent character `%` in each element
strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))
# sort a list of strings `strings` based on regex match
strings.sort(key=lambda str: re.sub('.*%', '', str))
# split string "This is a string" into words that do not contain whitespaces
"""This is a string""".split()
# split string "This     is a     string" into words that does not contain whitespaces
"""This     is a     string""".split()
# merge a pandas data frame `distancesDF` and column `dates` in pandas data frame `datesDF` into single
pd.concat([distancesDF, datesDF.dates], axis=1)
# convert a list `my_list` into string with values separated by spaces
""" """.join(my_list)
# generate a list of all unique pairs of integers in `range(9)`
list(permutations(list(range(9)), 2))
# Split a string `text` with comma, question mark or exclamation by non-consuming regex using look-behind
re.split('(?<=[\\.\\?!]) ', text)
# Subtract the mean of each row in dataframe `df` from the corresponding row's elements
df.sub(df.mean(axis=1), axis=0)
# replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg'
print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
# find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'
re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)
# find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'
re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)
# Parse String `s` to Float or Int
try:
    return int(s)
except ValueError:
    return float(s)
# convert a list `L` of ascii values to a string
"""""".join(chr(i) for i in L)
# sort list `['10', '3', '2']` in ascending order based on the integer value of its elements
sorted(['10', '3', '2'], key=int)
# custom sort an alphanumeric list `l`
sorted(l, key=lambda x: x.replace('0', 'Z'))
# remove white space padding around a saved image `test.png` in matplotlib
plt.savefig('test.png', bbox_inches='tight')
# execute a jar file 'Blender.jar' using subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
# Find next sibling element in Python Selenium?
driver.find_element_by_xpath("//p[@id, 'one']/following-sibling::p")
# convert Unicode codepoint to utf8 hex
chr(int('fd9b', 16)).encode('utf-8')
# zip keys with individual values in lists `k` and `v`
[dict(zip(k, x)) for x in v]
# read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`
df = pd.read_csv('comma.csv', quotechar="'")
# sort list of lists `L` by the second item in each list
L.sort(key=operator.itemgetter(1))
# extract dictionary values by key 'Feature3' from data frame `df`
feature3 = [d.get('Feature3') for d in df.dic]
# drop rows whose index value in list `[1, 3]` in dataframe `df`
df.drop(df.index[[1, 3]], inplace=True)
# extract the 2nd elements from a list of tuples
[x[1] for x in elements]
# find the first letter of each element in string `input`
output = ''.join(item[0].upper() for item in input.split())
# replace percent-encoded code in request `f` to their single-character equivalent
f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))
# call base class's __init__ method from the child class `ChildClass`
super(ChildClass, self).__init__(*args, **kwargs)
# extract only alphabetic characters from a string `your string`
""" """.join(re.split('[^a-zA-Z]*', 'your string'))
# Extract only characters from a string as a list
re.split('[^a-zA-Z]*', 'your string')
# Convert binary string to list of integers using Python
[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]
# find maximum with lookahead = 4 in a list `arr`
[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]
# replace single quote character in string "didn't" with empty string ''
"""didn't""".replace("'", '')
# Find a max value of the key `count` in a nested dictionary `d`
max(d, key=lambda x: d[x]['count'])
# Get a list of tuples with multiple iterators using list comprehension
[(i, j) for i in range(1, 3) for j in range(1, 5)]
# read a binary file 'test/test.pdf'
f = open('test/test.pdf', 'rb')
# remove all characters from string `stri` upto character 'I'
re.sub('.*I', 'I', stri)
# insert string `foo` at position `0` of list `list`
list.insert(0, 'foo')
# get the text of multiple elements found by xpath "//*[@type='submit']/@value"
browser.find_elements_by_xpath("//*[@type='submit']/@value").text
# find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium
browser.find_elements_by_xpath("//*[@type='submit']").get_attribute('value')
# converting string '(1,2,3,4)' to a tuple
ast.literal_eval('(1,2,3,4)')
# store data frame `df` to file `file_name` using pandas, python
df.to_pickle(file_name)
# extract all the values of a specific key named 'values' from a list of dictionaries
results = [item['value'] for item in test_data]
# convert a date string `s` to a datetime object
datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
# Get only first element in each of the innermost of the multidimensional list `listD`
[[[x[0]] for x in listD[i]] for i in range(len(listD))]
# print a floating point number 2.345e-67 without any truncation
print('{:.100f}'.format(2.345e-67))
# remove duplicate characters from string 'ffffffbbbbbbbqqq'
re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')
# split string "a;bcd,ef g" on delimiters ';' and ','
"""a;bcd,ef g""".replace(';', ' ').replace(',', ' ').split()
# extract all rows from dataframe `data` where the value of column 'Value' is True
data[data['Value'] == True]
# split string `s` into strings of repeating elements
print([a for a, b in re.findall('((\\w)\\2*)', s)])
# Trimming a string "Bob has a cat"
'Bob has a cat'.strip()
# Trimming "\n" from string `myString`
myString.strip('\n')
# left trimming "\n\r" from string `myString`
myString.lstrip('\n\r')
# right trimming "\n\t" from string `myString`
myString.rstrip('\n\t')
# Trimming a string "  Hello\n" by space
'  Hello\n'.strip(' ')
# read csv file 'my_file.csv' into numpy array
my_data = genfromtxt('my_file.csv', delimiter=',')
# read csv file 'myfile.csv' into array
df = pd.read_csv('myfile.csv', sep=',', header=None)
# read csv file 'myfile.csv' into array
np.genfromtxt('myfile.csv', delimiter=',')
# read csv file 'myfile.csv' into array
np.genfromtxt('myfile.csv', delimiter=',', dtype=None)
# multiply column 'A' and column 'B' by column 'C' in datafram `df`
df[['A', 'B']].multiply(df['C'], axis='index')
# Normalize string `str` from 'cp1252' code to 'utf-8' code
print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8'))
# Iterating over a dictionary `d` using for loops
for (key, value) in d.items():
    pass
# Iterating over a dictionary `d` using for loops
for (key, value) in list(d.items()):
    pass
# Iterating key and items over dictionary `d`
for (letter, number) in list(d.items()):
    pass
# Iterating key and items over dictionary `d`
for (k, v) in list(d.items()):
    pass
# Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of values
X = numpy.loadtxt('somefile.csv', delimiter=',')
# control the keyboard and mouse with dogtail in linux
dogtail.rawinput.click(100, 100)
# sort datetime objects `birthdays` by `month` and `day`
birthdays.sort(key=lambda d: (d.month, d.day))
# remove trailing newline in string "test string\n"
'test string\n'.rstrip()
# remove trailing newline in string 'test string \n\n'
'test string \n\n'.rstrip('\n')
# remove newline in string 'Mac EOL\r'
'Mac EOL\r'.rstrip('\r\n')
# remove newline in string 'Windows EOL\r\n' on the right side
'Windows EOL\r\n'.rstrip('\r\n')
# remove newline in string 'Unix EOL\n' on the right side
'Unix EOL\n'.rstrip('\r\n')
# remove newline in string "Hello\n\n\n" on the right side
'Hello\n\n\n'.rstrip('\n')
# split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)'
re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)
# split a string `s` by ';' and convert to a dictionary
dict(item.split('=') for item in s.split(';'))
# create a list where each element is a value of the key 'Name' for each dictionary `d` in the list `thisismylist`
[d['Name'] for d in thisismylist]
# create a list of tuples with the values of keys 'Name' and 'Age' from each dictionary `d` in the list `thisismylist`
[(d['Name'], d['Age']) for d in thisismylist]
# Reverse key-value pairs in a dictionary `map`
dict((v, k) for k, v in map.items())
# assign value in `group` dynamically to class property `attr`
setattr(self, attr, group)
# sort list of date strings 'd'
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
# test if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']`
set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])
# Check if all the values in a list `['a', 'b']` are present in another list `['b', 'a', 'foo', 'bar']`
all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
# format float `3.5e+20`  to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`
ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))
# set text color as `red` and background color as `#A3C1DA` in qpushbutton
setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
# convert an rgb image 'messi5.jpg' into grayscale `img`
img = cv2.imread('messi5.jpg', 0)
# create list `levels` containing 3 empty dictionaries
levels = [{}, {}, {}]
# parse string '01-Jan-1995' into a datetime object using format '%d-%b-%Y'
datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')
# Convert integer elements in list `wordids` to strings
[str(wi) for wi in wordids]
# get a list `cleaned` that contains all non-empty elements in list `your_list`
cleaned = [x for x in your_list if x]