text
stringlengths
4
1.08k
How to center a window on the screen in Tkinter?,root.mainloop()
Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')"
How do you extract a column from a multi-dimensional array?,"A = [[1, 2, 3, 4], [5, 6, 7, 8]]"
strncmp in python,S2[:len(S1)] == S1
Pythonic way to insert every 2 elements in a string,"""""""-"""""".join(s[i:i + 2] for i in range(0, len(s), 2))"
Python: use of Counter in a dictionary of lists,Counter(v for sublist in list(d.values()) for v in sublist)
How to fetch a substring from text file in python?,"print(re.sub('.+ \\+(\\d+ ){3}', '', data))"
rename multiple files in python,"os.rename(file, 'year_{}'.format(file.split('_')[1]))"
how to replace back slash character with empty string in python,"result = string.replace('\\', '')"
Django template convert to string,{{(value | stringformat): 'i'}}
How do I remove the first and last rows and columns from a 2D numpy array?,"Hsub = H[1:-1, 1:-1]"
Python regex findall,"re.findall('\\[P\\]\\s?(.+?)\\s?\\[\\/P\\]', line)"
How to set up Python server side with javascript client side,server.serve_forever()
Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.yaxis.tick_left()
How to unpack a list?,"print(tuple(chain(['a', 'b', 'c'], 'd', 'e')))"
Pandas replace values in dataframe timeseries,df = pd.DataFrame({'Close': [2.389000000001]})
Python: Lambda function in List Comprehensions,[(lambda x: x * x) for _ in range(3)]
Fastest way to uniqify a list in Python,"set([a, b, c, a])"
Calculating cumulative minimum with numpy arrays,"numpy.minimum.accumulate([5, 4, 6, 10, 3])"
Finding index of maximum value in array with NumPy,np.where(x == 5)
How to check if an element exists in a Python array (Equivalent of PHP in_array)?,"1 in [0, 1, 2, 3, 4, 5]"
How to prevent automatic escaping of special characters in Python,"""""""hello\\nworld"""""""
hexadecimal string to byte array in python,"map(ord, hex_data)"
Having trouble with beautifulsoup in python,divs = soup.select('#fnd_content div.fnd_day')
Get time of execution of a block of code in Python 2.7,time.sleep(1)
How to extract all UPPER from a string? Python,""""""""""""".join(c for c in s if c.isupper())"
fors in python list comprehension,[y for y in x for x in data]
run multiple tornado processess,tornado.ioloop.IOLoop.instance().start()
How do I assign a dictionary value to a variable in Python?,"my_dictionary = {'foo': 10, 'bar': 20}"
Pandas: joining items with same index,"df.assign(id=df.groupby([0]).cumcount()).set_index(['id', 0]).unstack(level=1)"
setting color range in matplotlib patchcollection,plt.show()
Python merging two lists with all possible permutations,"[list(zip(a, p)) for p in permutations(b)]"
Data in a list within a list,"[set([1, 4, 5, 6]), set([0, 2, 3, 7])]"
How to convert a list by mapping an element into multiple elements in python?,"print([y for x in l for y in (x, x + 1)])"
How do I make this simple list comprehension?,"[sum(nums[i:i + 3]) for i in range(0, len(nums), 3)]"
How to add a scrollbar to a window with tkinter?,"root.wm_title(""Got Skills' Skill Tracker"")"
How to log python exception?,logging.exception('')
Add items to a dictionary of lists,"print(dict(zip(keys, [list(i) for i in zip(*data)])))"
check if a string contains a number,return any(i.isdigit() for i in s)
Python list initialization using multiple range statements,"list(range(1, 6)) + list(range(15, 20))"
Python String and Integer concatenation,[('string' + str(i)) for i in range(11)]
How do I get a empty array of any size I want in python?,a = [0] * 10
3D plot with Matplotlib,ax.set_ylabel('Y')
"How to Print ""Pretty"" String Output in Python","print(template.format('CLASSID', 'DEPT', 'COURSE NUMBER', 'AREA', 'TITLE'))"
Dot notation string manipulation,""""""""""""".join('[{}]'.format(e) for e in s.split('.'))"
How do I parse XML in Python?,e = xml.etree.ElementTree.parse('thefile.xml').getroot()
Replace values in pandas Series with dictionary,s.replace({'abc': 'ABC'})
"Pythonic way to modify all items in a list, and save list to .txt file",f.write('\n'.join(newList))
How to clone a key in Amazon S3 using Python (and boto)?,"bucket.copy_key(new_key, source_bucket, source_key)"
How to create a dictionary with certain specific behaviour of values,"{'A': 4, 'B': 1, 'C': 1}"
How to decode an invalid json string in python,"demjson.decode('{ hotel: { id: ""123"", name: ""hotel_name""} }')"
How to use different formatters with the same logging handler in python,logging.getLogger('base.baz').error('Log from baz')
How to close a Tkinter window by pressing a Button?,window.destroy()
Mutli-threading python with Tkinter,root.mainloop()
Python: Anyway to use map to get first element of a tuple,print([x[0] for x in data])
Using scikit-learn DecisionTreeClassifier to cluster,"clf.fit(X, y)"
"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)"
Reference to an element in a list,c[:] = b
How to pass default & variable length arguments together in python?,"any_func('Mona', 45, 'F', ('H', 'K', 'L'))"
"Merge values of same key, in list of dicts","[{'id1': k, 'price': temp[k]} for k in temp]"
How do I get a list of all the duplicate items using pandas in python?,"df[df.duplicated(['ID'], keep=False)]"
Is there any way to get a REPL in pydev?,pdb.set_trace()
How to deal with certificates using Selenium?,driver.get('https://expired.badssl.com')
Regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['k', 'c', 't', 'a'])))"
Reading array from config file in python,"config.get('common', 'folder').split('\n')"
PostgreSQL ILIKE query with SQLAlchemy,Post.query.filter(Post.title.ilike('%some_phrase%'))
How to get the index of a maximum element in a numpy array along one axis,a.argmax(axis=0)
How to generate all possible strings in python?,"map(''.join, itertools.product('ABC', repeat=3))"
How to append an element of a sublist in python,"[1, 2, 3]"
Python: Removing a single element from a nested list,"list = [[6, 5, 4], [4, 5, 6]]"
How do I get the user agent with Flask?,request.headers.get('User-Agent')
How to read typical function documentation in Python?,"Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)"
How can I efficiently move from a Pandas dataframe to JSON,aggregated_df.reset_index().to_json(orient='index')
Creating a log-linear plot in matplotlib using hist2d,plt.show()
Comma separated lists in django templates,{{(value | join): ' // '}}
How do you use multiple arguments in {} when using the .format() method in Python,"""""""{0:>15.2f}"""""".format(1464.1000000000001)"
Django - how to create a file and save it to a model's FileField?,"self.license_file.save(new_name, ContentFile('A string with the file content'))"
How do I check if a string exists within a string within a column,df[self.target].str.contains(t).any()
How to format pubDate with Python,"mytime.strftime('%a, %d %b %Y %H:%M:%S %z')"
multiple assigments with a comma in python,"a = b, c = 'AB'"
How to do a less than or equal to filter in Django queryset?,User.objects.filter(userprofile__level__lte=0)
How can I insert data into a MySQL database?,cursor.execute('SELECT * FROM anooog1;')
How to round to two decimal places in Python 2.7?,print('financial return of outcome 1 = {:.2f}'.format(1.23456))
How do I stack vectors of different lengths in NumPy?,"ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])"
Most pythonic way to extend a potentially incomplete list,"map(lambda a, b: a or b, choicesTxt, [('Choice %i' % n) for n in range(1, 10)])"
How to compare elements in a list of lists and compare keys in a list of lists in Python?,len(set(a))
Python filter/remove URLs from a list,list2 = [line for line in file if 'CONTENT_ITEM_ID' in line]
Capturing group with findall?,"re.findall('(1(23)45)', '12345')"
Removing duplicate strings from a list in python,a = list(set(a))
All possible permutations of a set of lists in Python,list(itertools.product(*s))
python - find the occurrence of the word in a file,"Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})"
What is the most effective way to incremente a large number of values in Python?,"boxes = [(0, gp1), (0, gp2), (1, gp3), (1, gp4), (0, gp5)]"
How to assert a dict contains another dict without assertDictContainsSubset in python?,set(d1.items()).issubset(set(d2.items()))
Parse and format the date from the GitHub API in Python,"date.strftime('%A %b %d, %Y at %H:%M GMT')"
Isolation level with Flask-SQLAlchemy,db.session.query(Printer).all()
Python: load words from file into a set,set(line.strip() for line in open('filename.txt'))
How to specify that a parameter is a list of specific objects in Python docstrings,"type([1, 2, 3]) == type(['a', 'b', 'c'])"
Combining two sorted lists in Python,"[2.860386848449707, 2.758984088897705, 2.768254041671753]"
Combining two sorted lists in Python,"[9.743937969207764, 9.884459972381592, 9.552299976348877]"
How to equalize the scales of x-axis and y-axis in Python matplotlib?,plt.draw()