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 |
|---|---|---|---|---|---|---|---|---|---|
Logging uncaught exceptions in Python | 6,234,405 | 72 | 2011-06-04T02:53:22Z | 6,234,420 | 22 | 2011-06-04T02:57:37Z | [
"python",
"logging",
"exception-handling"
] | How do you cause uncaught exceptions to output via the `logging` module rather than to `stderr`?
I realize the best way to do this would be:
```
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
```
But my situation is such that it would be *really nice* if `loggin... | The method `sys.excepthook` will be invoked if an exception is uncaught: <http://docs.python.org/library/sys.html#sys.excepthook>
> When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive ses... |
Logging uncaught exceptions in Python | 6,234,405 | 72 | 2011-06-04T02:53:22Z | 6,234,491 | 71 | 2011-06-04T03:26:14Z | [
"python",
"logging",
"exception-handling"
] | How do you cause uncaught exceptions to output via the `logging` module rather than to `stderr`?
I realize the best way to do this would be:
```
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
```
But my situation is such that it would be *really nice* if `loggin... | As Ned pointed out, `sys.excepthook` is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior of `sys.excepthook` to do whatever you want (including using `logging.exception`).
As a straw man example:
```
>>> import sys
>>>... |
Logging uncaught exceptions in Python | 6,234,405 | 72 | 2011-06-04T02:53:22Z | 8,168,122 | 11 | 2011-11-17T13:47:15Z | [
"python",
"logging",
"exception-handling"
] | How do you cause uncaught exceptions to output via the `logging` module rather than to `stderr`?
I realize the best way to do this would be:
```
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
```
But my situation is such that it would be *really nice* if `loggin... | Why not:
```
import sys
import logging
import traceback
def log_except_hook(*exc_info):
text = "".join(traceback.format_exception(*exc_info))
logging.error("Unhandled exception: %s", text)
sys.excepthook = log_except_hook
``` |
Logging uncaught exceptions in Python | 6,234,405 | 72 | 2011-06-04T02:53:22Z | 16,993,115 | 48 | 2013-06-07T21:18:24Z | [
"python",
"logging",
"exception-handling"
] | How do you cause uncaught exceptions to output via the `logging` module rather than to `stderr`?
I realize the best way to do this would be:
```
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
```
But my situation is such that it would be *really nice* if `loggin... | Here's a complete small example that also includes a few other tricks:
```
import os, sys
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInte... |
How to reload Python module in IDLE? | 6,234,414 | 10 | 2011-06-04T02:56:01Z | 6,234,432 | 9 | 2011-06-04T03:01:27Z | [
"python",
"module",
"reload",
"python-idle"
] | I'm trying to understand how my workflow can work with Python and IDLE.
Suppose I write a function:
```
def hello():
print 'hello!'
```
I save the file as `greetings.py`. Then in IDLE, I test the function:
```
>>> from greetings import *
>>> hello()
hello!
```
Then I alter the program, and want to try `hello()... | You need to redo this line:
`>>> from greetings import *`
after you do
`>>> reload(greetings)`
The reason just reloading the module doesn't work is because the \* actually imported everything inside the module, so you have to reload those individually. If you did the following it would behave as you expect:
```
>>... |
Python Turtle graphics - how do I control when the window closes? | 6,234,798 | 11 | 2011-06-04T04:59:29Z | 6,240,234 | 11 | 2011-06-05T00:26:07Z | [
"python",
"turtle-graphics",
"window-management"
] | I have a small python script which draws some turtle graphics. When my script has finished running, the turtle screen automatically closes, so to be able to see the graphics for a while I have to use `time.sleep(5)` at the end of the script to delay the closing.
Is there any way I can make this more dynamic, i.e. tell... | ```
import turtle
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
# etc.
turtle.getscreen()._root.mainloop() # <-- run the Tkinter main loop
```
(edit: `turtle.done()` as suggested by hua below is less ugly.) |
Python Turtle graphics - how do I control when the window closes? | 6,234,798 | 11 | 2011-06-04T04:59:29Z | 11,023,988 | 22 | 2012-06-13T22:03:23Z | [
"python",
"turtle-graphics",
"window-management"
] | I have a small python script which draws some turtle graphics. When my script has finished running, the turtle screen automatically closes, so to be able to see the graphics for a while I have to use `time.sleep(5)` at the end of the script to delay the closing.
Is there any way I can make this more dynamic, i.e. tell... | just use `done()` or `exitonclick()` as a last command of your turtle program. |
Python executables: py2exe or PyInstaller? | 6,235,123 | 32 | 2011-06-02T09:50:38Z | 6,235,314 | 38 | 2011-06-04T07:02:55Z | [
"windows",
"python",
"executable"
] | To create executable files (windows) I assume that we should use one of them:
Py2exe or PyInstaller.
What are the difference between them? | Py2exe and PyInstaller both are wrappers but here are few differences that I noticed,
1. Py2exe is compatible with python2.4+ including python3.0 & 3.1 whereas PyInstaller is currently, compatible with python2.2 to python2.7
2. As far I know, Py2exe didn't support signing whereas Pyinstaller has support for signing fr... |
How does "is" work in python? | 6,235,684 | 8 | 2011-06-04T08:37:10Z | 6,235,702 | 7 | 2011-06-04T08:40:19Z | [
"python",
"module"
] | Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble:
```
>>> Fraction(0, 1) is 0
False
>>> float(Fraction(0, 1))
0.0
>>> float(Fraction(0,1)) is 0.0
False
```
The only thing I found to work is:
```
>>> F = Fraction(a,b)
>>> if F >=... | From [the documentation](http://docs.python.org/reference/expressions.html#is):
> The operators `is` and `is not` test for object identity: `x is y` is true if and only if x and y are the same object. `x is not y` yields the inverse truth value.
What you want here is `==`, to test whether two objects are equal or equ... |
How does "is" work in python? | 6,235,684 | 8 | 2011-06-04T08:37:10Z | 6,235,705 | 7 | 2011-06-04T08:41:13Z | [
"python",
"module"
] | Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble:
```
>>> Fraction(0, 1) is 0
False
>>> float(Fraction(0, 1))
0.0
>>> float(Fraction(0,1)) is 0.0
False
```
The only thing I found to work is:
```
>>> F = Fraction(a,b)
>>> if F >=... | The `is` operator in python is used to check if two variables are pointing to the very same object and is not meant to be used to check about numeric equality. You should use `==` for that instead.
For example consider that
```
(1000 + 1000) is (1000 + 1000)
```
returns `False`. |
How to get the name of attribute in python object? | 6,235,779 | 3 | 2011-06-04T09:01:54Z | 6,235,797 | 7 | 2011-06-04T09:04:34Z | [
"python",
"object",
"attributes"
] | For example I have next python class
```
class Myclass():
a = int
b = int
```
Imagine that I don't know the name this class, so I need to get **the names** of attributes? ("a" and "b") | If you want all (including private) attributes, just
```
dir(Myclass)
```
Attributes starting with `_` are private/internal, though. For example, even your simple `Myclass` will have a `__module__` and an empty `__doc__` attribute. To filter these out, use
```
filter(lambda aname: not aname.startswith('_'), dir(Mycl... |
best practice for passing values between functions in Python | 6,236,032 | 9 | 2011-06-04T09:53:54Z | 6,236,041 | 9 | 2011-06-04T09:56:43Z | [
"function",
"return-value",
"python"
] | What is pythonic best practice for allowing one function to use another function's returned values? e.g. Is it better to call one function within another, or better that function1 returns to the class, and class variables are assigned that are then used by function2? Secondly, how many different ways *could* you pass v... | As `import this` would say, "explicit is better than implicit"; so go with the first form.
If the number of return values becomes large, let `use_value` take a sequence argument instead. |
python groupby behaviour? | 6,236,081 | 7 | 2011-06-04T10:05:33Z | 6,236,257 | 12 | 2011-06-04T10:43:49Z | [
"python",
"dictionary",
"iterator",
"group-by"
] | > ```
> >>from itertools import groupby
> >>keyfunc = lambda x : x > 500
> >>obj = dict(groupby(range(1000), keyfunc))
> >>list(obj[True])
> [999]
> >>list(obj[False])
> []
> ```
*range(1000)* is obviously sorted by default for the condition (x > 500).
I was expecting the numbers from 0 to 999 to be grouped in a *d... | From the docs: "The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list". And you are storing iterators in `o... |
How much is the difference between html parsing and web crawling in python | 6,236,794 | 5 | 2011-06-04T12:41:22Z | 6,236,927 | 9 | 2011-06-04T13:11:50Z | [
"python",
"django",
"web-crawler"
] | I need to grab some data from websites in my django website.
Now i am confused whether i should use python parsing libraries or web crawling libraries. Does search engine libraries also fall in same category
I want to know how much is the difference between the two and if i want to use those functions inside my websit... | If you can get away with background web crawling use [scrapy](http://scrapy.org/). If need to immediately grab something use [html5lib](http://code.google.com/p/html5lib/) (more robust) or [lxml](http://lxml.de/) (faster). If you are going to be doing the later, use the awesome [requests](http://docs.python-requests.or... |
insert into sqlite table with unique column | 6,237,378 | 6 | 2011-06-04T14:45:23Z | 6,237,842 | 9 | 2011-06-04T16:09:03Z | [
"python",
"sqlite"
] | I'm inserting values into my table (from python code) as follows:
```
cur.execute("insert into t(a, b, c) values (?, ?, ?)", (a, b, c))
```
There is a `unique constraint` on column c. What is a common way of `insert` if I want to cover the case when we're inserting duplicate value for c column?
I have some ideas
1... | You could use [INSERT OR REPLACE](https://sqlite.org/lang_insert.html) to update rows with a unique constraint,
or [INSERT OR IGNORE](https://sqlite.org/lang_insert.html) to ignore inserts which conflict with a unique constraint:
```
import sqlite3
def insert_or_replace():
# https://sqlite.org/lang_insert.html
... |
Write to a Remote file with Fabric | 6,237,514 | 3 | 2011-06-04T15:11:10Z | 6,240,597 | 7 | 2011-06-05T02:07:33Z | [
"python",
"fabric"
] | I am trying to backup databases and move them around to different servers using [Fabric](http://docs.fabfile.org/en/1.0.1/index.html).
When on a remote server, to open a file for writing it fails with the error.
```
newFile = open('%s%s' % (dumpPath,newFileName) ,'w')
IOError: [Errno 2] No such file or directory: '/h... | In Fabric, you are never "on a remote server". Some Fabric commands run locally, and some run on the remote server. In this case, you are using Python's `open` function, which tries to open the file on your local computer, and understandably fails. You can use Fabric's [put and get functions](http://docs.fabfile.org/en... |
Python socket.send() can only send once, then socket.error: [Errno 32] Broken pipe occurred | 6,237,569 | 9 | 2011-06-04T15:21:44Z | 6,237,888 | 13 | 2011-06-04T16:16:27Z | [
"python",
"socketserver",
"broken-pipe"
] | I'm a newbie in network programming, so please forgive me if this is a dumb question :)
I created 1 client and 1 SocketServer.ThreadingMixIn server on Ubuntu 10.04.2 using Python2.7, but
it seems like I can only call sock.send() once in client, then I'll get a:
```
Traceback (most recent call last):
File "testClient... | handle() is called in the `SocketServer.StreamRequestHandler` once for each *connection*. If you return from `handle` the connection is closed.
If you want the server to handle more than one send/recv, you must loop until recv() returns 0, indicating the client closed the connection (or at least called shutdown() on s... |
Optional dependencies in distutils / pip | 6,237,946 | 13 | 2011-06-04T16:29:43Z | 13,681,679 | 12 | 2012-12-03T10:49:47Z | [
"python",
"distutils",
"pip"
] | When installing my python package, I want to be able to tell the user about various optional dependencies. Ideally I would also like to print out a message about these optional requirements and what each of them do.
I haven't seen anything yet in the docs of either pip or docutils. Do tools these support optional depe... | These are called extras, [here is how to use them in your setup.py](https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies).
The base support is in pkg\_resources. You need to enable distribute in your `setup.py`. pip will also understand them:
```
p... |
PyQt: new API with Python 2 | 6,238,193 | 6 | 2011-06-04T17:12:19Z | 6,238,226 | 8 | 2011-06-04T17:16:33Z | [
"python",
"pyqt"
] | PyQt has two different API's: the old and the new.
By default you get the old API with Python 2 and the new API with Python 3.
Is it possible to enable the new PyQt API with Python 2? How? | Perhaps you could try using [`sip.setapi`](http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html). A simple example from the docs:
```
import sip
sip.setapi('QString', 2)
```
And a list of the supported APIs:
```
QDate v1, v2
QDateTime v1, v2
QString v1, v2
QTextStream v1, v2
QTime v1, v2
QUrl v1, v2
QVarian... |
PyQt: new API with Python 2 | 6,238,193 | 6 | 2011-06-04T17:12:19Z | 8,513,865 | 12 | 2011-12-15T01:04:35Z | [
"python",
"pyqt"
] | PyQt has two different API's: the old and the new.
By default you get the old API with Python 2 and the new API with Python 3.
Is it possible to enable the new PyQt API with Python 2? How? | From [this reddit comment](http://www.reddit.com/r/Python/comments/gwwp3/learning_python_qt_programming_with_pyqt_pyside/c1r1i10),
```
import sip
API_NAMES = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"]
API_VERSION = 2
for name in API_NAMES:
sip.setapi(name, API_VERSION)
from PyQt4... |
Multivariate spline interpolation in python/scipy? | 6,238,250 | 22 | 2011-06-04T17:21:27Z | 6,238,859 | 37 | 2011-06-04T19:17:12Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | Is there a library module or other straightforward way to implement multivariate spline interpolation in python?
Specifically, I have a set of scalar data on a regularly-spaced three-dimensional grid which I need to interpolate at a small number of points scattered throughout the domain. For two dimensions, I have bee... | If I'm understanding your question correctly, your input "observation" data is regularly gridded?
If so, [`scipy.ndimage.map_coordinates`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.map_coordinates.html) does exactly what you want.
It's a bit hard to understand at first pass, but ... |
How can I crop an image with Pygame? | 6,239,769 | 9 | 2011-06-04T22:28:07Z | 6,240,095 | 15 | 2011-06-04T23:50:04Z | [
"python",
"image",
"pygame",
"crop",
"surface"
] | I am learning `pygame` and want a graphic for a button with the three states: normal, hover, and pressed. I have an image like this one ...

... and I want to get a new `Surface` using a portion of it.
I'm loading the image with this code:... | ```
cropped = pygame.Surface((80, 80))
cropped.blit(buttonStates, (0, 0), (30, 30, 80, 80))
```
The blit method on a surface 'pastes' another surface on to it. The first argument to blit is the source surface. The second is the location to paste to (in this case, the top left corner). The third (optional) argument is ... |
What is the advantage of the new print function in Python 3.x over the Python 2 print statement? | 6,239,887 | 39 | 2011-06-04T22:56:22Z | 6,239,909 | 39 | 2011-06-04T23:03:03Z | [
"python",
"function",
"printing",
"python-3.x",
"python-2.x"
] | I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?
I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses).
I'd be interested to see some situations where the print statement just doesn't cut it, and... | The following is from <http://www.python.org/dev/peps/pep-3105/>
The print statement has long appeared on lists of dubious language features that are to be removed in Python 3000, such as Guido's "Python Regrets" presentation [1]. As such, the objective of this PEP is not new, though it might become much disputed amon... |
What is the advantage of the new print function in Python 3.x over the Python 2 print statement? | 6,239,887 | 39 | 2011-06-04T22:56:22Z | 6,239,919 | 25 | 2011-06-04T23:04:40Z | [
"python",
"function",
"printing",
"python-3.x",
"python-2.x"
] | I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?
I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses).
I'd be interested to see some situations where the print statement just doesn't cut it, and... | One advantage of `print` being a function is consistency. There is no reason for it to be a statement. Compare these two lines
```
2.x: print >> my_file, x
3.x: print(x, file=my_file)
```
The new version looks much more like Python, doesn't it?
Another advantage of the function version is flexibility. For example, i... |
What is the advantage of the new print function in Python 3.x over the Python 2 print statement? | 6,239,887 | 39 | 2011-06-04T22:56:22Z | 6,239,932 | 10 | 2011-06-04T23:06:52Z | [
"python",
"function",
"printing",
"python-3.x",
"python-2.x"
] | I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?
I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses).
I'd be interested to see some situations where the print statement just doesn't cut it, and... | You can replace the built-in `print` by a custom one:
```
import os
import sys
def print(s):
sys.stderr.write('Will now print ' + str(s) + '.' + os.linesep)
sys.stdout.write(str(s) + os.linesep)
print(['A', 'list'])
# Output:
# stderr: Will now print ['A', 'list'].
# stdout: ['A', 'list']
```
You can use `pr... |
What is the advantage of the new print function in Python 3.x over the Python 2 print statement? | 6,239,887 | 39 | 2011-06-04T22:56:22Z | 6,241,519 | 28 | 2011-06-05T07:21:00Z | [
"python",
"function",
"printing",
"python-3.x",
"python-2.x"
] | I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?
I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses).
I'd be interested to see some situations where the print statement just doesn't cut it, and... | Everything Jochen + Sven said, plus:
You can use `print()` it in places where you can't use `print`, such as:
```
[print(x) for x in range(10)]
``` |
What is the advantage of the new print function in Python 3.x over the Python 2 print statement? | 6,239,887 | 39 | 2011-06-04T22:56:22Z | 24,438,151 | 11 | 2014-06-26T19:00:06Z | [
"python",
"function",
"printing",
"python-3.x",
"python-2.x"
] | I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?
I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses).
I'd be interested to see some situations where the print statement just doesn't cut it, and... | I thought over this question and had no idea about pros of python 3 version. But when I needed to print the columns of `pandas.DataFrame` (without `Index([...])`), I've found out that
```
print *df.columns
```
throws an exception, while
```
print(*df.columns)
```
works fine! And if you want to have same (configurab... |
Add custom html between two model fields in Django admin's change_form | 6,239,966 | 3 | 2011-06-04T23:17:19Z | 6,343,271 | 8 | 2011-06-14T12:12:09Z | [
"python",
"django",
"django-admin"
] | Let's say I've two models:
```
class Book(models.Model):
name = models.CharField(max_length=50)
library = models.ForeignKeyField('Library')
class Library(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
tel = models.CharField(max_length=50)
```
... | *models.py:*
```
class Library(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
tel = models.CharField(max_length=50)
def book_count(self):
return self.book_set.count()
```
*admin.py:*
```
class LibraryAdmin(admin.ModelAdmin):
fieldsets ... |
Determining whether an value is a whole number in Python | 6,239,967 | 8 | 2011-06-04T23:17:37Z | 6,239,983 | 22 | 2011-06-04T23:22:23Z | [
"python"
] | I would like to determine if a numeric value in Python is a whole number. For example, given:
```
y = x / 3
```
I want to distinguish between values of `x` which are evenly divisible by 3 those which are not. | ```
if x % 3 == 0:
print 'x is divisible by 3'
``` |
Determining whether an value is a whole number in Python | 6,239,967 | 8 | 2011-06-04T23:17:37Z | 6,239,987 | 34 | 2011-06-04T23:22:46Z | [
"python"
] | I would like to determine if a numeric value in Python is a whole number. For example, given:
```
y = x / 3
```
I want to distinguish between values of `x` which are evenly divisible by 3 those which are not. | Integers have no decimals. If you meant "check if **a number** got decimals in Python", you can do:
```
not float(your_number).is_integer()
``` |
gae Model get_by_id() vs get_by_key_name() | 6,240,312 | 8 | 2011-06-05T00:49:28Z | 6,240,499 | 10 | 2011-06-05T01:39:26Z | [
"python",
"google-app-engine"
] | I am wondering about fetching records using Model.get\_by\_key\_name() vs Model.get\_by\_id()
For example, let's say I am returning some JSON that will be used to display a table of records, and for each record, there is a button to delete that record. Suppose I have model 'Foo' and model instance 'foo'.
I believe I ... | You're confusing a Key name with the stringified Key. They're different. A key's name is something you give an entity via the reserved key\_name property at construction time. If you don't, the system will generate an id. An entity key can have either a name or an id, but not both.
If you've intentionally stringified ... |
Python socket.sendall() function | 6,240,737 | 12 | 2011-06-05T02:58:05Z | 6,240,775 | 11 | 2011-06-05T03:08:47Z | [
"python",
"sockets"
] | I'm reading *[Tutorial on Network Programming with Python](http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf)*, and in this document the author is saying that "The function sendall() should be used only with blocking sockets."
But I do not see any such condition in the Python documentation, *[socket.sendall(stri... | When in doubt, [check the source](http://svn.python.org/view/python/trunk/Modules/socketmodule.c?view=markup#l2729).
`socket_sendall` clearly gives up once send() returns -1, which it will do (with errno of EAGAIN or EWOULDBLOCK) if you call it on a non-blocking socket without calling poll() or select(). (And the `int... |
how can I program a large number of for loops | 6,240,770 | 2 | 2011-06-05T03:07:44Z | 6,240,917 | 13 | 2011-06-05T03:54:54Z | [
"java",
"python",
"algorithm",
"math",
"loops"
] | I'm new to programming so I'm sorry in phrasing if I'm not asking this question correctly.
I have the following code:
```
int sum = 100;
int a1 = 20;
int a2 = 5;
int a3 = 10;
for (int i = 0; i * a1 <= sum; i++) {
for (int j = 0; i * a1 + j * a2 <= sum; j++) {
for (int k = 0; i * a1 + j * a2 + k * a3 <= su... | Recursion.
This is what it sounds like you are trying to solve:
> your current example: 20x1 + 5x2 + 10x3 = 100
>
> so in general you are doing: A1x1 + A2x2 + ... + Anxn = SUM
>
> so you pass in an array of constants {A1, A2, ..., An}
> and you want to solve for {x1, x2, ..., xn}
```
public void findVariables(in... |
how can I program a large number of for loops | 6,240,770 | 2 | 2011-06-05T03:07:44Z | 6,241,191 | 7 | 2011-06-05T05:32:00Z | [
"java",
"python",
"algorithm",
"math",
"loops"
] | I'm new to programming so I'm sorry in phrasing if I'm not asking this question correctly.
I have the following code:
```
int sum = 100;
int a1 = 20;
int a2 = 5;
int a3 = 10;
for (int i = 0; i * a1 <= sum; i++) {
for (int j = 0; i * a1 + j * a2 <= sum; j++) {
for (int k = 0; i * a1 + j * a2 + k * a3 <= su... | Although it may not scale, here's a really simple brute-force python solution that doesn't require recursion:
```
import itertools
target_sum = 100
a = 20
b = 5
c = 10
a_range = range(0, target_sum + 1, a)
b_range = range(0, target_sum + 1, b)
c_range = range(0, target_sum + 1, c)
for i, j, k in itertools.product(a_ra... |
How can I make ipdb show more lines of context while debugging? | 6,240,887 | 20 | 2011-06-05T03:46:11Z | 6,449,663 | 12 | 2011-06-23T05:19:44Z | [
"python",
"debugging",
"ipython"
] | By default, during debugging in IPython, [ipdb](http://pypi.python.org/pypi/ipdb) shows one line above and one line below the current position in code.
Is there an easy way to make the area shown a bit bigger? I'd think it would be configurable, but haven't been able to find it. | OK, I found the place in the IPython source code to do this. In my installation it's at
```
.../python2.7/site-packages/ipython-0.10.2-py2.7.egg/IPython/Debugger.py:327:
```
Change this:
```
def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
context = 3):
```
to
```
def print_stac... |
How can I make ipdb show more lines of context while debugging? | 6,240,887 | 20 | 2011-06-05T03:46:11Z | 14,711,217 | 20 | 2013-02-05T15:38:57Z | [
"python",
"debugging",
"ipython"
] | By default, during debugging in IPython, [ipdb](http://pypi.python.org/pypi/ipdb) shows one line above and one line below the current position in code.
Is there an easy way to make the area shown a bit bigger? I'd think it would be configurable, but haven't been able to find it. | You can type `l` in ipdb to show a few more lines of the current context
and you can keep hitting `l` and it continue revealing more lines from the file
If you want to show more lines of context around the current line you can type `l` to get the current line. And then type `l curr_line - 10, curr_line + 10`. Say I w... |
Python for x in list basic question | 6,240,906 | 3 | 2011-06-05T03:51:40Z | 6,240,915 | 9 | 2011-06-05T03:54:46Z | [
"python"
] | I am trying to create a function which will load a whole lot of images and map them to appropriate names in PyGame. I'm not all that great with python and this really has me stuck. My current code is this:
```
tile1 = pygame.image.load("/one.bmp")
tile2 = pygame.image.load("/two.bmp")
tile3 = pygame.image.load("/three... | [List comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) to the rescue.
```
tiles = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [pygame.img.load(tile) for tile in tiles]
```
---
As [@isakkarlsson](http://stackoverflow.com/users/197497/isakkarlsson) commented,
> ...or easi... |
How can I see the details of an exception in Python's debugger? | 6,241,200 | 16 | 2011-06-05T05:34:17Z | 29,477,335 | 12 | 2015-04-06T18:35:11Z | [
"python",
"debugging"
] | Sometimes while I'm debugging an exception will be raised.
For example, consider this code:
```
def some_function(): # Pretend this function is in a library...
# ...and deep within the library is an exception:
raise Exception('An exception message with valuable information.')
import pdb; pdb.set_trace()
try... | `pdb` stores the exception type and value in `__exception__`. You can print the exception part of a traceback in `pdb` with:
```
import traceback; print "".join(traceback.format_exception_only(*__exception__))
```
For example:
```
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this poi... |
python named pipes problem | 6,241,260 | 10 | 2011-06-05T05:53:55Z | 6,241,288 | 11 | 2011-06-05T06:03:39Z | [
"python"
] | I am trying to setup two way communication beween a daemon and a client using named pipes. The code hangs while trying to open the named pipe used for input Why?
```
class comm(threading.Thread):
def __init__(self):
self.srvoutf = './tmp/serverout'
self.srvinf = './tmp/serverin'
if os.path.exists(self.srv... | From the [specification for open()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html):
> When opening a FIFO with O\_RDONLY or
> O\_WRONLY set:
>
> If O\_NONBLOCK is set, an
> open() for reading-only shall return
> without delay. An open() for
> writing-only shall return an error if
> no process cur... |
How to retrieve inserted id after inserting row in SQLite using Python? | 6,242,756 | 88 | 2011-06-05T11:59:13Z | 6,242,813 | 140 | 2011-06-05T12:09:47Z | [
"python",
"sqlite",
"sqlite3"
] | How to retrieve inserted id after inserting row in SQLite using Python? I have table like this:
```
id INT AUTOINCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
```
I insert a new row with example data `username="test"` and `password="test"`. How do I retrieve the generated id in a transaction safe wa... | You could use [cursor.lastrowid](http://www.python.org/dev/peps/pep-0249/) (see "Optional DB API Extensions"):
```
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
... |
How to get the physical interface IP address from an interface | 6,243,276 | 13 | 2011-06-05T13:38:38Z | 6,250,688 | 30 | 2011-06-06T10:27:48Z | [
"python",
"python-3.x",
"pyqt",
"ip-address"
] | What I have done so far, using PyQt classes:
```
all_Addresses = QNetworkInterface.allAddresses() #list-of-QHostAddress
for addr in all_Addresses:
print(addr.toString())
```
Output:
```
172.16.0.186 - Virtual Interface IP address
192.168.10.2 - Physical interface IP address. I want this one.
127.0.0.1
```
U... | You should use [netifaces](http://pypi.python.org/pypi/netifaces/). It is designed to be cross-platform and contains specialised code for Windows together with a variety of generic versions that work on different UNIX/UNIX-like platforms.
As of [netifaces](http://pypi.python.org/pypi/netifaces/) version 0.10.0, Python... |
How to get the physical interface IP address from an interface | 6,243,276 | 13 | 2011-06-05T13:38:38Z | 17,667,982 | 8 | 2013-07-16T04:24:40Z | [
"python",
"python-3.x",
"pyqt",
"ip-address"
] | What I have done so far, using PyQt classes:
```
all_Addresses = QNetworkInterface.allAddresses() #list-of-QHostAddress
for addr in all_Addresses:
print(addr.toString())
```
Output:
```
172.16.0.186 - Virtual Interface IP address
192.168.10.2 - Physical interface IP address. I want this one.
127.0.0.1
```
U... | I use this solution. It's a little bit tricky actually, and it's only works on linux family.
```
import commands
intf = 'eth0'
intf_ip = commands.getoutput("ip address show dev " + intf).split()
intf_ip = intf_ip[intf_ip.index('inet') + 1].split('/')[0]
print intf_ip
```
Those code utilize `ip` command on linux famil... |
How to get the physical interface IP address from an interface | 6,243,276 | 13 | 2011-06-05T13:38:38Z | 27,423,915 | 8 | 2014-12-11T13:22:35Z | [
"python",
"python-3.x",
"pyqt",
"ip-address"
] | What I have done so far, using PyQt classes:
```
all_Addresses = QNetworkInterface.allAddresses() #list-of-QHostAddress
for addr in all_Addresses:
print(addr.toString())
```
Output:
```
172.16.0.186 - Virtual Interface IP address
192.168.10.2 - Physical interface IP address. I want this one.
127.0.0.1
```
U... | Uses the Linux SIOCGIFADDR ioctl to find the IP address associated with a network interface, given the name of that interface, e.g. "`eth0`". The address is returned as a string containing a dotted quad.
```
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, soc... |
Python lambda function | 6,243,460 | 14 | 2011-06-05T14:17:59Z | 6,243,470 | 15 | 2011-06-05T14:19:31Z | [
"python",
"lambda"
] | What is happening here?
```
reduce(lambda x,y: x+y, [x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0])
```
I understand how x is iterating through all of the numbers from 1 to 999 and taking out those that are divisible by 3 or 5, but the 'lambda x,y: x+y' part is stumping me. | This is bad Python for
```
sum(x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0)
```
It simply sums all numbers in the range 1..999 divisible by 3 or 5.
[`reduce()`](http://docs.python.org/library/functions.html#reduce) applies the given function to the first two items of the iterable, then to the result and the... |
Writing a virtual webcam? | 6,243,891 | 13 | 2011-06-05T15:37:25Z | 6,244,367 | 18 | 2011-06-05T16:53:14Z | [
"c++",
"python",
"webcam",
"wia"
] | I need to create a virtual webcam that poses as a webcam, but takes as input a set of images that it plays. I have seen solutions like ManyCam, and Fake Webcam, but they all seem to one limitation or the other (resolution, max file size, fps etc.) I am working on Windows XP SP3.
I understand that I have to write a WIA... | You need to write DirectShow filter which is a COM server that implements an [`IPin`](http://msdn.microsoft.com/en-us/library/dd390397%28v=vs.85%29.aspx), [`IAMStreamConfig`](http://msdn.microsoft.com/en-us/library/dd319784%28v=vs.85%29.aspx) and [`IKsPropertySet`](http://msdn.microsoft.com/en-us/library/dd390144%28v=v... |
sqlalchemy filter by count column | 6,244,038 | 2 | 2011-06-05T16:00:04Z | 6,251,564 | 7 | 2011-06-06T11:48:17Z | [
"python",
"sqlalchemy"
] | I have a User query which filters by the amount of orders each user has (ordersCount).
```
User.query.filter('ordersCount>2')
```
If I run it it says: "Unknown column 'ordersCount' in 'where clause'"
From my experience I should be using having on such operations because mysql won't allow it for fields not part of th... | See documentation of [Ordering, Grouping, Limiting, Offset...ing](http://www.sqlalchemy.org/docs/core/tutorial.html#ordering-grouping-limiting-offset-ing). Based on the sample code provided and an assumption that your orders are stored in the `orders` table, your version would look similar to:
```
>>> s = select([orde... |
Given two lists in python one with strings and one with objects, how do you map them? | 6,244,171 | 4 | 2011-06-05T16:21:22Z | 6,244,185 | 8 | 2011-06-05T16:23:54Z | [
"python",
"list",
"sorting"
] | I have a list of strings
```
string_list = ["key_val_1", "key_val_2", "key_val_3", "key_val_4", ...]
```
and a list with objects
```
object_list = [object_1, object_2, object_3,...]
```
Every object `object_i` has an attribute `key`.
I want to **sort the objects in `object_list` by the order of `string_list`**.
I... | First, create a dictionary mapping object keys to objects:
```
d = dict((x.key, x) for x in object_list)
```
Next create the sorted list using a list comprehension:
```
new_list = [d[key] for key in string_list]
``` |
Can/should I implement Python methods by assignment to attributes? | 6,244,342 | 6 | 2011-06-05T16:49:07Z | 6,244,366 | 8 | 2011-06-05T16:53:03Z | [
"python",
"coding-style"
] | Is there any stylistic taboo or other downside to implementing trivial methods by assignment to class attributes? E.g. like `bar` and `baz` below, as opposed to the more ususal `foo`.
```
class MyClass(object):
def hello(self):
return 'hello'
def foo(self):
return self.hello()
bar = lambda ... | Personally, I think things like
```
__str__ = __repr__ = hello
```
are fine, but
```
bar = lambda self: self.hello()
```
is evil. You cannot easily give a lambda a docstring, and the `.func_name` attribute will have the meaningless value `<lambda>`. Both those problems don't occur for the first line. |
python & SQLite in Production | 6,244,892 | 2 | 2011-06-05T18:22:40Z | 6,244,941 | 7 | 2011-06-05T18:31:07Z | [
"python",
"sqlite"
] | When using `python`, can `SQLite` be used as production database to manage say 10,000 databases files (each in a separate file -- of size 500[MB])?
Only one thread will be used to write data to the database files (no concurrency).
Are there alternatives libraries that can work better / faster / more reliably? | Maybe you'll look at [this page](http://www.sqlite.org/whentouse.html) titled "appropriate uses for sqlite". To quote:
> The basic rule of thumb for when it is
> appropriate to use SQLite is this: Use
> SQLite in situations where simplicity
> of administration, implementation, and
> maintenance are more important than... |
Python 3.2 Idle vs terminal | 6,244,956 | 4 | 2011-06-05T18:33:12Z | 6,245,080 | 7 | 2011-06-05T18:54:30Z | [
"python",
"python-idle"
] | In python 3.2 under OSX, if I'll run "type(sys.stdin)" under Idle I get a strange answer as shown below
```
>>> type(sys.stdin)
<class 'idlelib.rpc.RPCProxy'>
>>>
```
But if I'll reun the same command under terminal, I get:
```
>>> import sys
>>> type(sys.stdin)
<class '_io.TextIOWrapper'>
>>>
```
I understand this... | This is a filed Python bug:
<http://bugs.python.org/issue9290>
> The fact that in IDLE sys.stdin is a
> `idlelib.rpc.RPCProxy` results in
> programs having different behavior in
> IDLE and in Command Line mode.
>
> I noticed that when grading many
> students exercises in IDLE. Things
> like:
>
> ```
> sys.stdin.readl... |
Python combinatorials w/o repetition - Pyncomb? | 6,245,108 | 6 | 2011-06-05T18:57:37Z | 6,245,134 | 9 | 2011-06-05T19:01:06Z | [
"python",
"combinatorics"
] | I'm trying to do some combinatorial stuff with data in Python.
I looked the question [How to generate all permutations of a list in Python](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python), but think that doesn't fit my needs..
I have data of this type...:
```
group1-... | The easiest way is to use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product):
```
group1 = ["Steve", "Mark", "Tom"]
group2 = ["Brett", "Mick", "Foo"]
group3 = ["Dan", "Phil"]
for x in itertools.product(group1, group2, group3):
print x
```
prints
```
('Steve', 'Brett', 'Dan')... |
zero mq pub/sub with multipart not working | 6,245,224 | 5 | 2011-06-05T19:13:44Z | 6,245,579 | 8 | 2011-06-05T20:15:18Z | [
"python",
"publish-subscribe",
"zeromq"
] | Here's my script.
```
#!/usr/bin/env python
import traceback
import sys
import zmq
from time import sleep
print "Creating the zmq.Context"
context = zmq.Context()
print "Binding the publisher to the local socket at port 5557"
sender = context.socket(zmq.PUB)
sender.bind("tcp://*:5557")
print "Binding the subscribe... | Credit: Chuck Remes
> You may need a "sleep" between the socket creation steps (bind, connect, setsockopt) and the actual transmission of the messages. The bind & connect operations are asynchronous, so they may not complete by the time you get to the logic that sends all of the messages. In that case, any messages se... |
Is it possible to use Mysql with SqlAlchemy and Flask if my mysql socket isn't in /tmp? | 6,245,813 | 13 | 2011-06-05T20:57:24Z | 6,245,857 | 19 | 2011-06-05T21:04:22Z | [
"python",
"sqlalchemy",
"flask"
] | The location for mysql.sock on my system is **/usr/local/mysql5/mysqld.sock**
```
thrilllap-2:tmp reuven$ mysqld --print-defaults
mysqld would have been started with the following arguments:
--socket=/usr/local/mysql5/mysqld.sock --port=3306
```
When I try to use mysql via sqlalchemy from flask, I get:
```
File "b... | You'll have to dig up the exact syntax, but for MySQL I think they use a `unix_socket` query opt. Something like:
```
mysql:///dbname?unix_socket=/opt/mysql/mysql.sock'
```
Should be your connect URI for SQLAlchemy. |
Is it possible to use Mysql with SqlAlchemy and Flask if my mysql socket isn't in /tmp? | 6,245,813 | 13 | 2011-06-05T20:57:24Z | 6,245,962 | 10 | 2011-06-05T21:24:05Z | [
"python",
"sqlalchemy",
"flask"
] | The location for mysql.sock on my system is **/usr/local/mysql5/mysqld.sock**
```
thrilllap-2:tmp reuven$ mysqld --print-defaults
mysqld would have been started with the following arguments:
--socket=/usr/local/mysql5/mysqld.sock --port=3306
```
When I try to use mysql via sqlalchemy from flask, I get:
```
File "b... | Yes! Sean was right
```
app.config['SQLALCHEMY_DATABASE_URI'] = ''mysql://dayenu:secret.word@localhost/dayenu?unix_socket=/usr/local/mysql5/mysqld.sock
db = SQLAlchemy(app)
```
works fine! I think this parameter is used by pyodbc, which is what sqlachemy uses to talk to mysql, but I couldn't find this parameter anywh... |
uwsgi + python + nginx + willy nilly file execution | 6,247,667 | 4 | 2011-06-06T04:07:08Z | 6,247,788 | 9 | 2011-06-06T04:35:00Z | [
"python",
"nginx",
"uwsgi"
] | I'm using uwsgi on Nginx to run some Python code.
I'd like to bind uwsgi to a directory and make it render any .py file that I call from the server in the browser. I'm thinking like PHP, here (/index.php executes that file, /login.php executes that file).
Is this a possibility? Or am I only able to explicitly specify... | WSGI is not like PHP. You can't just point uwsgi to a directory with a bunch of .py files. In fact, never, ever make your python modules available in a public directory, accessible from the server. You need to hook uwsgi up to a WSGI application, preferably a framework. Read more about WSGI [here](http://lucumr.pocoo.o... |
Storing an array of integers with Django | 6,248,239 | 5 | 2011-06-06T05:55:30Z | 21,121,828 | 9 | 2014-01-14T19:04:43Z | [
"python",
"django",
"arrays",
"integer"
] | I've been trying to store an array of integers in a field of a Django model. Based on [this reply](http://stackoverflow.com/questions/1429293/storing-an-integer-array-in-a-django-database), I've been trying to do so using a CommaSeparatedIntegerField, however this has proved less intuitive than the name would imply.
I... | Eval was accepted as answer above -- avoid the temptation it's just not safe
See: [Python: make eval safe](http://stackoverflow.com/questions/3513292/python-make-eval-safe)
There is a [literal\_eval](http://docs.python.org/2/library/ast.html?highlight=literal#ast.literal_eval) function that could be used the same way... |
EXIF like thing for Videos | 6,248,347 | 3 | 2011-06-06T06:09:54Z | 6,249,119 | 7 | 2011-06-06T07:53:31Z | [
"c++",
"python",
"c",
"perl",
"exif"
] | Is there any standard way to get information from a video file? For images we have EXIF data which can be used to get information about the date/time , size etc of the image file. I was wondering if there is such a thing for videos as well.
The use case is - I have lot of videos which I shot from my digital camera. I ... | [exiftool](http://p3rl.org/exiftool) reads video containers and their metadata. |
elegant way of using a range using an if statement? | 6,248,639 | 8 | 2011-06-06T06:49:05Z | 6,248,672 | 12 | 2011-06-06T06:52:35Z | [
"python"
] | I've got this very crude way of writing this IF statement .
```
for a in range (2,3000):
if ( a % 1) == 0 and ( a % 2) == 0 and ( a % 3) == 0 and ( a % 4) == 0 and ( a % 5) == 0 and ( a % 6) == 0 and ( a % 7) == 0 and ( a % 8) == 0 and ( a % 9) == 0 and ( a % 10) == 0 :
print a
```
I assume there is a much b... | For a more-or-less direct translation, how about
```
for a in range(2, 3000):
if all(a % k == 0 for k in range(1,11)):
print a
```
although of course a % 1 == 0 for all integers a, so that check is unnecessary. |
elegant way of using a range using an if statement? | 6,248,639 | 8 | 2011-06-06T06:49:05Z | 6,249,362 | 7 | 2011-06-06T08:23:45Z | [
"python"
] | I've got this very crude way of writing this IF statement .
```
for a in range (2,3000):
if ( a % 1) == 0 and ( a % 2) == 0 and ( a % 3) == 0 and ( a % 4) == 0 and ( a % 5) == 0 and ( a % 6) == 0 and ( a % 7) == 0 and ( a % 8) == 0 and ( a % 9) == 0 and ( a % 10) == 0 :
print a
```
I assume there is a much b... | What you need is the multiples of LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) which fall within your range. There's multiple ways of computing LCM (see. <http://en.wikipedia.org/wiki/Least_common_multiple>)
Since LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) = 2^3 \* 3^2 \* 5 \* 7 = 2520, you can do something like
```
lcm = 2520
i = 2/l... |
numpy argmin elegant solution required. | 6,249,514 | 3 | 2011-06-06T08:40:58Z | 6,249,954 | 7 | 2011-06-06T09:24:17Z | [
"python",
"numpy",
"scipy"
] | In python to find the index of the minimum value of the array I use`y = numpy.argmin(someMat)`
Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way? | "Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way?"
If you only care about the minimum value satisfying some condition and not the location, then
```
>>> numpy.random.seed(1)
>>> m = numpy.random.randn(5.,5.)
>>> m
array([[ 1.62434536, -0.61175641, -0.528171... |
What happened to Python's rect class? | 6,249,753 | 5 | 2011-06-06T09:04:41Z | 6,250,343 | 8 | 2011-06-06T09:56:51Z | [
"python",
"rect"
] | On a Google Search, I found this article:
<http://docs.python.org/release/1.4/lib/node201.html>
Which showed examples of using the rect class, to perform union/intersections/checking if points are inside rect. Importing rect fails in Python 2.7. Is this class in another package? | I assume the question isn't really "*what happened to it?*", but "*where can I find a class like this that I can use?*".
Most GUI libraries have a class like this. For example: [wx.Rect](http://www.wxpython.org/docs/api/wx.Rect-class.html), [QRect](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qrect.html)... |
How can I remove the fragment identifier from a URL? | 6,250,046 | 5 | 2011-06-06T09:31:13Z | 6,250,083 | 8 | 2011-06-06T09:33:52Z | [
"python",
"string"
] | I have a string containing a link. The link often has the form:
> http://www.address.com/something#something
Is there a function in python that can remove "#something" from a link? | Just use `split()`
```
>>> foo = "http://www.address.com/something#something"
>>> foo = foo.split('#')[0]
>>> foo
'http://www.address.com/something'
>>>
``` |
How can I remove the fragment identifier from a URL? | 6,250,046 | 5 | 2011-06-06T09:31:13Z | 6,250,107 | 25 | 2011-06-06T09:36:07Z | [
"python",
"string"
] | I have a string containing a link. The link often has the form:
> http://www.address.com/something#something
Is there a function in python that can remove "#something" from a link? | use [urlparse.urldefrag](http://docs.python.org/library/urlparse.html#urlparse.urldefrag):
```
>>> urlparse.urldefrag("http://www.address.com/something#something")
('http://www.address.com/something', 'something')
``` |
converting text size into data coordinates | 6,251,569 | 3 | 2011-06-06T11:48:33Z | 6,256,948 | 9 | 2011-06-06T19:24:24Z | [
"python",
"matplotlib"
] | In matplotlib, what is a way of converting the text box size into data coordinates?
For example, in this toy script I'm fine-tuning the coordinates of the text box so that it's next to a data point.
```
#!/usr/bin/python
import matplotlib.pyplot as plt
xx=[1,2,3]
yy=[2,3,4]
dy=[0.1,0.2,0.05]
fig=plt.figure()
ax=fig... | Generally speaking, you can't get the size of the text until after it's drawn (thus the hacks in @DSM's answer).
For what you're wanting to do, you'd be far better off using [annotate](http://matplotlib.sourceforge.net/users/annotations.html).
E.g. `ax.annotate('Your text string', xy=(x, y), xytext=(x-0.1, y-0.4))`
... |
using python nltk to find similarity between two web pages? | 6,252,236 | 4 | 2011-06-06T12:47:26Z | 6,259,146 | 12 | 2011-06-06T23:25:35Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | I want to find whether two web pages are similar or not. Can someone suggest if python nltk with wordnet similarity functions helpful and how? What is the best similarity function to be used in this case? | The [spotsigs](http://ilpubs.stanford.edu:8090/821/) paper mentioned by *joyceschan* addresses content duplication detection and it contains plenty of food for thought.
If you are looking for a quick comparison of key terms, `nltk` standard functions might suffice.
With `nltk` you can pull synonyms of your terms by l... |
find the most frequent number in a numpy vector | 6,252,280 | 32 | 2011-06-06T12:51:40Z | 6,252,400 | 69 | 2011-06-06T13:01:19Z | [
"python",
"numpy"
] | Suppose I have the following:
```
a = [1,2,3,1,2,1,1,1,3,2,2,1]
```
How to find the most frequent number in this list in a neat way? | If your list contains all non-negative ints, you should take a look at numpy.bincounts:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html>
and then probably use np.argmax:
```
a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
counts = np.bincount(a)
print np.argmax(counts)
```
For a more complicated li... |
find the most frequent number in a numpy vector | 6,252,280 | 32 | 2011-06-06T12:51:40Z | 6,252,494 | 18 | 2011-06-06T13:10:09Z | [
"python",
"numpy"
] | Suppose I have the following:
```
a = [1,2,3,1,2,1,1,1,3,2,2,1]
```
How to find the most frequent number in this list in a neat way? | If you're willing to use [SciPy](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html):
```
>>> from scipy.stats import mode
>>> mode([1,2,3,1,2,1,1,1,3,2,2,1])
(array([ 1.]), array([ 6.]))
>>> most_frequent = mode([1,2,3,1,2,1,1,1,3,2,2,1])[0][0]
>>> most_frequent
1.0
``` |
find the most frequent number in a numpy vector | 6,252,280 | 32 | 2011-06-06T12:51:40Z | 28,736,715 | 14 | 2015-02-26T07:29:49Z | [
"python",
"numpy"
] | Suppose I have the following:
```
a = [1,2,3,1,2,1,1,1,3,2,2,1]
```
How to find the most frequent number in this list in a neat way? | You may use
```
(values,counts) = np.unique(a,return_counts=True)
ind=np.argmax(counts)
print values[ind] # prints the most frequent element
```
If some element is as frequent as another one, this code will return only the first element. |
Python: default comparison | 6,252,758 | 6 | 2011-06-06T13:31:25Z | 6,252,953 | 12 | 2011-06-06T13:45:49Z | [
"python",
"object",
"comparison"
] | In Python 2.7, I define an empty new-style class:
```
In [43]: class C(object): pass
....:
```
then create a list of instances of the new class:
```
In [44]: c = [C() for i in xrange(10)]
```
then attempt to sort the list:
```
In [45]: sorted(c)
Out[45]:
[<__main__.C object at 0x1950a490>,
<__main__.C object a... | I think the only rationale is that it is convenient that objects can be sorted and e.g. used as dictionary keys with some default behavior. The relevant chapter in the language definition is here: <https://docs.python.org/2/reference/expressions.html#not-in>
> "The choice whether one object is considered smaller or la... |
Python Vertical Array Slicing | 6,253,586 | 4 | 2011-06-06T14:32:49Z | 6,253,606 | 13 | 2011-06-06T14:34:04Z | [
"python"
] | Can anyone show me how to slice the structure below:
```
[[1, A], [2, B], [3,C]]
```
Into two separate lists:
```
[1, 2, 3]
[A, B, C]
```
I can obviously do this using code, but wondered if Python was able to do it natively? | ```
my_list = [[1, A], [2, B], [3, C]]
a, b = zip(*my_list)
```
Note that `a` and `b` will end up being tuples. |
Testing for specific method in a Python class | 6,254,586 | 2 | 2011-06-06T15:48:18Z | 6,254,615 | 10 | 2011-06-06T15:50:28Z | [
"python",
"oop",
"class",
"methods"
] | What is the best (or 'Pythonic') way to test if a class has a specific method defined?
Both of these work but don't feel 'correct' in that in the second one, I just try to access it and trap for an exception if it doesn't exist.
Is there a better / more correct way?
```
class TestClass(object):
def TestFunc(self... | Use [`hasattr`](http://docs.python.org/library/functions.html#hasattr):
```
class Foo(object):
def bar():
pass
assert hasattr(Foo, 'bar')
```
If you really mean to test whether the attribute is a *method*, you could do this:
```
assert hasattr(Foo, 'bar') and callable(getattr(Foo, 'bar'))
``` |
Python: min(None, x) | 6,254,871 | 11 | 2011-06-06T16:09:17Z | 6,254,950 | 16 | 2011-06-06T16:16:47Z | [
"python",
"python-2.x"
] | I would like to perform the following:
```
a=max(a,3)
b=min(b,3)
```
However sometimes `a` and `b` may be `None`.
I was happy to discover that in the case of `max` it works out nicely, giving my required result `3`, however if `b` is `None`, `b` remains `None`...
Anyone can think of an elegant little trick to make... | Why don't you just create a generator without None values? It's simplier and cleaner.
```
>>> l=[None ,3]
>>> min(i for i in l if i is not None)
3
``` |
python threading: will Event.set() really notify every waiting thread | 6,254,977 | 10 | 2011-06-06T16:19:04Z | 6,256,704 | 8 | 2011-06-06T18:59:31Z | [
"python",
"multithreading",
"events",
"wait"
] | If I have a threading.Event and the following two lines of code...
```
event.set()
event.clear()
```
...and I have some threads who are waiting for that event.
My question is related to what happens when calling the set() method:
* Can I be ABSOLUTELY sure that all the waiting thread(s) will be notified? (i.e. Even... | In the internals of Python, an event is implemented with a [`Condition()`](http://docs.python.org/library/threading.html#condition-objects) object.
When calling the `event.set()` method, the [`notify_all()`](http://docs.python.org/library/threading.html#threading.Condition.notify_all) of the condition is called (after... |
python threading: will Event.set() really notify every waiting thread | 6,254,977 | 10 | 2011-06-06T16:19:04Z | 6,256,784 | 9 | 2011-06-06T19:05:32Z | [
"python",
"multithreading",
"events",
"wait"
] | If I have a threading.Event and the following two lines of code...
```
event.set()
event.clear()
```
...and I have some threads who are waiting for that event.
My question is related to what happens when calling the set() method:
* Can I be ABSOLUTELY sure that all the waiting thread(s) will be notified? (i.e. Even... | It's easy enough to verify that things work as expected:
```
import threading
e = threading.Event()
threads = []
def runner():
tname = threading.current_thread().name
print 'Thread waiting for event: %s' % tname
e.wait()
print 'Thread got event: %s' % tname
for t in range(100):
t = threading.Thr... |
Python: thinking of a module and its variables as a singleton â Clean approach? | 6,255,050 | 18 | 2011-06-06T16:25:03Z | 6,255,101 | 14 | 2011-06-06T16:28:36Z | [
"python",
"module",
"singleton"
] | I'd like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I'd like to put all the singleton-related functions and variables within a module and consider it an actual singleton.
For example, say this is to be in the file 'singleton\_module.py':... | A common alternative to using a module as a singleton is Alex Martelli's [Borg pattern](http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/):
```
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
# and whatever else you... |
Parsing Multipart emails in python and saving attachments | 6,255,202 | 8 | 2011-06-06T16:37:49Z | 6,270,317 | 9 | 2011-06-07T19:07:20Z | [
"python",
"email",
"gmail",
"attachment",
"imaplib"
] | I am pretty new to python and I am trying to parse email from gmail via python's imaplib and email. It is working pretty well but I am having issues with email attachments.
I would like to parse out all of the plaintext from the email while ignoring any HTML that may be inserted as a secondary content type while also ... | If you just need to keep text attachments out of the `body` variable with what you have there, it should be as simple as this:
```
mail = email.message_from_string(email_body)
for part in mail.walk():
c_type = part.get_content_type()
c_disp = part.get('Content-Disposition')
if c_type == 't... |
Find names of positional arguments through introspection | 6,255,284 | 9 | 2011-06-06T16:45:12Z | 6,255,300 | 10 | 2011-06-06T16:46:57Z | [
"python"
] | Is there a way to figure out the names of the positional arguments to a python function?
```
def foo(arg1, arg2):
pass
f=foo
# How do I find out want the 1st argument to f is called? I want 'arg1' as an answer
``` | The function [`inspect.getargspec()`](http://docs.python.org/library/inspect.html#inspect.getargspec) does what you need. |
What is the cleanest way to do HTTP POST with basic auth in Python? | 6,256,126 | 10 | 2011-06-06T18:00:26Z | 6,256,341 | 22 | 2011-06-06T18:23:44Z | [
"python",
"http",
"basic-authentication"
] | What is the cleanest way to do HTTP POST with Basic Auth in Python?
Using only the Python core libs. | Seriously, just use [`requests`](http://docs.python-requests.org/en/latest/index.html):
```
import requests
resp = requests.post(url, data={}, auth=('user', 'pass'))
```
It's a pure python library, installing is as easy as `easy_install requests` or `pip install requests`. It has an extremely simple and easy to use A... |
Python 3.2 - Concatenate and string formatting behavior not behaving as expected | 6,256,369 | 5 | 2011-06-06T18:26:53Z | 6,256,424 | 8 | 2011-06-06T18:32:46Z | [
"python",
"python-3.x",
"string-formatting",
"string-concatenation"
] | I want to create a "full file name" variable from several other variables, but the string concatenation and string format operations aren't behaving the way I expect.
My code is below:
```
file_date = str(input("Enter file date: "))
root_folder = "\\\\SERVER\\FOLDER\\"
file_prefix = "sample_file_"
file_extension = "... | I think the method input used in your example, like so:
```
file_date = str(input("Enter file date: "))
```
may be returning a carriage return character at the end.
This causes the cursor to go back to the start of the line when you try to print it out.
You may want to trim the return value of input(). |
Uninstantiable superclass | 6,256,603 | 15 | 2011-06-06T18:48:16Z | 6,256,632 | 7 | 2011-06-06T18:51:19Z | [
"python",
"superclass"
] | So, I'm writing a module for connecting to external account providers (Twitter, Facebook etc) and I have a superclass that is useless on its own, but contains generic methods that need to be invoked by the subclasses for persisting auth tokens, getting auth tokens and deauthorizing the provider. My question is, is ther... | ```
class NoInstantiation: # "class NoInstantiation(object):" in Python 2.2+ or whatever
def __new__(cls):
"This class is not meant to be instantiated, so __new__ returns None."
return None
```
This won't stop people from overriding that functionality if they want to, but it should be a fairly d... |
Uninstantiable superclass | 6,256,603 | 15 | 2011-06-06T18:48:16Z | 6,256,803 | 7 | 2011-06-06T19:07:42Z | [
"python",
"superclass"
] | So, I'm writing a module for connecting to external account providers (Twitter, Facebook etc) and I have a superclass that is useless on its own, but contains generic methods that need to be invoked by the subclasses for persisting auth tokens, getting auth tokens and deauthorizing the provider. My question is, is ther... | Building on JAB's answer, it might be more convenient to write `__new__()` like this:
```
class NoInstantiation(object):
def __new__(cls, *args, **kwargs):
if cls is NoInstantiation:
raise RuntimeError(
"NoInstantiation isn't meant to be instantiated")
else:
... |
Uninstantiable superclass | 6,256,603 | 15 | 2011-06-06T18:48:16Z | 6,257,141 | 7 | 2011-06-06T19:42:41Z | [
"python",
"superclass"
] | So, I'm writing a module for connecting to external account providers (Twitter, Facebook etc) and I have a superclass that is useless on its own, but contains generic methods that need to be invoked by the subclasses for persisting auth tokens, getting auth tokens and deauthorizing the provider. My question is, is ther... | I'm seconding [Sven Marnach's edit](http://stackoverflow.com/questions/6256603/uninstantiable-superclass/6256803#6256803): I think you should follow the "consenting adults" rule and mention in the docstring that the class is not meant to be instantiated.
The key phrase in your question is "I have a superclass *that is... |
How are deques in Python implemented, and when are they worse than lists? | 6,256,983 | 29 | 2011-06-06T19:28:43Z | 6,257,042 | 22 | 2011-06-06T19:35:13Z | [
"python",
"deque"
] | I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemen... | Check out [`collections.deque`](http://docs.python.org/library/collections.html). From the docs:
> Deques support thread-safe, memory
> efficient appends and pops from either
> side of the deque with approximately
> the same O(1) performance in either
> direction.
>
> Though list objects support similar
> operations, ... |
How are deques in Python implemented, and when are they worse than lists? | 6,256,983 | 29 | 2011-06-06T19:28:43Z | 6,257,048 | 32 | 2011-06-06T19:35:52Z | [
"python",
"deque"
] | I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemen... | <https://hg.python.org/cpython/file/3.5/Modules/_collectionsmodule.c>
> A `dequeobject` is composed of a doubly-linked list of `block` nodes.
So yes, a `deque` is a (doubly-)linked list as another answer suggests.
Elaborating: What this means is that Python lists are much better for random-access and fixed-length op... |
How are deques in Python implemented, and when are they worse than lists? | 6,256,983 | 29 | 2011-06-06T19:28:43Z | 6,257,050 | 9 | 2011-06-06T19:35:56Z | [
"python",
"deque"
] | I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemen... | The documentation entry for [`deque` objects](http://docs.python.org/library/collections.html#deque-objects) spells out most of what you need to know, I suspect. Notable quotes:
> Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in... |
How are deques in Python implemented, and when are they worse than lists? | 6,256,983 | 29 | 2011-06-06T19:28:43Z | 15,464,206 | 8 | 2013-03-17T18:01:05Z | [
"python",
"deque"
] | I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemen... | In addition to all the other helpful answers, [here](http://wiki.python.org/moin/TimeComplexity) is some more information comparing the time complexity (Big-Oh) of various operations on Python lists, deques, sets, and dictionaries. This should help in selecting the right data structure for a particular problem. |
Pylint recursively for a given filename | 6,257,547 | 12 | 2011-06-06T20:19:33Z | 6,257,603 | 14 | 2011-06-06T20:25:25Z | [
"python",
"django",
"pylint"
] | I have a Django project and I'm working on Pylinting my way through it.
I have a couple situations where I'd like to be able to recursively find all files with a given name and pylint them differently (using different options). For example, I'd like to set different options for pylinting urls.py and admin.py
The foll... | Depending on your operating system, you could use:
```
find project_name -name urls.py | xargs pylint
``` |
Python generator to yield everything from another generator call | 6,257,644 | 10 | 2011-06-06T20:28:22Z | 6,258,413 | 13 | 2011-06-06T21:47:36Z | [
"python",
"recursion",
"generator",
"yield"
] | I have a Python generator that can call itself to get more elements to yield. It looks like this:
```
def gen(list):
# ...
if list:
for x in gen(list[1:]):
yield x
```
My question is about the last two lines: is there a more concise way to express this? I am hoping for something like this ... | There's been some call for a `yield from` or the like that "passes through" all the values returned by a subgenerator. See [PEP 380](http://www.python.org/dev/peps/pep-0380/) for some ideas that have been bounced around. However, nothing has been implemented yet. Your first example is correct. |
Convert hash.digest() to unicode | 6,257,647 | 12 | 2011-06-06T20:28:51Z | 6,257,716 | 11 | 2011-06-06T20:33:00Z | [
"python",
"unicode",
"unicode-string"
] | ```
import hashlib
string1 = u'test'
hashstring = hashlib.md5()
hashstring.update(string1)
string2 = hashstring.digest()
unicode(string2)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 1: ordinal
not in range(128)
```
The string HAS to be unicode for it to be any use to me, can this be done?
Us... | The result of `.digest()` is a bytestring¹, so converting it to Unicode is pointless. Use `.hexdigest()` if you want a readable representation.
¹ Some bytestrings can be converted to Unicode, but the bytestrings returned by `.digest()` do not contain textual data. They can contain any byte including the null byte: t... |
Convert hash.digest() to unicode | 6,257,647 | 12 | 2011-06-06T20:28:51Z | 6,258,224 | 20 | 2011-06-06T21:27:21Z | [
"python",
"unicode",
"unicode-string"
] | ```
import hashlib
string1 = u'test'
hashstring = hashlib.md5()
hashstring.update(string1)
string2 = hashstring.digest()
unicode(string2)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 1: ordinal
not in range(128)
```
The string HAS to be unicode for it to be any use to me, can this be done?
Us... | Ignacio just gave the perfect answer. Just a complement: when you convert some string from an encoding which has chars not found in ASCII to unicode, you have to pass the encoding as a parameter:
```
>>> unicode("órgão")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'as... |
python: What's the rationale behind not allowing * in relative imports? | 6,257,995 | 8 | 2011-06-06T21:03:15Z | 6,258,092 | 7 | 2011-06-06T21:14:03Z | [
"python",
"design",
"module",
"import",
"relative"
] | What's the rationale behind not allowing \* in relative imports? e.g.
```
from ..new_tool import *
```
or doing a relative import directly:
```
import ..new_tool
``` | The reason the latter is prohibited is that `..new_tool` is not usable in an expression [(PEP 328)](http://www.python.org/dev/peps/pep-0328/):
> The reason `import .foo` is prohibited
> is because after
>
> ```
> import XXX.YYY.ZZZ
> ```
>
> then `XXX.YYY.ZZZ` is usable in an
> expression. But
>
> ```
> .modul... |
In python how can I iterate through a string splitting it at different spots as I go? | 6,258,091 | 2 | 2011-06-06T21:13:59Z | 6,258,112 | 7 | 2011-06-06T21:16:04Z | [
"python",
"string",
"math"
] | I'm trying to write a quick solve for Kaprekar number's to show a friend of mine how easy it is to implement something like this in Python. I know how to do all the steps except for iterating through the squared number as a string. For example 45 is a Kaprekar number because
45 \*\* 2 = 2025 and 20 + 25 = 45
What I'm... | ```
>>> s = '2025'
>>> for i in range(1, len(s)):
... print s[:i], s[i:]
...
2 025
20 25
202 5
``` |
sqlalchemy bind values | 6,258,562 | 2 | 2011-06-06T22:04:26Z | 6,259,615 | 12 | 2011-06-07T00:47:26Z | [
"python",
"sqlalchemy"
] | I want to get the value of a paramer in a sqlalchemy query object dynamically:
```
q = session.query(Model).filter(Model.foo = 6)
```
I now want to be able to retrive the value 6 from q
```
assert(q.magic == 6)
```
Attempts:
print q.\_criterion # -> models.foo = :foo\_1
But where is the value of foo\_1? | SQLAlchemy generates a tree structure from your filter predicates, appending each leaf on as appropriate and putting the result in `Query._criterion`. You can explore this with the `get_children()` method of various `ClauseElement` and `ColumnElement` classes.
For `Model.foo == 6` you'll end up with something like thi... |
Docstrings in C extensions to Python? | 6,259,114 | 14 | 2011-06-06T23:20:34Z | 6,259,198 | 15 | 2011-06-06T23:33:38Z | [
"python",
"cpython",
"python-c-extension"
] | When creating a C extension to Python, is it possible to be able to somehow write comments that are exposed as [docstrings](http://epydoc.sourceforge.net/docstrings.html) to users of the extension? | Docstrings for **types** can be included as the [`tp_doc`](http://docs.python.org/c-api/typeobj.html#c.PyTypeObject.tp_doc) member in the `PyTypeObject` structure, see [an example in the docs](http://docs.python.org/extending/newtypes.html#the-basics).
Docstrings for **functions** can be included in the [`ml_doc`](htt... |
How do I add a header to urllib2 opener? | 6,259,489 | 28 | 2011-06-07T00:20:58Z | 6,259,541 | 16 | 2011-06-07T00:30:40Z | [
"python",
"http",
"header",
"urllib2"
] | ```
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.open('http://abc.com')
opener.open('http://google.com')
```
As you can see, I use opener to visit different websites, using a cookie jar. Can I set a header so that each time a website is it, the header is applied? | ```
headers = {'foo': 'bar',}
req = urllib2.Request(url, None, headers)
resp = urllib2.urlopen(req)
```
or
```
req = urllib2.Request(url)
req.add_header('foo', 'bar')
resp = urllib2.urlopen(req)
``` |
How do I add a header to urllib2 opener? | 6,259,489 | 28 | 2011-06-07T00:20:58Z | 6,259,602 | 50 | 2011-06-07T00:43:40Z | [
"python",
"http",
"header",
"urllib2"
] | ```
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.open('http://abc.com')
opener.open('http://google.com')
```
As you can see, I use opener to visit different websites, using a cookie jar. Can I set a header so that each time a website is it, the header is applied? | You can add the headers directly to the `OpenerDirector` object returned by `build_opener`. From the last example in the [urllib2 docs](http://docs.python.org/release/2.6/library/urllib2.html#examples):
> OpenerDirector automatically adds a User-Agent header to every Request. To change this:
```
import urllib2
opener... |
How to display the current year in a Django template? | 6,259,775 | 96 | 2011-06-07T01:23:45Z | 6,259,781 | 9 | 2011-06-07T01:25:10Z | [
"python",
"django"
] | What is the inbuilt template tag to display the present year dynamically. Like "2011" what would be the template tag to display that? | [`{% now %}`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#now) |
How to display the current year in a Django template? | 6,259,775 | 96 | 2011-06-07T01:23:45Z | 6,259,981 | 185 | 2011-06-07T02:10:49Z | [
"python",
"django"
] | What is the inbuilt template tag to display the present year dynamically. Like "2011" what would be the template tag to display that? | The full tag to print just the current year is `{% now "Y" %}`. Note that the Y must be in quotes. |
How to display the current year in a Django template? | 6,259,775 | 96 | 2011-06-07T01:23:45Z | 6,602,387 | 18 | 2011-07-06T20:15:36Z | [
"python",
"django"
] | What is the inbuilt template tag to display the present year dynamically. Like "2011" what would be the template tag to display that? | `{% now 'Y' %}` is the correct syntax |
In matplotlib, how do you draw R-style axis ticks that point outward from the axes? | 6,260,055 | 15 | 2011-06-07T02:22:38Z | 9,863,901 | 25 | 2012-03-25T20:46:44Z | [
"python",
"matplotlib",
"plot"
] | Because they are drawn inside the plot area, axis ticks are obscured by the data in many matplotlib plots. A better approach is to draw the ticks extending from the axes *outward*, as is the default in `ggplot`, R's plotting system.
In theory, this can be done by redrawing the tick lines with the `TICKDOWN` and `TICKL... | In your matplotlib config file, matplotlibrc, you can set:
```
xtick.direction : out # direction: in or out
ytick.direction : out # direction: in or out
```
and this will draw both the major and minor ticks *outward* by default, like R. For a single program, simply do:
```
>> from matplotlib import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.