neulab/docprompting-conala huggingface dataset:
# Get a new list `list2`by removing empty list from a list of lists `list1`
list2 = [x for x in list1 if x != []]
# Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`
list2 = [x for x in list1 if x]
# get all text that is not enclosed within square brackets in string `example_str`
re.findall('(.*?)\\[.*?\\]', example_str)
# Use a regex to get all text in a string `example_str` that is not surrounded by square brackets
re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)
# get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'
re.findall('\\(.+?\\)|\\w', '(zyx)bc')
# match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'
re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')
# match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`
re.findall('\\(.*?\\)|\\w', '(zyx)bc')
# formate each string cin list `elements` into pattern '%{0}%'
elements = ['%{0}%'.format(element) for element in elements]
# get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'
[mydict[x] for x in mykeys]
# convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary
dict([('Name', 'Joe'), ('Age', 22)])
# average each two columns of array `data`
data.reshape(-1, j).mean(axis=1).reshape(data.shape[0], -1)
# double backslash escape all double quotes in string `s`
print(s.encode('unicode-escape').replace('"', '\\"'))
# split a string into a list of words and whitespace
re.split('(\\W+)', s)
# plotting stacked barplots on a panda data frame
df.plot(kind='barh', stacked=True)
# reverse the keys and values in a dictionary `myDictionary`
{i[1]: i[0] for i in list(myDictionary.items())}
# check if `obj_to_test` is a string
isinstance(obj_to_test, str)
# append list `list1` to `list2`
list2.extend(list1)
# append list `mylog` to `list1`
list1.extend(mylog)
# append items in list `mylog` to `list1`
for line in mylog:
    list1.append(line)
