text
stringlengths
4
1.08k
check if all elements in a list 'lst' are the same type 'int',"all(isinstance(x, int) for x in lst)"
strip a string `line` of all carriage returns and newlines,line.strip()
scroll to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, Y)')"
scroll a to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')"
convert Date object `dateobject` into a DateTime object,"datetime.datetime.combine(dateobject, datetime.time())"
check if any item from list `b` is in list `a`,print(any(x in a for x in b))
save a numpy array `image_array` as an image 'outfile.jpg',"scipy.misc.imsave('outfile.jpg', image_array)"
Remove anything in parenthesis from string `item` with a regex,"item = re.sub(' ?\\([^)]+\\)', '', item)"
Remove word characters in parenthesis from string `item` with a regex,"item = re.sub(' ?\\(\\w+\\)', '', item)"
Remove all data inside parenthesis in string `item`,"item = re.sub(' \\(\\w+\\)', '', item)"
check if any elements in one list `list1` are in another list `list2`,len(set(list1).intersection(list2)) > 0
convert hex string `s` to decimal,"i = int(s, 16)"
"convert hex string ""0xff"" to decimal","int('0xff', 16)"
"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)"
take screenshot 'screen.png' on mac os x,os.system('screencapture screen.png')
"Set a window size to `1400, 1000` using selenium webdriver","driver.set_window_size(1400, 1000)"
replace non-ascii chars from a unicode string u'm\xfasica',"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')"
concatenate dataframe `df1` with `df2` whilst removing duplicates,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)"
Construct an array with data type float32 `a` from data in binary file 'filename',"a = numpy.fromfile('filename', dtype=numpy.float32)"
execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
print a character that has unicode value `\u25b2`,print('\u25b2'.encode('utf-8'))
compare contents at filehandles `file1` and `file2` using difflib,"difflib.SequenceMatcher(None, file1.read(), file2.read())"
"Create a dictionary from string `e` separated by `-` and `,`","dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))"
"check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`","all(i in (1, 2, 3, 4, 5) for i in (1, 6))"
extract unique dates from time series 'Date' in dataframe `df`,df['Date'].map(lambda t: t.date()).unique()
right align string `mystring` with a width of 7,"""""""{:>7s}"""""".format(mystring)"
read an excel file 'ComponentReport-DJI.xls',"open('ComponentReport-DJI.xls', 'rb').read(200)"
sort dataframe `df` based on column 'b' in ascending and column 'c' in descending,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)"
sort dataframe `df` based on column 'a' in ascending and column 'b' in descending,"df.sort_values(['a', 'b'], ascending=[True, False])"
sort a pandas data frame with column `a` in ascending and `b` in descending order,"df1.sort(['a', 'b'], ascending=[True, False], inplace=True)"
"sort a pandas data frame by column `a` in ascending, and by column `b` in descending order","df.sort(['a', 'b'], ascending=[True, False])"
django redirect to view 'Home.views.index',redirect('Home.views.index')
"remove all values within one list `[2, 3, 7]` from another list `a`","[x for x in a if x not in [2, 3, 7]]"
"remove the punctuation '!', '.', ':' from a string `asking`","out = ''.join(c for c in asking if c not in ('!', '.', ':'))"
BeautifulSoup get value associated with attribute 'content' where attribute 'name' is equal to 'City' in tag 'meta' in HTML parsed string `soup`,"soup.find('meta', {'name': 'City'})['content']"
unquote a urlencoded unicode string '%0a',urllib.parse.unquote('%0a')
decode url `url` from UTF-16 code to UTF-8 code,urllib.parse.unquote(url).decode('utf8')
empty a list `lst`,del lst[:]
empty a list `lst`,del lst1[:]
empty a list `lst`,lst[:] = []
empty a list `alist`,alist[:] = []
reset index of series `s`,s.reset_index(0).reset_index(drop=True)
convert unicode text from list `elems` with index 0 to normal text 'utf-8',elems[0].getText().encode('utf-8')
create a list containing the subtraction of each item in list `L` from the item prior to it,"[(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))"
import all classes from module `some.package`,globals().update(importlib.import_module('some.package').__dict__)
"convert 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('&')
sort dictionary `d` by key,od = collections.OrderedDict(sorted(d.items()))
sort 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)"
replace everything that is not an alphabet or a digit with '' in 's'.,"re.sub('[\\W_]+', '', s)"
create 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]
convert string `x' to dictionary splitted by `=` using list comprehension,dict([x.split('=') for x in s.split()])
remove index 2 element from a list `my_list`,my_list.pop(2)
"Delete character ""M"" from a string `s` using python","s = s.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))"
sum 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)))"
sum 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))"
sum 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]
set color marker styles `--bo` in matplotlib,"plt.plot(list(range(10)), '--bo')"
"set 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')"
split strings in list `l` on the first occurring tab `\t` and enter only the first resulting substring in a new list,"[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)
attach 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())}"
add one day and three hours to the present time from datetime.now(),"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)"
switch keys and values in a dictionary `my_dict`,"dict((v, k) for k, v in my_dict.items())"
sort 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)
"remove all instances of [1, 1] from list `a`","a[:] = [x for x in a if x != [1, 1]]"
"remove all instances of `[1, 1]` from a list `a`","[x for x in a if x != [1, 1]]"
"convert 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)}"
check 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())"
randomly 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""')"
access the class variable `a_string` from a class object `test`,"getattr(test, a_string)"
Display a image file `pathToFile`,Image.open('pathToFile').show()
"replace single quote character in string ""didn't"" with empty string ''","""""""didn't"""""".replace(""'"", '')"
sort list `files` based on variable `file_number`,files.sort(key=file_number)
remove all whitespace in a string `sentence`,"sentence.replace(' ', '')"
remove all whitespace in a string `sentence`,"pattern = re.compile('\\s+')
sentence = re.sub(pattern, '', sentence)"
remove whitespace in string `sentence` from beginning and end,sentence.strip()
remove all whitespaces in string `sentence`,"sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)"
remove all whitespaces in a string `sentence`,sentence = ''.join(sentence.split())
sum all the values in a counter variable `my_counter`,sum(my_counter.values())
find the euclidean distance between two 3-d arrays `A` and `B`,np.sqrt(((A - B) ** 2).sum(-1))
create list `levels` containing 3 empty dictionaries,"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]