text stringlengths 4 1.08k |
|---|
find phone numbers in python script,reg = re.compile('\\d{3}\\d{3}\\d{4}') |
converting datetime to posix time,print(time.mktime(d.timetuple())) |
how do i suppress scientific notation in python?,"""""""{:.20f}"""""".format(a)" |
vertical text in tkinter canvas,root.mainloop() |
python requests: get attributes from returned json string,print(resp['headers']['Host']) |
python convert csv to xlsx,workbook.close() |
python: count number of elements in list for if condition,[i for i in x if 60 < i < 70] |
how to convert 2d float numpy array to 2d int numpy array?,y.astype(int) |
"reduce the first element of list of strings `data` to a string, separated by '.'",print('.'.join([item[0] for item in data])) |
how to insert a small image on the corner of a plot with matplotlib?,plt.show() |
how to assert output with nosetest/unittest in python?,"self.assertEqual(output, 'hello world!')" |
how to print floating point numbers as it is without any truncation in python?,print('{:.100f}'.format(2.345e-67)) |
remove uppercased characters in string `s`,"re.sub('[^A-Z]', '', s)" |
simple python regex find pattern,"print(re.findall('\\bv\\w+', thesentence))" |
remove characters in `b` from a string `a`,"a = a.replace(char, '')" |
an elegant way of finding the closest value in a circular ordered list,"min(L, key=lambda theta: angular_distance(theta, 1))" |
flask sqlalchemy querying a column with not equals,seats = Seat.query.filter(Seat.invite_id != None).all() |
"concatenating unicode with string: print 'ps' + '1' works, but print 'ps' + u'1' throws unicodedecodeerror",print('\xa31'.encode('latin-1')) |
what are some good ways to set a path in a multi-os supported python script,"os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')" |
assigning a value to python list doesn't work?,l = [0] * N |
changing multiple numpy array elements using slicing in python,"array([0, 100, 100, 100, 4, 5, 100, 100, 100, 9])" |
is there a numpy function to return the first index of something in an array?,itemindex = numpy.where(array == item) |
join numpy array `b` with numpy array 'a' along axis 0,"b = np.concatenate((a, a), axis=0)" |
converting a dict into a list,print([y for x in list(dict.items()) for y in x]) |
"missing data, insert rows in pandas and fill with nan",df.set_index('A').reindex(new_index).reset_index() |
how can i see the entire http request that's being sent by my python application?,requests.get('https://httpbin.org/headers') |
list comprehension with if statement,[y for y in a if y not in b] |
convert a python dictionary `d` to a list of tuples,"[(v, k) for k, v in list(d.items())]" |
convert django model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}" |
python - get path of root project structure,os.path.dirname(sys.modules['__main__'].__file__) |
sort python list of objects by date,results.sort(key=lambda r: r.person.birthdate) |
how to get the union of two lists using list comprehension?,list(set(a).union(b)) |
how to extend a fixed-length python list by variable number of characters?,list2 = list1 + [''] * (5 - len(list1)) |
"creating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`","np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" |
how can i set the location of minor ticks in matplotlib,plt.show() |
removing _id element from pymongo results,"db.collection.find({}, {'_id': False})" |
django redirect to view 'home.views.index',redirect('Home.views.index') |
is there a built-in or more pythonic way to try to parse a string to an integer,print(sint('1340')) |
string encoding and decoding from possibly latin1 and utf8,print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8')) |
python - insert into list,my_list = my_list[:8] + new_array |
removing key values pairs from a list of dictionaries,"[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]" |
python map list of strings to integer list,"s = ['michael', 'michael', 'alice', 'carter']" |
read an xml file in python,root = tree.getroot() |
count the number of elements in array `myarray`,len(myArray) |
how to get the current port number in flask?,app.run(port=port) |
"run a python script from another python script, passing in args",os.system('script2.py 1') |
upload uploaded file from path '/upload' to google cloud storage 'my_bucket' bucket,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')" |
sort a multidimensional array `a` by column with index 1,"sorted(a, key=lambda x: x[1])" |
plotting histograms from grouped data in a pandas dataframe,df['N'].hist(by=df['Letter']) |
convert a python dictionary 'a' to a list of tuples,"[(k, v) for k, v in a.items()]" |
is it possible to make post request in flask?,app.run(debug=True) |
read the contents of the file 'file.txt' into `txt`,txt = open('file.txt').read() |
"random python dictionary key, weighted by values",random.choice([k for k in d for x in d[k]]) |
checking if any elements in one list are in another,len(set(list1).intersection(list2)) > 0 |
"in a matplotlib plot, can i highlight specific x-value ranges?",plt.show() |
how do you extract a column from a multi-dimensional array?,return [row[i] for row in matrix] |
arrange labels for plots on multiple panels to be in one line in matplotlib,"P.ylabel('$\\cos{(x)}\\cdot{}10^4$', labelpad=20)" |
arrow on a line plot with matplotlib,plt.show() |
how to code autocompletion in python?,self.matches = [s for s in self.options if s and s.startswith(text)] |
sort a python dictionary `a_dict` by element `1` of the value,"sorted(list(a_dict.items()), key=lambda item: item[1][1])" |
multiple 'in' operators in python?,"all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])" |
using insert with a postgresql database using python,conn.commit() |
string formatting in python,"print('[%i, %i, %i]' % tuple(numberList))" |
how to add columns to sqlite3 python?,"c.execute(""alter table linksauthor add column '%s' 'float'"" % author)" |
can i get a list of the variables that reference an other in python 2.7?,"['c', 'b', 'a', 'obj', 'a', 'a']" |
how to merge two columns together in pandas,"pd.melt(df, id_vars='year')['year', 'value']" |
how do i sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) |
extracting data from a text file with python,print('\n'.join(to_search[NAME])) |
how to send the content in a list from server in twisted python?,client.transport.write(message) |
how to use map to lowercase strings in a dictionary?,"map(lambda x: {'content': x['content'].lower()}, messages)" |
obtaining length of list as a value in dictionary in python 2.7,"[(1, [1, 2, 3, 4]), (2, [5, 6, 7])]" |
exclude column names when writing dataframe `df` to a csv file `filename.csv`,"df.to_csv('filename.csv', header=False)" |
how to improve the performance of this python code?,"G[i, j] = C_abs[i, j] + C_abs[j, i]" |
how to check if a file is a directory or regular file in python?,os.path.isdir('bob') |
how to create a ssh tunnel using python and paramiko?,ssh.close() |
how do i find the scalar product of a numpy matrix ?,"b = np.fill_diagonal(np.zeros_like(a), value)" |
matplotlib custom marker/symbol,plt.show() |
"difference between using commas, concatenation, and string formatters in python",print('here is a number: ' + str(2)) |
composite keys in sqlalchemy,"candidates = db.relationship('Candidate', backref='post', lazy='dynamic')" |
python: comprehension to compose two dictionaries,"result = {k: d2.get(v) for k, v in list(d1.items())}" |
how do i hide a sub-menu in qmenu,self.submenu2.setVisible(False) |
concatenate row values for the same index in pandas,df.groupby('A')['expand'].apply(list) |
count the number of words in a string `s`,len(s.split()) |
imshow subplots with the same colorbar,plt.colorbar() |
how to make a numpy array from an array of arrays?,np.vstack(counts_array) |
return the column name(s) for a specific value in a pandas dataframe,"df.ix[:, (df.loc[0] == 38.15)].columns" |
how to use list (or tuple) as string formatting value,x = '{} {}'.format(*s) |
how to write stereo wav files in python?,self.f.close() |
setting timezone in python,time.strftime('%X %x %Z') |
beautifulsoup find a tag whose id ends with string 'para',soup.findAll(id=re.compile('para$')) |
confusing with the usage of regex in python,"re.findall('[a-z]*', '123abc789')" |
dates along x-axis of quadmesh,ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) |
"how to do ""if-for"" statement in python?",do_stuff() |
finding the largest delta between two integers in a list in python,"max(abs(x - y) for x, y in zip(values[1:], values[:-1]))" |
how to create a nested dictionary from a list in python?,"from functools import reduce |
lambda l: reduce(lambda x, y: {y: x}, l[::-1], {})" |
"save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`","np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])" |
combine dataframe `df1` and dataframe `df2` by index number,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')" |
double each character in string `text.read()`,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" |
removing entries from a dictionary based on values,"dict((k, v) for k, v in hand.items() if v)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.