prompt
stringlengths
4
181
completion
stringlengths
2
232
earche in HTML string for elements that have text 'Python'
soup.body.findAll(text='Python')
BeautifulSoup find string 'Python Jobs' in HTML body `body`
soup.body.findAll(text='Python Jobs')
Sort items in dictionary `d` using the first part of the key after splitting the key
sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))
eate a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]
set([1, 2, 3]) ^ set([3, 4, 5])
Get a list values of a dictionary item `pass_id` from post requests in django
request.POST.getlist('pass_id')
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())
Get pandas GroupBy object with sum over the rows with same column names within dataframe `df`
df.groupby(df.columns, axis=1).sum()
vert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary
dict(zip(list(range(1, 5)), list(range(7, 11))))
Get all indexes of boolean numpy array where boolean value `mask` is True
numpy.where(mask)
ase insensitive comparison of strings `string1` and `string2`
if (string1.lower() == string2.lower()): print('The strings are the same (case insensitive)') else: print('The strings are not the same (case insensitive)')
ase insensitive string comparison between `string1` and `string2`
if (string1.lower() == string2.lower()): pass
ase insensitive string comparison between `string1` and `string2`
(string1.lower() == string2.lower())
ase insensitive string comparison between `first` and `second`
(first.lower() == second.lower())
ase insensitive comparison between strings `first` and `second`
(first.upper() == second.upper())
Taking the results of a bash command awk '{print $10, $11}' test.txt > test2.txt
os.system("awk '{print $10, $11}' test.txt > test2.txt")
emove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.
del my_list[2:6]
vert a string `s` to its base10 representatio
int(s.encode('hex'), 16)
h regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`
re.findall('TAA(?:[ATGC]{3})+?TAA', seq)
a set `s` by numerical value
sorted(s, key=float)
vert an int 65 to hex string
hex(65)
ppend a pandas series `b` to the series `a` and get a continuous index
a.append(b).reset_index(drop=True)
mple way to append a pandas series `a` and `b` with same index
pd.concat([a, b], ignore_index=True)
Get a list of tuples with multiple iterators using list comprehensio
[(i, j) for i in range(1, 3) for j in range(1, 5)]
everse sort items in dictionary `mydict` by value
sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)
elect the last business day of the month for each month in 2014 in pand
pd.date_range('1/1/2014', periods=12, freq='BM')
disable the certificate check in https requests for url `https://kennethreitz.com`
requests.get('https://kennethreitz.com', verify=False)
eturn dataframe `df` with last row dropped
df.ix[:-1]
heck if blah is in string `somestring`
if ('blah' not in somestring): pass
heck if string `needle` is in `haystack`
if (needle in haystack): pass
heck if string substring is in string
string.find('substring')
heck if string `s` contains is
if (s.find('is') == (-1)): print("No 'is' here!") else: print("Found 'is' in the string.")
extract first and last row of a dataframe `df`
pd.concat([df.head(1), df.tail(1)])
filter a Django model `MyModel` to have charfield length of max `255`
MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254'])
Filter queryset for all objects in Django model `MyModel` where texts length are greater than `254`
MyModel.objects.filter(text__regex='^.{254}.*')
he number of rows with missing values in a pandas dataframe `df`
sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)
Sorting while preserving order in pytho
sorted(enumerate(a), key=lambda x: x[1])
et the font 'Purisa' of size 12 for a canvas' text item `k`
canvas.create_text(x, y, font=('Purisa', 12), text=k)
eate a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehensio
[y['baz'] for x in foos for y in x['bar']]
ead pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`
df = pd.read_csv('comma.csv', quotechar="'")
eplace string 'in.' with ' in. ' in dataframe `df` column 'a'
df['a'] = df['a'].str.replace('in.', ' in. ')
Get all indexes of a list `a` where each value is greater than `2`
[i for i in range(len(a)) if a[i] > 2]
heck if a local variable `myVar` ex
('myVar' in locals())
heck if a global variable `myVar` ex
('myVar' in globals())
heck if object `obj` has attribute 'attr_name'
hasattr(obj, 'attr_name')
heck if a local variable 'myVar' ex
if ('myVar' in locals()): pass
heck if a global variable 'myVar' ex
if ('myVar' in globals()): pass
lambda function that adds two operand
lambda x, y: x + y
he number of items in a generator/iterator `it`
sum(1 for i in it)
get tuples of the corresponding elements from lists `lst` and `lst2`
[(x, lst2[i]) for i, x in enumerate(lst)]
eate tuples containing elements that are at the same index of list `lst` and list `lst2`
[(i, j) for i, j in zip(lst, lst2)]
get tuples from lists `lst` and `lst2` using list comprehension in python 2
[(lst[i], lst2[i]) for i in range(len(lst))]
vert hex triplet string `rgbstr` to rgb tuple
struct.unpack('BBB', rgbstr.decode('hex'))
Check if 3 is not in a list [2, 3, 4]
(3 not in [2, 3, 4])
Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]
((2, 3) not in [(2, 3), (5, 6), (9, 1)])
Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), hi]
((2, 3) not in [(2, 7), (7, 3), 'hi'])
Check if 3 is not in the list [4,5,6]
(3 not in [4, 5, 6])
eate a list by appending components from list `a` and reversed list `b` interchangeably
[value for pair in zip(a, b[::-1]) for value in pair]
delete the last column of numpy array `a` and assign resulting array to `b`
b = np.delete(a, -1, 1)
mmit all the changes after executing a query.
dbb.commit()
join two dataframes based on values in selected colum
pd.merge(a, b, on=['A', 'B'], how='outer')
et text color as `red` and background color as `#A3C1DA` in qpushbutto
setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
find the mean of elements in list `l`
sum(l) / float(len(l))
Find all the items from a dictionary `D` if the key contains the string `Light`
[(k, v) for k, v in D.items() if 'Light' in k]
Get a md5 hash from string `thecakeisalie`
k = hashlib.md5('thecakeisalie').hexdigest()
w to get only the last part of a path in Python?
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
datetime objects `birthdays` by `month` and `day`
birthdays.sort(key=lambda d: (d.month, d.day))
extract table data from table `rows` using beautifulsoup
[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
p the string `.txt` from anywhere in the string `Boat.txt.txt`
"""Boat.txt.txt""".replace('.txt', '')
get a list of the row names from index of a pandas data frame
list(df.index)
get the row names from index in a pandas data frame
df.index
eate a list of all unique characters in string 'aaabcabccd'
"""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))
get list of all unique characters in a string 'aaabcabccd'
list(set('aaabcabccd'))
List of all unique characters in a string?
"""""".join(set('aaabcabccd'))
find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe
df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]
pload file with Python Mechanize
br.form.add_file(open(filename), 'text/plain', filename)
heck if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`
all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])
hide output of subprocess `['espeak', text]`
subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)
eplace nans by preceding values in pandas dataframe `df`
df.fillna(method='ffill', inplace=True)
eate 4 numbers in range between 1 and 3
print(np.linspace(1, 3, num=4, endpoint=False))
Create numpy array of `5` numbers starting from `1` with interval of `3`
print(np.linspace(1, 3, num=5))
eate a symlink directory `D:\\testdirLink` for directory `D:\\testdir` with unicode support using ctypes library
kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)
get a list `slice` of array slices of the first two rows and columns from array `arr`
slice = [arr[i][0:2] for i in range(0, 2)]
pload uploaded file from path '/upload' to Google cloud storage 'my_bucket' bucke
upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')
hange directory to the directory of a python scrip
os.chdir(os.path.dirname(__file__))
all a function with argument list `args`
func(*args)
plit column 'AB' in dataframe `df` into two columns by first whitespace ' '
df['AB'].str.split(' ', 1, expand=True)
pandas dataframe, how do i split a column 'AB' into two 'A' and 'B' on delimiter ' '
df['A'], df['B'] = df['AB'].str.split(' ', 1).str
list `xs` based on the length of its eleme
print(sorted(xs, key=len))
list `xs` in ascending order of length of eleme
xs.sort(lambda x, y: cmp(len(x), len(y)))
list of strings `xs` by the length of string
xs.sort(key=lambda s: len(s))
plot point marker '.' on series `ts`
ts.plot(marker='.')
get all combination of n binary value
lst = list(itertools.product([0, 1], repeat=n))
get all combination of n binary value
lst = map(list, itertools.product([0, 1], repeat=n))
get all combination of 3 binary value
bin = [0, 1] [(x, y, z) for x in bin for y in bin for z in bin]
get all combination of 3 binary value
lst = list(itertools.product([0, 1], repeat=3))
ppend string 'str' at the beginning of each value in column 'col' of dataframe `df`
df['col'] = 'str' + df['col'].astype(str)
get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their value
dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])
dd a colorbar to plot `plt` using image `im` on axes `ax`
plt.colorbar(im, ax=ax)
vert nested list 'Cards' into a flat l
[a for c in Cards for b in c for a in b]
eate a list containing keys of dictionary `d` and sort it alphabetically
sorted(d, key=d.get)