intent
stringlengths
4
183
snippet
stringlengths
2
1k
from a list of floats, how to keep only mantissa in python?
[(a - int(a)) for a in l]
execute a file './abc.py' with arguments `arg1` and `arg2` in python shell
subprocess.call(['./abc.py', arg1, arg2])
python selenium click on button
driver.find_element_by_css_selector('.button .c_button .s_button').click()
how to safely open/close files in python 2.4
f.close()
sorting list based on values from another list?
[x for y, x in sorted(zip(Y, X))]
trying to converting a matrix 1*3 into a list
my_list = [col for row in matrix for col in row]
how to hide firefox window (selenium webdriver)?
driver = webdriver.PhantomJS()
python regex to replace all windows newlines with spaces
htmlspaced = re.sub('\\r\\n', ' ', html)
selecting specific column in each row from array
array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
get the number of all keys in a dictionary of dictionaries in python
len(dict_test) + sum(len(v) for v in dict_test.values())
how to get all sub-elements of an element tree with python elementtree?
[elem.tag for elem in a.iter()]
python: how to ignore #comment lines when reading in a file
print(line.rstrip())
remove null columns in a dataframe `df`
df = df.dropna(axis=1, how='all')
convert django model object to dict with all of the fields intact
list(SomeModel.objects.filter(id=instance.id).values())[0]
print a celsius symbol with matplotlib
ax.set_xlabel('Temperature ($^\\circ$C)')
how to read numbers from file in python?
array.append([int(x) for x in line.split()])
unpythonic way of printing variables in python?
print('{foo}, {bar}, {baz}'.format(**locals()))
how to calculate moving average in python 3?
print(sum(map(int, x[num - n:num])))
python dictionary match key values in two dictionaries
set(aa.items()).intersection(set(bb.items()))
convert string to image in python
img = Image.new('RGB', (200, 100), (255, 255, 255))
how to extract nested lists?
list(chain.from_iterable(list_of_lists))
open a text file using notepad as a help file in python?
webbrowser.open('file.txt')
how to dynamically load a python class
__import__('foo.bar.baz.qux')
use regular expressions to replace overlapping subpatterns
re.sub('([a-zA-Z0-9])\\s+(?=[a-zA-Z0-9])', '\\1*', '3 /a 5! b')
add one day and three hours to the present time from datetime.now()
datetime.datetime.now() + datetime.timedelta(days=1, hours=3)
finding the average of a list
sum(l) / float(len(l))
how to position and align a matplotlib figure legend?
plt.show()
given a list of variable names in python, how do i a create a dictionary with the variable names as keys (to the variables' values)?
dict((name, locals()[name]) for name in list_of_variable_names)
how to calculate the percentage of each element in a list?
[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]
python berkeley db/sqlite
c.execute('bla bla bla sql')
how to write list of strings to file, adding newlines?
data.write('%s%s\n' % (c, n))
python/django: how to remove extra white spaces & tabs from a string?
""" """.join(s.split())
drawing a correlation graph in matplotlib
plt.show()
python: how to calculate the sum of a list without creating the whole list first?
sum(a)
python date interval intersection
return t1start <= t2start <= t1end or t2start <= t1start <= t2end
how to rotate secondary y axis label so it doesn't overlap with y-ticks, matplotlib
ax2.set_ylabel('Cost ($)', color='g', rotation=270, labelpad=15)
python dictionary creation syntax
d1 = {'yes': [1, 2, 3], 'no': [4]}
python converting lists into 2d numpy array
array([[2.0, 18.0, 2.3], [7.0, 29.0, 4.6], [8.0, 44.0, 8.9], [5.0, 33.0, 7.7]])
is it possible to take an ordered "slice" of a dictionary in python based on a list of keys?
zip(my_list, map(my_dictionary.get, my_list))
how can i get the output of a matplotlib plot as an svg?
plt.savefig('test.svg', format='svg')
find the newest folder in a directory in python
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
python: setting an element of a numpy matrix
a[i, j] = 5
get unique values from a list in python
mynewlist = list(myset)
why is it a syntax error to invoke a method on a numeric literal in python?
(5).bit_length()
writing a pandas dataframe into a csv file with some empty rows
df.to_csv('pandas_test.txt', header=False, index=False, na_rep=' ')
how to login to a website with python and mechanize
browser.submit()
use python selenium to get span text
print(element.get_attribute('innerHTML'))
python: how to calculate the sum of a list without creating the whole list first?
result = sum(x for x in range(1, 401, 4))
how can i send email using python?
server = smtplib.SMTP('smtp.gmail.com:587')
terminate a multi-thread python program
time.sleep(0.1)
how do i pythonically set a value in a dictionary if it is none?
count.setdefault('a', 0)
searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)
[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]
how do i convert user input into a list?
['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']
matplotlib axis label format
ax1.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
iteration order of sets in python
set(['a', 'b', 'c'])
django model auto increment primary key based on foreign key
super(ModelA, self).save(*args, **kwargs)
find the coordinates of a cuboid using list comprehension in python
[list(l) for l in it.product([0, 1], repeat=3) if sum(l) != 2]
colored latex labels in plots
plt.xlabel('$x=\\frac{ \\color{red}{red text} }{ \\color{blue}{blue text} }$')
numpy: find the euclidean distance between two 3-d arrays
np.sqrt(((A - B) ** 2).sum(-1))
how to drop duplicate from dataframe taking into account value of another column
df.drop_duplicates('name', keep='last')
drawing cards from a deck in scipy with scipy.stats.hypergeom
scipy.stats.hypergeom.cdf(k, M, n, N)
add key "item3" and value "3" to dictionary `default_data `
default_data.update({'item3': 3, })
split a string `a , b; cdf` using both commas and semicolons as delimeters
re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')
python-numpy: apply a function to each row of a ndarray
np.random.seed(1)
how to merge two python dictionaries in a single expression?
dict((k, v) for d in dicts for k, v in list(d.items()))
convert python list with none values to numpy array with nan values
np.array(my_list, dtype=np.float)
operate on a list in a pythonic way when output depends on other elements
['*abc', '*de', '*f', '*g']
get max key in dictionary `mycount`
max(list(MyCount.keys()), key=int)
how can i simulate input to stdin for pyunit?
return int(input('prompt> '))
element-wise minimum of multiple vectors in numpy
np.minimum.reduce([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])
using savepoints in python sqlite3
conn.execute('create table example (A, B);')
how to remove two chars from the beginning of a line
[line[2:] for line in lines]
how to test if gtk+ dialog has been created?
Gtk.main()
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)
python, zip multiple lists where one list requires two items each
list(zip(a, b, zip(c[0::2], c[1::2]), d))
distributed programming in python
print(p.map_async(f, [1, 2, 3]))
get the path of the python module `amodule`
path = os.path.abspath(amodule.__file__)
convert dictionary `adict` into string
"""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))
how to count the occurrence of certain item in an ndarray in python?
collections.Counter(a)
how to count number of rows in a group in pandas group by object?
df[['col1', 'col2', 'col3', 'col4']]
how to upload binary file with ftplib in python?
ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))
how to indent python list-comprehensions?
[transform(x) for x in results if condition(x)]
regex for getting all digits in a string after a character
re.findall('\\d+(?=[^[]+$)', s)
how to center a window with pygobject
window.set_position(Gtk.WindowPosition.CENTER)
removing items from unnamed lists in python
[x for x in something_iterable if x != 'item']
how to remove multiple indexes from a list at the same time?
del my_list[2:6]
convert a datetime object `dt` to microtime
time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
how to capture the entire string while using 'lookaround' with chars in regex?
re.findall('(b+a)+b+', mystring)
open file with a unicode filename?
open('someUnicodeFilename\u03bb')
django set default form values
form = JournalForm(initial={'tank': 123})
set utc offset by 9 hrs ahead for date '2013/09/11 00:17'
dateutil.parser.parse('2013/09/11 00:17 +0900')
inserting an element before each element of a list
[item for sublist in l for item in sublist]
how to do a regex replace with matching case?
re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is Foo', flags=re.I)
find array corresponding to minimal values along an axis in another array
np.tile(np.arange(y), x)
remove all data inside parenthesis in string `item`
item = re.sub(' \\(\\w+\\)', '', item)
copy 2d array into 3rd dimension, n times (python)
c = np.array([1, 2, 3])
python string replacement with % character/**kwargs weirdness
'%%%s%%' % 'PLAYER_ID'
finding the first list element for which a condition is true
next((e for e in mylist if my_criteria(e)), None)
convert a string to preexisting variable names
print(eval('self.post.id'))
how to add group labels for bar charts in matplotlib?
plt.show()