title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Why does Django use tuples for settings and not lists? | 12,349,784 | 14 | 2012-09-10T10:27:08Z | 12,363,023 | 9 | 2012-09-11T05:00:43Z | [
"python",
"django",
"list",
"tuples",
"semantics"
] | Quoting [this answer](http://stackoverflow.com/questions/626759/whats-the-difference-between-list-and-tuples-in-python):
> Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while ... | Based on user1474837's helpful link to the [Django ticket](https://code.djangoproject.com/ticket/8846) on this question, it seems clear that tuples are used for backwards compatibility with the way settings were done from the start, which was with tuples due to the belief they were faster than lists. (They are, but onl... |
Python not equal operator | 12,351,221 | 8 | 2012-09-10T11:58:33Z | 12,351,237 | 13 | 2012-09-10T11:59:25Z | [
"python",
"deprecated",
"not-operator"
] | I come from a c style languages, so I am natural in using `!=` as not equal, but when I came to Python, from the documentation I read, I learned that for this purpose the `<>` operator is used.
Recently, I have seen a lot of code using `!=`, so my question is if one of them is preferred over the other or is one of the... | Python 2 supports *both*, in python 3 the `<>` operator has been removed.
There is no difference between the two, but [`!=` is the preferred form](http://docs.python.org/library/stdtypes.html#comparisons). |
Python : Converting CLI to GUI | 12,351,786 | 5 | 2012-09-10T12:30:49Z | 12,352,237 | 9 | 2012-09-10T12:57:54Z | [
"python",
"tkinter"
] | I have a Python program which performs a set of operations and prints the response on STDOUT. Now I am writing a GUI which will call that already existing code and I want to print the same contents in the GUI instead of STDOUT. I will be using the Text widget for this purpose. I do not want to modify my existing code w... | You can probably solve this by replacing `sys.stdout` with your own file-like object that writes to the text widget.
For example:
```
import Tkinter as tk
import sys
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
toolbar = tk.Frame(self)
toolbar.pack(side="top", fill="x... |
How to use SQLAlchemy to seamlessly access multiple databases? | 12,352,455 | 5 | 2012-09-10T13:10:57Z | 12,352,483 | 7 | 2012-09-10T13:12:53Z | [
"python",
"postgresql",
"sqlalchemy"
] | Lets say I created a product database system for different departments of my company. Each department has its own PostgreSQL-databse-instance for various reasons. The schemata of the databases are the same, however the data in them is not. For each of these systems a Python application exists that does some business lo... | Sure you can do that with SQLAlchemy.
All you need to do is create different connection engines, each with their own session maker. Nothing in SQLAlchemy limits you to only one database at a time.
```
engines = []
sessions = []
for dbconninfo in databases:
engine = create_engine(dbconninfo)
engines.append(eng... |
Python JSON get values | 12,353,288 | 6 | 2012-09-10T14:00:42Z | 12,353,363 | 17 | 2012-09-10T14:04:09Z | [
"python",
"json",
"simplejson"
] | While I am trying to retrieve values from JSON string, it gives me an error:
```
data = json.loads('{"lat":444, "lon":555}')
return data["lat"]
```
But, if I iterate over the data, it gives me the elements (lat and lon), but not the values:
```
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in da... | If you want to iterate over both keys and values of the dictionary, do this:
```
for key, value in data.items():
print key, value
``` |
Python JSON get values | 12,353,288 | 6 | 2012-09-10T14:00:42Z | 12,353,373 | 9 | 2012-09-10T14:04:35Z | [
"python",
"json",
"simplejson"
] | While I am trying to retrieve values from JSON string, it gives me an error:
```
data = json.loads('{"lat":444, "lon":555}')
return data["lat"]
```
But, if I iterate over the data, it gives me the elements (lat and lon), but not the values:
```
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in da... | What error is it giving you?
If you do exactly this:
```
data = json.loads('{"lat":444, "lon":555}')
```
Then:
```
data['lat']
```
**SHOULD NOT** give you any error at all. |
x11 forwarding with paramiko | 12,354,047 | 11 | 2012-09-10T14:43:31Z | 12,903,844 | 13 | 2012-10-15T20:56:06Z | [
"python",
"x11",
"paramiko",
"x11-forwarding"
] | I'm trying to run a command with `paramiko` that should be able to open an X window. The script I'm using would something as follows:
```
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('192.168.1... | Reading the paramiko code, I realized that paramiko only implements a way to establish an x11 channel. It does not connect the channel to the local x11 display. That is left to you.
Here is a small implementation that I have just written:
```
#!/usr/bin/env python
import os
import select
import sys
import paramiko
... |
What is the difference between sets and lists in Python? | 12,354,515 | 9 | 2012-09-10T15:09:41Z | 12,354,550 | 29 | 2012-09-10T15:11:41Z | [
"python",
"list",
"set"
] | Is the only difference between sets and lists in Python the fact that you can use the union, intersect, difference, symmetric difference functions to compare two sets? Why can't these functions simply be applied to lists? In what situations are sets more useful than lists? | There's a huge difference.
1. Sets can't contain duplicates
2. Sets are unordered
3. In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes `__contains__` (`in` operator) a lot more efficient for sets than lists.
4. Sets can only contain hashable items (see #3). If yo... |
Python: what are the nearest Linux and OSX equivalents of winsound.Beep? | 12,354,586 | 20 | 2012-09-10T15:14:01Z | 12,354,772 | 9 | 2012-09-10T15:25:57Z | [
"python",
"linux",
"osx",
"audio"
] | If one wishes to beep the speaker on Windows, Python 2 apparently provides a useful function: `winsound.Beep()`. The neat thing about this function is that it takes arguments specifying the exact frequency and duration of the beep. This is exactly what I want to do, except that I don't use Windows. So...
What are the ... | I found a potential solution here:
<http://bytes.com/topic/python/answers/25217-beeping-under-linux>
It involves writing directly to /dev/audio. Not sure how portable it is or if it even works at all - i'm not on a linux machine atm.
```
def beep(frequency, amplitude, duration):
sample = 8000
half_period = in... |
Django: cannot import name formset_factory | 12,355,293 | 4 | 2012-09-10T15:58:16Z | 12,355,339 | 11 | 2012-09-10T16:00:51Z | [
"python",
"django",
"pycharm",
"python-import"
] | I have trouble importing formset\_factory from django.
Here's the traceback:
```
from django.forms import formset_factory
Environment:
Request Method: GET
Request URL: http://localhost:8000/forma/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
['debug_toolbar',
'django_extensions',
'gunico... | You are importing it from the wrong location, you need to import from `django.forms.formsets` instead:
```
from django.forms.formsets import formset_factory
```
See the [Formsets documentation](https://docs.djangoproject.com/en/dev/topics/forms/formsets/). |
Pandas: create two new columns in a dataframe with values calculated from a pre-existing column | 12,356,501 | 55 | 2012-09-10T17:17:38Z | 12,356,541 | 76 | 2012-09-10T17:20:49Z | [
"python",
"pandas"
] | I am working with the [pandas](http://pandas.pydata.org/) library and I want to add two new columns to a dataframe `df` with n columns (n > 0).
These new columns result from the application of a function to one of the columns in the dataframe.
The function to apply is like:
```
def calculate(x):
...operate...
... | I'd just use `zip`:
```
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2... |
use of yield with a dict comprehension | 12,358,063 | 18 | 2012-09-10T19:18:06Z | 12,358,279 | 11 | 2012-09-10T19:34:20Z | [
"python",
"generator",
"yield"
] | As a contrived example:
```
myset = set(['a', 'b', 'c', 'd'])
mydict = {item: (yield ''.join([item, 's'])) for item in myset}
```
and `list(mydict)` gives:
```
['as', 'cs', 'bs', 'ds', {'a': None, 'b': None, 'c': None, 'd': None}]
```
What happens here? What does `yield` do? And is this behavior consistent no matte... | First of all, what does `yield` return? The answer in this case is `None`, because `yield` returns the parameter passed to `next()`, which is nothing in this case (`list` doesn't pass anything to `next`).
Now here's your answer:
```
>>> myset = set(['a', 'b', 'c', 'd'])
>>> mydict = {item: (yield ''.join([item, 's'])... |
Keep plotting window open in Matplotlib | 12,358,312 | 16 | 2012-09-10T19:36:13Z | 12,359,099 | 10 | 2012-09-10T20:39:59Z | [
"python",
"matplotlib"
] | When writing scripts that use matplotlib, I temporally get an interactive graphing window when I run the script, which immediately goes away before I can view the plot. If I execute the same code interactively inside iPython, the graphing window stays open. How can I get matplotlib to keep a plot open once it is produc... | According to the [documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.show), there's an experimental `block` parameter you can pass to `plt.show()`. Of course, if your version of matplotlib isn't new enough, it won't have this.
If you have this feature, you should be able to replace ... |
Python pandas order column according to the values in a row | 12,358,360 | 11 | 2012-09-10T19:39:24Z | 12,358,601 | 17 | 2012-09-10T20:00:09Z | [
"python",
"sorting",
"pandas"
] | How do I order columns according to the values of the last row? In the example below, my final df will have columns in the following order: 'ddd' 'aaa' 'ppp' 'fff'.
```
>>> df = DataFrame(np.random.randn(10, 4), columns=['ddd', 'fff', 'aaa', 'ppp'])
>>> df
ddd fff aaa ppp
0 -0.177438 0.10256... | [updated to simplify]
tl;dr:
```
In [29]: new_columns = df.columns[df.ix[df.last_valid_index()].argsort()]
In [30]: df[new_columns]
Out[30]:
aaa ppp fff ddd
0 0.328281 0.375458 1.188905 0.503059
1 0.305457 0.186163 0.077681 -0.543215
2 0.684265 0.681724 0.210636 -0.532685
3 -1.13... |
Python - Importing Excel dates converts to number | 12,359,853 | 3 | 2012-09-10T21:37:47Z | 12,360,030 | 7 | 2012-09-10T21:57:43Z | [
"python",
"xlrd"
] | I'm trying to learn to the use the xlrd package in Python to read Excel files, and I have made a sample file which contains a list of chronological dates and in the second column the day of the week it corresponds to.
The problem is that when I read in the data it displays it as a number. How can I get the date to dis... | you want
```
wb = xlrd.open_workbook("somewb.xls")
my_date_tuple = xlrd.xldate_as_tuple(xls_timestamp_number,wb.datemode)
```
which then returns a date tuple that is much easier to work with :) |
twitter bootstrap href button does not work | 12,361,018 | 3 | 2012-09-11T00:02:51Z | 12,361,036 | 12 | 2012-09-11T00:05:41Z | [
"python",
"html",
"django",
"twitter-bootstrap",
"django-templates"
] | I am creating a html template for a django based app. I am using the twitter bootstrap API for buttons here, but one of them (the cancel button) doesn't seem to be working correctly. I link it to another page using an href, but when I click on the button, it redirects to the current page's post method. See below:
```
... | You have a `<button>` inside an `<a>` element - get rid of the button, otherwise you'll be submitting your form.
If you want your anchor to be styled as a button, give it a `btn` class.
And Bootstrap is just a big set of CSS facilities with little js thrown in - no APIs at all :))
EDIT: nowadays HTML semantics and a... |
Repetitive code in unittest testcase | 12,361,990 | 5 | 2012-09-11T02:40:39Z | 12,362,086 | 9 | 2012-09-11T02:52:47Z | [
"python",
"unit-testing",
"python-3.x",
"refactoring"
] | I have a testcase that looks like this:
```
def MyTestCase(unittest.Testcase):
def test_input01(self):
input = read_from_disk('input01')
output = run(input)
validated_output = read_from_disk('output01')
self.assertEquals(output, validated_output)
def test_input02(self):
input = read_from_disk('... | Write a helper function to remove the repetition from the test cases:
```
def MyTestCase(unittest.Testcase):
def run_input_output(self, suffix):
input = read_from_disk('input'+suffix)
output = run(input)
validated_output = read_from_disk('output'+suffix)
self.assertEquals(output, validated_output)
... |
Same consistent-hashing algorithm implementation for Java and Python program | 12,362,417 | 6 | 2012-09-11T03:38:49Z | 12,365,295 | 7 | 2012-09-11T08:02:41Z | [
"java",
"python",
"consistent-hashing"
] | We have an app that the Python module will write data to redis shards and the Java module will read data from redis shards, so I need to implement the exact same consistent hashing algorithm for Java and Python to make sure the data can be found.
I googled around and tried several implementations, but found the J... | You seem to be running into two issues simultaneously: encoding issues and representation issues.
Encoding issues come about particularly since you appear to be using Python 2 - Python 2's `str` type is not at all like Java's `String` type, and is actually more like a Java array of `byte`. But Java's `String.getBytes(... |
Python server "Only one usage of each socket address is normally permitted" | 12,362,542 | 9 | 2012-09-11T03:56:38Z | 12,362,623 | 12 | 2012-09-11T04:07:35Z | [
"python",
"sockets",
"connection",
"webserver"
] | I'm trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:
```
from socket import *
serverName = "localhost"
serverPor... | Enable the [SO\_REUSEADDR](http://hea-www.harvard.edu/~fine/Tech/addrinuse.html) socket option before calling bind(). This allows the address/port to be reused immediately instead of it being stuck in the TIME\_WAIT state for several minutes, waiting for late packets to arrive.
```
s.setsockopt(SOL_SOCKET, SO_REUSEADD... |
What does the ./ (dot slash) operator represent in Python? | 12,363,665 | 2 | 2012-09-11T06:07:53Z | 12,363,684 | 11 | 2012-09-11T06:09:34Z | [
"python"
] | I am trying to port a piece of code from Python to PHP. I've come across a line that I don't understand the notation for.
```
secLat = 1./cos(lat)
```
What does the ./ operator do in this context? | You are reading that wrong I'm afraid; it's:
```
(1.)/cos(lat)
```
so, divide floating point value `1.0` (with the zero omitted) by the `cos()` of `lat`. |
South - How to force certain migration? | 12,364,157 | 17 | 2012-09-11T06:47:17Z | 12,365,317 | 55 | 2012-09-11T08:04:10Z | [
"python",
"django",
"django-south"
] | I have a migration, 003, that creates a new table, but for some reason, South isn't creating a new table after executing that migration:
I am doing the following command:
```
[kelp@web187 goals]$ python2.7 manage.py migrate main 0003_auto__add_nudge
Running migrations for main:
- Migrating backwards to just after 000... | It seems like you've faked migration 0006 forward, you should fake it backward too:
```
manage.py migrate --fake yourapp 0005
```
This will set the current migration to 0005.
Apparently, you want to migrate back to 0002:
```
manage.py migrate --fake yourapp 0002
```
And then start over at 0003:
```
manage.py migr... |
How to delete Tkinter widgets from a window? | 12,364,981 | 21 | 2012-09-11T07:41:19Z | 12,365,098 | 34 | 2012-09-11T07:49:10Z | [
"python",
"tkinter"
] | I have a list of Tkinter widgets that I want to change dynamically.
How can I go about completely deleting the widgets from my window? | You can call [`pack_forget`](http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_forget-method) to remove a widget (if you use [`pack`](http://effbot.org/tkinterbook/pack.htm) to add it to the window).
Example:
```
from tkinter import *
root = Tk()
b = Button(root, text="Delete me", command=lambda: b.pack_forg... |
How do I catch a pyqt closeEvent and minimize the dialog instead of exiting? | 12,365,202 | 4 | 2012-09-11T07:56:26Z | 12,366,684 | 9 | 2012-09-11T09:29:52Z | [
"python",
"pyqt",
"pyqt4",
"qdialog"
] | I have a QDialog object. When the user clicks on the `X` button or presses `Ctrl+Q`, I want the dialog to go to a minimized view or system tray icon, instead of closing. How do I do that? | A simple subclass that minimizes instead of closing is the following:
```
class MyDialog(QtGui.QDialog):
# ...
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
# when you want to destroy the dialog set this to True
self._want_to_close = False
def closeEvent(... |
Sorting based on one of the list among Nested list in python | 12,368,231 | 3 | 2012-09-11T11:02:04Z | 12,368,333 | 7 | 2012-09-11T11:08:45Z | [
"python",
"list",
"sorting",
"nested"
] | I have a list as `[[4,5,6],[2,3,1]]`. Now I want to sort the list based on `list[1]` i.e. output should be `[[6,4,5],[1,2,3]]`. So basically I am sorting `2,3,1` and maintaining the order of `list[0]`.
While searching I got a function which sorts based on first element of every list but not for this. Also I do not wan... | Since `[4, 5, 6]` and `[2, 3, 1]` serves two different purposes I will make a function taking *two* arguments: the list to be reordered, and the list whose sorting will decide the order. I'll only return the reordered list.
[This answer](http://stackoverflow.com/a/6979121/566644) has timings of three different solutio... |
What is the scope of a random seed in Python? | 12,368,996 | 8 | 2012-09-11T11:46:41Z | 12,369,081 | 11 | 2012-09-11T11:51:58Z | [
"python",
"random",
"scope",
"random-seed"
] | If I use the Python function `random.seed(my_seed)` in one class in my module, will this seed remain for all the other classes instantiated in this module? | Yes, the seed is set for the (hidden) global `Random()` instance in the module. From the [documentation](http://docs.python.org/library/random.html):
> The functions supplied by this module are actually bound methods of a hidden instance of the `random.Random` class. You can instantiate your own instances of`Random` t... |
What is the difference between Python and IPython? | 12,370,457 | 110 | 2012-09-11T13:08:09Z | 12,370,479 | 88 | 2012-09-11T13:09:30Z | [
"python",
"ipython"
] | What exactly is the difference between Python and [IPython](http://en.wikipedia.org/wiki/IPython)?
If I write code in Python, will it run in IPython as is or does it need to be modified?
I know IPython is supposed to be an interactive shell for Python, but is that all? Or is there a language called IPython? If I writ... | [`ipython`](http://ipython.org/) is an interactive shell built with python.
From the project website:
> IPython provides a rich toolkit to help you make the most out of using Python, with:
>
> * Powerful Python shells (terminal and Qt-based).
> * A web-based notebook with the same core features but support for code, ... |
What is the difference between Python and IPython? | 12,370,457 | 110 | 2012-09-11T13:08:09Z | 24,313,569 | 8 | 2014-06-19T18:13:12Z | [
"python",
"ipython"
] | What exactly is the difference between Python and [IPython](http://en.wikipedia.org/wiki/IPython)?
If I write code in Python, will it run in IPython as is or does it need to be modified?
I know IPython is supposed to be an interactive shell for Python, but is that all? Or is there a language called IPython? If I writ... | Even after viewing this thread, I had thought that ipython was a synonym for the python shell, in other words that typing python at the command line put one into ipython mode.
It is in fact, as referenced above, a very cool interactive shell (command line program) that can be installed from [iPython.org](http://ipytho... |
Parse JSON and store data in Python Class | 12,370,498 | 4 | 2012-09-11T13:10:30Z | 12,370,776 | 10 | 2012-09-11T13:24:09Z | [
"python",
"json",
"class"
] | This is my JSON data
```
[
{
"id":1,
"name":"abc",
"phone": "12345",
"Charecteristics": [
{
"id":1,
"name":"Good Looking",
"rating": "Average",
}
{
"id":2,
"name":"Sma... | Take a look at [colander](http://docs.pylonsproject.org/projects/colander/en/latest/); it makes turning a JSON data structure into Python objects dead easy.
You define a schema:
```
import colander
class Characteristic(collander.MappingSchema):
id = colander.SchemaNode(colander.Int(),
... |
Using variables in signal handler - require global? | 12,371,361 | 9 | 2012-09-11T13:54:39Z | 12,371,637 | 11 | 2012-09-11T14:08:27Z | [
"python"
] | I have a signal handler to handle ctrl-c interrupt. If in the signal handler I want to read a variable set in my main script, is there an alternative to using a "global" statement when setting the variable?
I don't mind doing this, but read this post ([Do you use the "global" statement in Python?](http://stackoverflow... | You can use a closure as the signal handler that acquires its state from the main script:
```
import signal
import sys
import time
def main_function():
data_for_signal_handler = 10
def signal_handler(*args):
print data_for_signal_handler
sys.exit()
signal.signal(signal.SIGINT, signal_ha... |
Why does Python (IronPython) report "Illegal characters in path" when the word bin is used? | 12,371,417 | 8 | 2012-09-11T13:57:22Z | 12,371,451 | 13 | 2012-09-11T13:59:00Z | [
"python",
"ironpython",
"illegal-characters"
] | I am getting an "Illegal characters in path" error when doing chdir commands in Iron Python. This is happening in run time with my code, but even in the Iron Python console it has this issue. I'm using the nt module because in code the os module does not work (appears to be a known issue).
Doing a little bit of playin... | The `\` path separator is also a python escape character. Double them, or better yet, use `r''` raw python literals instead:
```
r'c:\Users\xxxxx\Documents\Visual Studio 2010\Projects\xxx'
'c:\\Users\\xxxxx\\Documents\\Visual Studio 2010\\Projects\\xxx'
```
For example, `\n` is a newline character, and `\t` is interp... |
Can't compare strings in Python | 12,372,281 | 2 | 2012-09-11T14:40:53Z | 12,372,595 | 7 | 2012-09-11T14:55:57Z | [
"python",
"string",
"compare",
"match",
"readline"
] | I have this code that should open and read two text files, and match when a word is present in both. The match is represented by printing "SUCESS" and by writing the word to a temp.txt file.
```
dir = open('listac.txt','r')
path = open('paths.txt','r')
paths = path.readlines()
paths_size = len(paths)
matches = open('t... | While we're reading the entire datafiles into memory anyway, why not try to use `sets` and get the intersection?:
```
def format_data(x):
return x.rstrip().replace(' ','').split('.')[0].lower()
with open('listac.txt') as dirFile:
dirStuff = set( format_data(dline) for dline in dirFile )
with open('paths.txt... |
How do I make Pip respect requirements? | 12,372,336 | 10 | 2012-09-11T14:43:47Z | 12,372,382 | 14 | 2012-09-11T14:45:51Z | [
"python",
"dependencies",
"pip"
] | If I create a setup.py using `requires`, Pip doesn't install my dependencies.
Here's my setup.py:
```
from distutils.core import setup
setup(name='my_project',
description="Just a test project",
version="1.0",
py_modules=['sample'],
requires=['requests'])
```
I wrote a simple sample.py:
```... | The correct spelling is `install_requires`, not `requires`; this does require that you use [`setuptools`](http://pythonhosted.org/setuptools/setuptools.html), not `distutils`:
```
from setuptools import setup
setup(name='my_project',
description="Just a test project",
version="1.0",
py_modules=['sam... |
Using numpy.median on a masked array | 12,372,594 | 6 | 2012-09-11T14:55:54Z | 12,372,625 | 8 | 2012-09-11T14:57:25Z | [
"python",
"numpy"
] | I'm a little confused about the output of numpy.median in the case of masked arrays. Here is a simple example (assuming numpy is imported - I have version 1.6.2):
```
>>> a = [3.0, 4.0, 5.0, 6.0, numpy.nan]
>>> am = numpy.ma.masked_array(a, [numpy.isnan(x) for x in a])
```
I'd like to be able to use the masked array ... | Use `np.ma.median` on a `MaskedArray`.
[*Explanation: If I remember correctly, the `np.median` does not support subclasses, so it fails to work correctly on `np.ma.MaskedArray`.*] |
Python try block does not catch os.system exceptions | 12,373,563 | 3 | 2012-09-11T15:51:36Z | 12,373,653 | 12 | 2012-09-11T15:56:44Z | [
"python",
"try-catch",
"os.system",
"except"
] | I have this python code:
```
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
```
The code prints:
```
wrongcommand: command not found
```
Instead of `command does not work`. Does anyone know why it's not printing my error message? | If you want to have an exception thrown when the command doesn't exist, you should use `subprocess`:
```
import subprocess
try:
subprocess.call(['wrongcommand'])
except OSError:
print ('wrongcommand does not exist')
```
Come to think of it, you should probably use `subprocess` instead of `os.system` anyw... |
heapq module python | 12,373,837 | 5 | 2012-09-11T16:08:53Z | 12,373,856 | 9 | 2012-09-11T16:09:53Z | [
"python",
"list",
"priority-queue"
] | I'm using the `heapq` module to determine the smallest item in a list.
I have this below code, but the `heapq.heapify()` return value is None.
How do I get the result in a new list?
```
>>> a=heapq.heapify(lista)
>>> a
>>> lista=[1,2,3,4,5]
>>> a=heapq.heapify(lista)
>>> print(a)
None
``` | `heapq.heapify` doesn't return anything, it heapifies the list in place; it's far more efficient to do it that way:
```
>>> import heapq
>>> lista = [44, 42, 3, 89, 10]
>>> heapq.heapify(lista)
>>> lista
[3, 10, 44, 89, 42]
```
If you need a *new* list, create a copy fist:
```
>>> lista = [44, 42, 3, 89, 10]
>>> new... |
Recursion to find depth of expression | 12,374,193 | 5 | 2012-09-11T16:35:44Z | 12,374,234 | 11 | 2012-09-11T16:39:07Z | [
"python",
"recursion",
"tracking",
"depth"
] | I am trying to use recursion to find the depth of an "expression", i.e., how many layers of nested tuples there are: For example,
```
depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2
depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
```
Basically, I figured that I need to ch... | You're on the right track, but instead of finding the "total" depth with `count += 1 + depth(expr[x])`, use `max` to find the maximum:
```
def depth(expr):
if not isinstance(expr, tuple):
return 0
# this says: return the maximum depth of any sub-expression + 1
return max(map(depth, expr)) + 1
prin... |
python continue with except if condition not met | 12,374,694 | 5 | 2012-09-11T17:12:57Z | 12,374,733 | 7 | 2012-09-11T17:16:02Z | [
"python",
"try-catch"
] | I often find myself wanting to do something like this, I have something wrapped in try excepts like this
```
item= get_item()
try:
do_work(item)
except SomeError as err:
if err.code == 123:
do_something(item)
else:
# Actually I don't want to do something with this error code... I want to ha... | If you are using a recent enough python version (2.5 and up), you should switch to using a [context manager](http://docs.python.org/reference/datamodel.html#context-managers) instead:
```
class WorkItemContextManager(object):
def __enter__(self):
self.item = get_item()
return self.item
def __e... |
How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay? | 12,374,781 | 5 | 2012-09-11T17:19:11Z | 12,380,595 | 7 | 2012-09-12T02:52:22Z | [
"python",
"numpy",
"scipy",
"triangulation",
"delaunay"
] | I have been searching for an answer to this question but cannot find anything useful.
I am working with the python scientific computing stack (scipy,numpy,matplotlib) and I have a set of 2 dimensional points, for which I compute the Delaunay traingulation ([wiki](https://en.wikipedia.org/wiki/Delaunay_triangulation)) ... | I figured it out on my own, so here's an explanation for anyone future person who is confused by this.
As an example, let's use the simple lattice of points that I was working with in my code, which I generate as follows
```
import numpy as np
import itertools as it
from matplotlib import pyplot as plt
import scipy a... |
Matplotlib - why is Bar graph line color is black? | 12,375,478 | 5 | 2012-09-11T18:10:42Z | 12,375,521 | 20 | 2012-09-11T18:13:06Z | [
"python",
"colors",
"matplotlib",
"bar-chart"
] | I am using Matplotlib to graph list of floats. If my list is 100 floats long the graph displays the proper colors. But if the list is 785 floats long then the it only shows black color. Here is the code.
```
import numpy as np
import matplotlib.pyplot as plt
import Image
Consensus = []
Prediction = []
Final = []
for ... | The borders of your bars are black. It's possible that when you have so many bars, they become very narrow and the borders mush together, so you only see the borders and not the colored insides. Try zooming in on your graph to see if the colors are there. You could also pass an `edgecolor='none'` argument to `bar` to r... |
Plotting elliptical orbits | 12,375,609 | 3 | 2012-09-11T18:19:26Z | 12,375,710 | 7 | 2012-09-11T18:26:54Z | [
"python",
"matplotlib",
"astronomy",
"orbital-mechanics"
] | I'm trying to write a code that plots the elliptical paths of an object using the equation for the ellipse r=a(1-e^2)/(1+e\*cos(theta)). I'd also like this data to be put into an array for other use.
```
from numpy import *#Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot lib... | Do not call `plt.polar` once for every point. Instead, call it once, with all the data as input:
```
import numpy as np #Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot library
cos = np.cos
pi = np.pi
a = 5
e = 0.3
theta = np.linspace(0,2*pi, 360)
r = (a*(1-e**2))/(1+e*cos(... |
Check if any value of a dictionary matches a condition | 12,376,079 | 8 | 2012-09-11T18:51:00Z | 12,376,181 | 15 | 2012-09-11T18:58:13Z | [
"python",
"python-2.7"
] | How does a python programmer check if any value of a dictionary matches a condition (is greater than `0` in my case). I'm looking for the most "pythonic" way that has minimal performance-impact.
my dictionary:
```
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
```
I used these 2 (mo... | You can use `any` [[docs]](http://docs.python.org/library/functions.html#any):
```
>>> pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
>>> any(v > 0 for v in pairs.itervalues())
True
>>> any(v > 3000 for v in pairs.itervalues())
False
```
See also `all` [[docs]](http://docs.python.org... |
Should I "Compile .py Files to Byte Code after Installation"? | 12,376,188 | 26 | 2012-09-11T18:58:50Z | 12,376,330 | 31 | 2012-09-11T19:08:35Z | [
"python",
"python-3.x",
"installation"
] | I am installing python 3.2 32bit on Win7 machine, there is option "Compile .py Files to Byte Code after Installation".
Should I leave option unchecked or is compilation recommended?
Thank you | Since the bytecode is unlikely to change regardless of how many times it is compiled, the interpreter can take advantage of the small speedup gain. Unless you are *very* short of hard drive space, you should select this option. |
Adding calculated column(s) to a dataframe in pandas | 12,376,863 | 44 | 2012-09-11T19:48:28Z | 12,377,080 | 22 | 2012-09-11T20:04:39Z | [
"python",
"pandas"
] | I have an OHLC price data set, that I have parsed from CSV into a Pandas dataframe and resampled to 15 min bars:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 500047 entries, 1998-05-04 04:45:00 to 2012-08-07 00:15:00
Freq: 15T
Data columns:
Close 363152 non-null values
High 363152 non-null values
... | You could have `is_hammer` in terms of `row["Open"]` etc. as follows
```
def is_hammer(rOpen,rLow,rClose,rHigh):
return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
and closed_in_top_half_of_range(rHigh,rLow,rClose)
```
Then you can use map:
```
df["isHammer"] = map(is_hammer, df["Open"], df["... |
Adding calculated column(s) to a dataframe in pandas | 12,376,863 | 44 | 2012-09-11T19:48:28Z | 12,377,083 | 44 | 2012-09-11T20:04:56Z | [
"python",
"pandas"
] | I have an OHLC price data set, that I have parsed from CSV into a Pandas dataframe and resampled to 15 min bars:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 500047 entries, 1998-05-04 04:45:00 to 2012-08-07 00:15:00
Freq: 15T
Data columns:
Close 363152 non-null values
High 363152 non-null values
... | The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the `map` and `apply` functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise... |
Is there a library function in Python to turn a generator-function into a function returning a list? | 12,377,013 | 16 | 2012-09-11T19:59:45Z | 12,377,059 | 16 | 2012-09-11T20:03:26Z | [
"python",
"generator"
] | A number of times I've thought that generator style can be more direct that returning a list, for example,
```
def foo(input_array):
for x in input_array:
yield processed(x)
```
vs.
```
def bar(input_array):
accumulator = []
for x in input_array:
accumulator.append(processed(x))
retur... | To the best of my knowledge (and I've looked, because I've wondered exactly the same thing), no: there is no direct way of doing this with the standard library.
There is a thoroughly tested `listify` wrapper in unstdlib.py library, though: <https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L... |
How can a Python function determine if (and how) a kwarg default was explicitly passed? | 12,377,450 | 2 | 2012-09-11T20:30:05Z | 12,377,543 | 7 | 2012-09-11T20:36:55Z | [
"python",
"introspection"
] | Suppose a function `spam` has signature `spam(ham=None)`. The following three calls will all cause the local variable `ham` in `spam`'s namespace to have value `None`:
```
spam()
spam(None)
spam(ham=None)
```
How can `spam` find out which of these three alternatives was actually used? | It can't. [This question](http://stackoverflow.com/questions/1408818/getting-the-the-keyword-arguments-actually-passed-to-a-python-method) describes a way to use a decorator to wrap the function and set the passed arguments as attributes on it. But there is no way to find out from within `spam` without help from outsid... |
Python - write() versus writelines() and concatenated strings | 12,377,473 | 35 | 2012-09-11T20:31:47Z | 12,377,541 | 46 | 2012-09-11T20:36:47Z | [
"python",
"string",
"file-io",
"python-2.x"
] | So I'm learning Python. I am going through the lessons and ran into a problem where I had to condense a great many `target.write()` into a single `write()`, while having a `"\n"` between each user input variable(the object of `write()`).
I came up with:
```
nl = "\n"
lines = line1, nl, line2, nl, line3, nl
textdoc.wr... | `writelines` expects a list of strings, while `write` expects a single string.
`line1 + "\n" + line2` merges those strings together into a single string before passing it to `write`.
Note that if you have many lines, you may want to use `"\n".join(list_of_lines)`. |
Python - write() versus writelines() and concatenated strings | 12,377,473 | 35 | 2012-09-11T20:31:47Z | 12,377,575 | 51 | 2012-09-11T20:40:17Z | [
"python",
"string",
"file-io",
"python-2.x"
] | So I'm learning Python. I am going through the lessons and ran into a problem where I had to condense a great many `target.write()` into a single `write()`, while having a `"\n"` between each user input variable(the object of `write()`).
I came up with:
```
nl = "\n"
lines = line1, nl, line2, nl, line3, nl
textdoc.wr... | *Why am I unable to use a string for a newline in write() but I can use it in writelines()?*
The idea is the following: if you want to write a single string you can do this with `write()`. If you have a sequence of strings you can write them all using `writelines()`.
`write(arg)` expects a string as argument and writ... |
How is exponentiation implemented in Python? | 12,377,632 | 9 | 2012-09-11T20:45:15Z | 12,377,729 | 8 | 2012-09-11T20:52:00Z | [
"python"
] | I am able to compute any normally computable fibonnaci number (unless the result becomes to large) in a constant time using Binet's formula ie closed solution formula to compute fibonnaci numbers. Here is my code:
for the non-recursive implementation of fibonnaci:
```
gr = (1 + 5**0.5) / 2
def gfib(n):
return int... | Exponents for integers can be calculated much more efficiently than you think. Here's what [Wikipedia has to say about it](https://en.wikipedia.org/wiki/Exponentiation#Efficient_computation_of_integer_powers):
> The simplest method of computing bâ¿ requires nâ1 multiplication operations, but it can be computed more... |
How is exponentiation implemented in Python? | 12,377,632 | 9 | 2012-09-11T20:45:15Z | 12,378,443 | 11 | 2012-09-11T21:50:21Z | [
"python"
] | I am able to compute any normally computable fibonnaci number (unless the result becomes to large) in a constant time using Binet's formula ie closed solution formula to compute fibonnaci numbers. Here is my code:
for the non-recursive implementation of fibonnaci:
```
gr = (1 + 5**0.5) / 2
def gfib(n):
return int... | The [float.\_\_pow\_\_()](http://hg.python.org/cpython/file/6fea947edead/Objects/floatobject.c#l744) method uses C's [*libm*](http://www.slac.stanford.edu/comp/unix/package/rtems/doc/html/libm/libm.info.pow.html) which takes full advantage of hardware support for binary floating point arithmetic. The latter represents ... |
How to create numpy structured array with multiple fields of different shape? | 12,377,722 | 3 | 2012-09-11T20:51:34Z | 12,377,831 | 10 | 2012-09-11T20:59:52Z | [
"python",
"arrays",
"numpy",
"structure"
] | I'm new to working with numpy arrays and I'm having trouble creating a structured array. I'd like to create something similar to a Matlab structure where the fields can be arrays of different shapes.
```
a=numpy.array([1, 2, 3, 4, 5, 6,]);
b=numpy.array([7,8,9]);
c=numpy.array([10,11,12,13,14,15,16,17,18,19,20]);
##D... | I'm afraid it's not possible without twisting NumPy's arm a lot.
See, the idea behind NumPy is to provide *homogeneous* arrays, that is, arrays of elements that all have the same type. This type can be simple (`int`, `float`...) or more complicated (`[('',int),('',float),('',"|S10")])`, but in any case, all the elemen... |
MySQLdb with multiple transaction per connection | 12,378,227 | 5 | 2012-09-11T21:32:40Z | 12,379,023 | 11 | 2012-09-11T22:52:43Z | [
"python",
"mysql",
"database",
"database-connection",
"mysql-python"
] | Is it okay to use a single MySQLdb connection for multiple transactions without closing the connection between them? In other words, something like this:
```
conn = MySQLdb.connect(host="1.2.3.4", port=1234, user="root", passwd="x", db="test")
for i in range(10):
try:
cur = conn.cursor()
query = "... | I think there is a misunderstanding about what constitutes a transaction here.
Your example opens up one connection, then executes *one* transaction on it. You execute multiple SQL statements in that transaction, but you close it completely after committing. Of course that's more than fine.
Executing multiple *transa... |
Django-tastypie: Any example on file upload in POST? | 12,381,016 | 16 | 2012-09-12T03:59:19Z | 12,383,362 | 19 | 2012-09-12T07:42:50Z | [
"python",
"django",
"tastypie"
] | Could anyone give a complete example on using the tastypie FileField, both server-side and client-side please?
Here's what I have tried:
```
#models.py
class Foo(models.Model):
img = models.ImageField(upload_to="images", null=True, blank=True)
body = models.CharField()
#api.py
class FooResource(ModelResource... | Your Resources should look like this:
```
class FooResource(ModelResource):
img = fields.FileField(attribute="img", null=True, blank=True)
class Meta:
queryset = Foo.objects.all()
```
The `attribute` should correspond to the field in the model.
As stated in the documentation:
> ApiField.**attribute**... |
Twisted clients within pygame mainloop? | 12,381,446 | 6 | 2012-09-12T04:55:10Z | 12,382,295 | 8 | 2012-09-12T06:25:04Z | [
"python",
"twisted",
"pygame",
"main"
] | I'm trying to run a twisted-server with pygame-clients:
```
class ChatClientProtocol(LineReceiver):
def lineReceived(self,line):
print (line)
class ChatClient(ClientFactory):
def __init__(self):
self.protocol = ChatClientProtocol
def main():
flag = 0
default_screen()
while True:
... | You should *not* write your own main loop (with `while`) when using twisted. twisted has to control the main loop, and pygame is flexible enough to not care about (it does not need its *own* loop).
You should put everything which is inside your main loop into a function, and shedule it with the twisted reactor by call... |
Django: Calling .update() on a single model instance retrieved by .get()? | 12,381,756 | 13 | 2012-09-12T05:33:46Z | 12,381,801 | 19 | 2012-09-12T05:38:55Z | [
"python",
"django",
"models"
] | Have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects. If it returns 0, I create a new model instance in the `except DoesNotExist` clause of the function. Otherwise, I would like to update the fields in the pre-existing instance, without creating a new one. I was originall... | With the advent of Django 1.7, there is now a new [`update_or_create`](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#update-or-create) QuerySet method which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.
Example from the ... |
Django: Calling .update() on a single model instance retrieved by .get()? | 12,381,756 | 13 | 2012-09-12T05:33:46Z | 12,381,919 | 9 | 2012-09-12T05:49:22Z | [
"python",
"django",
"models"
] | Have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects. If it returns 0, I create a new model instance in the `except DoesNotExist` clause of the function. Otherwise, I would like to update the fields in the pre-existing instance, without creating a new one. I was originall... | I don't know how good or bad this is, but you can try something like this:
```
try:
obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
obj = Model.objects.create()
obj.__dict__.update(your_fields_dict)
obj.save()
``` |
Django: Calling .update() on a single model instance retrieved by .get()? | 12,381,756 | 13 | 2012-09-12T05:33:46Z | 19,288,528 | 19 | 2013-10-10T06:25:30Z | [
"python",
"django",
"models"
] | Have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects. If it returns 0, I create a new model instance in the `except DoesNotExist` clause of the function. Otherwise, I would like to update the fields in the pre-existing instance, without creating a new one. I was originall... | As of Django 1.5, there is an update\_fields property on model save. eg:
`obj.save(update_fields=['field1', 'field2', ...])`
<https://docs.djangoproject.com/en/dev/ref/models/instances/>
I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different pa... |
Django: Calling .update() on a single model instance retrieved by .get()? | 12,381,756 | 13 | 2012-09-12T05:33:46Z | 30,353,795 | 7 | 2015-05-20T15:15:56Z | [
"python",
"django",
"models"
] | Have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects. If it returns 0, I create a new model instance in the `except DoesNotExist` clause of the function. Otherwise, I would like to update the fields in the pre-existing instance, without creating a new one. I was originall... | if you want only to update model if exist (without create it):
```
Model.objects.filter(id = 223).update(field1 = 2)
```
mysql query:
```
UPDATE `model` SET `field1` = 2 WHERE `model`.`id` = 223
``` |
Python decimal rounding | 12,381,785 | 5 | 2012-09-12T05:37:40Z | 12,381,994 | 9 | 2012-09-12T05:58:00Z | [
"python",
"decimal"
] | Opinion #18, in [20 controversial programming opinions](http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/)
got me thinking. So i tried out printing pi's value to 5 decimal places.
It was okay since I thought I could definitely do it in Python quickly. A few seconds on Google I got to ... | Just like you specify precision using the Decimal context you can also specify rounding rules.
```
from decimal import *
getcontext().prec = 6
getcontext().rounding = ROUND_FLOOR
print Decimal(22)/Decimal(7)
```
the result will be
```
3.14285
```
<http://docs.python.org/release/3.1.5/library/decimal.html#decimal... |
Django Query distinct values works but i cant use the query result | 12,382,232 | 4 | 2012-09-12T06:19:40Z | 12,382,314 | 10 | 2012-09-12T06:26:45Z | [
"python",
"django",
"django-views",
"distinct",
"django-queryset"
] | I have a table column which some values are double or triple written. I want to have a distinct query.
I tried
```
staff = Staff.objects.all().values('person').distinct()
for k in staff:
j = k.person
print j,k
```
I get "dict object has not attribute as person" for k.person
And I get k gives me a result l... | Its not problem with `distinct` but with `values()`. `values()` gives you dict of values you requested. And to get attribute from dict you can use `dict['attr_name']`.
So you can try this:
```
staff = Staff.objects.all().values('person').distinct()
for k in staff:
j = k['person']
print j,k
``` |
Why does setup.py run the module __init__.py during installation? | 12,383,246 | 3 | 2012-09-12T07:34:33Z | 12,383,343 | 7 | 2012-09-12T07:41:40Z | [
"python",
"setup.py"
] | I'm installing a package using setup.py:
```
python setup.py install
```
My `__init__.py` in the package I'm installing includes some package level checks, one of it checks whether an attribute is available in `settings.py`. Since it is a redistributable package the `settings.py` is not delivered via the package, but... | Your `setup.py` is executable python. It is run as a python script to discover your package distribution configuration.
Your `setup.py` runs this code:
```
version=__import__('lock').__version__,
```
This imports your `lock` package, so the `__init__.py` file in that package is loaded. Remove that call and your ... |
Authenticate by IP address in Django | 12,383,540 | 5 | 2012-09-12T07:53:52Z | 12,388,907 | 7 | 2012-09-12T13:07:44Z | [
"python",
"django",
"authentication"
] | I have a small Django application with a view that I want to restrict to certain users. Anyone from a specific network should be able to see that view without any further authentication, based on IP address alone. Anyone else from outside this IP range should be asked for a password and authenticated against the defaul... | There are two suitable approaches for that kind of authentication:
* **As Decorator:** if some of views (but not many of them) requires this check, then it is better to write a decorator for that (something like @Jingo had written)
* **As Middleware:** if that check needed to be done by all (or many) views, instead of... |
Tornado secure cookie expiration (aka secure session cookie) | 12,383,697 | 7 | 2012-09-12T08:04:15Z | 12,385,159 | 9 | 2012-09-12T09:32:39Z | [
"python",
"cookies",
"tornado"
] | How can I set in Tornado a secure cookie that expires when the browser is closed?
If I use `set_cookie` I can do this without passing extra arguments (I just set the cookie), but how if I have to use `set_secure_cookie`?
I tried almost everything:
* passing nothing: expiration is set to its default value, that is 1... | It seems to me that you are really on the right track. You try lower and lower values, and the cookie has a lower and lower expiration time.
Pass `expires_days=None` to make it a session cookie (which expires when the browser is closed). |
Allow only positive decimal numbers | 12,384,460 | 18 | 2012-09-12T08:52:50Z | 12,384,584 | 33 | 2012-09-12T08:59:45Z | [
"python",
"django"
] | Within my Django models I have created a decimal field like this:
```
price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12)
```
Obviously it makes no sense for the price to be negative or zero. Is there a way to limit the decimal number to only positive numbers?
Or do I have to capture this using... | Use the [`MinValueValidator`](https://docs.djangoproject.com/en/dev/ref/validators/#minvaluevalidator).
```
price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))])
``` |
How can I capture mouseevents and keyevents using python in background on linux | 12,384,772 | 7 | 2012-09-12T09:10:46Z | 12,387,122 | 8 | 2012-09-12T11:28:38Z | [
"python",
"linux",
"background",
"mouseevent",
"keyevent"
] | I'd like to make a python script that can run in the background but print text when a mouseevent or keyevent happens. Are there any libraries/builtin functionality to achieve this? Or any system commands I can call to get this info? Being root is no issue. | I guess, you might use python bindings for evdev: <http://packages.python.org/evdev/index.html>. In tutorial they give an example for keyboard, but it should be similar for mouse events:
```
>>> from evdev import InputDevice, categorize, ecodes
>>> from select import select
>>> dev = InputDevice('/dev/input/event1')
... |
Python - Defining an integer variable over multiple lines | 12,385,040 | 3 | 2012-09-12T09:26:34Z | 12,385,150 | 12 | 2012-09-12T09:32:05Z | [
"python",
"python-2.7"
] | I want to define a variable that is a 1000 digits long and I'm loathe to have it all on one line. Is there a way to split an integer variable over several lines?
I have tried using different indentations and parentheses yet to no avail.
Should I just accept that the below has to be stored on one line or am I just mis... | ```
num = int("""
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238... |
How to send a "multipart/form-data" with requests in python? | 12,385,179 | 69 | 2012-09-12T09:33:22Z | 12,385,661 | 55 | 2012-09-12T09:59:56Z | [
"python",
"python-2.7",
"multipartform-data",
"python-requests"
] | How to send a `multipart/form-data` with requests in python? How to send a file, I understand, but how to send the form data by this method can not understand. | Basically, if you specify a `files` parameter (a dictionary), then `requests` will send a `multipart/form-data` POST instead of a `application/x-www-form-urlencoded` POST. You are not limited to using actual files in that dictionary, however:
```
>>> import requests
>>> response = requests.post('http://httpbin.org/pos... |
How to send a "multipart/form-data" with requests in python? | 12,385,179 | 69 | 2012-09-12T09:33:22Z | 22,974,646 | 40 | 2014-04-09T21:50:45Z | [
"python",
"python-2.7",
"multipartform-data",
"python-requests"
] | How to send a `multipart/form-data` with requests in python? How to send a file, I understand, but how to send the form data by this method can not understand. | Since the previous answers were written, requests have changed. Have a look at the [bug thread at Github](https://github.com/kennethreitz/requests/issues/1081) for more detail and [this comment](https://github.com/kennethreitz/requests/issues/1081#issuecomment-32956681) for an example.
In short, the files parameter ta... |
returning 1 instead of true in python | 12,386,196 | 2 | 2012-09-12T10:30:56Z | 12,386,311 | 12 | 2012-09-12T10:37:36Z | [
"python",
"python-2.7",
"boolean"
] | I am trying to return one instead of true in python.
The code i am working on is:
```
delimiters = ( '()', '[]', '{}', "''", '""' )
esc = '\\'
def is_balanced(s, delimiters=delimiters, esc=esc):
stack = []
opening = tuple(str[0] for str in delimiters)
closing = tuple(str[1] for str in delimiters)
for... | Alternatively you could cast your boolean to an int:
```
>>>myBoolean = True
>>>int(myBoolean)
1
>>>myBoolean = False
>>>int(myBoolean)
0
``` |
Applying multiple filters to list of tuples | 12,386,199 | 11 | 2012-09-12T10:31:14Z | 12,386,406 | 27 | 2012-09-12T10:43:23Z | [
"python",
"filter",
"tuples"
] | I am looking for an efficient, pythonic way to apply multiple filters to a list of tuples.
As an example, assume filters like this:
```
def f1(t): return t[3]<10
def f2(t): return t[0]!=1
def f3(t): return t[1] in ("lisa","eric")
def f4(t): return t[3]>2
```
And n-tuples (i.e. db-records) like this:
```
tuples=[
(0... | You could use the [*all*](http://docs.python.org/library/functions.html#all) function to combine the filters and have [*filter*](http://docs.python.org/library/functions.html#filter) to do the actual filtering.
```
def nFilter(filters, tuples):
return filter(lambda t: all(f(t) for f in filters), tuples)
```
Anoth... |
Applying multiple filters to list of tuples | 12,386,199 | 11 | 2012-09-12T10:31:14Z | 12,386,419 | 7 | 2012-09-12T10:43:52Z | [
"python",
"filter",
"tuples"
] | I am looking for an efficient, pythonic way to apply multiple filters to a list of tuples.
As an example, assume filters like this:
```
def f1(t): return t[3]<10
def f2(t): return t[0]!=1
def f3(t): return t[1] in ("lisa","eric")
def f4(t): return t[3]>2
```
And n-tuples (i.e. db-records) like this:
```
tuples=[
(0... | Are you looking for something like this?
```
filters = (f1,f2,f3,f4)
filtered_list = filter( lambda x: all(f(x) for f in filters), your_list )
```
This has the advantage that as soon as a single filter returns `False`, that list element won't be included. |
Openpyxl setting number format | 12,387,212 | 13 | 2012-09-12T11:32:30Z | 26,334,956 | 16 | 2014-10-13T07:35:26Z | [
"python",
"xlsx",
"openpyxl"
] | Could please someone show an example of applying the number format to the cell. For example, I need scientific format, form would be like '2.45E+05' but I couldn't figure a way how to do that in openpyxl.
I tried in several ways but they are all reporting errors when saving the workbook.
for example:
```
import ... | For people being sent here by Google (like I was). The accepted answer does not work with openpyxl 2.0.
The number\_format can be changed directly.
The given example becomes:
```
from openpyxl import Workbook
wb = Workbook()
ws = wb.create_sheet(title='testSheet')
_cell = ws.cell('A1')
_cell.number_format = '0.00E+0... |
Updating a list of embedded documents in mongoengine | 12,387,478 | 9 | 2012-09-12T11:47:05Z | 12,407,167 | 13 | 2012-09-13T13:15:32Z | [
"python",
"mongodb",
"pymongo",
"mongoengine"
] | I'm struggling with mongoengine syntax.
I have the following models...
```
class Post(EmbeddedDocument):
uid = StringField(required=True)
text = StringField(required=True)
when = DateTimeField(required=True)
class Feed(Document):
label = StringField(required=True)
feed_url = StringField(required... | No with list field you cannot do an upsert into a list in a single query. `$addToSet` wont work as you've changed the `post` so you cant match. You can code round this but it does create a race condition where there is a small window of opportunity for error eg:
```
class Post(EmbeddedDocument):
uid = Stri... |
delete all keys except one in dictionary | 12,387,575 | 8 | 2012-09-12T11:52:21Z | 12,387,590 | 14 | 2012-09-12T11:53:18Z | [
"python",
"dictionary"
] | I have a dictionary
```
lang = {'ar':'arabic', 'ur':'urdu','en':'english'}
```
What I want to do is to delete all the keys except one key.
Suppose I want to save only `en` here.
How can I do it ? (pythonic solution)
**What I have tried**:
```
In [18]: for k in lang:
....: if k != 'en':
....: del ... | Why don't you just create a new one?
```
lang = {'en': lang['en']}
```
**Edit**: Benchmark between mine and jimifiki's solution:
```
$ python -m timeit "lang = {'ar':'arabic', 'ur':'urdu','en':'english'}; en_value = lang['en']; lang.clear(); lang['en'] = en_value"
1000000 loops, best of 3: 0.369 usec per loop
$ pyt... |
delete all keys except one in dictionary | 12,387,575 | 8 | 2012-09-12T11:52:21Z | 12,387,892 | 12 | 2012-09-12T12:10:51Z | [
"python",
"dictionary"
] | I have a dictionary
```
lang = {'ar':'arabic', 'ur':'urdu','en':'english'}
```
What I want to do is to delete all the keys except one key.
Suppose I want to save only `en` here.
How can I do it ? (pythonic solution)
**What I have tried**:
```
In [18]: for k in lang:
....: if k != 'en':
....: del ... | This is quite fast:
```
En_Value = lang['en']
lang.clear()
lang['en'] = En_Value
``` |
import inside of a Python thread | 12,389,526 | 11 | 2012-09-12T13:39:32Z | 12,391,178 | 8 | 2012-09-12T15:04:24Z | [
"python",
"multithreading",
"concurrency",
"locking",
"python-import"
] | I have some functions that interactively load python modules using `__import__`
I recently stumbled upon some article about an "import lock" in Python, that is, a lock specifically for imports (not just the GIL). But the article was old so maybe that's not true anymore.
This makes me wonder about the practice of impo... | Normal imports are thread safe because they acquire an import lock prior to execution and release it once the import is done. If you add your own custom imports using the hooks available, be sure to add this locking scheme to it. Locking facilities in Python may be accessed by the `imp` module (`imp.lock_held()`/`acqui... |
Python Pandas: how to add a totally new column to a data frame inside of a groupby/transform operation | 12,389,898 | 18 | 2012-09-12T13:58:12Z | 12,394,122 | 24 | 2012-09-12T18:19:35Z | [
"python",
"group-by",
"transform",
"dataframe",
"pandas"
] | I want to mark some quantiles in my data, and for each row of the DataFrame, I would like the entry in a new column called e.g. "xtile" to hold this value.
For example, suppose I create a data frame like this:
```
import pandas, numpy as np
dfrm = pandas.DataFrame({'A':np.random.rand(100),
'... | What problems are you running into with `apply`? It works for this toy example here and the group lengths are different:
```
In [82]: df
Out[82]:
X Y
0 0 -0.631214
1 0 0.783142
2 0 0.526045
3 1 -1.750058
4 1 1.163868
5 1 1.625538
6 1 0.076105
7 2 0.183492
8 2 0.541400
9 2 -0.672809
In [83... |
what is sre_constants.error: nothing to repeat | 12,390,238 | 3 | 2012-09-12T14:16:50Z | 12,390,289 | 11 | 2012-09-12T14:19:01Z | [
"python",
"regex"
] | I'm having a problem with a seemingly simple Python regular expression.
```
# e.g. If I wanted to find "mark has wonderful kittens, but they're mischievous.."
p = re.compile("*kittens*")
```
This will fail with the error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64... | You're confusing regular expressions with [globs](http://en.wikipedia.org/wiki/Glob_%28programming%29).
You mean:
```
p = re.compile(".*kittens.*")
```
Note that a bare asterisk doesn't mean the same in an RE as it does in a glob expression. |
Time-complexity of checking if two set are equal in Python | 12,390,298 | 6 | 2012-09-12T14:19:23Z | 12,390,447 | 14 | 2012-09-12T14:27:20Z | [
"python",
"time-complexity"
] | Reading [this question](http://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets-in-python), I wondered how much time (asymptotically speaking) does it takes to Python to evaluate expressions like
```
{1,2}=={2,1}
```
that is to say, to check if two instances of the [set clas... | Comparison between sets is implemented by the [function `set_richcompare` in `setobject.c`, line 1848](http://hg.python.org/cpython/file/2fa7c104f909/Objects/setobject.c#l1848). You'll see that equality is implemented as follows:
1. If the sets do not have the same size, return false.
2. If both sets have been hashed,... |
How to fill the missing record of Pandas dataframe in pythonic way? | 12,390,336 | 9 | 2012-09-12T14:21:11Z | 13,297,472 | 8 | 2012-11-08T20:42:12Z | [
"python",
"pandas"
] | I have a Pandas dataframe 'df' like this :
```
X Y
IX1 IX2
A A1 20 30
A2 20 30
A5 20 30
B B2 20 30
B4 20 30
```
It lost some rows, and I want to fill in the gap in the middle like this:
```
X Y
IX1 IX2
A A1 20 30
A2 20 30
A3 NaN NaN
A4 NaN NaN
... | You need to construct your full index, and then use the `reindex` method of the dataframe. Like so...
```
import pandas
import StringIO
datastring = StringIO.StringIO("""\
C1,C2,C3,C4
A,A1,20,30
A,A2,20,30
A,A5,20,30
B,B2,20,30
B,B4,20,30""")
dataframe = pandas.read_csv(datastring, index_col=['C1', 'C2'])
full_index ... |
MongoEngine ListField within a EmbeddedDocument throws TypeError on validation | 12,392,362 | 8 | 2012-09-12T16:10:57Z | 12,503,831 | 11 | 2012-09-19T22:34:15Z | [
"python",
"mongodb",
"typeerror",
"mongoengine"
] | I am not sure if it is a bug within MongoEngine or if I miss something.
I have the following Models set up:
```
class Features(EmbeddedDocument):
version = FloatField()
data = ListField(StringField)
class Article(Document):
vendor = ReferenceField(Vendor)
url = URLField()
author = StringField()
... | I found the error.
It has to be:
```
class Features(EmbeddedDocument):
version = FloatField()
data = ListField(StringField())
``` |
What Is The Cleanest Way to Call A Python Function From C++ with a SWIG Wrapped Object | 12,392,703 | 7 | 2012-09-12T16:34:13Z | 12,463,876 | 9 | 2012-09-17T16:55:29Z | [
"c++",
"python",
"swig"
] | I have the following code, which implements a simple C++ class (ObjWithPyCallback) with a Python callback function. The idea is to call the Python function with "this" as the single argument.
The problem is that since ObjWithPyCallback is a SWIG wrapped object I need the SWIG typeinfo in order to create a Python objec... | Below is my working solution for solving this problem. It uses the suggestions from both @omnifarious and @flexo above.
In particular we create a Callback class with a SWIG director and then derive from it in Python to get the required callback functionality without introducing a circular dependency.
In addition we p... |
User groups and permissions | 12,393,726 | 23 | 2012-09-12T17:51:03Z | 12,393,845 | 46 | 2012-09-12T17:59:49Z | [
"python",
"django",
"django-models",
"django-permissions",
"usergroups"
] | I need to implement user rights for user groups (pretty similar to facebook groups). For example, each group can have members with rights like: can\_post, can\_delete, can\_ban, etc. Of course, one user can be a member of many groups and group can have many different users with different rights.
What models i need for ... | Django has a built in groups system. Whenever you have a question like this, I recommend [searching the Django docs](https://docs.djangoproject.com/search/?q=groups&release=1), which are extensive, helpful, and well written.
So long as you are using the `django.contrib.auth` app, you have access to groups. You can the... |
scrapy: Call a function when a spider quits | 12,394,184 | 18 | 2012-09-12T18:23:49Z | 12,394,371 | 36 | 2012-09-12T18:40:11Z | [
"python",
"scrapy"
] | Is there a way to trigger a method in a Spider class just before it terminates?
I can terminate the spider myself, like this:
```
class MySpider(CrawlSpider):
#Config stuff goes here...
def quit(self):
#Do some stuff...
raise CloseSpider('MySpider is quitting now.')
def my_parser(self, r... | It looks like you can register a signal listener through `dispatcher`.
I would try something like:
```
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
class MySpider(CrawlSpider):
def __init__(self):
dispatcher.connect(self.spider_closed, signals.spider_closed)
def spider_cl... |
scrapy: Call a function when a spider quits | 12,394,184 | 18 | 2012-09-12T18:23:49Z | 18,905,838 | 7 | 2013-09-19T22:17:43Z | [
"python",
"scrapy"
] | Is there a way to trigger a method in a Spider class just before it terminates?
I can terminate the spider myself, like this:
```
class MySpider(CrawlSpider):
#Config stuff goes here...
def quit(self):
#Do some stuff...
raise CloseSpider('MySpider is quitting now.')
def my_parser(self, r... | For me the above did not work / is outdated at least for scrapy 0.19.
I got it to work with the following though:
```
from scrapy.signalmanager import SignalManager
from scrapy.xlib.pydispatch import dispatcher
class MySpider(CrawlSpider):
def __init__(self, *args, **kwargs):
super(MySpider, self).__init_... |
scrapy: Call a function when a spider quits | 12,394,184 | 18 | 2012-09-12T18:23:49Z | 33,312,325 | 9 | 2015-10-23T22:29:51Z | [
"python",
"scrapy"
] | Is there a way to trigger a method in a Spider class just before it terminates?
I can terminate the spider myself, like this:
```
class MySpider(CrawlSpider):
#Config stuff goes here...
def quit(self):
#Do some stuff...
raise CloseSpider('MySpider is quitting now.')
def my_parser(self, r... | Just to update, you can just call [`closed`](http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=closed#scrapy.spiders.Spider.closed) function like this:
```
class MySpider(CrawlSpider):
def closed(self, reason):
do-something()
``` |
Click on a dropdown element menu with Selenium Webdriver | 12,395,228 | 8 | 2012-09-12T19:46:11Z | 12,395,568 | 7 | 2012-09-12T20:12:42Z | [
"python",
"selenium",
"automation",
"webdriver",
"selenium-webdriver"
] | I'm trying to automate an administration task, so far I have made selenium to click on an element to show a dropdown menu.

When it comes the time to click on one of those menu elements I've got an error saying that the element must be displayed.
Cod... | Why don't you select an option like this
```
el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
if option.text == 'The Options I Am Looking For':
option.click() # select() in earlier versions of webdriver
```
If your click is not firing an ajax call to pop... |
Socket.io python server | 12,396,655 | 6 | 2012-09-12T21:51:56Z | 12,396,747 | 8 | 2012-09-12T22:02:22Z | [
"python",
"node.js",
"socket.io"
] | I am using <https://github.com/invisibleroads/socketIO-client> to have my Node.JS server communicate with a Python Backend.
However, this is a bit tricky because I actually want to use my Python as a backend, and it makes more sense to have Python act as a server and Node.JS act as a client. Ideally, Node.JS code init... | Oops, reading the bottom of <https://github.com/learnboost/socket.io/wiki> reveals that
<http://github.com/abourget/gevent-socketio>
does the trick. There is also a <https://github.com/evanw/socket.io-python> library that is deprecated because of an outdated socket.io |
python regular expression matching anything | 12,396,919 | 7 | 2012-09-12T22:19:37Z | 12,396,965 | 8 | 2012-09-12T22:25:20Z | [
"python",
"regex"
] | My regular expression isnt doing anything to my string.
python
```
data = 'random\n<article stuff\n</article>random stuff'
datareg = re.sub(r'.*<article(.*)</article>.*', r'<article\1</article>', data, flags=re.MULTILINE)
print datareg
```
i get
```
random
<article stuff
</article>random stuff
```
i want
```
<art... | [`re.MULTILINE`](http://docs.python.org/library/re.html#re.MULTILINE) doesn't actually make your regex multiline in the way you want it to be.
> When specified, the pattern character `'^'` matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern cha... |
Pipe STDIN to a script that is itself being piped to the Python interpreter? | 12,397,469 | 7 | 2012-09-12T23:33:50Z | 12,443,850 | 10 | 2012-09-16T01:48:26Z | [
"python",
"bash",
"svn",
"pipe",
"pre-commit-hook"
] | I need to implement an SVN pre-commit hook which executes a script that itself is stored in SVN.
I can use the `svn cat` command to pipe that script to the Python interpreter, as follows:
```
svn cat file://$REPO/trunk/my_script.py | python - --argument1 --argument2
```
However, `my_script.py` itself requires data t... | I figured out how to do this without creating any temporary files, but not strictly with "pipes".
`curl http://example.com/huge_file.txt | python <(svn cat file://$REPO/trunk/my_script.py) --argument1 --argument2`
I used the "anonymous file descriptor" construct in Bash, which can be used in place of any file path.
... |
Why is local variable access faster than class member access in Python? | 12,397,984 | 5 | 2012-09-13T00:48:55Z | 12,398,055 | 15 | 2012-09-13T01:00:40Z | [
"python",
"performance",
"benchmarking"
] | While trying to tackle a more complex problem, I came to compare access speed to local variable vs member variables.
Here a test program:
```
#!/usr/bin/env python
MAX=40000000
class StressTestMember(object):
def __init__(self):
self.m = 0
def do_work(self):
self.m += 1
self.m *= 2
... | `self.m += 1` means you have to look up a local variable called `self` and then find the attribute called `m`
Of course if you just have to look up a local variable, it will be faster without the extra step.
It can be useful to look at what is happening under the hood:
```
>>> import dis
>>> dis.dis(StressTestLocal.... |
read filenames and write directly into a list | 12,398,311 | 2 | 2012-09-13T01:43:24Z | 12,398,331 | 9 | 2012-09-13T01:46:21Z | [
"python",
"filenames"
] | Is it possible to get Python to look in a folder and put all of the filenames (with a certain extension) into a list?
e.g.:
```
[filename1.txt, filename2.txt,...]
``` | You can do this easily with the `glob` module:
```
import glob
filenames = glob.glob('<some_path>/*.<extension>')
``` |
Finding the level of recursion call in python | 12,399,259 | 5 | 2012-09-13T04:06:42Z | 12,399,275 | 18 | 2012-09-13T04:08:41Z | [
"python"
] | I have a function which is called recursively and I want to know the current level of recursion. Below code shows the method that I am using to calculate it, but it is not giving the expected results.
E.g. : To find the recursion level for a system path:
```
import os
funccount = 0
def reccount(src):
... | ```
def some_method(data, level=0):
some_method(..., level=level+1)
if __name__ == '__main__':
some_method(my_data)
``` |
Finding the level of recursion call in python | 12,399,259 | 5 | 2012-09-13T04:06:42Z | 12,399,856 | 10 | 2012-09-13T05:19:58Z | [
"python"
] | I have a function which is called recursively and I want to know the current level of recursion. Below code shows the method that I am using to calculate it, but it is not giving the expected results.
E.g. : To find the recursion level for a system path:
```
import os
funccount = 0
def reccount(src):
... | ```
from inspect import getouterframes, currentframe
import os
def runrec(src):
level = len(getouterframes(currentframe(1)))
print("Function level of {} is {}".format(src, level))
for x in os.listdir(src):
srcname = os.path.join(src, x)
if os.path.isdir(srcname):
runrec(srcname)... |
How To Check If A Key in **kwargs Exists? | 12,399,803 | 38 | 2012-09-13T05:14:59Z | 12,399,836 | 62 | 2012-09-13T05:17:45Z | [
"python",
"dictionary",
"python-3.x",
"kwargs"
] | Python 3.2.3. Sorry if this is a dumb question, I can't seem to figure it out or find an answer for it. There were some ideas [listed here](http://stackoverflow.com/questions/9390126/pythonic-way-to-check-if-something-exists), which work on regular var's, but it seems \*\*kwargs play by different rules... so why doesn'... | You want
```
if 'errormessage' in kwargs:
print("found it")
```
In this way, `kwargs` is just another `dict`. Your first example, `if kwargs['errormessage']`, means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a `KeyError`.
... |
How To Check If A Key in **kwargs Exists? | 12,399,803 | 38 | 2012-09-13T05:14:59Z | 12,399,855 | 8 | 2012-09-13T05:19:51Z | [
"python",
"dictionary",
"python-3.x",
"kwargs"
] | Python 3.2.3. Sorry if this is a dumb question, I can't seem to figure it out or find an answer for it. There were some ideas [listed here](http://stackoverflow.com/questions/9390126/pythonic-way-to-check-if-something-exists), which work on regular var's, but it seems \*\*kwargs play by different rules... so why doesn'... | It is just this:
```
if 'errormessage' in kwargs:
print("yeah it's here")
```
You need to check, if the key is in the dictionary. The syntax for that is `some_key in some_dict` (where `some_key` is something hashable, not necessarily a string).
The ideas you have linked ([these ideas](http://stackoverflow.com/qu... |
How To Check If A Key in **kwargs Exists? | 12,399,803 | 38 | 2012-09-13T05:14:59Z | 12,403,373 | 7 | 2012-09-13T09:35:11Z | [
"python",
"dictionary",
"python-3.x",
"kwargs"
] | Python 3.2.3. Sorry if this is a dumb question, I can't seem to figure it out or find an answer for it. There were some ideas [listed here](http://stackoverflow.com/questions/9390126/pythonic-way-to-check-if-something-exists), which work on regular var's, but it seems \*\*kwargs play by different rules... so why doesn'... | DSM's and Tadeck's answers answer your question directly.
In my scripts I often use the convenient `dict.pop()` to deal with optional, and additional arguments. Here's an example of a simple `print()` wrapper:
```
def my_print(*args, **kwargs):
prefix = kwargs.pop('prefix', '')
print(prefix, *args, **kwargs)
... |
Python: Converting Epoch time into the datetime | 12,400,256 | 92 | 2012-09-13T06:00:51Z | 12,400,584 | 104 | 2012-09-13T06:27:03Z | [
"python"
] | I am getting a response from the rest is an Epoch time format like
```
start_time = 1234566
end_time = 1234578
```
I want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database.
I tried:
```
>>> import time
>>> time.gmtime(123456)
time.struct_time(tm_year=1970,... | To convert your time value (float or int) to a formatted string, use:
```
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
``` |
Python: Converting Epoch time into the datetime | 12,400,256 | 92 | 2012-09-13T06:00:51Z | 15,953,715 | 70 | 2013-04-11T16:09:44Z | [
"python"
] | I am getting a response from the rest is an Epoch time format like
```
start_time = 1234566
end_time = 1234578
```
I want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database.
I tried:
```
>>> import time
>>> time.gmtime(123456)
time.struct_time(tm_year=1970,... | You can also use `datetime`:
```
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%c')
'2012-09-13 02:22:50'
``` |
How to set font size of Matplotlib axis Legend? | 12,402,561 | 19 | 2012-09-13T08:43:58Z | 14,499,442 | 14 | 2013-01-24T10:45:51Z | [
"python",
"matplotlib",
"font-size",
"legend"
] | I have a code like this:
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('xx-small')
fig=plt.figure()
ax1=fig.add_subplot(111)
plot([1,2,3], label="test1")
ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, ... | Here is how to change the fontsize of the legend list and/or legend title:
```
legend=plt.legend(list,loc=(1.05,0.05), title=r'$\bf{Title}$') #Legend: list, location, Title (in bold)
legend.get_title().set_fontsize('6') #legend 'Title' fontsize
plt.setp(plt.gca().get_legend().get_texts(), fontsize='12') #legend 'list'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.