code
stringlengths 11
529
| comment
stringlengths 19
200
|
|---|---|
os.kill(os.getpid(), signal.SIGUSR1)
|
send a signal `signal.SIGUSR1` to the current process
|
bytes.fromhex('4a4b4c').decode('utf-8')
|
decode a hex string '4a4b4c' to UTF-8.
|
all(x == myList[0] for x in myList)
|
check if all elements in list `myList` are identical
|
print('%*s : %*s' % (20, 'Python', 20, 'Very Good'))
|
format number of spaces between strings `Python`, `:` and `Very Good` to be `20`
|
res = {k: v for k, v in list(kwargs.items()) if v is not None}
|
get rid of None values in dictionary `kwargs`
|
res = dict((k, v) for k, v in kwargs.items() if v is not None)
|
get rid of None values in dictionary `kwargs`
|
subprocess.check_output('ps -ef | grep something | wc -l', shell=True)
|
capture final output of a chain of system commands `ps -ef | grep something | wc -l`
|
"""""".join(['a', 'b', 'c'])
|
concatenate a list of strings `['a', 'b', 'c']`
|
pd.Series(list(set(s1).intersection(set(s2))))
|
find intersection data between series `s1` and series `s2`
|
client.send('HTTP/1.0 200 OK\r\n')
|
sending http headers to `client`
|
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
|
Format a datetime string `when` to extract date only
|
inputString.split('\n')
|
split a multi-line string `inputString` into separate strings
|
' a \n b \r\n c '.split('\n')
|
Split a multi-line string ` a \n b \r\n c ` by new line character `\n`
|
""":""".join(str(x) for x in b)
|
concatenate elements of list `b` by a colon ":"
|
Entry.objects.filter()[:1].get()
|
get the first object from a queryset in django model `Entry`
|
a.sum(axis=1)
|
Calculate sum over all rows of 2D numpy array
|
warnings.simplefilter('always')
|
enable warnings using action 'always'
|
print(' '.join(map(str, l)))
|
concatenate items of list `l` with a space ' '
|
subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])
|
run script 'hello.py' with argument 'htmlfilename.htm' on terminal using python executable
|
my_float = float(my_string.replace(',', ''))
|
convert a string `my_string` with dot and comma into a float number `my_float`
|
float('123,456.908'.replace(',', ''))
|
convert a string `123,456.908` with dot and comma into a floating number
|
sys.path.append('/path/to/whatever')
|
set pythonpath in python script.
|
re.split('(\\W+)', 'Words, words, words.')
|
split string 'Words, words, words.' using a regex '(\\W+)'
|
file = open('Output.txt', 'a')
|
open a file `Output.txt` in append mode
|
urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
|
download a file "http://www.example.com/songs/mp3.mp3" over HTTP and save to "mp3.mp3"
|
u = urllib.request.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders('Content-Length')[0])
print(('Downloading: %s Bytes: %s' % (file_name, file_size)))
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if (not buffer):
break
file_size_dl += len(buffer)
f.write(buffer)
status = ('%10d [%3.2f%%]' % (file_size_dl, ((file_size_dl * 100.0) / file_size)))
status = (status + (chr(8) * (len(status) + 1)))
print(status, end=' ')
f.close()
|
download a file `url` over HTTP and save to `file_name`
|
response = urllib.request.urlopen('http://www.example.com/')
html = response.read()
|
download a file 'http://www.example.com/' over HTTP
|
r = requests.get(url)
|
download a file `url` over HTTP
|
response = requests.get(url, stream=True)
with open('10MB', 'wb') as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
|
download a file `url` over HTTP and save to "10MB"
|
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
|
argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`
|
{i: d[i] for i in d if i != 'c'}
|
remove key 'c' from dictionary `d`
|
pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))
|
Create new DataFrame object by merging columns "key" of dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively
|
s.split(' ', 4)
|
Split a string `s` by space with `4` splits
|
input('Enter your input:')
|
read keyboard-input
|
app.run(debug=True)
|
enable debug mode on Flask application `app`
|
pickle.dump(mylist, open('save.txt', 'wb'))
|
python save list `mylist` to file object 'save.txt'
|
scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)
|
Multiply a matrix `P` with a 3d tensor `T` in scipy
|
numpy.zeros((3, 3, 3))
|
Create 3d array of zeroes of size `(3,3,3)`
|
""" """.join(content.split(' ')[:-1])
|
cut off the last word of a sentence `content`
|
x = np.asarray(x).reshape(1, -1)[(0), :]
|
convert scalar `x` to array
|
sum(sum(i) if isinstance(i, list) else i for i in L)
|
sum all elements of nested list `L`
|
struct.unpack('!f', '470FC614'.decode('hex'))[0]
|
convert hex string '470FC614' to a float number
|
my_dict.update((x, y * 2) for x, y in list(my_dict.items()))
|
Multiple each value by `2` for all keys in a dictionary `my_dict`
|
subprocess.call('sleep.sh', shell=True)
|
running bash script 'sleep.sh'
|
""",""".join(l)
|
Join elements of list `l` with a comma `,`
|
myList = ','.join(map(str, myList))
|
make a comma-separated string from a list `myList`
|
list(reversed(list(range(10))))
|
reverse the list that contains 1 to 10
|
print('lamp, bag, mirror'.replace('bag,', ''))
|
remove substring 'bag,' from a string 'lamp, bag, mirror'
|
""".""".join(s.split('.')[::-1])
|
Reverse the order of words, delimited by `.`, in string `s`
|
datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
|
convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f'
|
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0))
|
parse milliseconds epoch time '1236472051807' to format '%Y-%m-%d %H:%M:%S'
|
(datetime.datetime.now() - datetime.timedelta(days=7)).date()
|
get the date 7 days before the current date
|
print(sum(row[column] for row in data))
|
sum elements at index `column` of each list in list `data`
|
[sum(row[i] for row in array) for i in range(len(array[0]))]
|
sum columns of a list `array`
|
base64.b64encode(bytes('your string', 'utf-8'))
|
encode binary string 'your string' to base64 code
|
dict((k, [d[k] for d in dicts]) for k in dicts[0])
|
combine list of dictionaries `dicts` with the same keys in each list to a single dictionary
|
{k: [d[k] for d in dicts] for k in dicts[0]}
|
Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`
|
[k for k, v in list(Counter(mylist).items()) if v > 1]
|
identify duplicate values in list `mylist`
|
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))
|
Insert directory 'apps' into directory `__file__`
|
sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))
|
modify sys.path for python module `subdir`
|
db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))
|
Insert a 'None' value into a SQLite3 table.
|
[image for menuitem in list_of_menuitems for image in menuitem]
|
flatten list `list_of_menuitems`
|
a.extend(b)
|
append elements of a set `b` to a list `a`
|
np.savetxt('c:\\data\\np.txt', df.values, fmt='%d')
|
write the data of dataframe `df` into text file `np.txt`
|
df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')
|
write content of DataFrame `df` into text file 'c:\\data\\pandas.txt'
|
print(x.rpartition('-')[0])
|
Split a string `x` by last occurrence of character `-`
|
print(x.rsplit('-', 1)[0])
|
get the last part of a string before the character '-'
|
ftp.storlines('STOR ' + filename, open(filename, 'r'))
|
upload file using FTP
|
browser.execute_script("document.getElementById('XYZ').value+='1'")
|
add one to the hidden web element with id 'XYZ' with selenium python script
|
np.maximum([2, 3, 4], [1, 5, 2])
|
create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`
|
print(l[3:] + l[:3])
|
print a list `l` and move first 3 elements to the end of the list
|
for fn in os.listdir('.'):
if os.path.isfile(fn):
pass
|
loop over files in directory '.'
|
for (root, dirs, filenames) in os.walk(source):
for f in filenames:
pass
|
loop over files in directory `source`
|
[int(1000 * random.random()) for i in range(10000)]
|
create a random list of integers
|
db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())
|
Google App Engine execute GQL query 'SELECT * FROM Schedule WHERE station = $1' with parameter `foo.key()`
|
df.b.str.contains('^f')
|
filter rows in pandas starting with alphabet 'f' using regular expression.
|
print('\n'.join('\t'.join(str(col) for col in row) for row in tab))
|
print a 2 dimensional list `tab` as a table with delimiters
|
df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()
|
pandas: delete rows in dataframe `df` based on multiple columns values
|
"""({:d} goals, ${:d})""".format(self.goals, self.penalties)
|
format the variables `self.goals` and `self.penalties` using string formatting
|
"""({} goals, ${})""".format(self.goals, self.penalties)
|
format string "({} goals, ${})" with variables `goals` and `penalties`
|
"""({0.goals} goals, ${0.penalties})""".format(self)
|
format string "({0.goals} goals, ${0.penalties})"
|
[int(''.join(str(d) for d in x)) for x in L]
|
convert list of lists `L` to list of integers
|
[''.join(str(d) for d in x) for x in L]
|
combine elements of each list in list `L` into digits of a single integer
|
L = [int(''.join([str(y) for y in x])) for x in L]
|
convert a list of lists `L` to list of integers
|
myfile.write('\n'.join(lines))
|
write the elements of list `lines` concatenated by special character '\n' to file `myfile`
|
[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]
|
removing an element from a list based on a predicate 'X' or 'N'
|
text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text)
|
Remove duplicate words from a string `text` using regex
|
df.astype(bool).sum(axis=1)
|
count non zero values in each column in pandas data frame
|
re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe')
|
search for string that matches regular expression pattern '(?<!Distillr)\\\\AcroTray\\.exe' in string 'C:\\SomeDir\\AcroTray.exe'
|
"""QH QD JC KD JS""".split()
|
split string 'QH QD JC KD JS' into a list on white spaces
|
print(re.search('>.*<', line).group(0))
|
search for occurrences of regex pattern '>.*<' in xml string `line`
|
open(filename, 'w').close()
|
erase all the contents of a file `filename`
|
datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')
|
convert a string into datetime using the format '%Y-%m-%d %H:%M:%S.%f'
|
[index for index, item in enumerate(thelist) if item[0] == '332']
|
find the index of a list with the first element equal to '332' within the list of lists `thelist`
|
re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip()
|
lower a string `text` and remove non-alphanumeric characters aside from space
|
re.sub('(?!\\s)[\\W_]', '', text).lower().strip()
|
remove all non-alphanumeric characters except space from a string `text` and lower it
|
plt.plot(x, y, label='H\u2082O')
|
subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.
|
plt.plot(x, y, label='$H_2O$')
|
subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.
|
[x for x in mylist if len(x) == 3]
|
loop over a list `mylist` if sublists length equals 3
|
lst = [Object() for _ in range(100)]
|
initialize a list `lst` of 100 objects Object()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.