intent
stringlengths
4
183
snippet
stringlengths
2
1k
how can i color python logging output?
console = logging.StreamHandler()
can i prevent fabric from prompting me for a sudo password?
sudo('some_command', shell=False)
execute command 'source .bashrc; shopt -s expand_aliases; nuke -x scriptpath' from python script
os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')
cross-platform addressing of the config file
config_file = os.path.expanduser('~/foo.ini')
django: convert a post request parameters to query string
request.META['QUERY_STRING']
remove certain keys from a dictionary in python
FieldSet = dict((k, v) for k, v in FieldSet.items() if len(v) != 1)
what's the simplest way to extend a numpy array in 2 dimensions?
array([[1, 2, 0], [3, 4, 0]])
finding index of maximum value in array with numpy
np.where(x == 5)
converting a dict into a list
[y for x in list(dict.items()) for y in x]
how to subset a data frame using pandas based on a group criteria?
df.groupby('User')['X'].filter(lambda x: x.sum() == 0)
how to bind spacebar key to a certain method in tkinter (python)
root.mainloop()
matplotlib: group boxplots
ax.set_xticklabels(['A', 'B', 'C'])
how do i convert a string to a buffer in python 3.1?
"""insert into egg values ('egg');""".encode('ascii')
pandas group by time windows
s.groupby(grouper).sum()
how to print out the indexes in a list with repetitive elements
[1, 4, 5, 6, 7]
inserting a python datetime.datetime object into mysql
time.strftime('%Y-%m-%d %H:%M:%S')
counting the number of true booleans in a python list
sum([True, True, False, False, False, True])
download a remote image and save it to a django model
request.FILES['imgfield']
why would a python regex compile on linux but not windows?
'\ud800', '\udc00', '-', '\udbff', '\udfff'
python requests getting sslerror
requests.get('https://www.reporo.com/', verify=False)
get the index of the last negative value in a 2d array per column
np.maximum.accumulate((A2 < 0)[:, ::-1], axis=1)[:, ::-1]
decoding json string in python
data = json.load(f)
sort dictionary of lists `mydict` by the third item in each list
sorted(list(myDict.items()), key=lambda e: e[1][2])
lxml create xml fragment with no root element?
print(etree.tostring(root, pretty_print=True))
is there a way to specify the build directory for py2exe
setup(console=['myscript.py'], options=options)
divide each element in list `mylist` by integer `myint`
myList[:] = [(x / myInt) for x in myList]
sorting files in a list
files.sort(key=file_number)
python dryscrape scrape page with cookies
session.visit('<url to visit with proper cookies>')
split string "jvm.args= -dappdynamics.com=true, -dsomeotherparam=false," on the first occurrence of delimiter '='
"""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,""".split('=', 1)
print list of items `mylist`
print('\n'.join(str(p) for p in myList))
array initialization in python
[(i * y + x) for i in range(10)]
how can i read inputs as integers in python?
y = int(eval(input('Enter a number: ')))
how to get everything after last slash in a url?
url.rsplit('/', 1)
how to reliably open a file in the same directory as a python script
print(os.path.dirname(os.path.abspath(sys.argv[0])))
how to pass default & variable length arguments together in python?
any_func('Mona', 45, 'F', ('H', 'K', 'L'))
python - how to extract the last x elements from a list
my_list[-10:]
sum all the values in a counter variable `my_counter`
sum(my_counter.values())
flask and sqlalchemy how to delete records from manytomany table?
db.session.commit()
get modification time of file `filename`
t = os.path.getmtime(filename)
count unique index values in column 'a' in pandas dataframe `ex`
ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
return a random word from a word list 'words'
print(random.choice(words))
how to prevent automatic escaping of special characters in python
winpath = 'C:\\Users\\Administrator\\bin'
how to do camelcase split in python
['Camel', 'Case', 'XYZ']
how do convert a pandas/dataframe to xml?
xml.etree.ElementTree.parse('xml_file.xml')
python: how to generate a 12-digit random number?
'%012d' % random.randrange(10 ** 12)
python get time stamp on file `file` in '%m/%d/%y' format
time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
how to plot a graph in python?
pl.show()
round number 6.005 up to 2 decimal places
round(6.005, 2)
how to extract first two characters from string using regex
df.c_contofficeID.str.replace('^12(?=.{4}$)', '')
how to create a range of random decimal numbers between 0 and 1
[random.random() for _ in range(0, 10)]
how to get the n next values of a generator in a list (python)
list(itertools.islice(it, 0, n, 1))
printing each item of a variable on a separate line in python
print('\n'.join(str(port) for port in ports))
using name of list as a string to access list
x = {'0': [], '2': [], '16': []}
how to convert ndarray to array?
np.zeros((3, 3)).ravel()
python - download images from google image search?
img = Image.open(file)
how to add multiple values to a key in a python dictionary
print(dict(new_dict))
how to use sadd with multiple elements in redis using python api?
r.sadd('a', 1, 2, 3)
python - split string into smaller chunks and assign a variable
a, b, c, d = x.split(' ')
how to run two functions simultaneously
threading.Thread(target=SudsMove).start()
splitting a string into a list (but not separating adjacent numbers) in python
re.findall('\\d+|\\S', string)
in django, how do i check if a user is in a certain group?
return user.groups.filter(name__in=['group1', 'group2']).exists()
python requests can't send multiple headers with same key
requests.get(url, headers=headers)
dynamically updating a bar plot in matplotlib
plt.show()
calculate the mean of the nonzero values' indices of dataframe `df`
np.flatnonzero(x).mean()
plot timeseries of histograms in python
bins = np.linspace(0, 360, 10)
how to create a number of empty nested lists in python
lst = [[] for _ in range(a)]
label width in tkinter
root.mainloop()
"pythonic" method to parse a string of comma-separated integers into a list of integers?
mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]
get the number of all keys in a dictionary of dictionaries in python
n = sum([(len(v) + 1) for k, v in list(dict_test.items())])
hexadecimal string to byte array in python
bytearray.fromhex('de ad be ef 00')
how do i draw a grid onto a plot in python?
plt.show()
how to import a module in python with importlib.import_module
importlib.import_module('.c', 'a.b')
find maximum with limited length in a list
[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]
comma separated lists in django templates
{{(value | join): ' // '}}
implementing a kolmogorov smirnov test in python scipy
stats.kstest(np.random.normal(0, 1, 10000), 'norm')
calculating cumulative minimum with numpy arrays
numpy.minimum.accumulate([5, 4, 6, 10, 3])
get date from iso week number in python
datetime.strptime('2011221', '%Y%W%w')
how to decode an invalid json string in python
kludged = re.sub('(?i)([a-z_].*?):', '"\\1":', string)
how to pause and wait for command input in a python script
pdb.set_trace()
how to get output of exe in python script?
output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]
is it possible to take an ordered "slice" of a dictionary in python based on a list of keys?
res = [(x, my_dictionary[x]) for x in my_list]
using python logging in multiple modules
logger.debug('My message with %s', 'variable data')
summation of elements of dictionary that are list of lists
{k: [(a + b) for a, b in zip(*v)] for k, v in list(d.items())}
convert a string of bytes into an int (python)
int.from_bytes('y\xcc\xa6\xbb', byteorder='little')
find array corresponding to minimal values along an axis in another array
np.repeat(np.arange(x), y)
how to get the symmetric difference of two dictionaries
dict_symmetric_difference({'a': 1, 'b': 2}, {'b': 2, 'c': 3})
display a pdf file that has been downloaded as `my_pdf.pdf`
webbrowser.open('file:///my_pdf.pdf')
how can i split a single tuple into multiple using python?
d = {t[0]: t[1:] for t in l}
how to extract all upper from a string? python
"""""".join([c for c in s if c.isupper()])
find all n-dimensional lines and diagonals with numpy
np.split(x.reshape(x.shape[0], -1), 9, axis=1)
use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`
df.groupby(level=0).agg(['sum', 'count', 'std'])
find the index of sub string 'cc' in string 'sdfasdf'
'sdfasdf'.index('cc')
how can i count the occurrences of an item in a list of dictionaries?
sum(1 for d in my_list if d.get('id') == 1)
efficient way to convert numpy record array to a list of dictionary
[dict(zip(r.dtype.names, x)) for x in r]
create list `listy` containing 3 empty lists
listy = [[] for i in range(3)]
how to write a simple bittorrent application?
time.sleep(1)
is it possible to print using different color in ipython's notebook?
print('\x1b[31m"red"\x1b[0m')
how to enable cors in flask and heroku
app.run()
how can i convert a unicode string into string literals in python 2.7?
print(re.sub('\u032f+', '\u032f', unicodedata.normalize('NFKD', s)))
increase the linewidth of the legend lines in matplotlib
plt.show()