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 |
|---|---|---|---|---|---|---|---|---|---|
Difference between yield in Python and yield in C# | 1,704,607 | 20 | 2009-11-09T23:13:41Z | 1,704,637 | 24 | 2009-11-09T23:19:24Z | [
"c#",
"python"
] | What is the difference between `yield` keyword in Python and `yield` keyword in C#? | C#'s `yield return` is equivalent to Python's `yield` , and `yield break` is just `return` in Python.
Other than those minor differences, they have basically the same purpose. |
Difference between yield in Python and yield in C# | 1,704,607 | 20 | 2009-11-09T23:13:41Z | 1,704,639 | 12 | 2009-11-09T23:19:52Z | [
"c#",
"python"
] | What is the difference between `yield` keyword in Python and `yield` keyword in C#? | This may help you understand it : [Iterators in C#, Python, and Ruby](http://mg.to/2004/08/03/iterator-cpr) |
The easiest DHT to implement | 1,704,646 | 14 | 2009-11-09T23:20:59Z | 1,704,695 | 7 | 2009-11-09T23:37:05Z | [
"python",
"p2p",
"dht"
] | Which Distributed Hash Table (DHT) is easiest to implement in Python? Any good example that is not bloated?
I not am looking for a definition of DHT because I am more oriented and focused on design and implementation of such. | If you are focused on implementation, rather than looking for an out-of-the-box solution, this article might help a bit: <http://www.linuxjournal.com/article/6797> |
The easiest DHT to implement | 1,704,646 | 14 | 2009-11-09T23:20:59Z | 1,705,028 | 10 | 2009-11-10T01:02:29Z | [
"python",
"p2p",
"dht"
] | Which Distributed Hash Table (DHT) is easiest to implement in Python? Any good example that is not bloated?
I not am looking for a definition of DHT because I am more oriented and focused on design and implementation of such. | In my job I'm working with [entagled](http://pypi.python.org/pypi/entangled/0.1). I can't say it's great code, but it seems to be the only [Kademlia](http://en.wikipedia.org/wiki/Kademlia) implementation for Python around.
I think Kademlia has become the default DHT for most applications today, because it's quite simp... |
Convert gzipped data fetched by urllib2 to HTML | 1,704,754 | 5 | 2009-11-09T23:55:18Z | 1,704,786 | 13 | 2009-11-10T00:02:27Z | [
"python",
"gzip",
"urllib2"
] | I currently use mechanize to read gzipped web page as below:
```
br = mechanize.Browser()
br.set_handle_gzip(True)
response = br.open(url)
data = response.read()
```
I wonder how to decompress gzipped data fetched by urllib2 to HTML text?
```
req = urllib2.Request(url)
opener = urllib2.build_opener()
response = open... | Try this:
```
import StringIO
data = StringIO.StringIO(data)
import gzip
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
```
`html` should now hold the HTML (*Print it to see*). See [here](http://docs.activestate.com/activepython/2.6/diveintopython/html/http%5Fweb%5Fservices/gzip%5Fcompression.html) for m... |
Find images with similar color palette with Python | 1,704,793 | 5 | 2009-11-10T00:03:40Z | 1,704,811 | 10 | 2009-11-10T00:07:39Z | [
"python",
"image",
"colors"
] | Suppose there are 10,000 JPEG, PNG images in a gallery, how to find all images with similar color palettes to a selected image sorted by descending similarity? | Build a color histogram for each image. Then when you want to match an image to the collection, simply order the list by how close their histogram is to your selected image's histogram.
The number of buckets will depend on how accurate you want to be. The type of data combined to make a bucket will define how you prio... |
Initializing numpy matrix to something other than zero or one | 1,704,823 | 61 | 2009-11-10T00:10:07Z | 1,704,848 | 20 | 2009-11-10T00:16:58Z | [
"python",
"numpy"
] | I have the following code:
```
r = numpy.zeros(shape = (width, height, 9))
```
It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaN.
Is there any? Without having to resort to manually doing loops and such?
Thanks | Are you familiar with `numpy.nan`?
You can create your own method such as:
```
def nans(shape, dtype=float):
a = numpy.empty(shape, dtype)
a.fill(numpy.nan)
return a
```
Then
```
nans([3,4])
```
would output
```
array([[ NaN, NaN, NaN, NaN],
[ NaN, NaN, NaN, NaN],
[ NaN, NaN, NaN... |
Initializing numpy matrix to something other than zero or one | 1,704,823 | 61 | 2009-11-10T00:10:07Z | 1,704,853 | 87 | 2009-11-10T00:17:49Z | [
"python",
"numpy"
] | I have the following code:
```
r = numpy.zeros(shape = (width, height, 9))
```
It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaN.
Is there any? Without having to resort to manually doing loops and such?
Thanks | You rarely need loops for vector operations in numpy.
You can create an uninitialized array and assign to all entries at once:
```
>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.NAN
>>> a
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
```
---
I have timed the alternatives `a[:] = num... |
Initializing numpy matrix to something other than zero or one | 1,704,823 | 61 | 2009-11-10T00:10:07Z | 26,289,777 | 28 | 2014-10-09T23:50:13Z | [
"python",
"numpy"
] | I have the following code:
```
r = numpy.zeros(shape = (width, height, 9))
```
It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaN.
Is there any? Without having to resort to manually doing loops and such?
Thanks | Another option is to use `np.full`, an option available in numpy 1.8+
> > a = np.full([width, height, 9],np.nan)
This is pretty flexible and you can fill it with any other number that you want. |
Python library for Linux process management | 1,705,077 | 12 | 2009-11-10T01:14:23Z | 4,229,517 | 12 | 2010-11-19T21:26:36Z | [
"python",
"linux",
"process"
] | Through my web interface I would like to start/stop certain processes and determine whether a started process is still running.
My existing website is Python based and running on a Linux server, so do you know of a suitable library that supports this functionality?
Thanks | To start/stop python sub processes you can use the subprocess module.
To check whether they are running you might use [psutil](http://code.google.com/p/psutil/):
```
>>> import psutil
>>> pid = 1034 # some pid
>>> psutil.pid_exists(pid)
True
>>>
```
...or this (it will also check if the PID has been reused):
```
>>... |
Python Form Processing alternatives | 1,705,217 | 3 | 2009-11-10T02:02:14Z | 1,705,237 | 13 | 2009-11-10T02:09:34Z | [
"python",
"google-app-engine",
"forms"
] | `django.forms` is very nice, and does almost exactly what I want to do on my current project, but unfortunately, Google App Engine makes most of the rest of Django unusable, and so packing it along with the app seems kind of silly.
I've also discovered FormAlchemy, which is an SQLAlchemy analog to Django forms, and I ... | I've grown to love [WTForms](http://wtforms.simplecodes.com/), it's simple, straightforward, and very flexible. It's part of my django-free web stack.
It's completely standalone, and carries over the good parts of django's form libraries, while imho having some things much better. |
Problem with making object callable in python | 1,705,928 | 14 | 2009-11-10T06:06:35Z | 1,705,948 | 11 | 2009-11-10T06:12:50Z | [
"python"
] | I wrote code like this
```
>>> class a(object):
def __init__(self):
self.__call__ = lambda x:x
>>> b = a()
```
I expected that object of class a should be callable object but eventually it is not.
```
>>> b()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
b()
TypeError: '... | `__call__` needs to be defined on the class, not the instance
```
class a(object):
def __init__(self):
pass
__call__ = lambda x:x
```
but most people probably find it more readable to define the method the usual way
```
class a(object):
def __init__(self):
pass
def __call__(self):
... |
Problem with making object callable in python | 1,705,928 | 14 | 2009-11-10T06:06:35Z | 1,705,954 | 15 | 2009-11-10T06:15:20Z | [
"python"
] | I wrote code like this
```
>>> class a(object):
def __init__(self):
self.__call__ = lambda x:x
>>> b = a()
```
I expected that object of class a should be callable object but eventually it is not.
```
>>> b()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
b()
TypeError: '... | Special methods are looked up on the *type* (e.g., class) of the object being operated on, not on the specific instance. Think about it: otherwise, if a class defines `__call__` for example, when the class is called that `__call__` should get called... what a disaster! But fortunately the special method is instead look... |
Python: How to ignore #comment lines when reading in a file | 1,706,198 | 26 | 2009-11-10T07:36:44Z | 1,706,204 | 39 | 2009-11-10T07:38:47Z | [
"python",
"string",
"file-io",
"comments",
"skip"
] | In Python, I have just read a line form a text file and I'd like to know how to code to ignore comments with a hash # at the beginning of the line.
I think it should be something like this:
```
for
if line !contain #
then ...process line
else end for loop
```
But I'm new to Python and I don't know the s... | you can use [startswith()](http://docs.python.org/library/stdtypes.html#str.startswith)
eg
```
for line in open("file"):
li=line.strip()
if not li.startswith("#"):
print line.rstrip()
``` |
Python: How to ignore #comment lines when reading in a file | 1,706,198 | 26 | 2009-11-10T07:36:44Z | 1,706,334 | 26 | 2009-11-10T08:13:19Z | [
"python",
"string",
"file-io",
"comments",
"skip"
] | In Python, I have just read a line form a text file and I'd like to know how to code to ignore comments with a hash # at the beginning of the line.
I think it should be something like this:
```
for
if line !contain #
then ...process line
else end for loop
```
But I'm new to Python and I don't know the s... | I recommend you don't ignore the whole line when you see a `#` character; just ignore the rest of the line. You can do that easily with a string method function called `partition`:
```
with open("filename") as f:
for line in f:
line = line.partition('#')[0]
line = line.rstrip()
# ... do som... |
Understanding Zope internals, from Django eyes | 1,706,309 | 7 | 2009-11-10T08:05:26Z | 1,707,894 | 15 | 2009-11-10T13:15:42Z | [
"python",
"django",
"zope",
"zodb",
"acquisition"
] | I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
1. What is the "real" purpose of zodb as such? I know what it does, but tell me one g... | First things first: current zope2 versions include all of zope3, too. And if you look at modern zope2 applications like Plone, you'll see that it uses a lot of "zope 3" (now called the "zope tool kit", ZTK) under the hood.
The real purpose of the ZODB: it is one of the few object databases (as opposed to relational SQ... |
Understanding Zope internals, from Django eyes | 1,706,309 | 7 | 2009-11-10T08:05:26Z | 1,733,045 | 9 | 2009-11-14T02:39:54Z | [
"python",
"django",
"zope",
"zodb",
"acquisition"
] | I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
1. What is the "real" purpose of zodb as such? I know what it does, but tell me one g... | On the ZODB:
Another way to ask "What is the real purpose of the ZODB?" is to ask, "Why was the ZODB originally created?"
The answer to that is the project was started very early on, around 1996. This was before the existance of MySQL or PostgreSQL, when miniSQL (a free-to-use but not free software) database was stil... |
Uploading multiple files in Django through one form field | 1,706,880 | 7 | 2009-11-10T10:11:13Z | 10,983,127 | 9 | 2012-06-11T15:27:59Z | [
"python",
"django",
"forms",
"upload"
] | Is there any custom widget (or a special magic way) to upload multiple files (or a whole folder!) through one form field?
I have tried [this multifile widget](http://scompt.com/blog/archives/2007/11/03/multiple-file-uploads-in-django) but it uses many simple FileFileds. | HTML 5 now allows for multiple file uploads in a single form control.
<http://www.w3.org/TR/html-markup/input.file.html#input.file.attrs.multiple> |
How to get interactive input from user and to be able to use arrowkeys while entering input? | 1,706,945 | 5 | 2009-11-10T10:24:19Z | 11,110,661 | 8 | 2012-06-19T22:57:55Z | [
"python"
] | When I do a raw\_input() and enter values, I am not able to use my arrow-keys to change stuff... is there any way for doing that?
Thanx readline module helps in line editing features. How to use the readline module?
Just importing the readline module works! | Try loading the readline module (import readline). That will make things work for you. |
How to disable the OptionParser default help view? | 1,707,380 | 2 | 2009-11-10T11:44:47Z | 1,707,433 | 7 | 2009-11-10T11:54:25Z | [
"python"
] | I am using the OptionParser from optparse module to parse my command that I get using the raw\_input(). When I give a -h it displays the help screen and exits my application. I dont want it to display the help screen or exit the application. How can this be accomplished?
Thanx in advance. | set [`add_help_option`](http://docs.python.org/library/optparse.html#creating-the-parser) to False
```
parser = optparse.OptionParser(add_help_option=False)
parser.add_option('-h', '--help', help='show this help message')
options, args = parser.parse_args()
if options.help:
parser.print_help()
```
> `add_help_opti... |
How to disable the OptionParser default help view? | 1,707,380 | 2 | 2009-11-10T11:44:47Z | 1,707,437 | 8 | 2009-11-10T11:54:49Z | [
"python"
] | I am using the OptionParser from optparse module to parse my command that I get using the raw\_input(). When I give a -h it displays the help screen and exits my application. I dont want it to display the help screen or exit the application. How can this be accomplished?
Thanx in advance. | optparse has a strange penchange for exiting your program, which I think is really unfortunate. You can initialize it like this to prevent it:
```
oparser = OptionParser(add_help_option=False, ...)
```
Note that now you have to handle the `-h` and `--help` options yourself. You can print the help message formatted by... |
Can Python remove double quotes from a string, when reading in text file? | 1,707,558 | 18 | 2009-11-10T12:20:44Z | 1,707,581 | 23 | 2009-11-10T12:23:54Z | [
"python",
"csv",
"strip"
] | I have some text file like this, with several 5000 lines:
```
5.6 4.5 6.8 "6.5" (new line)
5.4 8.3 1.2 "9.3" (new line)
```
so the last term is a number between double quotes.
What I want to do is, using Python (if possible), to assign the four columns to double variables. But the main problem is the last term... | ```
for line in open(name, "r"):
line = line.replace('"', '').strip()
a, b, c, d = map(float, line.split())
```
This is kind of bare-bones, and will raise exceptions if (for example) there aren't four values on the line, etc. |
Can Python remove double quotes from a string, when reading in text file? | 1,707,558 | 18 | 2009-11-10T12:20:44Z | 1,707,586 | 9 | 2009-11-10T12:24:25Z | [
"python",
"csv",
"strip"
] | I have some text file like this, with several 5000 lines:
```
5.6 4.5 6.8 "6.5" (new line)
5.4 8.3 1.2 "9.3" (new line)
```
so the last term is a number between double quotes.
What I want to do is, using Python (if possible), to assign the four columns to double variables. But the main problem is the last term... | ```
for line in open(fname):
line = line.split()
line[-1] = line[-1].strip('"\n')
floats = [float(i) for i in line]
```
another option is to use built-in module, that is **intended** for this task. namely [`csv`](http://docs.python.org/library/csv.html):
```
>>> import csv
>>> for line in csv.reader(open(... |
Can Python remove double quotes from a string, when reading in text file? | 1,707,558 | 18 | 2009-11-10T12:20:44Z | 1,707,624 | 13 | 2009-11-10T12:31:50Z | [
"python",
"csv",
"strip"
] | I have some text file like this, with several 5000 lines:
```
5.6 4.5 6.8 "6.5" (new line)
5.4 8.3 1.2 "9.3" (new line)
```
so the last term is a number between double quotes.
What I want to do is, using Python (if possible), to assign the four columns to double variables. But the main problem is the last term... | There's a module you can use from the standard library called [**`shlex`**](http://doc.python.org/library/shlex.html):
```
>>> import shlex
>>> print shlex.split('5.6 4.5 6.8 "6.5"')
['5.6', '4.5', '6.8', '6.5']
``` |
Can Python remove double quotes from a string, when reading in text file? | 1,707,558 | 18 | 2009-11-10T12:20:44Z | 13,013,495 | 9 | 2012-10-22T14:25:26Z | [
"python",
"csv",
"strip"
] | I have some text file like this, with several 5000 lines:
```
5.6 4.5 6.8 "6.5" (new line)
5.4 8.3 1.2 "9.3" (new line)
```
so the last term is a number between double quotes.
What I want to do is, using Python (if possible), to assign the four columns to double variables. But the main problem is the last term... | The `csv` module (standard library) does it automatically, although the docs isn't very specific about `skipinitialspace`
```
>>> import csv
>>> with open(name, 'rb') as f:
... for row in csv.reader(f, delimiter=' ', skipinitialspace=True):
... print '|'.join(row)
5.6|4.5|6.8|6.5
5.4|8.3|1.2|9.3
``` |
List all the modules that are part of a python package? | 1,707,709 | 54 | 2009-11-10T12:47:30Z | 1,707,786 | 75 | 2009-11-10T12:58:55Z | [
"python",
"module",
"packages",
"introspection",
"python-import"
] | Is there a straightforward way to find all the modules that are part of a python package? I've found [this old discussion](http://bytes.com/topic/python/answers/36924-how-get-list-modules-package), which is not really conclusive, but I'd love to have a definite answer before I roll out my own solution based on os.listd... | Yes, you want something based on `pkgutil` or similar -- this way you can treat all packages alike regardless if they are in eggs or zips or so (where os.listdir won't help).
```
import pkgutil
# this is the package we are inspecting -- for example 'email' from stdlib
import email
package = email
for importer, modna... |
List all the modules that are part of a python package? | 1,707,709 | 54 | 2009-11-10T12:47:30Z | 1,708,706 | 21 | 2009-11-10T15:15:48Z | [
"python",
"module",
"packages",
"introspection",
"python-import"
] | Is there a straightforward way to find all the modules that are part of a python package? I've found [this old discussion](http://bytes.com/topic/python/answers/36924-how-get-list-modules-package), which is not really conclusive, but I'd love to have a definite answer before I roll out my own solution based on os.listd... | The right tool for this job is pkgutil.walk\_packages.
To list all the modules on your system:
```
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
print(modname)
```
Be aware that walk\_packages imports all subpackages, but not submodules.
If you wish to ... |
Call Python function from MATLAB | 1,707,780 | 46 | 2009-11-10T12:57:59Z | 1,707,851 | 11 | 2009-11-10T13:09:31Z | [
"python",
"matlab",
"language-interoperability"
] | I need to call a Python function from MATLAB. how can I do this? | You could [embed your Python script in a C program](http://www.linuxjournal.com/article/8497) and then [MEX the C program with MATLAB](http://www.mathworks.com/support/tech-notes/1600/1605.html) but that might be a lot of work compared dumping the results to a file.
You can call MATLAB functions in Python using [PyMat... |
Call Python function from MATLAB | 1,707,780 | 46 | 2009-11-10T12:57:59Z | 1,709,660 | 34 | 2009-11-10T17:22:51Z | [
"python",
"matlab",
"language-interoperability"
] | I need to call a Python function from MATLAB. how can I do this? | I had a similar requirement on my system and this was my solution:
In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like
```
C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m
```
Create a c... |
Call Python function from MATLAB | 1,707,780 | 46 | 2009-11-10T12:57:59Z | 10,797,152 | 14 | 2012-05-29T10:16:14Z | [
"python",
"matlab",
"language-interoperability"
] | I need to call a Python function from MATLAB. how can I do this? | Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : <http://algoholic.eu/matpy/>
You can do something like this easily:
```
[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import m... |
Call Python function from MATLAB | 1,707,780 | 46 | 2009-11-10T12:57:59Z | 11,804,197 | 11 | 2012-08-03T22:37:44Z | [
"python",
"matlab",
"language-interoperability"
] | I need to call a Python function from MATLAB. how can I do this? | As @dgorissen said, Jython is the easiest solution.
Just install Jython from the [homepage](http://www.jython.org/downloads.html).
Then:
```
javaaddpath('/path-to-your-jython-installation/jython.jar')
import org.python.util.PythonInterpreter;
python = PythonInterpreter; %# takes a long time to load!
python.exec('i... |
Call Python function from MATLAB | 1,707,780 | 46 | 2009-11-10T12:57:59Z | 29,189,167 | 7 | 2015-03-21T23:17:51Z | [
"python",
"matlab",
"language-interoperability"
] | I need to call a Python function from MATLAB. how can I do this? | With Matlab 2014b python libraries can be called [directly from matlab](http://www.mathworks.com/help/matlab/call-python-libraries.html). A prefix `py.` is added to all packet names:
```
wrapped = py.textwrap.wrap(T); % calls textwrap.wrap in python
``` |
Fast way to filter illegal xml unicode chars in python? | 1,707,890 | 19 | 2009-11-10T13:15:25Z | 22,273,639 | 8 | 2014-03-08T18:57:19Z | [
"python",
"xml",
"unicode"
] | The [XML specification](http://www.w3.org/TR/xml11/#charsets) lists a bunch of Unicode characters that are either illegal or "discouraged". Given a string, how can I remove all illegal characters from it?
I came up with the following regular expression, but it's a bit of a mouthful.
```
illegal_xml_re = re.compile(u'... | Recently we (Trac [XmlRpcPlugin](http://trac-hacks.org/wiki/XmlRpcPlugin) maintainers) have been notified of the fact that the regular expression above strips surrogate pairs on Python narrow builds (see [th:comment:13:ticket:11050](http://trac-hacks.org/ticket/11050#comment:13)) . An alternative approach consists in u... |
Meaning of using commas and underscores with Python assignment operator? | 1,708,292 | 29 | 2009-11-10T14:16:59Z | 1,708,304 | 13 | 2009-11-10T14:18:27Z | [
"python",
"syntax",
"iterable-unpacking"
] | Reading through Peter Norvig's [Solving Every Sudoku Puzzle essay](http://norvig.com/sudoku.html), I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
```
def f():
ret... | `_` is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
```
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
``` |
Meaning of using commas and underscores with Python assignment operator? | 1,708,292 | 29 | 2009-11-10T14:16:59Z | 1,708,333 | 29 | 2009-11-10T14:22:14Z | [
"python",
"syntax",
"iterable-unpacking"
] | Reading through Peter Norvig's [Solving Every Sudoku Puzzle essay](http://norvig.com/sudoku.html), I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
```
def f():
ret... | `d2, = values[s]` is just like `a,b=f()`, except for unpacking 1 element tuples.
```
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
```
`a` is tuple, `b` is an integer. |
convert decimal to hex python | 1,708,598 | 2 | 2009-11-10T15:00:42Z | 1,708,617 | 8 | 2009-11-10T15:03:39Z | [
"python",
"networking",
"decimal",
"hex"
] | Im building a server in python, i need to convert a decimal value to hex like this :
let's say the packet start by 4 bytes which define the packet lenght :
00 00 00 00
if the len(packet) = 255 we would send :
00 00 00 ff
Now my problem is that sometimes the packet is bigger than 256 as for example 336, then it would ... | ```
>>> import struct
>>> struct.pack(">i", 336)
'\x00\x00\x01P'
```
The [`struct` module](http://docs.python.org/library/struct) packs and unpacks python values into bytes. The `">i"` format means big-endian 4-byte integer. |
Python OCR library or handwritten character recognition engine | 1,708,779 | 8 | 2009-11-10T15:25:43Z | 1,709,223 | 7 | 2009-11-10T16:26:32Z | [
"python",
"ocr",
"image-recognition"
] | Could you recommend some python libraries or source code for OCR and handwritten character recognition? | Have you tried [pytesser](http://code.google.com/p/pytesser/)? |
Python socket receive - incoming packets always have a different size | 1,708,835 | 19 | 2009-11-10T15:34:11Z | 1,716,173 | 25 | 2009-11-11T16:02:59Z | [
"python",
"networking",
"timeout",
"recv"
] | I'm using the SocketServer module for a TCP server.
I'm experiencing some issue here with the `recv()` function, because the incoming packets always have a different size, so if I specify `recv(1024)` (I tried with a bigger value, and smaller), it gets stuck after 2 or 3 requests because the packet length will be small... | The network is *always* unpredictable. TCP makes a lot of this random behavior go away for you. One wonderful thing TCP does: it guarantees that the bytes will arrive in the same order. But! It does *not* guarantee that they will arrive chopped up in the same way. You simply *cannot* assume that every send() from one e... |
Python socket receive - incoming packets always have a different size | 1,708,835 | 19 | 2009-11-10T15:34:11Z | 1,806,965 | 84 | 2009-11-27T05:43:38Z | [
"python",
"networking",
"timeout",
"recv"
] | I'm using the SocketServer module for a TCP server.
I'm experiencing some issue here with the `recv()` function, because the incoming packets always have a different size, so if I specify `recv(1024)` (I tried with a bigger value, and smaller), it gets stuck after 2 or 3 requests because the packet length will be small... | The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the `recv(bufsize)` method works in the Python socket module.
So, to clarify, since this may be confusing to others looking to this for help:
1. The bufsize param for the `recv(bufsize)` ... |
Python socket receive - incoming packets always have a different size | 1,708,835 | 19 | 2009-11-10T15:34:11Z | 1,830,689 | 9 | 2009-12-02T04:40:21Z | [
"python",
"networking",
"timeout",
"recv"
] | I'm using the SocketServer module for a TCP server.
I'm experiencing some issue here with the `recv()` function, because the incoming packets always have a different size, so if I specify `recv(1024)` (I tried with a bigger value, and smaller), it gets stuck after 2 or 3 requests because the packet length will be small... | You can alternatively use recv(x\_bytes, socket.MSG\_WAITALL), which seems to work only on Unix, and will return exactly x\_bytes. |
What does 'u' mean in a list? | 1,709,110 | 18 | 2009-11-10T16:11:41Z | 1,709,126 | 7 | 2009-11-10T16:13:11Z | [
"python",
"string",
"unicode"
] | This is the first time I've came across this. Just printed a list and each element seems to have a `u` in front of it i.e.
```
[u'hello', u'hi', u'hey']
```
**What does it mean and why would a list have this in front of each element?**
As I don't know how common this is, if you'd like to see how I came across it, I'... | The `u` just means that the following string is a unicode string (as opposed to a plain ascii string). It has nothing to do with the list that happens to contain the (unicode) strings. |
What does 'u' mean in a list? | 1,709,110 | 18 | 2009-11-10T16:11:41Z | 1,709,132 | 41 | 2009-11-10T16:13:28Z | [
"python",
"string",
"unicode"
] | This is the first time I've came across this. Just printed a list and each element seems to have a `u` in front of it i.e.
```
[u'hello', u'hi', u'hey']
```
**What does it mean and why would a list have this in front of each element?**
As I don't know how common this is, if you'd like to see how I came across it, I'... | it's an indication of unicode string. similar to `r''` for raw string.
```
>>> type(u'abc')
<type 'unicode'>
>>> r'ab\c'
'ab\\c'
``` |
What does 'u' mean in a list? | 1,709,110 | 18 | 2009-11-10T16:11:41Z | 1,709,136 | 11 | 2009-11-10T16:13:38Z | [
"python",
"string",
"unicode"
] | This is the first time I've came across this. Just printed a list and each element seems to have a `u` in front of it i.e.
```
[u'hello', u'hi', u'hey']
```
**What does it mean and why would a list have this in front of each element?**
As I don't know how common this is, if you'd like to see how I came across it, I'... | [Unicode.](http://docs.python.org/tutorial/introduction.html#unicode-strings) |
Run nosetests with warnings as errors? | 1,709,388 | 15 | 2009-11-10T16:45:00Z | 20,998,338 | 7 | 2014-01-08T14:25:54Z | [
"python",
"unit-testing",
"warnings",
"nose"
] | When running `nosetests` from the command line, how do you specify that 'non-ignored' warnings should be treated as errors?
By default, warnings are printed, but not counted as failures:
```
[snip]/service/accounts/database.py:151: SADeprecationWarning: Use session.add()
self.session.save(state)
[snip]/service/acco... | `nosetests` is a small Python script. Open it with an editor, and add `-W error` at the end of the first line. This tells the Python interpreter to convert warnings into exceptions.
Even simpler is to use Python environment variable to inject "treat warnings as errors" flag:
```
PYTHONWARNINGS=error nosetests test/te... |
PyQt: translating standard buttons | 1,709,528 | 3 | 2009-11-10T17:03:15Z | 4,627,177 | 7 | 2011-01-07T15:33:41Z | [
"python",
"qt",
"pyqt",
"translation",
"button"
] | How can I easily translate standard buttons (Yes, No) from QMessageBox? I can't use self.tr on those arguments, so I would like to achieve it in some other simple way. Do I have to use whole translation system? | Here is how I did :
First you need to copy the `qt_LOCALE.qm` file to your application directory. Mine was :
```
cp /usr/share/qt4/translations/qt_fr.qm .
```
Secondly, you need to load a translator for your application.
```
application = QApplication(argv)
locale = QLocale.system().name()
qtTranslator = QTranslat... |
Euclidian Distance Python Implementation | 1,709,720 | 6 | 2009-11-10T17:29:29Z | 1,709,751 | 12 | 2009-11-10T17:33:53Z | [
"python",
"euclidean-distance"
] | I am playing with the following code from programming collective intelligence, this is a function from the book that calculated eclidian distance between two movie critics.
This function sums the difference of the rankings in the dictionary, but euclidean distance in n dimensions also includes the square root of that ... | The reason the square root is not used is because it is computationally expensive; it is monotonic (i.e., it preserves order) with the square function, so if all you're interested in is the order of the distances, the square root is unnecessary (and, as mentioned, very expensive computationally). |
How does wrapping an unsafe python method (e.g os.chdir) in a class make it thread/exception safe? | 1,709,770 | 4 | 2009-11-10T17:35:56Z | 1,710,140 | 7 | 2009-11-10T18:29:13Z | [
"python",
"exception-handling"
] | In the question [How do I "cd" in python](http://stackoverflow.com/questions/431684/how-do-i-cd-in-python), the accepted answer recommended wrapping the os.chdir call in a class to make the return to your original dir exception safe. Here was the recommended code:
```
class Chdir:
def __init__( self, newPat... | Thread safety and exception safety are not really the same thing at all. Wrapping the `os.chdir` call in a class like this is an attempt to make it exception safe **not thread safe**.
Exception safety is something you'll frequently hear C++ developers talk about. It isn't talked about nearly as much in the Python comm... |
Custom distutils commands | 1,710,839 | 21 | 2009-11-10T20:08:02Z | 1,712,268 | 12 | 2009-11-11T00:41:01Z | [
"python",
"deployment",
"distutils"
] | I have a library called "example" that I'm installing into my global site-packages directory. However, I'd like to be able to install two versions, one for production and one for testing (I have a web application and other things that are versioned this way).
Is there a way to specify, say "python setup.py stage" that... | Sure, you can extend distutils with new commands. In your distutil configuration file, add:
```
[global]
command-packages=foo.bar
```
this can be in `distutils.cfg` in the `distutils` package itself, `..pydistutils.cfg` in your home directory (no leading dot on Windows), or `setup.cfg` in the current directory.
Th... |
Custom distutils commands | 1,710,839 | 21 | 2009-11-10T20:08:02Z | 1,712,544 | 47 | 2009-11-11T02:07:20Z | [
"python",
"deployment",
"distutils"
] | I have a library called "example" that I'm installing into my global site-packages directory. However, I'd like to be able to install two versions, one for production and one for testing (I have a web application and other things that are versioned this way).
Is there a way to specify, say "python setup.py stage" that... | This can easily be done with distutils by subclassing **distutils.core.Command** inside of setup.py.
For example:
```
from distutils.core import setup, Command
import os, sys
class CleanCommand(Command):
description = "custom clean command that forcefully removes dist/build directories"
user_options = []
... |
Help installing cx_Oracle | 1,711,408 | 18 | 2009-11-10T21:38:03Z | 1,711,468 | 17 | 2009-11-10T21:48:05Z | [
"python",
"cx-oracle"
] | I'm trying to install the cx\_Oracle for Python 2.6, but it is failing. I don't know enough about C or MS Vis. Studio's compiler to even approach fixing it myself.
This is what is output on the command line:
```
C:\pydev\cx_Oracle-5.0.1>C:\python26\python setup.py install
running install
running build
running build_e... | Why don't you use a binary package like [Windows Installer (Oracle 10g, Python 2.6)](http://prdownloads.sourceforge.net/cx-oracle/cx%5FOracle-5.0.2-10g.win32-py2.6.msi?download)?
See <http://cx-oracle.sourceforge.net/> for other binary packages
---
Addendum (as requested): you must ensure to use the cx\_Oracle that ... |
Help installing cx_Oracle | 1,711,408 | 18 | 2009-11-10T21:38:03Z | 1,711,623 | 8 | 2009-11-10T22:15:10Z | [
"python",
"cx-oracle"
] | I'm trying to install the cx\_Oracle for Python 2.6, but it is failing. I don't know enough about C or MS Vis. Studio's compiler to even approach fixing it myself.
This is what is output on the command line:
```
C:\pydev\cx_Oracle-5.0.1>C:\python26\python setup.py install
running install
running build
running build_e... | You also need some type of Oracle client installed on your machine, since cx\_Oracle is just a bridge between Python and the Oracle Client. Valid Oracle Clients include a full Oracle installation (like Standard or XE) or the [Instant Client](http://www.oracle.com/technology/tech/oci/instantclient/index.html)
From the ... |
Python web hosting: Why are server restarts necessary? | 1,711,483 | 6 | 2009-11-10T21:50:06Z | 1,711,705 | 7 | 2009-11-10T22:30:35Z | [
"python",
"web-hosting"
] | We currently run a small shared hosting service for a couple of hundred small PHP sites on our servers. We'd like to offer Python support too, but from our initial research at least, a server restart seems to be required after each source code change.
Is this really the case? If so, we're just not going to be able to ... | Python is a compiled language; the compiled byte code is cached by the Python process for later use, to improve performance. PHP, by default, is interpreted. It's a tradeoff between usability and speed.
If you're using a standard WSGI module, such as Apache's `mod_wsgi`, then you don't have to restart the server -- ju... |
Python: "Indentation Error: unindent does not match any outer indentation level" | 1,711,756 | 13 | 2009-11-10T22:38:02Z | 1,711,766 | 38 | 2009-11-10T22:40:47Z | [
"python",
"indentation"
] | I just can't figure out what's wrong with this...
```
#!/usr/bin/env python
#
# Bugs.py
#
from __future__ import division
# No Module!
if __name__ != '__main__':
print "Bugs.py is not meant to be a module"
exit()
# App
import pygame, sys, random, math
pygame.init()
# Configuration Vars
conf =... | It's possible that you have mixed tabs and spaces in your file. You can have python help check for such errors with
```
python -m tabnanny <name of python file>
``` |
JavaScript equivalent of Python's __setitem__ | 1,712,074 | 7 | 2009-11-10T23:48:15Z | 1,712,126 | 10 | 2009-11-11T00:03:16Z | [
"javascript",
"python",
"syntactic-sugar"
] | ```
var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
```
JavaScript doesn't have \_\_setitem\_\_ and this example obviously doesn't work.
In python [\_\_setitem\_\_](http://docs.python.org/reference/datamodel.html#object.__setitem__) works like:
```
c... | > Is it possible to implement \_\_setitem\_\_ behavior in JavaScript?
No. There is no getter/setter for arbitrary properties in JavaScript.
In Firefox you can use JavaScript 1.5+'s getters and setters to define `x` and `y` properties that square their values on assignment, eg.:
```
var obj= {
_x: 0,
get x() ... |
JavaScript equivalent of Python's __setitem__ | 1,712,074 | 7 | 2009-11-10T23:48:15Z | 1,712,152 | 7 | 2009-11-11T00:07:43Z | [
"javascript",
"python",
"syntactic-sugar"
] | ```
var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
```
JavaScript doesn't have \_\_setitem\_\_ and this example obviously doesn't work.
In python [\_\_setitem\_\_](http://docs.python.org/reference/datamodel.html#object.__setitem__) works like:
```
c... | No, but there are plans for supporting a similar feature in JavaScript 2. The following object literal syntax has been suggested on [Mozilla bug 312116](https://bugzilla.mozilla.org/show%5Fbug.cgi?id=312116) and it seems that it might be how it will be done for object literals:
```
({
get * (property) {
// handl... |
Formatting "yesterday's" date in python | 1,712,116 | 85 | 2009-11-11T00:01:16Z | 1,712,127 | 139 | 2009-11-11T00:03:31Z | [
"python",
"datetime",
"date"
] | I need to find "yesterday's" date in this format `MMDDYY` in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday". | ```
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(1)
>>> print yesterday.strftime('%m%d%y')
'110909'
``` |
Formatting "yesterday's" date in python | 1,712,116 | 85 | 2009-11-11T00:01:16Z | 1,712,128 | 7 | 2009-11-11T00:03:40Z | [
"python",
"datetime",
"date"
] | I need to find "yesterday's" date in this format `MMDDYY` in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday". | This should do what you want:
```
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
``` |
Formatting "yesterday's" date in python | 1,712,116 | 85 | 2009-11-11T00:01:16Z | 1,712,131 | 103 | 2009-11-11T00:04:20Z | [
"python",
"datetime",
"date"
] | I need to find "yesterday's" date in this format `MMDDYY` in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday". | ```
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
``` |
How to get the size of a list | 1,712,227 | 996 | 2009-11-11T00:30:54Z | 1,712,236 | 1,389 | 2009-11-11T00:33:22Z | [
"python",
"list"
] | ```
items = []
items.append("apple")
items.append("orange")
items.append("banana")
# FAKE METHOD::
items.amount() # Should return 3
```
How do I do it right? | The [`len()`](https://docs.python.org/2/library/functions.html#len) function can be used with a lot of types in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) - both built-in types and library types.
```
>>> len([1,2,3])
3
``` |
How to get the size of a list | 1,712,227 | 996 | 2009-11-11T00:30:54Z | 16,114,025 | 37 | 2013-04-19T21:51:10Z | [
"python",
"list"
] | ```
items = []
items.append("apple")
items.append("orange")
items.append("banana")
# FAKE METHOD::
items.amount() # Should return 3
```
How do I do it right? | While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a `length` property:
```
class slist(list):
@property
def length(self):
return len(self)
```
You can use it like so:
```
>>> l = sl... |
How to get the size of a list | 1,712,227 | 996 | 2009-11-11T00:30:54Z | 27,137,427 | 29 | 2014-11-25T21:51:55Z | [
"python",
"list"
] | ```
items = []
items.append("apple")
items.append("orange")
items.append("banana")
# FAKE METHOD::
items.amount() # Should return 3
```
How do I do it right? | > # How to get the size of a list?
To find the size of a list, use the builtin function, `len`:
```
items = []
items.append("apple")
items.append("orange")
items.append("banana")
```
And now:
```
len(items)
```
returns 3.
## From the [docs](https://docs.python.org/library/functions.html#len)
**`len(s)`**
> Retu... |
In Python: how do I say: if line.partition('#' or 'tab') ... do something | 1,712,348 | 3 | 2009-11-11T01:04:18Z | 1,712,372 | 10 | 2009-11-11T01:11:22Z | [
"python",
"string"
] | In Python: how do I say:
```
line = line.partition('#' or 'tab')[0] ... do something with
```
I know I can do:
```
line = line.partition('#')[0] ... do something
```
But what is the code for the tab character, and can I say # or tab?
Update: I'm trying to say read the first word on each line, if you read a # th... | partition doesn't allow for options, so you may need `re.split`:
```
re.split("(#|\t)", line, 1)
```
`re.split` has the interesting property that if the pattern is enclosed in parens, then the separator is returned in the results, and you can use maxsplit (as I have here set to 1). This will return a three-tuple simi... |
super() fails with error: TypeError "argument 1 must be type, not classobj" | 1,713,038 | 52 | 2009-11-11T04:36:05Z | 1,713,052 | 102 | 2009-11-11T04:40:10Z | [
"python"
] | I get some error that I can't figure out. Any clue what is wrong with my sample code?
```
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
```
I got the sample test code from help of 'super' built-in method. The class "C" is ... | Your problem is that class B is not declared as a "new-style" class. Change it like so:
```
class B(object):
```
and it will work.
`super()` and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that `(object)` on any class definition to make sure it i... |
super() fails with error: TypeError "argument 1 must be type, not classobj" | 1,713,038 | 52 | 2009-11-11T04:36:05Z | 18,392,639 | 41 | 2013-08-23T00:02:15Z | [
"python"
] | I get some error that I can't figure out. Any clue what is wrong with my sample code?
```
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
```
I got the sample test code from help of 'super' built-in method. The class "C" is ... | Also, if you can't change class B, you can fix the error by using multiple inheritance.
```
class B:
def meth(self, arg):
print arg
class C(B, object):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
``` |
Peak-finding algorithm for Python/SciPy | 1,713,335 | 78 | 2009-11-11T05:54:48Z | 1,720,766 | 10 | 2009-11-12T08:36:11Z | [
"python",
"scipy",
"fft",
"hough-transform"
] | I can write something myself by finding zero-crossings of the first derivative or something, but it seems like a common-enough function to be included in standard libraries. Anyone know of one?
My particular application is a 2D array, but usually it would be used for finding peaks in FFTs, etc.
Specifically, in these... | I do not think that what you are looking for is provided by SciPy. I would write the code myself, in this situation.
The spline interpolation and smoothing from scipy.interpolate are quite nice and might be quite helpful in fitting peaks and then finding the location of their maximum. |
Peak-finding algorithm for Python/SciPy | 1,713,335 | 78 | 2009-11-11T05:54:48Z | 1,923,180 | 33 | 2009-12-17T17:06:46Z | [
"python",
"scipy",
"fft",
"hough-transform"
] | I can write something myself by finding zero-crossings of the first derivative or something, but it seems like a common-enough function to be included in standard libraries. Anyone know of one?
My particular application is a 2D array, but usually it would be used for finding peaks in FFTs, etc.
Specifically, in these... | I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data). For a good thorough review of peaking finding algorithms read [this](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/). This is one of the best clearest reviews of peak finding te... |
Peak-finding algorithm for Python/SciPy | 1,713,335 | 78 | 2009-11-11T05:54:48Z | 18,850,555 | 7 | 2013-09-17T12:58:31Z | [
"python",
"scipy",
"fft",
"hough-transform"
] | I can write something myself by finding zero-crossings of the first derivative or something, but it seems like a common-enough function to be included in standard libraries. Anyone know of one?
My particular application is a 2D array, but usually it would be used for finding peaks in FFTs, etc.
Specifically, in these... | There is a function in scipy named `scipy.signal.find_peaks_cwt` which sounds like is suitable for your needs, however I didn't experience with it so I cannot recommend..
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html> |
Version number comparison | 1,714,027 | 57 | 2009-11-11T09:21:59Z | 1,714,090 | 12 | 2009-11-11T09:34:04Z | [
"python"
] | Python must have a more elegant solution to this ... maybe one of you can help:
I want to write a `cmp`-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections.
Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1.
Desired function outputs ar... | No need to iterate over the version tuples. The built in comparison operator on lists and tuples already works exactly like you want it. You'll just need to zero extend the version lists to the corresponding length. With python 2.6 you can use izip\_longest to pad the sequences.
```
from itertools import izip_longest
... |
Version number comparison | 1,714,027 | 57 | 2009-11-11T09:21:59Z | 1,714,132 | 9 | 2009-11-11T09:45:50Z | [
"python"
] | Python must have a more elegant solution to this ... maybe one of you can help:
I want to write a `cmp`-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections.
Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1.
Desired function outputs ar... | This is a little more compact than your suggestion. Rather than filling the shorter version with zeros, I'm removing trailing zeros from the version lists after splitting.
```
def normalize_version(v):
parts = [int(x) for x in v.split(".")]
while parts[-1] == 0:
parts.pop()
return parts
def mycmp(... |
Version number comparison | 1,714,027 | 57 | 2009-11-11T09:21:59Z | 1,714,190 | 27 | 2009-11-11T09:59:36Z | [
"python"
] | Python must have a more elegant solution to this ... maybe one of you can help:
I want to write a `cmp`-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections.
Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1.
Desired function outputs ar... | Remove the uninteresting part of the string (trailing zeroes and dots), and then compare the lists of numbers.
```
import re
def mycmp(version1, version2):
def normalize(v):
return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")]
return cmp(normalize(version1), normalize(version2))
```
EDIT: sa... |
Version number comparison | 1,714,027 | 57 | 2009-11-11T09:21:59Z | 1,714,378 | 21 | 2009-11-11T10:40:04Z | [
"python"
] | Python must have a more elegant solution to this ... maybe one of you can help:
I want to write a `cmp`-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections.
Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1.
Desired function outputs ar... | Is *reuse* considered elegance in this instance? :)
```
# pkg_resources is in setuptools
# See http://peak.telecommunity.com/DevCenter/PkgResources#parsing-utilities
def mycmp(a, b):
from pkg_resources import parse_version as V
return cmp(V(a),V(b))
``` |
Version number comparison | 1,714,027 | 57 | 2009-11-11T09:21:59Z | 6,972,866 | 185 | 2011-08-07T12:38:16Z | [
"python"
] | Python must have a more elegant solution to this ... maybe one of you can help:
I want to write a `cmp`-like function returning -1, 0 or 1 for version numbers, allowing for an arbitrary number of subsections.
Each subsection is supposed to be interpreted as a number, therefore 1.10 > 1.1.
Desired function outputs ar... | How about using Python's `distutils.version.StrictVersion`?
```
>>> from distutils.version import StrictVersion
>>> StrictVersion('10.4.10') > StrictVersion('10.4.9')
True
```
So for your `cmp` function:
```
>>> cmp = lambda x, y: StrictVersion(x).__cmp__(y)
>>> cmp("10.4.10", "10.4.11")
-1
```
If you want to compa... |
Python code comments | 1,714,633 | 2 | 2009-11-11T11:34:58Z | 1,714,637 | 9 | 2009-11-11T11:36:09Z | [
"python"
] | In C# and through Visual Studio, it is possible to comment your functions, so you can tell whoever is using your class what the input arguments should be, what it is supposed to return, etc. Is there anything remotely similar in python? | In Python you use [docstrings](http://www.python.org/dev/peps/pep-0257/) like this:
```
def foo():
""" Here is the docstring """
```
Basically you need to have a triple quoted string be on the first line of a function, class, or module to be considered a docstring.
**Note:** Actually I you don't *have* to use a ... |
Python code comments | 1,714,633 | 2 | 2009-11-11T11:34:58Z | 1,714,794 | 7 | 2009-11-11T12:09:08Z | [
"python"
] | In C# and through Visual Studio, it is possible to comment your functions, so you can tell whoever is using your class what the input arguments should be, what it is supposed to return, etc. Is there anything remotely similar in python? | I think what you are getting at is that C# has a strong cultural convention for the formatting of code comments, and Visual Studio provides tools that collect those comments together, format them according to agreed markup, and so on. Java is similar, with its Javadoc.
Python has some conventions like this, but they a... |
Inline editing of ManyToMany relation in Django | 1,714,995 | 4 | 2009-11-11T12:49:49Z | 1,715,204 | 9 | 2009-11-11T13:37:59Z | [
"python",
"django",
"django-admin",
"inline-editing"
] | After working through the Django tutorial I'm now trying to build a very simple invoicing application.
I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product object if I've got different quantites of the same P... | You need to change your model structure a bit. As you recognise, the quantity doesn't belong on the Product model - it belongs on the *relationship* between Product and Invoice.
To do this in Django, you can use a [ManyToMany relationship with a `through` table](http://docs.djangoproject.com/en/dev/topics/db/models/#e... |
Exception message (Python 2.6) | 1,715,198 | 29 | 2009-11-11T13:35:37Z | 1,715,206 | 81 | 2009-11-11T13:38:16Z | [
"python",
"exception-handling",
"message"
] | In Python, if I open a binary file that doesn't exist, the program exits with an error and prints:
```
Traceback (most recent call last):
File "C:\Python_tests\Exception_Handling\src\exception_handling.py",
line 4, in <module>
pkl_file = open('monitor.dat', 'rb')
IOError: [Errno 2] No such file or directory: ... | This prints the exception message:
```
except Exception, e:
print "Couldn't do it: %s" % e
```
This will show the whole traceback:
```
import traceback
# ...
except Exception, e:
traceback.print_exc()
```
But you might not want to catch Exception. The narrower you can make your catch, the better, generall... |
Exception message (Python 2.6) | 1,715,198 | 29 | 2009-11-11T13:35:37Z | 1,715,222 | 9 | 2009-11-11T13:39:48Z | [
"python",
"exception-handling",
"message"
] | In Python, if I open a binary file that doesn't exist, the program exits with an error and prints:
```
Traceback (most recent call last):
File "C:\Python_tests\Exception_Handling\src\exception_handling.py",
line 4, in <module>
pkl_file = open('monitor.dat', 'rb')
IOError: [Errno 2] No such file or directory: ... | Python has the [traceback](http://docs.python.org/library/traceback.html) module.
```
import traceback
try:
pkl_file = open('monitor.dat', 'rb')
monitoring_pickle = pickle.load(pkl_file)
pkl_file.close()
except IOError:
traceback.print_exc()
``` |
Exception message (Python 2.6) | 1,715,198 | 29 | 2009-11-11T13:35:37Z | 1,715,424 | 20 | 2009-11-11T14:15:49Z | [
"python",
"exception-handling",
"message"
] | In Python, if I open a binary file that doesn't exist, the program exits with an error and prints:
```
Traceback (most recent call last):
File "C:\Python_tests\Exception_Handling\src\exception_handling.py",
line 4, in <module>
pkl_file = open('monitor.dat', 'rb')
IOError: [Errno 2] No such file or directory: ... | If you want to capture the exception object passed by the Exception, it's best to start using the NEW format introduced in Python 2.6 (which currently supports both) because it will be the only way to do it into Python 3.
And that is:
```
try:
...
except IOError as e:
...
```
Example:
```
try:
pkfile = ... |
Best way to decode unknown unicoding encoding in Python 2.5 | 1,715,772 | 3 | 2009-11-11T15:06:57Z | 1,715,913 | 8 | 2009-11-11T15:25:52Z | [
"python",
"html",
"unicode",
"encoding",
"character-encoding"
] | Have I got that all the right way round? Anyway, I am parsing a lot of html, but I don't always know what encoding it's meant to be (a surprising number lie about it). The code below easily shows what I've been doing so far, but I'm sure there's a better way. Your suggestions would be much appreciated.
```
import logg... | There are two general purpose libraries for detecting unknown encodings:
* chardet, part of [Universal Feed Parser](http://feedparser.org)
* UnicodeDammit, part of [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/)
chardet is supposed to be a port of the [way that firefox does it](http://www.mozilla.org/... |
adding a keyword argument to an overriden method and using **kwarg | 1,715,840 | 11 | 2009-11-11T15:16:28Z | 1,715,904 | 9 | 2009-11-11T15:24:33Z | [
"python"
] | I am subclassing an object in order to override a method that I want to add some functionality to. I don't want to completely replace it or add a differently named method but remain compatible to the superclasses method by just adding an optional argument to the method.
Is it possible to work with `*args` and `**kwargs... | ```
class A(object):
def foo(self, arg1, arg2, argopt1="bar"):
print arg1, arg2, argopt1
class B(A):
def foo(self, *args, **kwargs):
argopt2 = kwargs.get('argopt2', default_for_argopt2)
# remove the extra arg so the base class doesn't complain.
del kwargs['argopt2']
pri... |
Something like pubsubhubbub that does not depend on google app engine | 1,716,117 | 6 | 2009-11-11T15:55:29Z | 1,716,209 | 12 | 2009-11-11T16:08:46Z | [
"python",
"rss",
"atom",
"feed",
"pubsubhubbub"
] | I am looking for something like [PubSubHubbub](http://en.wikipedia.org/wiki/PubSubHubbub) that does not depend on google app engine to run.
What I need is a tool that can track for me a big very large number of rss or atom feeds and issue events when they are updated. | pubsubhubbub is a protocol, and, as such, does not depend on app engine. For example, [superfeedr](http://superfeedr.com/) is another implementation of this protocol (I believe it's free for the first 1000 feeds, then something like 50 dollars a month for the next 1000 feeds, then decreasing gradually for even larger n... |
def next() for Python pre-2.6? (instead of object.next method) | 1,716,428 | 5 | 2009-11-11T16:35:51Z | 1,716,464 | 11 | 2009-11-11T16:39:56Z | [
"python",
"next"
] | Python 2.6+ and 3.\* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps? | ```
class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
"""next(iterator[, default])
Return the next item from the iterator. If default is given
and the iterator is exhausted, it is returned instead of
raising StopIteration.
"""
try:
iternext = iterator.nex... |
How do I put a dictionary in the datastore? | 1,717,027 | 7 | 2009-11-11T18:03:25Z | 1,717,064 | 7 | 2009-11-11T18:09:30Z | [
"python",
"google-app-engine",
"dictionary",
"gae-datastore"
] | Is there a good way to store a Python dictionary in the datastore? I want to do something like the following:
```
from google.appengine.ext import db
class Recipe(db.Model):
name = db.StringProperty()
style = db.StringProperty()
yeast = db.StringProperty()
hops = db.ListofDictionariesProperty()
```
Of course... | Serializing a dict with `repr` is a good way to do it. You can then reconstitute it with `eval`, or if you don't trust the data, a "[safe eval](http://code.activestate.com/recipes/496746/)".
An advantage of repr over pickling is that the data is readable in the database, even queryable in desperate cases. |
Is the += operator thread-safe in Python? | 1,717,393 | 25 | 2009-11-11T19:08:46Z | 1,717,514 | 24 | 2009-11-11T19:33:33Z | [
"python",
"thread-safety",
"increment"
] | I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
```
c = 0
def increment():
c += 1
def decrement():
c -= 1
```
Is this code thread safe?
If not, may I understand why it is not thread safe, and what kind of statements usually lea... | (note: you would need `global c` in each function to make your code work.)
> Is this code thread safe?
No. Only a single bytecode instruction is âatomicâ in CPython, and a `+=` may not result in a single opcode, even when the values involved are simple integers:
```
>>> c= 0
>>> def inc():
... global c
... ... |
Is the += operator thread-safe in Python? | 1,717,393 | 25 | 2009-11-11T19:08:46Z | 1,717,518 | 9 | 2009-11-11T19:34:44Z | [
"python",
"thread-safety",
"increment"
] | I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
```
c = 0
def increment():
c += 1
def decrement():
c -= 1
```
Is this code thread safe?
If not, may I understand why it is not thread safe, and what kind of statements usually lea... | Single opcodes are thread-safe because of the GIL but nothing else:
```
import time
class something(object):
def __init__(self,c):
self.c=c
def inc(self):
new = self.c+1
# if the thread is interrupted by another inc() call its result is wrong
time.sleep(0.001) # sleep makes the... |
Is the += operator thread-safe in Python? | 1,717,393 | 25 | 2009-11-11T19:08:46Z | 1,718,843 | 40 | 2009-11-11T23:37:10Z | [
"python",
"thread-safety",
"increment"
] | I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
```
c = 0
def increment():
c += 1
def decrement():
c -= 1
```
Is this code thread safe?
If not, may I understand why it is not thread safe, and what kind of statements usually lea... | No, this code is absolutely, demonstrably not threadsafe.
```
import threading
i = 0
def test():
global i
for x in range(100000):
i += 1
threads = [threading.Thread(target=test) for t in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
assert i == 1000000, i
```
fails con... |
Is the += operator thread-safe in Python? | 1,717,393 | 25 | 2009-11-11T19:08:46Z | 6,761,146 | 10 | 2011-07-20T11:27:40Z | [
"python",
"thread-safety",
"increment"
] | I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
```
c = 0
def increment():
c += 1
def decrement():
c -= 1
```
Is this code thread safe?
If not, may I understand why it is not thread safe, and what kind of statements usually lea... | To be sure I recommend to use a lock:
```
import threading
class ThreadSafeCounter():
def __init__(self):
self.lock = threading.Lock()
self.counter=0
def increment(self):
with self.lock:
self.counter+=1
def decrement(self):
with self.lock:
self.co... |
Customize HTML Output of Django ModelForm | 1,717,715 | 4 | 2009-11-11T20:05:51Z | 1,717,810 | 14 | 2009-11-11T20:22:00Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML.
```
class LeagueForm(ModelForm):
league = forms.ModelChoiceField(q... | Just refer to each field separately.
```
{{ nhl_form.league }}
```
will only show the `league` field, with no surrounding cruft. |
save Exceptions to file in python | 1,718,295 | 13 | 2009-11-11T21:43:51Z | 1,718,313 | 26 | 2009-11-11T21:49:19Z | [
"python",
"file",
"ubuntu",
"exception"
] | I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which saves all Exception to a file. Thank y... | If you have a convenient `main()` function (whatever it's called), then you can use the [logging module](http://docs.python.org/2/library/logging.html):
```
import logging
def main():
raise Exception("Hey!")
logging.basicConfig(level=logging.DEBUG, filename='/tmp/myapp.log')
try:
main()
except:
logging.... |
What do square brackets, "[]", mean in function/class documentation? | 1,718,903 | 13 | 2009-11-11T23:50:58Z | 1,718,913 | 11 | 2009-11-11T23:52:51Z | [
"python"
] | I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.
From the docmentation:
```
class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
```
I'd appreciate a summary of the arguments ... | The square brackets indicate that these arguments are **optional**. You can leave them out.
So, in this case you are only *required* to pass the `csvfile` argument to `csv.DictReader`. If you would pass a second parameter, it would be interpreted as the `fieldnames` arguments. The third would be `restkey`, etc.
If yo... |
Euler #26, how to convert rational number to string with better precision? | 1,719,776 | 7 | 2009-11-12T03:54:10Z | 1,719,903 | 9 | 2009-11-12T04:34:44Z | [
"python",
"floating-point",
"floating-point-precision"
] | I want to get `1/7` with better precision, but it got truncated. How can I get better precision when I convert a rational number?
```
>>> str(1.0/7)[:50]
'0.142857142857'
``` | Python has a built-in library for arbitrary-precision calculations: Decimal. For example:
```
>>>from decimal import Decimal, getcontext
>>>getcontext().prec = 50
>>>x = Decimal(1)/Decimal(7)
>>>x
Decimal('0.14285714285714285714285714285714285714285714285714')
>>>str(x)
'0.142857142857142857142857142857142857142857142... |
What is the Yahoo openid discovery endpoint | 1,720,097 | 5 | 2009-11-12T05:31:08Z | 1,720,265 | 7 | 2009-11-12T06:18:10Z | [
"python",
"openid",
"yahoo"
] | It used to be <http://yahoo.com>, but it is failing for me with DiscoveryFailure in python OpenID library (since today, I wasn't testing this earlier). Also this fails if you try to use the SO login with a yahoo button, so I am thinking it probably changed recently. | I noticed it was down a few hours ago. It isn't working for any RP I've tried... except for zoho.com
I viewed their source and saw they are using **<https://me.yahoo.com>**, which works.
Yahoo either made a mistake in a recent site change, or forgot to tell anyone (including themselves). [http://openid.yahoo.com/](ht... |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 1,720,432 | 1,574 | 2009-11-12T07:07:06Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | Python makes this ridiculously easy.
```
mergedlist = listone + listtwo
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 1,720,436 | 38 | 2009-11-12T07:07:37Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | This is quite simple, I think it was even shown in the [tutorial](http://docs.python.org/tutorial/):
```
>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 1,724,975 | 133 | 2009-11-12T20:01:50Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | It's also possible to create a generator that simply iterates over the items in both lists. This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:
```
import itertools
for item in itertools.chain(listone, listtwo):
# do something with each list item
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 3,749,835 | 101 | 2010-09-20T08:43:58Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | You can use sets to obtain merged list of unique values
```
mergedlist = list(set(listone + listtwo))
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 14,453,876 | 43 | 2013-01-22T07:51:41Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | You could also use [`extend`](https://docs.python.org/2.7/tutorial/datastructures.html#more-on-lists) in order to add a `list` add the end of another one:
```
listone = [1,2,3]
listtwo = [4,5,6]
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 14,700,501 | 16 | 2013-02-05T05:01:34Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | It's worth noting that the `itertools.chain` function accepts variable number of arguments:
```
>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']
```
If an iterable (tuple, list, ge... |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 15,219,904 | 23 | 2013-03-05T09:15:56Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | You could simply use the `+` or `+=` operator as follows:
```
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
```
Or:
```
c = []
a = [1, 2, 3]
b = [4, 5, 6]
c += (a + b)
```
Also, if you want the values in the merged list to be unique you can do:
```
c = list(set(a + b))
``` |
How to append list to second list (concatenate lists) | 1,720,421 | 919 | 2009-11-12T07:04:09Z | 24,856,361 | 12 | 2014-07-21T00:53:24Z | [
"python",
"list"
] | How do I concatenate two lists in Python?
Example:
```
listone = [1, 2, 3]
listtwo = [4, 5, 6]
```
Expected outcome:
```
joinedlist == [1, 2, 3, 4, 5, 6]
``` | With Python 3.3+ you can use [yield from](https://docs.python.org/3/whatsnew/3.3.html#pep-380):
```
listone = [1,2,3]
listtwo = [4,5,6]
def merge(l1, l2):
yield from l1
yield from l2
>>> list(merge(listone, listtwo))
[1, 2, 3, 4, 5, 6]
```
Or, if you want to support an arbitrary number of iterators:
```
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.