prompt
stringlengths
4
181
completion
stringlengths
2
232
empty a list `lst`
lst[:] = []
empty a list `alist`
alist[:] = []
eset index of series `s`
s.reset_index(0).reset_index(drop=True)
vert unicode text from list `elems` with index 0 to normal text 'utf8'
elems[0].getText().encode('utf-8')
eate a list containing the subtraction of each item in list `L` from the item prior to
[(y - x) for x, y in zip(L, L[1:])]
get value in string `line` matched by regex pattern '\\bLOG_ADDR\\s+(\\S+)'
print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))
mport all classes from module `some.package`
globals().update(importlib.import_module('some.package').__dict__)
vert a list of characters `['a', 'b', 'c', 'd']` into a string
"""""".join(['a', 'b', 'c', 'd'])
Slice `url` with '&' as delimiter to get http://www.domainname.com/page?CONTENT_ITEM_ID=1234 from url http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
url.split('&')
dictionary `d` by key
od = collections.OrderedDict(sorted(d.items()))
a dictionary `d` by key
OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))
Execute a put request to the url `url`
response = requests.put(url, data=json.dumps(data), headers=headers)
eplace everything that is not an alphabet or a digit with '' in 's'.
re.sub('[\\W_]+', '', s)
eate a list of aggregation of each element from list `l2` to all elements of list `l1`
[(x + y) for x in l2 for y in l1]
vert string `x' to dictionary splitted by `=` using list comprehensio
dict([x.split('=') for x in s.split()])
emove index 2 element from a list `my_list`
my_list.pop(2)
Delete character M from a string `s` using pytho
s = s.replace('M', '')
w to delete a character from a string using python?
newstr = oldstr.replace('M', '')
get the sum of the products of each pair of corresponding elements in lists `a` and `b`
sum(x * y for x, y in zip(a, b))
m the products of each two elements at the same index of list `a` and list `b`
list(x * y for x, y in list(zip(a, b)))
m the product of each two items at the same index of list `a` and list `b`
sum(i * j for i, j in zip(a, b))
m the product of elements of two lists named `a` and `b`
sum(x * y for x, y in list(zip(a, b)))
write the content of file `xxx.mp4` to file `f`
f.write(open('xxx.mp4', 'rb').read())
Add 1 to each integer value in list `my_list`
new_list = [(x + 1) for x in my_list]
get a list of all items in list `j` with values greater than `5`
[x for x in j if x >= 5]
et color marker styles `bo` in matplotlib
plt.plot(list(range(10)), '--bo')
et circle markers on plot for individual points defined in list `[1,2,3,4,5,6,7,8,9,10]` created by range(10)
plt.plot(list(range(10)), linestyle='--', marker='o', color='b')
plit strings in list `l` on the first occurring tab `\t` and enter only the first resulting substring in a new l
[i.split('\t', 1)[0] for i in l]
Split each string in list `myList` on the tab character
myList = [i.split('\t')[0] for i in myList]
Sum numbers in a list 'your_list'
sum(your_list)
ach debugger pdb to class `ForkedPdb`
ForkedPdb().set_trace()
Compose keys from dictionary `d1` with respective values in dictionary `d2`
result = {k: d2.get(v) for k, v in list(d1.items())}
dd one day and three hours to the present time from datetime.now()
datetime.datetime.now() + datetime.timedelta(days=1, hours=3)
Convert binary string to list of integers using Pytho
[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]
witch keys and values in a dictionary `my_dict`
dict((v, k) for k, v in my_dict.items())
a list `L` by number after second '.'
print(sorted(L, key=lambda x: int(x.split('.')[2])))
Check if the value of the key name is Test in a list of dictionaries `label`
any(d['name'] == 'Test' for d in label)
emove all instances of [1, 1] from list `a`
a[:] = [x for x in a if x != [1, 1]]
emove all instances of `[1, 1]` from a list `a`
[x for x in a if x != [1, 1]]
vert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value
b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}
heck whether elements in list `a` appear only once
len(set(a)) == len(a)
Generate MD5 checksum of file in the path `full_path` in hashlib
print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())
w 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 l
sorted(list(data.items()), key=lambda x: x[1][0])
andomly switch letters' cases in string `s`
"""""".join(x.upper() if random.randint(0, 1) else x for x in s)
force bash interpreter '/bin/bash' to be used instead of shell
os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
Run a command `echo hello world` in bash instead of shell
os.system('/bin/bash -c "echo hello world"')
ess the class variable `a_string` from a class object `test`
getattr(test, a_string)
Display a image file `pathToFile`
Image.open('pathToFile').show()
eplace single quote character in string didn't with empty string ''
"""didn't""".replace("'", '')
list `files` based on variable `file_number`
files.sort(key=file_number)
emove all whitespace in a string `sentence`
sentence.replace(' ', '')
emove all whitespace in a string `sentence`
pattern = re.compile('\\s+') sentence = re.sub(pattern, '', sentence)
emove whitespace in string `sentence` from beginning and end
sentence.strip()
emove all whitespaces in string `sentence`
sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)
emove all whitespaces in a string `sentence`
sentence = ''.join(sentence.split())
m all the values in a counter variable `my_counter`
sum(my_counter.values())
find the euclidean distance between two 3d arrays `A` and `B`
np.sqrt(((A - B) ** 2).sum(-1))
eate list `levels` containing 3 empty dictionarie
levels = [{}, {}, {}]
find the sums of length 7 subsets of a list `daily`
weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]
Delete an element `key` from a dictionary `d`
del d[key]
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')
Delete an element with key `key` dictionary `r`
del r[key]
lve for the least squares' solution of matrices `a` and `b`
np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))
plit dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`
pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
loop through 0 to 10 with step 2
for i in range(0, 10, 2): pass
loop through `mylist` with step 2
for i in mylist[::2]: pass
lowercase string values with key 'content' in a list of dictionaries `messages`
[{'content': x['content'].lower()} for x in messages]
vert a list `my_list` into string with values separated by space
""" """.join(my_list)
eplace each occurrence of the pattern '(http://\\S+|\\S*[^\\w\\s]\\S*)' within `a` with ''
re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)
heck if string `str` is palindrome
str(n) == str(n)[::-1]
pload binary file `myfile.txt` with ftplib
ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))
emove all characters from string `stri` upto character 'I'
re.sub('.*I', 'I', stri)
parse a commaseparated string number '1,000,000' into
int('1,000,000'.replace(',', ''))
mbine dataframe `df1` and dataframe `df2` by index number
pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
Combine two Pandas dataframes with the same index
pandas.concat([df1, df2], axis=1)
heck if all boolean values in a python dictionary `dict` are true
all(dict.values())
e regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeID` of dataframe `df`
df.c_contofficeID.str.replace('^12(?=.{4}$)', '')
everse a list `L`
L[::(-1)]
everse a list `array`
reversed(array)
everse a list `L`
L.reverse()
everse a list `array`
list(reversed(array))
get first element of each tuple in list `A`
[tup[0] for tup in A]
eplace character 'a' with character 'e' and character 's' with character '3' in file `contents`
newcontents = contents.replace('a', 'e').replace('s', '3')
erialise SqlAlchemy RowProxy object `row` to a json objec
json.dumps([dict(list(row.items())) for row in rs])
get file '~/foo.ini'
config_file = os.path.expanduser('~/foo.ini')
get multiple parameters with same name from a url in pylo
request.params.getall('c')
Convert array `x` into a correlation matrix
np.corrcoef(x)
Find the greatest number in set `(1, 2, 3)`
print(max(1, 2, 3))
Retrieve parameter 'var_name' from a GET request.
self.request.get('var_name')
Add 100 to each element of column x in dataframe `a`
a['x'].apply(lambda x, y: x + y, args=(100,))
Django get first 10 records of model `User` ordered by criteria 'age' of model 'pet'
User.objects.order_by('-pet__age')[:10]
delay for 5 second
time.sleep(5)
ke a 60 seconds time delay
time.sleep(60)
ke a 0.1 seconds time delay
sleep(0.1)
ke a 60 seconds time delay
time.sleep(60)
ke a 0.1 seconds time delay
time.sleep(0.1)
From a list of strings `my_list`, remove the values that contains numbers.
[x for x in my_list if not any(c.isdigit() for c in x)]
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])
draw a grid line on every tick of plot `plt`
plt.grid(True)