text stringlengths 4 1.08k |
|---|
getting the total number of lines in a tkinter text widget?,int(text_widget.index('end-1c').split('.')[0]) |
python pandas: how to run multiple univariate regression by group,"df.grouby('grp').apply(ols_res, xcols=['x1', 'x2'], ycol='y')" |
how to index multiple items of array with intervals in python,"np.array(a).reshape(-1, 100)[::2].ravel()" |
is there a more pythonic way to build this dictionary?,"dict((key_from_value(value), value) for value in values)" |
multicast in python,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" |
python print on same line,print('[DONE]') |
add text on image using pil,"font = ImageFont.truetype('sans-serif.ttf', 16)" |
how to visualize descriptor matching using opencv module in python,cv2.waitKey() |
is it possible to plot timelines with matplotlib?,"fig, ax = plt.subplots(figsize=(6, 1))" |
python: uniqueness for list of lists,unique_data = [list(x) for x in set(tuple(x) for x in testdata)] |
drawing lines between two plots in matplotlib,plt.show() |
how do i select a random element from an array in python?,random.choice(mylist) |
"efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0).asfreq('D') |
how can i tell if a string only contains letter and spaces,"""""""a b"""""".replace(' ', '').isalpha()" |
how to add new object attribute with python/django,{{post.featured_image}} |
python matplotlib: plot with 2-dimensional arguments : how to specify options?,"plot(x[0], y[0], 'red', x[1], y[1], 'black')" |
find row or column containing maximum value in numpy array,"np.argmax(np.max(x, axis=1))" |
how to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() / np.prod(a.shape) |
how can i dynamically get the set of classes from the current python module?,"getattr(sys.modules[__name__], 'A')" |
"check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`","""""""test.mp3"""""".endswith(('.mp3', '.avi'))" |
fill username and password using selenium in python,driver.find_element_by_name('submit').click() |
how to declare ports in cloud9 using python,"http_server.listen(int(os.environ.get('PORT')), address=os.environ['IP'])" |
equivalent of objects.latest() in app engine,MyObject.all().order('-time') |
wtforms: how to select options in selectmultiplefield?,"form = MyForm(myfield=['1', '3'])" |
python accessing values in a list of dictionaries,"[(d['Name'], d['Age']) for d in thisismylist]" |
making matplotlib graphs look like r by default?,plt.show() |
how do i create a list of unique random numbers?,"random.sample(list(range(100)), 10)" |
rotating a two-dimensional array in python,"zip([3, 4], [1, 2])" |
how to conditionally update dataframe column in pandas,"df.loc[df['line_race'] == 0, 'rating'] = 0" |
print +1 using format '{0:+d}',print('{0:+d}'.format(score)) |
regex to split on successions of newline characters,"re.split('[\\n\\r]+', line)" |
find all elements in a list of tuples `a` where the first element of each tuple equals 1,[item for item in a if item[0] == 1] |
perform a google search and return the number of results,"print(soup.find('div', {'id': 'resultStats'}).text)" |
round number 2.0005 up to 3 decimal places,"round(2.0005, 3)" |
send file using post from a python script,"r = requests.post('http://httpbin.org/post', files={'report.xls': open( |
'report.xls', 'rb')})" |
sorting json in python by a specific value,"entries = sorted(list(json_data.items()), key=lambda items: items[1]['data_two'])" |
get column name where value is something in pandas dataframe,"df['column'] = df.apply(lambda x: df.columns[x.argmax()], axis=1)" |
deleting a line from a file in python,"open('names.txt', 'w').write(''.join(lines))" |
optional dot in regex,"re.sub('\\bMr\\.|\\bMr\\b', 'Mister', s)" |
how to make a timer program in python,time.sleep(1) |
python count the number of substring in list from other string list without duplicates,"['Smith', 'Smith', 'Roger', 'Roger-Smith']" |
python getting a list of value from list of dict,[d['value'] for d in l if 'value' in d] |
python mysqldb typeerror: not all arguments converted during string formatting,"cursor.execute('select * from table where example=%s', (example,))" |
dropping a single (sub-) column from a multiindex,"df.drop(('col1', 'a'), axis=1)" |
perl like regex in python,"match = re.search('(.*?):([^-]*)-(.*)', line)" |
how to use concatenate a fixed string and a variable in python,msg['Subject'] = 'Auto Hella Restart Report ' + sys.argv[1] |
create dictionary from list of variables,"createDict('foo', 'bar')" |
collapse hierarchical column index to level 0 in dataframe `df`,df.columns = df.columns.get_level_values(0) |
"""pythonic"" method to parse a string of comma-separated integers into a list of integers?","map(int, myString.split(','))" |
get the widget which has currently the focus in tkinter instance `window2`,"print(('focus object class:', window2.focus_get().__class__))" |
"separate numbers from characters in string ""30m1000n20m""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')" |
python accessing values in a list of dictionaries,print('\n'.join(d['Name'] for d in thisismylist)) |
python pandas: how to get the row names from index of a dataframe?,df.index['Row 2':'Row 5'] |
pandas cumulative sum on column with condition,df.groupby(grouper)['value'].cumsum() |
extracting specific columns in numpy array,"data[:, ([1, 9])]" |
typeerror: expected string or buffer in google app engine's python,self.response.out.write(str(parsed_data['translatedText'])) |
how to align the bar and line in matplotlib two y-axes chart?,"ax.set_ylim((-10, 80.0))" |
convert python dict into a dataframe,"pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])" |
for loop in unittest,"self.assertEqual(iline, 'it is a test!')" |
how do i visualize a connection matrix with matplotlib?,plt.show() |
how to check if type of a variable is string?,"isinstance(s, str)" |
"python, lambda, find minimum","min([1, 2, 3])" |
kdb+ like asof join for timeseries data in pandas?,df1.apply(lambda x: x.asof(df2.index)) |
ipdb with python unittest module,"self.assertEqual('foo', 'bar')" |
django class-based view: how do i pass additional parameters to the as_view method?,"url('^(?P<slug>[a-zA-Z0-9-]+)/$', MyView.as_view(), name='my_named_view')" |
find an element in a list of tuples,"[(x, y) for x, y in a if x == 1]" |
python: replace with regex,"output = re.sub('(<textarea.*>).*(</textarea>)', '\\1Bar\\2', s)" |
how to convert signed to unsigned integer in python,bin(_) |
execute terminal command from python in new terminal window?,"subprocess.call('start /wait python bb.py', shell=True)" |
how do i plot multiple x or y axes in matplotlib?,plt.xlabel('Dose') |
is it possible to plot timelines with matplotlib?,ax.get_yaxis().set_ticklabels([]) |
how to remove \n from a list element?,[i.strip() for i in l] |
convert list of floats into buffer in python?,"return struct.pack('f' * len(data), *data)" |
find name of current directory,dir_path = os.path.dirname(os.path.realpath(__file__)) |
creating a json response using django and python,"return HttpResponse(json.dumps(response_data), content_type='application/json')" |
how to create range of numbers in python like in matlab,"print(np.linspace(1, 3, num=4, endpoint=False))" |
open file 'sample.json' in read mode with encoding of 'utf-8-sig',"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))" |
how to set the working directory for a fabric task?,run('ls') |
using python logging in multiple modules,logger = logging.getLogger(__name__) |
how do i avoid the capital placeholders in python's argparse module?,"parser.add_argument('-c', '--chunksize', type=int, help='no metavar specified')" |
insert to cassandra from python using cql,"connection = cql.connect('localhost:9160', cql_version='3.0.0')" |
python - find digits in a string,""""""""""""".join(c for c in my_string if c.isdigit())" |
how to calculate percentage in python,print('The total is ' + str(total) + ' and the average is ' + str(average)) |
trying to use reduce() and lambda with a list containing strings,"from functools import reduce |
reduce(lambda x, y: x * int(y), ['2', '3', '4'])" |
make a window `root` jump to the front,root.lift() |
how to show tick labels on top of matplotlib plot?,ax.xaxis.set_tick_params(labeltop='on') |
how to save an xml file to disk with python?,file_handle.close() |
get the age of directory (or file) `/tmp` in seconds.,print(os.path.getmtime('/tmp')) |
how do i print the content of a .txt file in python?,print(file_contents) |
subplots with dates on the x-axis,plt.xticks(rotation=30) |
how do i remove dicts from a list with duplicate fields in python?,"list(dict((x['id'], x) for x in L).values())" |
how to slice list into contiguous groups of non-zero integers in python,"[list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0]]" |
save xlsxwriter file to 'c:/users/steven/documents/demo.xlsx' path,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx') |
pandas split string into columns,df['stats'].apply(pd.Series) |
group spark dataframe by date,"df.selectExpr('year(timestamp) AS year', 'value').groupBy('year').sum()" |
how to include a quote in a raw python string?,"""""""what""ever""""""" |
how can i group equivalent items together in a python list?,"[list(g) for k, g in itertools.groupby(iterable)]" |
search a list of nested tuples of strings in python,"['alfa', 'bravo', 'charlie', 'delta', 'echo']" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.