question_id
int64 1.48k
42.8M
| intent
stringlengths 11
122
| rewritten_intent
stringlengths 4
183
⌀ | snippet
stringlengths 2
232
|
---|---|---|---|
53,513 |
check if a list is empty
|
check if list `a` is empty
|
if (not a):
pass
|
53,513 |
check if a list is empty
|
check if list `seq` is empty
|
if (not seq):
pass
|
53,513 |
check if a list is empty
|
check if list `li` is empty
|
if (len(li) == 0):
pass
|
13,717,463 |
Find the indices of elements greater than x
|
create a list containing the indices of elements greater than 4 in list `a`
|
[i for i, v in enumerate(a) if v > 4]
|
13,237,941 |
sorting list of nested dictionaries in python
|
reverse list `yourdata`
|
sorted(yourdata, reverse=True)
|
13,237,941 |
sorting list of nested dictionaries in python
|
sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey'
|
sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)
|
13,237,941 |
sorting list of nested dictionaries in python
|
sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey'
|
yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
|
37,084,812 |
How to remove decimal points in pandas
|
remove decimal points in pandas data frame using round
|
df.round()
|
8,938,449 |
How to extract data from matplotlib plot
|
Get data from matplotlib plot
|
gca().get_lines()[n].get_xydata()
|
37,125,495 |
How to get the N maximum values per row in a numpy ndarray?
|
get the maximum 2 values per row in array `A`
|
A[:, -2:]
|
23,531,030 |
MultiValueDictKeyError in Django
|
Get value for "username" parameter in GET request in Django
|
request.GET.get('username', '')
|
4,301,069 |
Any way to properly pretty-print ordered dictionaries in Python?
|
pretty-print ordered dictionary `o`
|
pprint(dict(list(o.items())))
|
32,458,541 |
Django can't find URL pattern
|
Confirm urls in Django properly
|
url('^$', include('sms.urls')),
|
32,458,541 |
Django can't find URL pattern
|
Configure url in django properly
|
url('^', include('sms.urls')),
|
1,874,194 |
Pythonic way to get the largest item in a list
|
get the tuple in list `a_list` that has the largest item in the second index
|
max_item = max(a_list, key=operator.itemgetter(1))
|
1,874,194 |
Pythonic way to get the largest item in a list
|
find tuple in list of tuples `a_list` with the largest second element
|
max(a_list, key=operator.itemgetter(1))
|
29,100,599 |
How to iterate over time periods in pandas
|
resample series `s` into 3 months bins and sum each bin
|
s.resample('3M', how='sum')
|
2,621,674 |
how to extract elements from a list in python?
|
extract elements at indices (1, 2, 5) from a list `a`
|
[a[i] for i in (1, 2, 5)]
|
5,245,058 |
Python: Filter lines from a text file which contain a particular word
|
filter lines from a text file 'textfile' which contain a word 'apple'
|
[line for line in open('textfile') if 'apple' in line]
|
2,721,782 |
How to convert a Date string to a DateTime object?
|
convert a date string `s` to a datetime object
|
datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
|
27,896,214 |
Reading tab-delimited file with Pandas - works on Windows, but not on Mac
|
reading tab-delimited csv file `filename` with pandas on mac
|
pandas.read_csv(filename, sep='\t', lineterminator='\r')
|
4,628,618 |
Replace first occurence of string
|
replace only first occurence of string `TEST` from a string `longlongTESTstringTEST`
|
'longlongTESTstringTEST'.replace('TEST', '?', 1)
|
12,777,222 |
How can I zip file with a flattened directory structure using Zipfile in Python?
|
zip file `pdffile` using its basename as directory name
|
archive.write(pdffile, os.path.basename(pdffile))
|
3,457,673 |
Elegant way to create a dictionary of pairs, from a list of tuples?
|
create a dictionary of pairs from a list of tuples `myListOfTuples`
|
dict(x[1:] for x in reversed(myListOfTuples))
|
8,194,156 |
How to subtract two lists in python
|
subtract elements of list `List1` from elements of list `List2`
|
[(x1 - x2) for x1, x2 in zip(List1, List2)]
|
5,577,501 |
How to tell if string starts with a number?
|
check if string `string` starts with a number
|
string[0].isdigit()
|
5,577,501 |
How to tell if string starts with a number?
|
Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
|
strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
|
4,934,806 |
How can I find script's directory with Python?
|
print script's directory
|
print(os.path.dirname(os.path.realpath(__file__)))
|
15,530,399 |
Finding the surrounding sentence of a char/word in a string
|
split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)'
|
re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)
|
21,519,203 |
Plotting a list of (x, y) coordinates in python matplotlib
|
Make a scatter plot using unpacked values of list `li`
|
plt.scatter(*zip(*li))
|
16,040,156 |
Rearrange tuple of tuples in Python
|
rearrange tuple of tuples `t`
|
tuple(zip(*t))
|
40,963,347 |
Find Average of Every Three Columns in Pandas dataframe
|
Get average for every three columns in `df` dataframe
|
df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()
|
180,606 |
How do I convert a list of ascii values to a string in python?
|
convert a list `L` of ascii values to a string
|
"""""".join(chr(i) for i in L)
|
13,462,365 |
Python 2.7 Counting number of dictionary items with given value
|
count the number of pairs in dictionary `d` whose value equal to `chosen_value`
|
sum(x == chosen_value for x in list(d.values()))
|
13,462,365 |
Python 2.7 Counting number of dictionary items with given value
|
count the number of values in `d` dictionary that are predicate to function `some_condition`
|
sum(1 for x in list(d.values()) if some_condition(x))
|
13,291,539 |
convert double to float in Python
|
convert double 0.00582811585976 to float
|
struct.unpack('f', struct.pack('f', 0.00582811585976))
|
8,777,753 |
Converting datetime.date to UTC timestamp in Python
|
convert datetime.date `dt` to utc timestamp
|
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
|
13,838,405 |
Custom sorting in pandas dataframe
|
sort column `m` in panda dataframe `df`
|
df.sort('m')
|
3,766,633 |
How to sort with lambda in Python
|
Sort a data `a` in descending order based on the `modified` attribute of elements using lambda function
|
a = sorted(a, key=lambda x: x.modified, reverse=True)
|
39,604,780 |
How can I print the Truth value of a variable?
|
print the truth value of `a`
|
print(bool(a))
|
42,142,756 |
How can I change a specific row label in a Pandas dataframe?
|
rename `last` row index label in dataframe `df` to `a`
|
df = df.rename(index={last: 'a'})
|
28,416,408 |
Scikit-learn: How to run KMeans on a one-dimensional array?
|
Fit Kmeans function to a one-dimensional array `x` by reshaping it to be a multidimensional array of single values
|
km.fit(x.reshape(-1, 1))
|
17,608,210 |
sorting a list in python
|
Sort a list of strings 'words' such that items starting with 's' come first.
|
sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)
|
21,414,159 |
login to a site using python and opening the login site in the browser
|
open the login site 'http://somesite.com/adminpanel/index.php' in the browser
|
webbrowser.open('http://somesite.com/adminpanel/index.php')
|
8,654,637 |
Pythonic way to fetch all elements in a dictionary, falling between two keys?
|
fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4
|
dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)
|
8,654,637 |
Pythonic way to fetch all elements in a dictionary, falling between two keys?
|
fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4
|
dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)
|
13,668,393 |
python sorting two lists
|
sort two lists `list1` and `list2` together using lambda function
|
[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]
|
10,543,303 |
number of values in a list greater than a certain number
|
get the number of values in list `j` that is greater than 5
|
sum(((i > 5) for i in j))
|
10,543,303 |
number of values in a list greater than a certain number
|
get the number of values in list `j` that is greater than 5
|
len([1 for i in j if (i > 5)])
|
10,543,303 |
number of values in a list greater than a certain number
|
get the number of values in list `j` that is greater than `i`
|
j = np.array(j)
sum((j > i))
|
12,655,007 |
Python: elegant way of creating a list of tuples?
|
zip list `a`, `b`, `c` into a list of tuples
|
[(x + tuple(y)) for x, y in zip(zip(a, b), c)]
|
16,249,440 |
Changing file permission in python
|
changing permission of file `path` to `stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH`
|
os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
|
26,727,314 |
Multiple files for one argument in argparse Python 2.7
|
argparse associate zero or more arguments with flag 'file'
|
parser.add_argument('file', nargs='*')
|
32,996,293 |
Comparing values in two lists in Python
|
get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal
|
z = [(i == j) for i, j in zip(x, y)]
|
32,996,293 |
Comparing values in two lists in Python
|
create a list which indicates whether each element in `x` and `y` is identical
|
[(x[i] == y[i]) for i in range(len(x))]
|
4,289,331 |
Python: Extract numbers from a string
| null |
[int(s) for s in re.findall('\\b\\d+\\b', "he33llo 42 I'm a 32 string 30")]
|
18,176,933 |
Create an empty data frame with index from another data frame
|
create an empty data frame `df2` with index from another data frame `df1`
|
df2 = pd.DataFrame(index=df1.index)
|
826,284 |
How do I convert a string 2 bytes long to an integer in python
|
unpack first and second bytes of byte string `pS` into integer
|
struct.unpack('h', pS[0:2])
|
16,677,816 |
Printing lists onto tables in python
|
print list `t` into a table-like shape
|
print('\n'.join(' '.join(map(str, row)) for row in t))
|
28,161,356 |
Sort Pandas Dataframe by Date
| null |
df.sort_values(by='Date')
|
14,442,636 |
How can I check if a checkbox is checked in Selenium Python Webdriver?
|
check if a checkbox is checked in selenium python webdriver
|
driver.find_element_by_name('<check_box_name>').is_selected()
|
14,442,636 |
How can I check if a checkbox is checked in Selenium Python Webdriver?
|
determine if checkbox with id '<check_box_id>' is checked in selenium python webdriver
|
driver.find_element_by_id('<check_box_id>').is_selected()
|
2,951,701 |
Is it possible to use 'else' in a python list comprehension?
|
replace `0` with `2` in the list `[0, 1, 0, 3]`
|
[(a if a else 2) for a in [0, 1, 0, 3]]
|
30,747,705 |
Parsing string containing Unicode character names
|
Produce a string that is suitable as Unicode literal from string 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'
|
'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape')
|
30,747,705 |
Parsing string containing Unicode character names
|
Parse a unicode string `M\\N{AMPERSAND}M\\N{APOSTROPHE}s`
|
'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape')
|
867,866 |
Convert unicode codepoint to UTF8 hex in python
|
convert Unicode codepoint to utf8 hex
|
chr(int('fd9b', 16)).encode('utf-8')
|
13,277,440 |
How can I get Python to use upper case letters to print hex values?
|
use upper case letters to print hex value `value`
|
print('0x%X' % value)
|
16,099,694 |
How to remove empty string in a list?
|
get a list `cleaned` that contains all non-empty elements in list `your_list`
|
cleaned = [x for x in your_list if x]
|
13,324,554 |
Python: Want to use a string as a slice specifier
|
create a slice object using string `string_slice`
|
slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
|
24,748,445 |
Beautiful Soup Using Regex to Find Tags?
|
Find all the tags `a` and `div` from Beautiful Soup object `soup`
|
soup.find_all(['a', 'div'])
|
7,142,062 |
Get function name as a string in python
|
get the name of function `func` as a string
|
print(func.__name__)
|
10,472,907 |
How to convert dictionary into string
|
convert dictionary `adict` into string
|
"""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))
|
10,472,907 |
How to convert dictionary into string
|
convert dictionary `adict` into string
|
"""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))
|
2,612,802 |
copy a list
|
copy list `old_list` as `new_list`
|
new_list = old_list[:]
|
2,612,802 |
copy a list
|
copy list `old_list` as `new_list`
|
new_list = list(old_list)
|
2,612,802 |
copy a list
|
copy list `old_list` as `new_list`
|
new_list = copy.copy(old_list)
|
2,612,802 |
copy a list
|
deep copy list `old_list` as `new_list`
|
new_list = copy.deepcopy(old_list)
|
2,612,802 |
copy a list
|
make a copy of list `old_list`
|
[i for i in old_list]
|
25,540,259 |
Remove or adapt border of frame of legend using matplotlib
|
remove frame of legend in plot `plt`
|
plt.legend(frameon=False)
|
38,147,259 |
How to work with surrogate pairs in Python?
|
Print a emoji from a string `\\ud83d\\ude4f` having surrogate pairs
|
"""\\ud83d\\ude4f""".encode('utf-16', 'surrogatepass').decode('utf-16')
|
3,061 |
Calling a function of a module from a string with the function's name in Python
|
calling a function named 'myfunction' in the module
|
globals()['myfunction']()
|
1,949,318 |
Checking if a website is up
|
Check the status code of url "http://www.stackoverflow.com"
|
urllib.request.urlopen('http://www.stackoverflow.com').getcode()
|
1,949,318 |
Checking if a website is up
|
Check the status code of url "www.python.org"
|
conn = httplib.HTTPConnection('www.python.org')
conn.request('HEAD', '/')
r1 = conn.getresponse()
print(r1.status, r1.reason)
|
1,949,318 |
Checking if a website is up
|
Check the status code of url `url`
|
r = requests.head(url)
return (r.status_code == 200)
|
1,949,318 |
Checking if a website is up
|
Checking if website "http://www.stackoverflow.com" is up
|
print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())
|
23,931,444 |
Selenium open pop up window [Python]
|
Selenium `driver` click a hyperlink with the pattern "a[href^='javascript']"
|
driver.find_element_by_css_selector("a[href^='javascript']").click()
|
17,098,654 |
How to store data frame using PANDAS, Python
|
store data frame `df` to file `file_name` using pandas, python
|
df.to_pickle(file_name)
|
40,311,987 |
Pandas: Mean of columns with the same names
|
calculate the mean of columns with same name in dataframe `df`
|
df.groupby(by=df.columns, axis=1).mean()
|
4,768,151 |
How to perform double sort inside an array?
|
sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order
|
bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)
|
1,962,795 |
How to get alpha value of a PNG image with PIL?
|
get alpha value `alpha` of a png image `img`
|
alpha = img.split()[-1]
|
22,749,706 |
How to get the length of words in a sentence?
| null |
[len(x) for x in s.split()]
|
3,945,750 |
Find a specific tag with BeautifulSoup
|
BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup`
|
soup.findAll('div', style='width=300px;')
|
9,336,270 |
Using a Python dict for a SQL INSERT statement
|
Execute SQL statement `sql` with values of dictionary `myDict` as parameters
|
cursor.execute(sql, list(myDict.values()))
|
32,533,944 |
Preserving Column Order - Python Pandas and Column Concat
|
Convert CSV file `Result.csv` to Pandas dataframe using separator ' '
|
df.to_csv('Result.csv', index=False, sep=' ')
|
8,306,171 |
Python: Extract variables out of namespace
|
update the `globals()` dictionary with the contents of the `vars(args)` dictionary
|
globals().update(vars(args))
|
9,889,635 |
Regular expression to return all characters between two special characters
|
find all substrings in `mystring` beginning and ending with square brackets
|
re.findall('\\[(.*?)\\]', mystring)
|
2,075,128 |
Python, print all floats to 2 decimal places in output
|
Format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places.
|
print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))
|
8,425,046 |
The best way to filter a dictionary in Python
|
Remove all items from a dictionary `d` where the values are less than `1`
|
d = dict((k, v) for k, v in d.items() if v > 0)
|
8,425,046 |
The best way to filter a dictionary in Python
|
Filter dictionary `d` to have items with value greater than 0
|
d = {k: v for k, v in list(d.items()) if v > 0}
|
17,690,738 |
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?
|
convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe
|
pd.to_datetime(pd.Series(date_stngs))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.