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 |
|---|---|---|---|---|---|---|---|---|---|
How to make my Python unit tests to import the tested modules if they are in sister folders? | 2,262,546 | 10 | 2010-02-14T20:03:15Z | 2,262,586 | 7 | 2010-02-14T20:12:52Z | [
"python",
"import",
"folders",
"code-organization",
"pyunit"
] | I am still getting my head around the `import` statement. If I have 2 folders in the same level:
1. src
2. test
How to make the `py` files in `test` import the modules in `src`?
Is there a better solution (like put a folder inside another?) | The code you want is for using src/module\_name.py
```
from src import module_name
```
and the root directory is on your PYTHONPATH e.g. you run from the root directory
Your directory structure is what I use but woth the model name instead from src. I got this structure from [J Calderone's blog](http://jcalderone.li... |
How to get unit test coverage results in Eclipse + Pydev? | 2,262,777 | 13 | 2010-02-14T21:07:28Z | 2,262,839 | 13 | 2010-02-14T21:24:19Z | [
"python",
"eclipse",
"code-coverage",
"pydev"
] | I know Eclipse + PyDev has an option `Run As` => `3 Python Coverage`. But all it reports is:
> Ran 6 tests in 0.001s
>
> OK
And it says nothing about code coverage. How to get a code coverage report in Pydev? | * Run a file with "Python Coverage"
* Window > Show View > Code Coverage Results View
* Select the directory in which the executed file is
* Double-click on the executed file in the file list
* Statistics are now at the right, not executed lines are marked red in the code view
Actually this is a really nice feature, d... |
How to get unit test coverage results in Eclipse + Pydev? | 2,262,777 | 13 | 2010-02-14T21:07:28Z | 5,648,086 | 7 | 2011-04-13T11:01:40Z | [
"python",
"eclipse",
"code-coverage",
"pydev"
] | I know Eclipse + PyDev has an option `Run As` => `3 Python Coverage`. But all it reports is:
> Ran 6 tests in 0.001s
>
> OK
And it says nothing about code coverage. How to get a code coverage report in Pydev? | Note that in pydev 2.0, the coverage support changed, now, you should first open the coverage view and select the 'enable code coverage for new launches'... after that, any launch you do (regular or unit-test) will have coverage information being gathered (and the results inspection also became a bit more intuitive). |
Generating & Merging PDF Files in Python | 2,263,263 | 4 | 2010-02-14T23:19:38Z | 2,263,405 | 8 | 2010-02-15T00:11:23Z | [
"python",
"pdf",
"merge",
"reportlab",
"pypdf"
] | I want to automatically generate booking confirmation PDF files in Python. Most of the content will be static (i.e. logos, booking terms, phone numbers), with a few dynamic bits (dates, costs, etc).
From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then usin... | > From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?
Unfortunately no. There are several tools that are good at producing PDFs from scratch (most commonly for Python, [ReportLab](http:... |
Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files? | 2,263,356 | 14 | 2010-02-14T23:48:52Z | 2,263,382 | 10 | 2010-02-14T23:58:29Z | [
"python"
] | A while ago I had to upgrade some servers from Python 2.4 to Python 2.5. I found that .pyc files created under Python 2.4 would crash when Python 2.5 tried to run them.
Will this happen again when I upgrade from 2.5 to 2.6?
EDIT: Here is a bit more detail
I have a fileserver that contains the python code. This is ac... | In general, `.pyc` files are specific to one Python version (although portable across different machine architectures, as long as they're running the same version); the files carry the information about the relevant Python version in their headers -- so, if you leave the corresponding `.py` files next to the `.pyc` one... |
Reading from Python dict if key might not be present | 2,263,761 | 20 | 2010-02-15T02:31:46Z | 2,263,826 | 53 | 2010-02-15T02:48:20Z | [
"python",
"json"
] | I am very new to Python and parsing data.
I can pull an external JSON feed into a Python dictionary and iterate over the dictionary.
```
for r in results:
print r['key_name']
```
As I walk through the results returned, I am getting an error when a key does not have a value (a value may not always exist for a re... | The preferred way, when applicable:
```
for r in results:
print r.get('key_name')
```
this will simply print `None` if `key_name` is not a key in the dictionary. You can also have a different default value, just pass it as the second argument:
```
for r in results:
print r.get('key_name', 'Missing: key_nam... |
Library to render Directed Graphs (similar to graphviz) on Google App Engine | 2,264,157 | 17 | 2010-02-15T05:23:31Z | 2,295,775 | 16 | 2010-02-19T11:04:14Z | [
"java",
"python",
"google-app-engine",
"graph",
"graphviz"
] | I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text description of a directed graph into an image of the graph.
For example:
Covert t... | [Canviz](http://code.google.com/p/canviz/) is what you are looking for: it is a JavaScript library for drawing Graphviz graphs to a web browser canvas. It works with [most browsers](http://code.google.com/p/canviz/wiki/Browsers).
> Using Canviz has advantages for your web application over generating and sending bitmap... |
Library to render Directed Graphs (similar to graphviz) on Google App Engine | 2,264,157 | 17 | 2010-02-15T05:23:31Z | 3,168,462 | 12 | 2010-07-02T19:06:48Z | [
"java",
"python",
"google-app-engine",
"graph",
"graphviz"
] | I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text description of a directed graph into an image of the graph.
For example:
Covert t... | Google Charts API [now supports GraphViz experimentally](http://code.google.com/apis/chart/docs/gallery/graphviz.html). (Note that the entire Image Charts project is officially deprecated.) |
Python: Draw a 2d grid and allow coloring of cells | 2,264,631 | 5 | 2010-02-15T08:06:25Z | 2,264,666 | 8 | 2010-02-15T08:13:06Z | [
"python"
] | I want to simulate the game of life problem using python. I want to draw a grid and be able to color its cells as the simulation progresses. How do I do that in Python? | You can use [pygame](http://www.pygame.org/) to do that.
To display the state of your simulation, you should create an 8 bit surface with a palette, and access it with the [pygame.surfarray](http://www.pygame.org/docs/ref/surfarray.html) module. |
Embed Google Docs PDF viewer in IFRAME | 2,264,684 | 4 | 2010-02-15T08:18:32Z | 2,311,327 | 7 | 2010-02-22T14:05:42Z | [
"python",
"gdata-api",
"google-docs"
] | When I upload PDF to Google Docs (using Python's gdata library), I get link to the document:
```
>>> e.GetAlternateLink().href
Out[14]: 'http://docs.google.com/a/my.dom.ain/fileview id=<veery-long-doc-id>&hl=en'
```
Unfortunately using that link in IFRAME is not working for me because PDF viewer is redirecting to its... | Just for the record - I haven't found any way to force "internal" google google pdf viewer to not go out of the iframe. And as I mentioned in the question, I found this nice standalone viewer: <http://googlesystem.blogspot.com/2009/09/embeddable-google-document-viewer.html>, that can be used like this:
```
<iframe s... |
What statically typed languages are similar to Python? | 2,264,889 | 36 | 2010-02-15T09:17:44Z | 2,264,900 | 34 | 2010-02-15T09:20:09Z | [
"python",
"programming-languages"
] | Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typ... | [Boo](https://github.com/bamboo/boo/wiki) is a statically typed language for the Common Language Infrastructure (aka. the Microsoft .NET platform). The syntax is *highly* inspired by Python, and hashes/lists/array are part of the syntax:
```
i = 5
if i > 5:
print "i is greater than 5."
else:
print "i is less t... |
What statically typed languages are similar to Python? | 2,264,889 | 36 | 2010-02-15T09:17:44Z | 2,264,904 | 7 | 2010-02-15T09:20:57Z | [
"python",
"programming-languages"
] | Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typ... | It may not match all your needs, but have a look at [Boo - The wristfriendly language for the CLI](http://boo.codehaus.org/)
If you do, I highly recommend [DSLs in Boo: Domain-Specific Languages in .NET](http://www.manning.com/rahien/) which apart from the DSL aspects, covers Boo syntax in a very nice appendix and a l... |
What statically typed languages are similar to Python? | 2,264,889 | 36 | 2010-02-15T09:17:44Z | 2,266,037 | 12 | 2010-02-15T12:59:54Z | [
"python",
"programming-languages"
] | Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typ... | [Cobra](http://cobra-language.com/) is a statically typed language for the CLR (as Boo). From its web page:
> Cobra is a general purpose programming
> language with:
>
> ```
> - a clean, high-level syntax
> - static and dynamic binding
> - first class support for unit tests and contracts
> - compiled performance w... |
What statically typed languages are similar to Python? | 2,264,889 | 36 | 2010-02-15T09:17:44Z | 2,269,515 | 8 | 2010-02-15T22:53:28Z | [
"python",
"programming-languages"
] | Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typ... | Although it is not object-oriented, [**Haskell**](http://www.haskell.org/) offers a significant number of the features that interest you:
* Syntax support for list comprehensions, plus `do` notation for a wide variety of sequencing/binding constructs. (Syntax support for dictionaries is limited to lists of pairs, e.g,... |
What statically typed languages are similar to Python? | 2,264,889 | 36 | 2010-02-15T09:17:44Z | 2,269,524 | 7 | 2010-02-15T22:56:05Z | [
"python",
"programming-languages"
] | Python is the nicest language I currently know of, but static typing is a big advantage due to auto-completion (although there is limited support for dynamic languages, it is nothing compared to that supported in static). I'm curious if there are any languages which try to add the benefits of Python to a statically typ... | try the Go programming language ? I've seen some similar paradigm. |
How to read from stdin or from a file if no data is piped in Python? | 2,264,991 | 16 | 2010-02-15T09:42:17Z | 2,265,114 | 7 | 2010-02-15T10:00:54Z | [
"python",
"pipe",
"stdin",
"command-line-interface"
] | I have a CLI script and want it to read data from a file. It should be able to read it in two ways :
* `cat data.txt | ./my_script.py`
* `./my_script.py data.txt`
âa bit like `grep`, for example.
What I know:
* `sys.argv` and `optparse` let me read any args and options easily.
* `sys.stdin` let me read data piped... | For unix/linux you can detect whether data is being piped in by looking at `os.isatty(0)`
```
$ date | python -c "import os;print os.isatty(0)"
False
$ python -c "import os;print os.isatty(0)"
True
```
I'm not sure there is an equivalent for Windows.
**edit**
Ok, I tried it with python2.6 on windows XP
```
C:\Pytho... |
How to read from stdin or from a file if no data is piped in Python? | 2,264,991 | 16 | 2010-02-15T09:42:17Z | 2,265,246 | 16 | 2010-02-15T10:26:15Z | [
"python",
"pipe",
"stdin",
"command-line-interface"
] | I have a CLI script and want it to read data from a file. It should be able to read it in two ways :
* `cat data.txt | ./my_script.py`
* `./my_script.py data.txt`
âa bit like `grep`, for example.
What I know:
* `sys.argv` and `optparse` let me read any args and options easily.
* `sys.stdin` let me read data piped... | [Argparse](http://code.google.com/p/argparse/) allows this to be done in a fairly easy manner, and you really should be using it instead of `optparse` unless you have compatibility issues.
The code would go something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input', type... |
How to read from stdin or from a file if no data is piped in Python? | 2,264,991 | 16 | 2010-02-15T09:42:17Z | 2,265,277 | 10 | 2010-02-15T10:32:30Z | [
"python",
"pipe",
"stdin",
"command-line-interface"
] | I have a CLI script and want it to read data from a file. It should be able to read it in two ways :
* `cat data.txt | ./my_script.py`
* `./my_script.py data.txt`
âa bit like `grep`, for example.
What I know:
* `sys.argv` and `optparse` let me read any args and options easily.
* `sys.stdin` let me read data piped... | Process your non-filename arguments however you'd like, so you wind up with an array of non-option arguments, then pass that array as the parameter to fileinput.input():
```
import fileinput
for line in fileinput.input(remaining_args):
process(line)
``` |
Python: How to access parent class object through derived class instance? | 2,265,060 | 2 | 2010-02-15T09:52:51Z | 2,265,207 | 14 | 2010-02-15T10:17:47Z | [
"python"
] | I'm sorry for my silly question, but... let's suppose I have these classes:
```
class A():
msg = 'hehehe'
class B(A):
msg = 'hohoho'
class C(B):
pass
```
and an instance of B or C. How do I get the variable 'msg' from the parent's class object through this instance?
I've tried this:
```
foo = B()
print... | You actually want to use
```
class A(object):
...
...
b = B()
bar = super(b.__class__, b)
print bar.msg
```
Base classes must be new-style classes (inherit from `object`) |
How to make an axes occupy multiple subplots with pyplot (Python) | 2,265,319 | 14 | 2010-02-15T10:42:14Z | 2,265,506 | 24 | 2010-02-15T11:18:21Z | [
"python",
"matplotlib"
] | I would like to have three plots in single figure. The figure should have a subplot layout of two by two, where the first plot should occupy the first two subplot cells (i.e. the whole first row of plot cells) and the other plots should be positioned underneath the first one in cells 3 and 4. I know that matlab allows ... | You can simply do:
```
x = numpy.arange(0, 7, 0.01)
subplot(2, 1, 1)
plot(x, sin(x))
subplot(2, 2, 3)
plot(x, cos(x))
subplot(2, 2, 4)
plot(x, sin(x)*cos(x))
```
i.e., the first plot is really a plot in the upper half (the figure is only divided into 2\*1 = 2 cells), and the following two smaller plots are done in... |
How to make an axes occupy multiple subplots with pyplot (Python) | 2,265,319 | 14 | 2010-02-15T10:42:14Z | 16,542,886 | 10 | 2013-05-14T12:15:34Z | [
"python",
"matplotlib"
] | I would like to have three plots in single figure. The figure should have a subplot layout of two by two, where the first plot should occupy the first two subplot cells (i.e. the whole first row of plot cells) and the other plots should be positioned underneath the first one in cells 3 and 4. I know that matlab allows ... | To have multiple subplots with an axis occupy, you can simply do:
```
from matplotlib import pyplot as plt
import numpy as np
b=np.linspace(-np.pi, np.pi, 100)
a1=np.sin(b)
a2=np.cos(b)
a3=a1*a2
plt.subplot(221)
plt.plot(b, a1)
plt.title('sin(x)')
plt.subplot(222)
plt.plot(b, a2)
plt.title('cos(x)')
plt.subplot... |
Parse date string and change format | 2,265,357 | 50 | 2010-02-15T10:49:25Z | 2,265,383 | 61 | 2010-02-15T10:54:34Z | [
"python",
"datetime"
] | I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this? | [`datetime`](http://docs.python.org/library/datetime.html) module could help you with that:
```
datetime.datetime.strptime(date_string, format1).strftime(format2)
``` |
Parse date string and change format | 2,265,357 | 50 | 2010-02-15T10:49:25Z | 2,265,499 | 16 | 2010-02-15T11:16:40Z | [
"python",
"datetime"
] | I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this? | ```
>>> from_date="Mon Feb 15 2010"
>>> import time
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
``` |
Parse date string and change format | 2,265,357 | 50 | 2010-02-15T10:49:25Z | 16,115,575 | 25 | 2013-04-20T01:25:52Z | [
"python",
"datetime"
] | I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this? | You can install the [dateutil](http://labix.org/python-dateutil) library. Its [`parse`](http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c) function can figure out what format a string is in without having to specify the format like you do with `datetime.strptime`.
```
from dateutil.parser ... |
Can we do a smart-copy in Python? | 2,266,234 | 4 | 2010-02-15T13:34:14Z | 2,266,269 | 7 | 2010-02-15T13:41:40Z | [
"python"
] | I'm a python newbie, and I'm writing a script to copy compiled files from one location to another. What I have is quite simple at the moment, something like this:
```
import os
import shutil
shutil.copy2 (src, dst)
#... many more shutil.copy commands
#src is a filename string
#dst is the directory where the file is t... | You could make use of the file modification time, if that's enough for you:
```
# If more than 1 second difference
if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1:
shutil.copy2 (src, dst)
```
Or call a synchronization tool like rsync. |
Django test FileField using test fixtures | 2,266,503 | 19 | 2010-02-15T14:23:06Z | 20,508,664 | 12 | 2013-12-11T01:10:01Z | [
"python",
"django",
"unit-testing",
"django-testing",
"filefield"
] | I'm trying to build tests for some models that have a FileField. The model looks like this:
```
class SolutionFile(models.Model):
'''
A file from a solution.
'''
solution = models.ForeignKey(Solution)
file = models.FileField(upload_to=make_solution_file_path)
```
I have encountered two problems:
... | Django provides a great way to write tests on FileFields without mucking about in the real filesystem - use a SimpleUploadedFile.
```
from django.core.files.uploadedfile import SimpleUploadedFile
my_model.file_field = SimpleUploadedFile('best_file_eva.txt', 'these are the file contents!')
```
It's one of django's ma... |
Paginating the results of a Django forms POST request | 2,266,554 | 15 | 2010-02-15T14:31:25Z | 2,266,950 | 19 | 2010-02-15T15:30:09Z | [
"python",
"django",
"django-forms",
"pagination"
] | I'm using Django Forms to do a filtered/faceted search via POST, and I would like to Django's paginator class to organize the results. How do I preserve the original request when passing the client between the various pages? In other words, it seems that I lose the POST data as soon as I pass the GET request for anothe... | If you want to access the store data in later request, you would have to store it somewhere. Django provides several ways to archive this:
**1) You can use [sessions](http://docs.djangoproject.com/en/dev/topics/http/sessions/) to store the query:** Every visitor who visits your site will get an empty session object an... |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 2,267,162 | 7 | 2010-02-15T16:05:17Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | No need to divert stdout. Here is better way to do it:
```
import logging
class MyLogHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger().addHandler(MyLogHandler())
```
An even simpler way is:
```
logging.getLogger().setLevel(100)
``` |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 2,267,304 | 42 | 2010-02-15T16:25:52Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | You can use:
```
logging.basicConfig(level=your_level)
```
where **your\_level** is one of those:
```
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
```
So, if you set **your\_level** to **logging.CRITICAL*... |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 2,267,567 | 106 | 2010-02-15T17:04:33Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | I found a solution for this:
```
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.
```
This will prevent logging from being send to the upper logger that includes the console logging. |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 3,116,067 | 38 | 2010-06-25T06:42:24Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | I use:
```
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
``` |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 6,459,613 | 24 | 2011-06-23T19:31:31Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | (long dead question, but for future searchers)
Closer to the original poster's code/intent, this works for me under python 2.6
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
lhStdout = logger.handlers[0] # stdout is the only handler initially
# ... here I add my own ... |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 8,495,374 | 18 | 2011-12-13T19:59:21Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | There are some really nice answers here, but apparently the simplest is not taken too much in consideration (only from infinito).
```
root_logger = logging.getLogger()
root_logger.disabled = True
```
This disables the root logger, and thus all the other loggers.
I haven't really tested but it should be also the faste... |
How to I disable and re-enable console logging in Python? | 2,266,646 | 68 | 2010-02-15T14:48:06Z | 20,251,235 | 19 | 2013-11-27T19:19:44Z | [
"python",
"logging",
"console",
"stdout"
] | I am using python [logging](http://docs.python.org/library/logging.html) module and I want to disable the console logging for some time but it doesn't work.
```
#!/usr/bin/python
import logging
logger = logging.getLogger() # this gets the root logger
# ... here I add my own handlers
#logger.removeHandler(s... | Context manager
```
import logging
class DisableLogger():
def __enter__(self):
logging.disable(logging.CRITICAL)
def __exit__(self, a, b, c):
logging.disable(logging.NOTSET)
```
Example of use:
```
with DisableLogger():
do_something()
``` |
How to break the following line of python | 2,266,659 | 2 | 2010-02-15T14:50:05Z | 2,266,687 | 14 | 2010-02-15T14:53:39Z | [
"python",
"pep8"
] | I have come upon a couple of lines of code similar to this one, but I'm unsure how I should break it:
```
blueprint = Blueprint(self.blueprint_map[str(self.ui.blueprint_combo.currentText())], runs=self.ui.runs_spin.text(), me=self.ui.me_spin.text(), pe=self.ui.pe_skill_combo.currentIndex())
```
Thanks in advance | ```
blueprint = Blueprint(
self.blueprint_map[str(self.ui.blueprint_combo.currentText())],
runs=self.ui.runs_spin.text(),
me=self.ui.me_spin.text(),
pe=self.ui.pe_skill_combo.currentIndex(),
)
``` |
Is there a Django ModelField that allows for multiple choices, aside from ManyToMany? | 2,267,332 | 12 | 2010-02-15T16:29:20Z | 2,267,379 | 9 | 2010-02-15T16:34:38Z | [
"python",
"django",
"forms"
] | I'd like the user to be able to make multiple selections via the admin interface, and store the result as a list of comma-separated values. A select-multiple or a list of checkboxes would be great. However, I don't need the items in this list of values to refer to any models in particular... I just want a text list of ... | There is a django snippet which does just this: [multiple choice model field](http://www.djangosnippets.org/snippets/1200/). It says:
> Usually you want to store multiple
> choices as a manytomany link to
> another table. Sometimes however it is
> useful to store them in the model
> itself. This field implements a mod... |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 2,267,404 | 9 | 2010-02-15T16:39:09Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | Python doesn't have a built-in function for printing an integer in an arbitrary base. You'll have to write your own if you want to. |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 2,267,428 | 67 | 2010-02-15T16:41:46Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | ```
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
```
ref:
<http://code.activestate.com/recipes/65212/> |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 2,267,446 | 52 | 2010-02-15T16:44:10Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | If you need compatibility with ancient versions of Python, you can either use [gmpy](https://github.com/aleaxit/gmpy) (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions -- you may need to try older releases since the recent ones have not been tes... |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 2,267,721 | 16 | 2010-02-15T17:28:27Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | Great answers!
I guess the answer to my question was "no" I was not missing some obvious solution.
Here is the function I will use that condenses the good ideas expressed in the answers.
* allow caller-supplied mapping of characters (allows base64 encode)
* checks for negative and zero
* maps complex numbers into tupl... |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 3,647,418 | 41 | 2010-09-05T19:23:40Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | ```
"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144
``` |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 12,590,717 | 8 | 2012-09-25T20:42:40Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | You could use baseconv.py: <https://github.com/semente/python-baseconv>
Sample usage:
```
>>> from baseconv import BaseConverter
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.encode(1234)
'31e'
>>> base20.decode('31e')
'1234'
>>> base20.encode(-1234)
'-31e'
>>> base20.decode('-31e')
'-1234'
>>> base11... |
convert integer to a string in a given numeric base in python | 2,267,362 | 103 | 2010-02-15T16:33:01Z | 28,666,223 | 32 | 2015-02-23T02:48:46Z | [
"python",
"base",
"radix"
] | Python allows easy creation of an integer from a string of a given base via
```
int(str,base).
```
I want to perform the inverse: creation of a string from an integer.
i.e. I want some function int2base(num,base)
such that:
```
int( int2base( X , BASE ) , BASE ) == X
```
*the function name/argument order is unimp... | Surprisingly, people were giving only solutions that convert to small bases (smaller then the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.
So here is a super simple solution:
```
def numberToBase(n, b):
if n == 0:
return ... |
overloading augmented arithmetic assignments in python | 2,267,466 | 6 | 2010-02-15T16:46:30Z | 2,267,486 | 13 | 2010-02-15T16:50:04Z | [
"python",
"operators",
"operator-overloading"
] | I'm new to Python so apologies in advance if this is a stupid question.
For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, \**=, %=) for a class myInt. I checked the Python documentation and this is what I came up with:
```
def __iadd__(self, other):
if isinstance(other, myInt)... | You need to add `return self` to your method. Explanation:
The semantics of `a += b`, when `type(a)` has a special method `__iadd__`, are defined to be:
```
a = a.__iadd__(b)
```
so if `__iadd__` returns something different than `self`, that's what will be bound to name `a` after the operation. By missing a `retur... |
overloading augmented arithmetic assignments in python | 2,267,466 | 6 | 2010-02-15T16:46:30Z | 2,267,669 | 7 | 2010-02-15T17:17:52Z | [
"python",
"operators",
"operator-overloading"
] | I'm new to Python so apologies in advance if this is a stupid question.
For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, \**=, %=) for a class myInt. I checked the Python documentation and this is what I came up with:
```
def __iadd__(self, other):
if isinstance(other, myInt)... | Augmented operators in Python have to return the final value to be assigned to the name they are called on, usually (and in your case) `self`. Like all Python methods, missing a return statement implies returning `None`.
Also,
* Never ever ever raise `Exception`, which is impossible to catch sanely. The code to do so... |
Dynamic class loading in Python 2.6: RuntimeWarning: Parent module 'plugins' not found while handling absolute import | 2,267,984 | 20 | 2010-02-15T18:13:26Z | 2,268,003 | 13 | 2010-02-15T18:16:31Z | [
"python",
"plugins",
"import",
"dynamic-class-loaders"
] | I am working on a plugin system where plugin modules are loaded like this:
```
def load_plugins():
plugins=glob.glob("plugins/*.py")
instances=[]
for p in plugins:
try:
name=p.split("/")[-1]
name=name.split(".py")[0]
log.debug("Possible plugin: %s", name)
f, file, des... | If the plugins directory does not have an `__init__.py`, it isn't a package, so when you create `plugins.whatever`, Python warns you that such a thing shouldn't really exist. (It couldn't be created by "`import plugins.whatever`" no matter what your path is.)
Also,
* Don't split on `/`, which is unportable. Use `os.p... |
Dynamic class loading in Python 2.6: RuntimeWarning: Parent module 'plugins' not found while handling absolute import | 2,267,984 | 20 | 2010-02-15T18:13:26Z | 2,268,226 | 12 | 2010-02-15T18:54:37Z | [
"python",
"plugins",
"import",
"dynamic-class-loaders"
] | I am working on a plugin system where plugin modules are loaded like this:
```
def load_plugins():
plugins=glob.glob("plugins/*.py")
instances=[]
for p in plugins:
try:
name=p.split("/")[-1]
name=name.split(".py")[0]
log.debug("Possible plugin: %s", name)
f, file, des... | If the directory `plugins` were a real package (contained `__init__.py` fine), you could easily use pkgutils to enumerate its plugin files and load them.
```
import pkgutil
# import our package
import plugins
list(pkgutil.iter_modules(plugins.__path__))
```
However, it can work without a plugin package anyway, try th... |
Expire a view-cache in Django? | 2,268,417 | 30 | 2010-02-15T19:33:39Z | 2,363,690 | 35 | 2010-03-02T14:17:47Z | [
"python",
"django",
"caching"
] | The `@cache_page decorator` is awesome. But for my blog I would like to keep a page in cache until someone comments on a post. This sounds like a great idea as people rarely comment so keeping the pages in memcached while nobody comments would be great. I'm thinking that someone must have had this problem before? And t... | Here's a solution I wrote to do just what you're talking about on some of my own projects:
```
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url ... |
Expire a view-cache in Django? | 2,268,417 | 30 | 2010-02-15T19:33:39Z | 5,890,333 | 9 | 2011-05-04T21:55:58Z | [
"python",
"django",
"caching"
] | The `@cache_page decorator` is awesome. But for my blog I would like to keep a page in cache until someone comments on a post. This sounds like a great idea as people rarely comment so keeping the pages in memcached while nobody comments would be great. I'm thinking that someone must have had this problem before? And t... | I wrote [Django-groupcache](http://syfou.bitbucket.org/django-groupcache/) for this kind of situations (you can [download the code here](https://bitbucket.org/syfou/django-groupcache)). In your case, you could write:
```
from groupcache.decorators import cache_tagged_page
@cache_tagged_page("blog", 60 * 15)
def blog(... |
Grab a line's whitespace/indention with Python | 2,268,532 | 8 | 2010-02-15T19:55:59Z | 2,268,559 | 23 | 2010-02-15T20:01:07Z | [
"python",
"whitespace",
"indentation"
] | Basically, if I have a line of text which starts with indention, what's the best way to grab that indention and put it into a variable in Python? For example, if the line is:
```
\t\tthis line has two tabs of indention
```
Then it would return '\t\t'. Or, if the line was:
```
this line has four spaces of indenti... | ```
import re
s = "\t\tthis line has two tabs of indention"
re.match(r"\s*", s).group()
// "\t\t"
s = " this line has four spaces of indention"
re.match(r"\s*", s).group()
// " "
```
And to strip leading spaces, use [lstrip](http://docs.python.org/library/stdtypes.html#str.lstrip).
---
As there are down votes ... |
Grab a line's whitespace/indention with Python | 2,268,532 | 8 | 2010-02-15T19:55:59Z | 2,268,588 | 10 | 2010-02-15T20:06:32Z | [
"python",
"whitespace",
"indentation"
] | Basically, if I have a line of text which starts with indention, what's the best way to grab that indention and put it into a variable in Python? For example, if the line is:
```
\t\tthis line has two tabs of indention
```
Then it would return '\t\t'. Or, if the line was:
```
this line has four spaces of indenti... | A sneaky way: abuse `lstrip`!
```
fullstr = "\t\tthis line has two tabs of indentation"
startwhites = fullstr[:len(fullstr)-len(fullstr.lstrip())]
```
This way you don't have to work through all the details of whitespace!
(Thanks Adam for the correction) |
How to convert an int to a hex string? | 2,269,827 | 83 | 2010-02-16T00:07:53Z | 2,269,836 | 99 | 2010-02-16T00:10:13Z | [
"python",
"string",
"hex",
"int"
] | I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in `65` and get out `'\x41'`, or `255` and get `'\xff'`.
I've tried doing this with the `struct.pack('c',`65`)`, but that chokes on anything above `9` since it wants to take in a single character string. | You are looking for the `chr` function.
You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.
```
>>> chr(0x65) == '\x65'
True
>>> hex(65)
'0x41'
>... |
How to convert an int to a hex string? | 2,269,827 | 83 | 2010-02-16T00:07:53Z | 2,269,841 | 29 | 2010-02-16T00:11:21Z | [
"python",
"string",
"hex",
"int"
] | I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in `65` and get out `'\x41'`, or `255` and get `'\xff'`.
I've tried doing this with the `struct.pack('c',`65`)`, but that chokes on anything above `9` since it wants to take in a single character string. | Try:
```
"0x%x" % 255 # => 0xff
```
or
```
"0x%X" % 255 # => 0xFF
```
Python Documentation says: "keep this under Your pillow: <http://docs.python.org/library/index.html>" |
How to convert an int to a hex string? | 2,269,827 | 83 | 2010-02-16T00:07:53Z | 2,269,848 | 24 | 2010-02-16T00:12:47Z | [
"python",
"string",
"hex",
"int"
] | I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in `65` and get out `'\x41'`, or `255` and get `'\xff'`.
I've tried doing this with the `struct.pack('c',`65`)`, but that chokes on anything above `9` since it wants to take in a single character string. | What about [`hex()`](http://docs.python.org/library/functions.html)?
```
hex(255) # 0xff
```
If you really want to have `\` in front you can do:
```
print '\\' + hex(255)[1:]
``` |
How to convert an int to a hex string? | 2,269,827 | 83 | 2010-02-16T00:07:53Z | 2,269,863 | 61 | 2010-02-16T00:17:09Z | [
"python",
"string",
"hex",
"int"
] | I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in `65` and get out `'\x41'`, or `255` and get `'\xff'`.
I've tried doing this with the `struct.pack('c',`65`)`, but that chokes on anything above `9` since it wants to take in a single character string. | This will convert an integer to a 2 digit hex string with the 0x prefix:
```
strHex = "0x%0.2X" % 255
``` |
How to convert an int to a hex string? | 2,269,827 | 83 | 2010-02-16T00:07:53Z | 7,470,721 | 7 | 2011-09-19T12:11:22Z | [
"python",
"string",
"hex",
"int"
] | I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in `65` and get out `'\x41'`, or `255` and get `'\xff'`.
I've tried doing this with the `struct.pack('c',`65`)`, but that chokes on anything above `9` since it wants to take in a single character string. | If you want to pack a struct with a value <255 (one byte unsigned, uint8\_t) and end up with a string of one character, you're probably looking for the [format B instead of c](http://docs.python.org/library/struct.html#format-characters). C converts a character to a string (not too useful by itself) while B converts an... |
Cannot bind to address after socket program crashes | 2,270,343 | 14 | 2010-02-16T02:47:04Z | 2,270,357 | 22 | 2010-02-16T02:50:51Z | [
"python",
"sockets"
] | If my program crashes before a socket is closed, the next time I run in, I get an error that looks like this;
```
socket.error: [Errno 48] Address already in use
```
Changing the port fixes the problem.
Is there any way to avoid this, and why does this happen (when the program exits, shouldn't the socket be garbage ... | Use `.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)` on your listening socket.
A search for those terms will net you many explanations for why this is necessary. Basically, after your first program closes down, the OS keeps the previous listening socket around in a shutdown state for `TIME_WAIT` time. `SO_REUSEADDR` says th... |
How to customize the auth.User Admin page in Django CRUD? | 2,270,537 | 33 | 2010-02-16T03:59:02Z | 2,270,704 | 63 | 2010-02-16T04:45:58Z | [
"python",
"django",
"django-admin",
"django-users"
] | I just want to add the subscription date in the User list in the Django CRUDÂ Administration site.
How can I do that ?
Thank you for your help | I finally did like this in my admin.py file :
```
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
UserAdmin.list_display = ('email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff')
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
``` |
Image color detection using python | 2,270,874 | 12 | 2010-02-16T05:31:48Z | 2,270,895 | 9 | 2010-02-16T05:37:46Z | [
"python"
] | After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current positi... | [Use a PIL (Python Image Library) histogram.](http://effbot.org/imagingbook/image.htm) Loop over the histogram and take the average of pixel color weighed by the pixel count. |
django calendar free/busy/availabilitty | 2,271,190 | 7 | 2010-02-16T07:17:52Z | 2,271,279 | 12 | 2010-02-16T07:36:58Z | [
"python",
"django",
"calendar"
] | I am trying to implement a calendar system with the ability to schedule other people for appointments. The system has to be able to prevent scheduling a person during another appointment or during their unavailable time.
I have looked at all the existing django calendar projects I have found on the internet and none o... | What about using Django's [range test](http://docs.djangoproject.com/en/dev/ref/models/querysets/#s-range).
For example:
```
appoinment = Appointment()
appointment.start_time = datetime.datetime.now()
# 1 hour appointment
appointment.end_time = appointment.start_time + datetime.timedelta(hours=1)
# more stuff here
ap... |
File deletion using rm command | 2,271,453 | 7 | 2010-02-16T08:27:58Z | 2,271,469 | 15 | 2010-02-16T08:31:35Z | [
"python",
"file",
"delete-file"
] | I want to make sure that I delete required files.
I have code something like
```
dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
```
The `dir` and `file` values are fetched from a database. How can I make sure I never end up running `rm -rf /`?
What things should I check before... | You might consider using [`os.remove()`](http://docs.python.org/library/os.html#files-and-directories) instead since it's a great deal less dangerous than what you're attempting. |
File deletion using rm command | 2,271,453 | 7 | 2010-02-16T08:27:58Z | 2,271,500 | 21 | 2010-02-16T08:37:54Z | [
"python",
"file",
"delete-file"
] | I want to make sure that I delete required files.
I have code something like
```
dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
```
The `dir` and `file` values are fetched from a database. How can I make sure I never end up running `rm -rf /`?
What things should I check before... | Don't use the `-r` switch if you just want to remove a single file. Also, there could be spaces in the file name.
Better use the functions in Python's [`os`](http://docs.python.org/library/os.html) module instead:
```
dirname = "/some/path/"
filename = "somefile.txt"
pathname = os.path.abspath(os.path.join(dirname, f... |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | 28 | 2010-02-16T09:36:50Z | 2,271,806 | 12 | 2010-02-16T09:41:02Z | [
"python",
"postgresql",
"psycopg2"
] | I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and [psycopg2](http://www.devx.com/opensource/Article/29071).
I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geometric `Simplify`.
Th... | Yeah, I would vote for COPY, providing you can write a file to the *server*'s hard drive (not the drive the app is running on) as COPY will only read off the server. |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | 28 | 2010-02-16T09:36:50Z | 2,272,062 | 8 | 2010-02-16T10:18:57Z | [
"python",
"postgresql",
"psycopg2"
] | I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and [psycopg2](http://www.devx.com/opensource/Article/29071).
I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geometric `Simplify`.
Th... | There is a new [psycopg2 manual](http://initd.org/psycopg/docs/) containing examples for all the options.
The [COPY](http://initd.org/psycopg/docs/usage.html#using-copy-to-and-copy-from) option is the most efficient. Then the executemany. Then the execute with pyformat. |
Round to 5 (or other number) in python | 2,272,149 | 75 | 2010-02-16T10:35:04Z | 2,272,174 | 141 | 2010-02-16T10:38:22Z | [
"python",
"rounding"
] | Is there a built-in function that can round like this:
```
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
``` | I don't know of a standard function in Python, but this works for me:
```
def myround(x, base=5):
return int(base * round(float(x)/base))
```
It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (`round(float(x)/5... |
Round to 5 (or other number) in python | 2,272,149 | 75 | 2010-02-16T10:35:04Z | 2,272,219 | 14 | 2010-02-16T10:44:38Z | [
"python",
"rounding"
] | Is there a built-in function that can round like this:
```
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
``` | It's just a matter of scaling
```
>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
``` |
Round to 5 (or other number) in python | 2,272,149 | 75 | 2010-02-16T10:35:04Z | 18,666,678 | 14 | 2013-09-06T21:13:23Z | [
"python",
"rounding"
] | Is there a built-in function that can round like this:
```
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
``` | For rounding to non-integer values, such as 0.05:
```
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
```
I found this useful since I could just do a search and replace in my code to change "round(" to "myround(", without having to change the parameter values. |
Sort a part of a list in place | 2,272,819 | 21 | 2010-02-16T12:29:06Z | 2,273,248 | 29 | 2010-02-16T13:42:31Z | [
"python",
"sorting",
"in-place"
] | Let's say we have a list:
```
a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]
```
Now, a.sort() will sort the list in place. What if we want to sort only *a part* of the list, still in place? In C++ we could write:
```
int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );
```
Is there a... | I'd write it this way:
```
a[i:j] = sorted(a[i:j])
```
It is not in-place sort either, but fast enough for relatively small segments.
Please note, that Python copies only object references, so the speed penalty won't be that huge compared to a real in-place sort as one would expect. |
Sort a part of a list in place | 2,272,819 | 21 | 2010-02-16T12:29:06Z | 2,275,504 | 9 | 2010-02-16T18:59:24Z | [
"python",
"sorting",
"in-place"
] | Let's say we have a list:
```
a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]
```
Now, a.sort() will sort the list in place. What if we want to sort only *a part* of the list, still in place? In C++ we could write:
```
int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );
```
Is there a... | if `a` is a `numpy` array then to sort `[i, j)` range in-place, type:
```
a[i:j].sort()
```
Example:
```
>>> import numpy as np
>>> a = np.array([4, 8, 1, 7, 3, 0, 5, 2, 6, 9])
>>> a[1:4].sort()
>>> a
array([4, 1, 7, 8, 3, 0, 5, 2, 6, 9])
``` |
SQLAlchemy subquery - average of sums | 2,273,127 | 14 | 2010-02-16T13:21:39Z | 2,273,845 | 22 | 2010-02-16T15:14:28Z | [
"python",
"sqlalchemy"
] | is there any way how to write the following SQL statement in SQLAlchemy ORM:
```
SELECT AVG(a1) FROM (SELECT sum(irterm.n) AS a1 FROM irterm GROUP BY irterm.item_id);
```
Thank you | ```
sums = session.query(func.sum(Irterm.n).label('a1')).group_by(Irterm.item_id)
average = session.query(func.avg(sums.subquery().columns.a1)).scalar()
``` |
Pythonic Way to reverse nested dictionaries | 2,273,691 | 7 | 2010-02-16T14:49:12Z | 2,273,738 | 16 | 2010-02-16T14:56:46Z | [
"python",
"list-comprehension"
] | I have a nested dictionary of people and item ratings, with people as the key. people may or may not share items.
Example:
```
{
'Bob' : {'item1':3, 'item2':8, 'item3':6},
'Jim' : {'item1':6, 'item4':7},
'Amy' : {'item1':6,'item2':5,'item3':9,'item4':2}
}
```
I'm looking for the simplest way to flip these relation... | [collections.defaultdict](http://docs.python.org/library/collections.html#defaultdict-objects) makes this pretty simple:
```
from collections import defaultdict
import pprint
data = {
'Bob' : {'item1':3, 'item2':8, 'item3':6},
'Jim' : {'item1':6, 'item4':7},
'Amy' : {'item1':6,'item2':5,'item3':9,'item4':2}
}
fli... |
SocketServer.ThreadingTCPServer - Cannot bind to address after program restart | 2,274,320 | 10 | 2010-02-16T16:15:23Z | 2,274,334 | 10 | 2010-02-16T16:17:02Z | [
"python",
"linux",
"sockets",
"tcpserver"
] | As a follow-up to [cannot-bind-to-address-after-socket-program-crashes](http://stackoverflow.com/questions/2270343/cannot-bind-to-address-after-socket-program-crashes), I was receiving this error after my program was restarted:
> socket.error: [Errno 98] Address already in use
In this particular case, instead of usin... | In this particular case, `.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)` may be called from the TCPServer class when the `allow_reuse_address` option is set. So I was able to solve it as follows:
```
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler, False) # Do not automatically bind
httpd.allow_r... |
SocketServer.ThreadingTCPServer - Cannot bind to address after program restart | 2,274,320 | 10 | 2010-02-16T16:15:23Z | 3,137,792 | 16 | 2010-06-29T04:09:00Z | [
"python",
"linux",
"sockets",
"tcpserver"
] | As a follow-up to [cannot-bind-to-address-after-socket-program-crashes](http://stackoverflow.com/questions/2270343/cannot-bind-to-address-after-socket-program-crashes), I was receiving this error after my program was restarted:
> socket.error: [Errno 98] Address already in use
In this particular case, instead of usin... | The above solution didn't work for me but this one did:
```
SocketServer.ThreadingTCPServer.allow_reuse_address = True
server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
server.serve_forever()
``` |
Reading binary file in python | 2,274,503 | 2 | 2010-02-16T16:36:55Z | 2,274,575 | 7 | 2010-02-16T16:47:58Z | [
"python"
] | I wrote a python script to create a binary file of integers.
```
import struct
pos = [7623, 3015, 3231, 3829]
inh = open('test.bin', 'wb')
for e in pos:
inh.write(struct.pack('i', e))
inh.close()
```
It worked well, then I tried to read the 'test.bin' file using the below code.
```
import struct
inh ... | `for rec in inh:` reads one **line** at a time -- not what you want for a *binary* file. Read 4 bytes at a time (with a `while` loop and `inh.read(4)`) instead (or read everything into memory with a single `.read()` call, then unpack successive 4-byte slices). The second approach is simplest and most practical as long ... |
What's the advantage of queues over pipes when communicating between processes? | 2,275,909 | 9 | 2010-02-16T20:03:18Z | 2,275,936 | 11 | 2010-02-16T20:07:00Z | [
"python",
"linux",
"queue",
"multiprocessing",
"pipe"
] | What would be the advantage(s) (if any) of using 2 **[Queues](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue)** over a **[Pipe](http://docs.python.org/library/multiprocessing.html#multiprocessing.Pipe)** to communicate between processes?
I am planning on using the `multiprocessing` python mo... | The big win is that queues are process- and thread- safe. Pipes are not: if two different processes try to read from or write to the same end of a pipe, bad things happen. Queues are also at a somewhat higher level of abstraction than pipes, which may or may not be an advantage in your specific case. |
How to change wx.Panel background color on MouseOver? | 2,275,917 | 4 | 2010-02-16T20:04:55Z | 2,275,975 | 11 | 2010-02-16T20:12:22Z | [
"python",
"wxpython",
"panel",
"wxwidgets"
] | this code:
```
import wx
app = None
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.SetBackgroundColour((11, 11, 11))
self.name = "plugin"
self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
self.Bind... | The method is named `SetBackgroundColour`, with a u.
Also, you're binding events twice with two different methods. Just use the `self.Bind` style, and remove the other two lines. |
How to get data in a histogram bin | 2,275,924 | 12 | 2010-02-16T20:05:45Z | 2,277,669 | 19 | 2010-02-17T01:12:32Z | [
"python",
"numpy",
"matplotlib",
"histogram"
] | I want to get a list of the data contained in a histogram bin. I am using numpy, and Matplotlib. I know how to traverse the data and check the bin edges. However, I want to do this for a 2D histogram and the code to do this is rather ugly. Does numpy have any constructs to make this easier?
For the 1D case, I can use ... | [`digitize`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html#numpy.digitize), from core NumPy, will give you the *index* of the bin to which each value in your histogram belongs:
```
import numpy as NP
A = NP.random.randint(0, 10, 100)
bins = NP.array([0., 20., 40., 60., 80., 100.])
# d is an... |
Program web applications in python without a framework? | 2,276,000 | 14 | 2010-02-16T20:15:09Z | 2,276,018 | 19 | 2010-02-16T20:17:54Z | [
"python"
] | I am just starting Python and I was wondering how I would go about programming web applications without the need of a framework. I am an experiance PHP developer but I have an urge to try out Python and I usually like to write from scratch without the restriction of a framework. | [WSGI](http://www.wsgi.org/wsgi/) is the Python standard for web server interfaces. If you want to create your own framework or operate without a framework, you should look into that. Specifically I have found [Ian Bicking's DIY Framework](http://pythonpaste.org/do-it-yourself-framework.html) article helpful.
As an as... |
Python multiprocessing process vs. standalone Python VM | 2,276,117 | 9 | 2010-02-16T20:33:23Z | 2,276,366 | 9 | 2010-02-16T21:10:28Z | [
"python",
"multiprocessing",
"virtual-machine"
] | Aside from the ease of use of the `multiprocessing` module when it comes to hooking up processes with communication resources, are there any other differences between spawning multiple processes using `multiprocessing` compared to using `subprocess` to launch separate Python VMs ? | On Posix platforms, `multiprocessing` primitives essentially wrap an `os.fork()`. What this means is that at point you spawn a process in multiprocessing, the code already imported/initialized remains so in the child process.
This can be a boon if you have a lot of things to initialize and then each subprocess essenti... |
Changing default encoding of Python? | 2,276,200 | 77 | 2010-02-16T20:46:28Z | 2,276,251 | 14 | 2010-02-16T20:52:49Z | [
"python",
"encoding",
"utf-8",
"console"
] | I have many "can't encode" and "can't decode" problems with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) when I run my applications from the console. But in the [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29) [PyDev](http://en.wikipedia.org/wiki/PyDev) IDE, the default charact... | Starting with [PyDev](http://en.wikipedia.org/wiki/PyDev) 3.4.1, the default encoding is not being changed anymore.
See [this ticket](https://sw-brainwy.rhcloud.com/tracker/PyDev/315) for details.
For earlier versions a solution is to make sure PyDev does not run with UTF-8 as the default encoding. Under Eclipse, run ... |
Changing default encoding of Python? | 2,276,200 | 77 | 2010-02-16T20:46:28Z | 7,892,892 | 35 | 2011-10-25T16:55:23Z | [
"python",
"encoding",
"utf-8",
"console"
] | I have many "can't encode" and "can't decode" problems with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) when I run my applications from the console. But in the [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29) [PyDev](http://en.wikipedia.org/wiki/PyDev) IDE, the default charact... | **A) To control `sys.getdefaultencoding()` output:**
```
python -c 'import sys; print(sys.getdefaultencoding())'
```
`ascii`
Then
```
echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py
```
and
```
PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'
```
`utf-1... |
Changing default encoding of Python? | 2,276,200 | 77 | 2010-02-16T20:46:28Z | 17,628,350 | 82 | 2013-07-13T08:18:16Z | [
"python",
"encoding",
"utf-8",
"console"
] | I have many "can't encode" and "can't decode" problems with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) when I run my applications from the console. But in the [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29) [PyDev](http://en.wikipedia.org/wiki/PyDev) IDE, the default charact... | Here is a simpler method (hack) that gives you back the `setdefaultencoding()` function that was deleted from `sys`:
```
import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
```
**PS**: This is obviously a hack, since `sys.setdefaultencoding(... |
Changing default encoding of Python? | 2,276,200 | 77 | 2010-02-16T20:46:28Z | 27,066,059 | 18 | 2014-11-21T16:33:51Z | [
"python",
"encoding",
"utf-8",
"console"
] | I have many "can't encode" and "can't decode" problems with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) when I run my applications from the console. But in the [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29) [PyDev](http://en.wikipedia.org/wiki/PyDev) IDE, the default charact... | If you get this error when you try to pipe/redirect output of your script
`UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)`
Just export PYTHONIOENCODING in console and then run your code.
**`export PYTHONIOENCODING=utf8`** |
Extending a list of lists in Python? | 2,276,416 | 8 | 2010-02-16T21:18:16Z | 2,276,443 | 13 | 2010-02-16T21:21:22Z | [
"python",
"list",
"extend"
] | I might be missing something about the intended behavior of list extend, but why does the following happen?
```
x = [[],[]]
y = [[]] * 2
print x # [[],[]]
print y # [[],[]]
print x == y # True
x[0].extend([1])
y[0].extend([1])
print x # [[1],[]], which is what I'd expect
print y # [[1],[1]], wtf?... | In the case of `[something] * 2`, python is simply making a reference-copy. Therefore, if the enclosed type(s) are mutable, changing them will be reflected anywhere the item is referenced.
In your example, `y[0]` and `y[1]` point to the same enclosed list object. You can verify this by doing `y[0] is y[1]` or alternat... |
How do I unit test a module that relies on urllib2? | 2,276,689 | 20 | 2010-02-16T22:02:16Z | 2,276,727 | 8 | 2010-02-16T22:08:52Z | [
"python",
"unit-testing",
"urllib2",
"urllib"
] | I've got a piece of code that I can't figure out how to unit test! The module pulls content from external XML feeds (twitter, flickr, youtube, etc.) with urllib2. Here's some pseudo-code for it:
```
params = (url, urlencode(data),) if data else (url,)
req = Request(*params)
response = urlopen(req)
#check headers, cont... | It would be best if you could write a mock urlopen (and possibly Request) which provides the minimum required interface to behave like urllib2's version. You'd then need to have your function/method which uses it able to accept this mock urlopen somehow, and use `urllib2.urlopen` otherwise.
This is a fair amount of wo... |
How do I unit test a module that relies on urllib2? | 2,276,689 | 20 | 2010-02-16T22:02:16Z | 2,276,884 | 23 | 2010-02-16T22:30:06Z | [
"python",
"unit-testing",
"urllib2",
"urllib"
] | I've got a piece of code that I can't figure out how to unit test! The module pulls content from external XML feeds (twitter, flickr, youtube, etc.) with urllib2. Here's some pseudo-code for it:
```
params = (url, urlencode(data),) if data else (url,)
req = Request(*params)
response = urlopen(req)
#check headers, cont... | urllib2 has a functions called `build_opener()` and `install_opener()` which you should use to mock the behaviour of `urlopen()`
```
import urllib2
from StringIO import StringIO
def mock_response(req):
if req.get_full_url() == "http://example.com":
resp = urllib2.addinfourl(StringIO("mock file"), "mock me... |
Django, query filtering from model method | 2,276,768 | 47 | 2010-02-16T22:14:24Z | 2,276,826 | 19 | 2010-02-16T22:22:03Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-orm"
] | I have these models:
```
def Foo(Models.model):
size = models.IntegerField()
# other fields
def is_active(self):
if check_condition:
return True
else:
return False
def Bar(Models.model):
foo = models.ForeignKey("Foo")
# other fields
```
Now I want ... | You cannot query against model methods or properties. Either use the criteria within it in the query, or filter in Python using a list comprehension or genex. |
Django, query filtering from model method | 2,276,768 | 47 | 2010-02-16T22:14:24Z | 2,276,848 | 9 | 2010-02-16T22:24:29Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-orm"
] | I have these models:
```
def Foo(Models.model):
size = models.IntegerField()
# other fields
def is_active(self):
if check_condition:
return True
else:
return False
def Bar(Models.model):
foo = models.ForeignKey("Foo")
# other fields
```
Now I want ... | You can't filter on methods, however if the is\_active method on Foo checks an attribute on Foo, you can use the double-underscore syntax like `Bar.objects.filter(foo__is_active_attribute=True)` |
Django, query filtering from model method | 2,276,768 | 47 | 2010-02-16T22:14:24Z | 15,224,757 | 8 | 2013-03-05T13:15:20Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-orm"
] | I have these models:
```
def Foo(Models.model):
size = models.IntegerField()
# other fields
def is_active(self):
if check_condition:
return True
else:
return False
def Bar(Models.model):
foo = models.ForeignKey("Foo")
# other fields
```
Now I want ... | I had similar problem: I am using class-based view `object_list` and I had to filter by model's method. (storing the information in database wasn't an option because the property was based on time and I would have to create a cronjob and/or... *no way*)
My answer is ineffective and I don't know how it's gonna scale on... |
Django, query filtering from model method | 2,276,768 | 47 | 2010-02-16T22:14:24Z | 21,363,053 | 17 | 2014-01-26T12:00:32Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-orm"
] | I have these models:
```
def Foo(Models.model):
size = models.IntegerField()
# other fields
def is_active(self):
if check_condition:
return True
else:
return False
def Bar(Models.model):
foo = models.ForeignKey("Foo")
# other fields
```
Now I want ... | You could also use a custom manager. Then you could run something like this:
```
Bar.objects.foo_active()
```
And all you have to do is:
```
class BarManager(models.Manager):
def foo_active(self):
# use your method to filter results
return you_custom_queryset
```
Check out the [docs](https://docs.... |
python: Regex matching file extension | 2,277,030 | 3 | 2010-02-16T22:57:20Z | 2,277,049 | 7 | 2010-02-16T22:59:59Z | [
"python",
"regex"
] | hi i am trying to get the extension of the file called in a url (eg `/wp-includes/js/jquery/jquery.js?ver=1.3.2 HTTP/1.1`) and get the query parameters passed to the file too.
What would be the best way to the extension? | [`urlparse.urlparse()`](http://docs.python.org/library/urlparse.html#urlparse.urlparse) and [`os.path.splitext()`](http://docs.python.org/library/os.path.html#os.path.splitext). |
How do I url unencode in Python? | 2,277,302 | 10 | 2010-02-16T23:50:49Z | 2,277,313 | 9 | 2010-02-16T23:52:56Z | [
"python",
"url",
"encoding"
] | GIven this:
It%27s%20me%21
Unencode it and turn it into regular text? | Take a look at `urllib.unquote` and `urllib.unquote_plus`. That will address your problem. Technically though url "encoding" is the process of passing arguments into a url with the & and ? characters (e.g. `www.foo.com?x=11&y=12`). |
How do I url unencode in Python? | 2,277,302 | 10 | 2010-02-16T23:50:49Z | 2,277,323 | 12 | 2010-02-16T23:55:07Z | [
"python",
"url",
"encoding"
] | GIven this:
It%27s%20me%21
Unencode it and turn it into regular text? | in python2
```
>>> import urlparse
>>> urlparse.unquote('It%27s%20me%21')
"It's me!"
```
In python3
```
>>> import urllib.parse
>>> urllib.parse.unquote('It%27s%20me%21')
"It's me!"
``` |
Python: Split a string at uppercase letters | 2,277,352 | 34 | 2010-02-17T00:01:22Z | 2,277,363 | 50 | 2010-02-17T00:04:44Z | [
"python",
"regex",
"string"
] | What is the pythonic way to split a string before the occurrences of a given set of characters?
For example, I want to split
`'TheLongAndWindingRoad'`
at any occurrence of an uppercase letter (possibly except the first), and obtain
`['The', 'Long', 'And', 'Winding', 'Road']`.
Edit: It should also split single occurre... | Unfortunately it's not possible to [split on a zero-width match](http://bugs.python.org/issue3262) in Python. But you can use `re.findall` instead:
```
>>> import re
>>> re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')
['The', 'Long', 'And', 'Winding', 'Road']
>>> re.findall('[A-Z][^A-Z]*', 'ABC')
['A', 'B', 'C']
`... |
Python: Split a string at uppercase letters | 2,277,352 | 34 | 2010-02-17T00:01:22Z | 2,277,407 | 14 | 2010-02-17T00:14:03Z | [
"python",
"regex",
"string"
] | What is the pythonic way to split a string before the occurrences of a given set of characters?
For example, I want to split
`'TheLongAndWindingRoad'`
at any occurrence of an uppercase letter (possibly except the first), and obtain
`['The', 'Long', 'And', 'Winding', 'Road']`.
Edit: It should also split single occurre... | ```
>>> import re
>>> re.findall('[A-Z][a-z]*', 'TheLongAndWindingRoad')
['The', 'Long', 'And', 'Winding', 'Road']
>>> re.findall('[A-Z][a-z]*', 'SplitAString')
['Split', 'A', 'String']
>>> re.findall('[A-Z][a-z]*', 'ABC')
['A', 'B', 'C']
```
If you want `"It'sATest"` to split to `["It's", 'A', 'Test']` change the r... |
Python: Split a string at uppercase letters | 2,277,352 | 34 | 2010-02-17T00:01:22Z | 2,279,177 | 12 | 2010-02-17T08:19:04Z | [
"python",
"regex",
"string"
] | What is the pythonic way to split a string before the occurrences of a given set of characters?
For example, I want to split
`'TheLongAndWindingRoad'`
at any occurrence of an uppercase letter (possibly except the first), and obtain
`['The', 'Long', 'And', 'Winding', 'Road']`.
Edit: It should also split single occurre... | Here is an alternative regex solution. The problem can be reprased as "how do I insert a space before each uppercase letter, before doing the split":
```
>>> s = "TheLongAndWindingRoad ABC A123B45"
>>> re.sub( r"([A-Z])", r" \1", s).split()
['The', 'Long', 'And', 'Winding', 'Road', 'A', 'B', 'C', 'A123', 'B45']
```
T... |
Count number of records by date in Django | 2,278,076 | 33 | 2010-02-17T03:16:54Z | 2,283,388 | 10 | 2010-02-17T18:32:57Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-1.1"
] | I have a model similar to the following:
```
class Review(models.Model):
venue = models.ForeignKey(Venue, db_index=True)
review = models.TextField()
datetime_created = models.DateTimeField(default=datetime.now)
```
I'd like to query the database to get the total number of reviews for a venue grouped by ... | If you were storing a date field, you could use this:
```
from django.db.models import Count
Review.objects.filter(venue__pk = 2)
.values('date').annotate(event_count = Count('id'))
```
Because you're storing datetime, it's a little more complicated, but this should offer a good starting point. Check out the agg... |
Count number of records by date in Django | 2,278,076 | 33 | 2010-02-17T03:16:54Z | 2,283,913 | 71 | 2010-02-17T19:51:30Z | [
"python",
"django",
"django-models",
"django-queryset",
"django-1.1"
] | I have a model similar to the following:
```
class Review(models.Model):
venue = models.ForeignKey(Venue, db_index=True)
review = models.TextField()
datetime_created = models.DateTimeField(default=datetime.now)
```
I'd like to query the database to get the total number of reviews for a venue grouped by ... | This should work (using the same MySQL specific function you used):
```
Review.objects.filter(venue__pk=2)
.extra({'date_created' : "date(datetime_created)"})
.values('date_created')
.annotate(created_count=Count('id'))
``` |
OpenCV Image Processing -- C++ vs C vs Python | 2,278,228 | 20 | 2010-02-17T04:04:40Z | 2,278,331 | 10 | 2010-02-17T04:35:31Z | [
"c++",
"python",
"c",
"opencv"
] | I was thinking of trying OpenCV for a project and noticed that it had C, C++ and Python.
I am trying to figure out whether I should use C++, C or Python -- and would like to use whatever has the best OpenCV support.
Just from looking at the index page for the various documentation it looks like the C++ bindings might... | The Python interface is still being developed whereas the C++ interface (especially with the new `Mat` class) is quite mature. If you're comfortable in C++, I would highly recommend using it - else, you can start using Python and contribute back any features you think OpenCV needs :) |
OpenCV Image Processing -- C++ vs C vs Python | 2,278,228 | 20 | 2010-02-17T04:04:40Z | 5,362,904 | 13 | 2011-03-19T15:06:58Z | [
"c++",
"python",
"c",
"opencv"
] | I was thinking of trying OpenCV for a project and noticed that it had C, C++ and Python.
I am trying to figure out whether I should use C++, C or Python -- and would like to use whatever has the best OpenCV support.
Just from looking at the index page for the various documentation it looks like the C++ bindings might... | Actually Python binding was finished [starting with release 2.2](http://opencv.willowgarage.com/wiki/PythonInterface). So i would go with python if i were you, because the performance will be almost the same anyway as you are using c libraries in both cases. However python will get you there faster, safely and you will... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.