question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
9,554,544
Python, running command line tools in parallel
subprocess run command 'start command -flags arguments' through the shell
subprocess.call('start command -flags arguments', shell=True)
9,554,544
Python, running command line tools in parallel
run command 'command -flags arguments &' on command line tools as separate processes
subprocess.call('command -flags arguments &', shell=True)
12,527,959
Passing the '+' character in a POST request in Python
replace percent-encoded code in request `f` to their single-character equivalent
f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))
2,372,573
How do I remove whitespace from the end of a string in Python?
remove white spaces from the end of string " xyz "
""" xyz """.rstrip()
8,905,864
URL encoding in python
Replace special characters in utf-8 encoded string `s` using the %xx escape
urllib.parse.quote(s.encode('utf-8'))
8,905,864
URL encoding in python
null
urllib.parse.quote_plus('a b')
28,207,743
Convert string to numpy array
Create an array containing the conversion of string '100110' into separate elements
np.array(map(int, '100110'))
28,207,743
Convert string to numpy array
convert a string 'mystr' to numpy array of integer values
print(np.array(list(mystr), dtype=int))
12,201,577
How can I convert an RGB image into grayscale in Python?
convert an rgb image 'messi5.jpg' into grayscale `img`
img = cv2.imread('messi5.jpg', 0)
11,584,773
sorting a graph by its edge weight. python
sort list `lst` in descending order based on the second item of each tuple in it
lst.sort(key=lambda x: x[2], reverse=True)
6,294,179
How to find all occurrences of an element in a list?
null
indices = [i for i, x in enumerate(my_list) if x == 'whatever']
18,050,937
How can I execute shell command with a | pipe in it
execute shell command 'grep -r PASSED *.log | sort -u | wc -l' with a | pipe in it
subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)
42,178,481
How to count the number of a specific character at the end of a string ignoring duplicates?
count the number of trailing question marks in string `my_text`
len(my_text) - len(my_text.rstrip('?'))
32,464,280
converting currency with $ to numbers in Python pandas
remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats
df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)
42,060,144
Conditionally fill a column of a pandas df with values of a different df
Merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`
df1.merge(df2, how='left', on='word')
30,628,176
Switch every pair of characters in a string
switch positions of each two adjacent characters in string `a`
print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')
1,892,339
How to make a window jump to the front?
make a window `root` jump to the front
root.attributes('-topmost', True)
1,892,339
How to make a window jump to the front?
make a window `root` jump to the front
root.lift()
17,731,822
Elegant way to convert list to hex string
Convert list of booleans `walls` into a hex string
hex(int(''.join([str(int(b)) for b in walls]), 2))
17,731,822
Elegant way to convert list to hex string
convert the sum of list `walls` into a hex presentation
hex(sum(b << i for i, b in enumerate(reversed(walls))))
15,286,401
Print multiple arguments in python
print the string `Total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.
print(('Total score for', name, 'is', score))
15,286,401
Print multiple arguments in python
print multiple arguments 'name' and 'score'.
print('Total score for {} is {}'.format(name, score))
15,286,401
Print multiple arguments in python
print a string using multiple strings `name` and `score`
print('Total score for %s is %s ' % (name, score))
15,286,401
Print multiple arguments in python
print string including multiple variables `name` and `score`
print(('Total score for', name, 'is', score))
30,650,254
Is it possible to serve a static html page at the root of a django project?
serve a static html page 'your_template.html' at the root of a django project
url('^$', TemplateView.as_view(template_name='your_template.html'))
12,096,252
use a list of values to select rows from a pandas dataframe
use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'A'
df[df['A'].isin([3, 6])]
521,502
How to get the concrete class name as a string?
null
instance.__class__.__name__
39,538,010
How can I execute Python code in a virtualenv from Matlab
execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab
system('/path/to/my/venv/bin/python myscript.py')
7,503,241
django models selecting single field
django return a QuerySet list containing the values of field 'eng_name' in model `Employees`
Employees.objects.values_list('eng_name', flat=True)
31,465,002
Python regex findall alternation behavior
find all digits in string '6,7)' and put them to a list
re.findall('\\d|\\d,\\d\\)', '6,7)')
983,354
How do I make python to wait for a pressed key
prompt string 'Press Enter to continue...' to the console
input('Press Enter to continue...')
21,947,035
Print string as hex literal python
print string "ABC" as hex literal
"""ABC""".encode('hex')
15,666,169
python + pymongo: how to insert a new field on an existing document in mongo from a for loop
insert a new field 'geolocCountry' on an existing document 'b' using pymongo
db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})
3,895,874
Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
Write a regex statement to match 'lol' to 'lolllll'.
re.sub('l+', 'l', 'lollll')
8,724,352
Getting the nth element using BeautifulSoup
BeautifulSoup find all 'tr' elements in HTML string `soup` at the five stride starting from the fourth element
rows = soup.findAll('tr')[4::5]
2,051,744
Reverse Y-Axis in PyPlot
reverse all x-axis points in pyplot
plt.gca().invert_xaxis()
2,051,744
Reverse Y-Axis in PyPlot
reverse y-axis in pyplot
plt.gca().invert_yaxis()
13,079,852
How do I stack two DataFrames next to each other in Pandas?
stack two dataframes next to each other in pandas
pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)
2,428,092
Creating a JSON response using Django and Python
create a json response `response_data`
return HttpResponse(json.dumps(response_data), content_type='application/json')
4,020,539
Process escape sequences in a string
decode escape sequences in string `myString`
myString.decode('string_escape')
16,874,598
How do I calculate the md5 checksum of a file in Python?
calculate the md5 checksum of a file named 'filename.exe'
hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()
7,657,457
Finding key from value in Python dictionary:
Find all keys from a dictionary `d` whose values are `desired_value`
[k for k, v in d.items() if v == desired_value]
11,399,384
Extract all keys from a list of dictionaries
create a set containing all keys' names from dictionary `LoD`
{k for d in LoD for k in list(d.keys())}
11,399,384
Extract all keys from a list of dictionaries
create a set containing all keys names from list of dictionaries `LoD`
set([i for s in [list(d.keys()) for d in LoD] for i in s])
11,399,384
Extract all keys from a list of dictionaries
extract all keys from a list of dictionaries `LoD`
[i for s in [list(d.keys()) for d in LoD] for i in s]
6,612,769
Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?
unpack keys and values of a dictionary `d` into two lists
keys, values = zip(*list(d.items()))
1,094,717
Convert a string to integer with decimal in Python
convert a string `s` containing a decimal to an integer
int(Decimal(s))
1,094,717
Convert a string to integer with decimal in Python
null
int(s.split('.')[0])
10,565,598
Numpy: How to check if array contains certain numbers?
check if array `b` contains all elements of array `a`
numpy.in1d(b, a).all()
10,565,598
Numpy: How to check if array contains certain numbers?
numpy: check if array 'a' contains all the numbers in array 'b'.
numpy.array([(x in a) for x in b])
15,548,506
Node labels using networkx
Draw node labels `labels` on networkx graph `G ` at position `pos`
networkx.draw_networkx_labels(G, pos, labels)
6,532,881
How to make a copy of a 2D array in Python?
make a row-by-row copy `y` of array `x`
y = [row[:] for row in x]
7,356,042
Pythonic way to populate numpy array
Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of values
X = numpy.loadtxt('somefile.csv', delimiter=',')
4,843,158
Check if a Python list item contains a string inside another string
get a list of items from the list `some_list` that contain string 'abc'
matching = [s for s in some_list if 'abc' in s]
11,041,411
How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file?
export a pandas data frame `df` to a file `mydf.tsv` and retain the indices
df.to_csv('mydf.tsv', sep='\t')
9,755,538
How do I create a LIST of unique random numbers?
null
random.sample(list(range(100)), 10)
15,012,228
Splitting on last delimiter in Python string?
split a string `s` on last delimiter
s.rsplit(',', 1)
13,252,333
Python check if all elements of a list are the same type
Check if all elements in list `lst` are tupples of long and int
all(isinstance(x, int) for x in lst)
13,252,333
Python check if all elements of a list are the same type
check if all elements in a list 'lst' are the same type 'int'
all(isinstance(x, int) for x in lst)
13,656,519
Python . How to get rid of '\r' in string?
strip a string `line` of all carriage returns and newlines
line.strip()
20,986,631
How can I scroll a web page using selenium webdriver in python?
scroll to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, Y)')
20,986,631
How can I scroll a web page using selenium webdriver in python?
scroll a to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
11,619,169
How do I convert a datetime.date object into datetime.datetime in python?
convert Date object `dateobject` into a DateTime object
datetime.datetime.combine(dateobject, datetime.time())
740,287
How to check if one of the following items is in a list?
check if any item from list `b` is in list `a`
print(any(x in a for x in b))
902,761
Saving a Numpy array as an image
save a numpy array `image_array` as an image 'outfile.jpg'
scipy.misc.imsave('outfile.jpg', image_array)
19,794,051
Regex for removing data in parenthesis
Remove anything in parenthesis from string `item` with a regex
item = re.sub(' ?\\([^)]+\\)', '', item)
19,794,051
Regex for removing data in parenthesis
Remove word characters in parenthesis from string `item` with a regex
item = re.sub(' ?\\(\\w+\\)', '', item)
19,794,051
Regex for removing data in parenthesis
Remove all data inside parenthesis in string `item`
item = re.sub(' \\(\\w+\\)', '', item)
16,138,015
Checking if any elements in one list are in another
check if any elements in one list `list1` are in another list `list2`
len(set(list1).intersection(list2)) > 0
9,210,525
convert hex to decimal
convert hex string `s` to decimal
i = int(s, 16)
9,210,525
convert hex to decimal
convert hex string "0xff" to decimal
int('0xff', 16)
9,210,525
convert hex to decimal
convert hex string "FFFF" to decimal
int('FFFF', 16)
9,210,525
convert hex to decimal
convert hex string '0xdeadbeef' to decimal
ast.literal_eval('0xdeadbeef')
9,210,525
convert hex to decimal
convert hex string 'deadbeef' to decimal
int('deadbeef', 16)
4,524,723
Take screenshot in Python on Mac OS X
take screenshot 'screen.png' on mac os x
os.system('screencapture screen.png')
21,899,953
How to set window size using phantomjs and selenium webdriver in python
Set a window size to `1400, 1000` using selenium webdriver
driver.set_window_size(1400, 1000)
3,704,731
Replace non-ascii chars from a unicode string in Python
replace non-ascii chars from a unicode string u'm\xfasica'
unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')
21,317,384
Pandas/Python: How to concatenate two dataframes without duplicates?
concatenate dataframe `df1` with `df2` whilst removing duplicates
pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)
4,365,964
numpy: efficiently reading a large array
Construct an array with data type float32 `a` from data in binary file 'filename'
a = numpy.fromfile('filename', dtype=numpy.float32)
21,804,935
How to use the mv command in Python with subprocess
execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess
subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)
21,804,935
How to use the mv command in Python with subprocess
null
subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)
16,658,068
How to use Unicode characters in a python string
print a character that has unicode value `\u25b2`
print('\u25b2'.encode('utf-8'))
977,491
Comparing two .txt files using difflib in Python
compare contents at filehandles `file1` and `file2` using difflib
difflib.SequenceMatcher(None, file1.read(), file2.read())
4,627,981
Creating a dictionary from a string
Create a dictionary from string `e` separated by `-` and `,`
dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))
34,468,983
How to check if all elements in a tuple or list are in another?
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))
14,673,394
python pandas extract unique dates from time series
extract unique dates from time series 'Date' in dataframe `df`
df['Date'].map(lambda t: t.date()).unique()
16,159,228
Formatting text to be justified in Python 3.3 with .format() method
right align string `mystring` with a width of 7
"""{:>7s}""".format(mystring)
118,516
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?
read an excel file 'ComponentReport-DJI.xls'
open('ComponentReport-DJI.xls', 'rb').read(200)
17,141,558
How to sort a dataFrame in python pandas by two or more columns?
sort dataframe `df` based on column 'b' in ascending and column 'c' in descending
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
17,141,558
How to sort a dataFrame in python pandas by two or more columns?
sort dataframe `df` based on column 'a' in ascending and column 'b' in descending
df.sort_values(['a', 'b'], ascending=[True, False])
17,141,558
How to sort a dataFrame in python pandas by two or more columns?
sort a pandas data frame with column `a` in ascending and `b` in descending order
df1.sort(['a', 'b'], ascending=[True, False], inplace=True)
17,141,558
How to sort a dataFrame in python pandas by two or more columns?
sort a pandas data frame by column `a` in ascending, and by column `b` in descending order
df.sort(['a', 'b'], ascending=[True, False])
7,284,952
Django redirect to root from a view
django redirect to view 'Home.views.index'
redirect('Home.views.index')
2,514,961
Remove all values within one list from another list in python
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]]
16,050,952
How to remove all the punctuation in a string? (Python)
remove the punctuation '!', '.', ':' from a string `asking`
out = ''.join(c for c in asking if c not in ('!', '.', ':'))
11,205,386
Python: BeautifulSoup - get an attribute value based on the name attribute
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']
300,445
How to unquote a urlencoded unicode string in python?
unquote a urlencoded unicode string '%0a'
urllib.parse.unquote('%0a')
300,445
How to unquote a urlencoded unicode string in python?
decode url `url` from UTF-16 code to UTF-8 code
urllib.parse.unquote(url).decode('utf8')
1,400,608
empty a list
empty a list `lst`
del lst[:]
1,400,608
empty a list
empty a list `lst`
del lst1[:]