# append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`
b.append((a[0][0], a[0][2]))
# Initialize `SECRET_KEY` in flask config with `Your_secret_string `
app.config['SECRET_KEY'] = 'Your_secret_string'
# find the index of an element 'MSFT' in a list `stocks_list`
[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']
# remove symbols from a string `s`
re.sub('[^\\w]', ' ', s)
# Get the current directory of a script
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
# Find octal characters matches from a string `str` using regex
print(re.findall("'\\\\[0-7]{1,3}'", str))
# split string `input` based on occurrences of regex pattern '[ ](?=[A-Z]+\\b)'
re.split('[ ](?=[A-Z]+\\b)', input)
# Split string `input` at every space followed by an upper-case letter
re.split('[ ](?=[A-Z])', input)
# send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`
r = requests.post(url, files=files, headers=headers, data=data)
# write bytes `bytes_` to a file `filename` in python 3
open('filename', 'wb').write(bytes_)
# get a list from a list `lst` with values mapped into a dictionary `dct`
[dct[k] for k in lst]
# find duplicate names in column 'name' of the dataframe `x`
x.set_index('name').index.get_duplicates()
# truncate float 1.923328437452 to 3 decimal places
round(1.923328437452, 3)
# sort list `li` in descending order based on the date value in second element of each list in list `li`
sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)
# place the radial ticks in plot `ax` at 135 degrees
ax.set_rlabel_position(135)
# check if path `my_path` is an absolute path
os.path.isabs(my_path)
# pandas dataframe get first row of each group by 'id'
df.groupby('id').first()
# extract attributes 'src="js/([^"]*\\bjquery\\b[^"]*)"' from string `data`
re.findall('src="js/([^"]*\\bjquery\\b[^"]*)"', data)
# Sum integers contained in strings in list `['', '3.4', '', '', '1.0']`
sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])
# make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`
df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])
# find all matches of regex pattern '([a-fA-F\\d]{32})' in string `data`
re.findall('([a-fA-F\\d]{32})', data)
# remove escape character from string "\\a"
"""\\a""".decode('string_escape')
# replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.
"""obama""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
# remove directory tree '/folder_name'
shutil.rmtree('/folder_name')
# create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`
data['weekday'] = data['my_dt'].apply(lambda x: x.weekday())
# reverse sort Counter `x` by values
sorted(x, key=x.get, reverse=True)
# reverse sort counter `x` by value
sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)
# append a numpy array 'b' to a numpy array 'a'
np.vstack((a, b))
# fetch address information for host 'google.com' ion port 80
print(socket.getaddrinfo('google.com', 80))
# add a column 'day' with value 'sat' to dataframe `df`
df.xs('sat', level='day', drop_level=False)
# Flask set folder 'wherever' as the default template folder
Flask(__name__, template_folder='wherever')
# How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?
session.execute('INSERT INTO t1 (SELECT * FROM t2)')
# sort a list of lists 'c2' such that third row comes first
c2.sort(key=lambda row: row[2])
# Sorting a list of lists in Python
c2.sort(key=lambda row: (row[2], row[1], row[0]))
# Sorting a list of lists in Python
c2.sort(key=lambda row: (row[2], row[1]))
# set font `Arial` to display non-ascii characters in matplotlib
matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})
# Convert  DateTime column 'date' of pandas dataframe 'df' to ordinal
df['date'].apply(lambda x: x.toordinal())
# get html source of Selenium WebElement `element`
element.get_attribute('innerHTML')
# open a 'gnome' terminal from python script and run  'sudo apt-get update' command.
os.system('gnome-terminal -e \'bash -c "sudo apt-get update; exec bash"\'')
# add an item with key 'third_key' and value 1 to an dictionary `my_dict`
my_dict.update({'third_key': 1})
# Insert item `12` to a list `my_list`
my_list.append(12)
# add an entry 'wuggah' at the beginning of list `myList`
myList.insert(0, 'wuggah')
# convert a hex-string representation to actual bytes
"""\\xF3\\xBE\\x80\\x80""".replace('\\x', '').decode('hex')
# get the first value from dataframe `df` where column 'Letters' is equal to 'C'
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
# get the 5th item of a generator
next(itertools.islice(range(10), 5, 5 + 1))
# join a list of strings `list` using a space ' '
""" """.join(list)
# create list `y` containing two empty lists
y = [[] for n in range(2)]
# read a file 'C:/name/MyDocuments/numbers' into a list `data`
data = [line.strip() for line in open('C:/name/MyDocuments/numbers', 'r')]
# Drop rows of pandas dataframe `df` having NaN in column at index "1"
df.dropna(subset=[1])
# get elements from list `myList`, that have a field `n` value 30
[x for x in myList if x.n == 30]
# round off the float that is the product of `2.52 * 100` and convert it to an int
int(round(2.51 * 100))
# loop through the IP address range "192.168.x.x"
for i in range(256):
    for j in range(256):
        ip = ('192.168.%d.%d' % (i, j))
        print(ip)
# loop through the IP address range "192.168.x.x"
for (i, j) in product(list(range(256)), list(range(256))):
    pass
# loop through the IP address range "192.168.x.x"
generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)
# Sum the corresponding decimal values for binary values of each boolean element in list `x`
sum(1 << i for i, b in enumerate(x) if b)
# write multiple strings `line1`, `line2` and `line3` in one line in a file `target`
target.write('%r\n%r\n%r\n' % (line1, line2, line3))
# Convert list of lists `data` into a flat list
[y for x in data for y in (x if isinstance(x, list) else [x])]
# Print new line character as `\n` in a string `foo\nbar`
print('foo\nbar'.encode('string_escape'))
# remove last comma character ',' in string `s`
"""""".join(s.rsplit(',', 1))
# calculate the mean of each element in array `x` with the element previous to it
(x[1:] + x[:-1]) / 2
# get an array of the mean of each two consecutive values in numpy array `x`
x[:-1] + (x[1:] - x[:-1]) / 2
# load data containing `utf-8` from file `new.txt` into numpy array `arr`
arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')
# reverse sort list of dicts `l` by value for key `time`
l = sorted(l, key=itemgetter('time'), reverse=True)
# Sort a list of dictionary `l` based on key `time` in descending order
l = sorted(l, key=lambda a: a['time'], reverse=True)
# get rows of dataframe `df` that match regex '(Hel|Just)'
df.loc[df[0].str.contains('(Hel|Just)')]
# find the string in `your_string` between two special characters "[" and "]"
re.search('\\[(.*)\\]', your_string).group(1)
# How to create a list of date string in 'yyyymmdd' format with Python Pandas?
[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]
# count number of times string 'brown' occurred in string 'The big brown fox is brown'
"""The big brown fox is brown""".count('brown')
# download the file from url `url` and save it under file `file_name`
urllib.request.urlretrieve(url, file_name)
# replace dot characters  '.' associated with ascii letters in list `s` with space ' '
[re.sub('(?<!\\d)\\.(?!\\d)', ' ', i) for i in s]
# sort list `list_of_strings` based on second index of each string `s`
sorted(list_of_strings, key=lambda s: s.split(',')[1])
# call multiple bash function ‘vasp’ and ‘tee tee_output’ using ‘|’
subprocess.check_call('vasp | tee tee_output', shell=True)
# eliminate all strings from list `lst`
[element for element in lst if isinstance(element, int)]
# get all the elements except strings from the list 'lst'.
[element for element in lst if not isinstance(element, str)]
# Sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
# sort a list of dictionaries `l` by values in key `name` in descending order
newlist = sorted(l, key=itemgetter('name'), reverse=True)
# How do I sort a list of dictionaries by values of the dictionary in Python?
list_of_dicts.sort(key=operator.itemgetter('name'))
# How do I sort a list of dictionaries by values of the dictionary in Python?
list_of_dicts.sort(key=operator.itemgetter('age'))
# join together with "," elements inside a list indexed with 'category' within a dictionary `trans`
""",""".join(trans['category'])
# concatenate array of strings `['A', 'B', 'C', 'D']` into a string
"""""".join(['A', 'B', 'C', 'D'])
# Remove all strings from a list a strings `sents` where the values starts with `@$\t` or `#`
[x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
# convert datetime object `(1970, 1, 1)` to seconds
(t - datetime.datetime(1970, 1, 1)).total_seconds()
# insert `_suff` before the file extension in `long.file.name.jpg` or replace `_a` with `suff` if it precedes the extension.
re.sub('(\\_a)?\\.([^\\.]*)$', '_suff.\\2', 'long.file.name.jpg')
# convert int values in list `numlist` to float
numlist = [float(x) for x in numlist]
# Create a list containing all ascii characters as its elements
[chr(i) for i in range(127)]
# python regex - check for a capital letter with a following lowercase in string `string`
re.sub('^[A-Z0-9]*(?![a-z])', '', string)
# write line "hi there" to file `f`
print('hi there', file=f)
# write line "hi there" to file `myfile`
f = open('myfile', 'w')
f.write('hi there\n')
f.close()
# write line "Hello" to file `somefile.txt`
with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')
# convert unicode string `s` to ascii
s.encode('iso-8859-15')
# Find all numbers and dots from a string `text` using regex
re.findall('Test([0-9.]*[0-9]+)', text)
# python regex  to find all numbers and dots from 'text'
re.findall('Test([\\d.]*\\d+)', text)
# execute script 'script.ps1' using 'powershell.exe' shell
os.system('powershell.exe', 'script.ps1')
# Sort a list of tuples `b` by third item in the tuple
b.sort(key=lambda x: x[1][2])
# get a list of all keys in Cassandra database `cf` with pycassa
list(cf.get_range().get_keys())
# get the index of an integer `1` from a list `lst` if the list also contains boolean items
next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)
# subtract 13 from every number in a list `a`
a[:] = [(x - 13) for x in a]
# choose a random file from the directory contents of the C drive, `C:\\`
random.choice(os.listdir('C:\\'))
# Get all urls within text `s`
re.findall('"(http.*?)"', s, re.MULTILINE | re.DOTALL)
# match urls whose domain doesn't start with `t` from string `document` using regex
re.findall('http://[^t][^s"]+\\.html', document)
# split a string `mystring` considering the spaces ' '
mystring.replace(' ', '! !').split('!')
# open file `path` with mode 'r'
open(path, 'r')
# sum elements at the same index in list `data`
[[sum(item) for item in zip(*items)] for items in zip(*data)]