prompt
stringlengths
4
181
completion
stringlengths
2
232
bprocess run command 'start command flags arguments' through the shell
subprocess.call('start command -flags arguments', shell=True)
mmand 'command flags arguments &' on command line tools as separate processe
subprocess.call('command -flags arguments &', shell=True)
eplace percentencoded code in request `f` to their singlecharacter equivale
f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))
emove white spaces from the end of string xyz
""" xyz """.rstrip()
Replace special characters in utf8 encoded string `s` using the %xx escape
urllib.parse.quote(s.encode('utf-8'))
URL encoding in pytho
urllib.parse.quote_plus('a b')
Create an array containing the conversion of string '100110' into separate eleme
np.array(map(int, '100110'))
vert a string 'mystr' to numpy array of integer value
print(np.array(list(mystr), dtype=int))
vert an rgb image 'messi5.jpg' into grayscale `img`
img = cv2.imread('messi5.jpg', 0)
list `lst` in descending order based on the second item of each tuple in
lst.sort(key=lambda x: x[2], reverse=True)
w to find all occurrences of an element in a list?
indices = [i for i, x in enumerate(my_list) if x == 'whatever']
execute shell command 'grep r PASSED *.log | sort u | wc l' with a | pipe in
subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)
he number of trailing question marks in string `my_text`
len(my_text) - len(my_text.rstrip('?'))
emove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into flo
df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)
Merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`
df1.merge(df2, how='left', on='word')
witch 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 '')
ke a window `root` jump to the fro
root.attributes('-topmost', True)
ke a window `root` jump to the fro
root.lift()
Convert list of booleans `walls` into a hex string
hex(int(''.join([str(int(b)) for b in walls]), 2))
vert the sum of list `walls` into a hex presentatio
hex(sum(b << i for i, b in enumerate(reversed(walls))))
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))
print multiple arguments 'name' and 'score'.
print('Total score for {} is {}'.format(name, score))
print a string using multiple strings `name` and `score`
print('Total score for %s is %s ' % (name, score))
print string including multiple variables `name` and `score`
print(('Total score for', name, 'is', score))
erve a static html page 'your_template.html' at the root of a django projec
url('^$', TemplateView.as_view(template_name='your_template.html'))
e a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'A'
df[df['A'].isin([3, 6])]
w to get the concrete class name as a string?
instance.__class__.__name__
execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab
system('/path/to/my/venv/bin/python myscript.py')
django return a QuerySet list containing the values of field 'eng_name' in model `Employees`
Employees.objects.values_list('eng_name', flat=True)
find all digits in string '6,7)' and put them to a l
re.findall('\\d|\\d,\\d\\)', '6,7)')
prompt string 'Press Enter to continue...' to the console
input('Press Enter to continue...')
print string ABC as hex literal
"""ABC""".encode('hex')
ert a new field 'geolocCountry' on an existing document 'b' using pymongo
db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})
Write a regex statement to match 'lol' to 'lolllll'.
re.sub('l+', 'l', 'lollll')
BeautifulSoup find all 'tr' elements in HTML string `soup` at the five stride starting from the fourth eleme
rows = soup.findAll('tr')[4::5]
everse all xaxis points in pyplo
plt.gca().invert_xaxis()
everse yaxis in pyplo
plt.gca().invert_yaxis()
ack two dataframes next to each other in pand
pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)
eate a json response `response_data`
return HttpResponse(json.dumps(response_data), content_type='application/json')
decode escape sequences in string `myString`
myString.decode('string_escape')
alculate the md5 checksum of a file named 'filename.exe'
hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()
Find all keys from a dictionary `d` whose values are `desired_value`
[k for k, v in d.items() if v == desired_value]
eate a set containing all keys' names from dictionary `LoD`
{k for d in LoD for k in list(d.keys())}
eate 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])
extract all keys from a list of dictionaries `LoD`
[i for s in [list(d.keys()) for d in LoD] for i in s]
pack keys and values of a dictionary `d` into two l
keys, values = zip(*list(d.items()))
vert a string `s` containing a decimal to an integer
int(Decimal(s))
Convert a string to integer with decimal in Pytho
int(s.split('.')[0])
heck if array `b` contains all elements of array `a`
numpy.in1d(b, a).all()
py: check if array 'a' contains all the numbers in array 'b'.
numpy.array([(x in a) for x in b])
Draw node labels `labels` on networkx graph `G ` at position `pos`
networkx.draw_networkx_labels(G, pos, labels)
ke a rowbyrow copy `y` of array `x`
y = [row[:] for row in x]
Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of value
X = numpy.loadtxt('somefile.csv', delimiter=',')
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]
export a pandas data frame `df` to a file `mydf.tsv` and retain the indice
df.to_csv('mydf.tsv', sep='\t')
w do I create a LIST of unique random numbers?
random.sample(list(range(100)), 10)
plit a string `s` on last delimiter
s.rsplit(',', 1)
Check if all elements in list `lst` are tupples of long and
all(isinstance(x, int) for x in lst)
heck if all elements in a list 'lst' are the same type 'int'
all(isinstance(x, int) for x in lst)
p a string `line` of all carriage returns and newline
line.strip()
ll to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, Y)')
ll a to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
vert Date object `dateobject` into a DateTime objec
datetime.datetime.combine(dateobject, datetime.time())
heck if any item from list `b` is in list `a`
print(any(x in a for x in b))
ave 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)
heck if any elements in one list `list1` are in another list `list2`
len(set(list1).intersection(list2)) > 0
vert hex string `s` to decimal
i = int(s, 16)
vert hex string 0xff to decimal
int('0xff', 16)
vert hex string FFFF to decimal
int('FFFF', 16)
vert hex string '0xdeadbeef' to decimal
ast.literal_eval('0xdeadbeef')
vert hex string 'deadbeef' to decimal
int('deadbeef', 16)
ake 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)
eplace nonascii chars from a unicode string u'm\xfasica'
unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')
atenate dataframe `df1` with `df2` whilst removing duplicate
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 subproce
subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)
w to use the mv command in Python with subproce
subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)
print a character that has unicode value `\u25b2`
print('\u25b2'.encode('utf-8'))
mpare 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(',')))
heck 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()
ght align string `mystring` with a width of 7
"""{:>7s}""".format(mystring)
ead an excel file 'ComponentReportDJI.xls'
open('ComponentReport-DJI.xls', 'rb').read(200)
dataframe `df` based on column 'b' in ascending and column 'c' in descending
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
dataframe `df` based on column 'a' in ascending and column 'b' in descending
df.sort_values(['a', 'b'], ascending=[True, False])
a pandas data frame with column `a` in ascending and `b` in descending order
df1.sort(['a', 'b'], ascending=[True, False], inplace=True)
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')
emove all values within one list `[2, 3, 7]` from another list `a`
[x for x in a if x not in [2, 3, 7]]
emove 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']
quote a urlencoded unicode string '%0a'
urllib.parse.unquote('%0a')
decode url `url` from UTF16 code to UTF8 code
urllib.parse.unquote(url).decode('utf8')
empty a list `lst`
del lst[:]
empty a list `lst`
del lst1[:]