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 |
|---|---|---|---|---|---|---|---|---|---|
Python - Memory Leak | 2,678,906 | 9 | 2010-04-20T21:47:01Z | 2,679,153 | 25 | 2010-04-20T22:28:13Z | [
"python",
"memory-leaks"
] | I'm working on solving a memory leak in my Python application.
Here's the thing - it really only appears to happen on Windows Server 2008 (not R2) but not earlier versions of Windows, and it also doesn't look like it's happening on Linux (although I haven't done nearly as much testing on Linux).
To troubleshoot it, I... | If there's never any garbage in gc.garbage, then I'm not sure what you're trying to do by enabling GC debugging. Sure, it'll tell you which objects are considered for cleanup, but that's not particularly interesting if you end up with no circular references that can't be cleaned up.
If your program is using more and m... |
Get coords of an oval in Tkinter | 2,679,418 | 6 | 2010-04-20T23:33:49Z | 2,679,823 | 11 | 2010-04-21T01:55:09Z | [
"python",
"tkinter"
] | I can't seem to figure out how to reterive the `x,y` position of an oval created on a Tkinter canvas using Python via
```
c.create_oval(x0, y0, x1, y2)
```
I understand that `Tkinter` creates the oval inside the box specified by `x0,y0,x1,y2` and if I can get those coordinates that would also work.
I need the coordi... | Assign the results of `c.create_oval` to `x` -- that's the "object ID" of the oval. Then,
```
c.coords(x)
```
gives you the `(x1, y1, x2, y2)` tuple of the oval's coordinates (you call `coords` with new coordinates following the `x` to move the oval). |
Python XLWT attempt to overwrite cell workaround | 2,679,502 | 11 | 2010-04-21T00:00:25Z | 2,679,641 | 35 | 2010-04-21T00:44:57Z | [
"python",
"xlwt"
] | Using the python module xlwt, writing to the same cell twice throws an error:
```
Message File Name Line Position
Traceback
<module> S:\********
write C:\Python26\lib\site-packages\xlwt\Worksheet.py 1003
write C:\Python26\lib\site-packages\xlwt\Row.py 231
... | The problem is that overwriting of worksheet data is disabled by default in `xlwt`. You have to allow it explicitly, like so:
```
worksheet = workbook.add_sheet("Sheet 1", cell_overwrite_ok=True)
``` |
how to write or create (when no exist) a file using python and Google AppEngine | 2,680,215 | 3 | 2010-04-21T03:55:48Z | 2,680,859 | 7 | 2010-04-21T06:53:02Z | [
"python",
"google-app-engine",
"file"
] | this is my code:
```
f = open('text/a.log', 'wb')
f.write('hahaha')
f.close()
```
and it is not create a new file when not exist
how to do this ,
thanks
**updated**
```
class MyThread(threading.Thread):
def run(self):
f = open('a.log', 'w')
f.write('hahaha')
f.close()
```
error is :
... | Its because of google appengine not allowed you to write files
its define like this
```
ALLOWED_MODES = frozenset(['r', 'rb', 'U', 'rU'])
```
and
```
if mode not in FakeFile.ALLOWED_MODES:
raise IOError('invalid mode: %s' % mode)
```
**Note**: 'U' is universal newline mode, <http://docs.python.org/library/io.htm... |
how to write or create (when no exist) a file using python and Google AppEngine | 2,680,215 | 3 | 2010-04-21T03:55:48Z | 2,680,889 | 9 | 2010-04-21T06:59:34Z | [
"python",
"google-app-engine",
"file"
] | this is my code:
```
f = open('text/a.log', 'wb')
f.write('hahaha')
f.close()
```
and it is not create a new file when not exist
how to do this ,
thanks
**updated**
```
class MyThread(threading.Thread):
def run(self):
f = open('a.log', 'w')
f.write('hahaha')
f.close()
```
error is :
... | You are using the Google App Engine.
From the [Google App Engine documentation](http://code.google.com/appengine/docs/whatisgoogleappengine.html):
> ## The Sandbox
>
> Applications run in a secure environment that provides limited access to the underlying operating system. These limitations allow App Engine to distri... |
In django changing the file name of an uploaded file | 2,680,391 | 16 | 2010-04-21T04:49:23Z | 2,680,596 | 38 | 2010-04-21T05:40:26Z | [
"python",
"django",
"django-models",
"django-forms",
"django-views"
] | Is it possible to change the file name of an uploaded file in django? I searched, but couldn't find any answer.
My requirement is whenever a file is uploaded its file name should be changed in the following format.
```
format = userid + transaction_uuid + file_extension
```
Thank you very much... | How are you uploading the file?
I assume with the `FileField`.
The documentation for [FileField.upload\_to](http://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to) says that the `upload_to` field,
> may also be a callable, such as a
> function, which will be called to
> obtain th... |
Python Django Global Variables | 2,680,902 | 29 | 2010-04-21T07:02:32Z | 2,681,127 | 21 | 2010-04-21T07:46:06Z | [
"python",
"django",
"memory",
"variables",
"global"
] | I'm looking for simple but recommended way in Django to store a variable in memory only. When Apache restarts or the Django development server restarts, the variable is reset back to 0. More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for pe... | You **mustn't** declare global variables. Settings (constants) are OK if done right. But variables violate with *shared-nothing* architecture and might cause a lot of trouble. (best case they'll be inconsistent)
I would simply store those statistics in the cache. (Well, actually I would store them in the database but ... |
Python Django Global Variables | 2,680,902 | 29 | 2010-04-21T07:02:32Z | 2,681,834 | 45 | 2010-04-21T09:52:04Z | [
"python",
"django",
"memory",
"variables",
"global"
] | I'm looking for simple but recommended way in Django to store a variable in memory only. When Apache restarts or the Django development server restarts, the variable is reset back to 0. More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for pe... | Why one **mustn't** declare global variables? O\_o. It just looks like a propaganda. If the author knows what he wants and what side-effects will be, why not. Maybe it's just a quick experiment.
You could declare your counter as a model *class*-member. Then to deal with race condition you have to add a method that wil... |
How should I declare default values for instance variables in Python? | 2,681,243 | 43 | 2010-04-21T08:11:40Z | 2,681,286 | 28 | 2010-04-21T08:20:52Z | [
"python",
"class",
"oop"
] | Should I give my class members default values like this:
```
class Foo:
num = 1
```
or like this?
```
class Foo:
def __init__(self):
self.num = 1
```
In [this question](http://stackoverflow.com/questions/2424451/about-python-class-and-instance-variables) I discovered that in both cases,
```
bar = F... | The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. [Python documentation](https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables) explains the difference, but here are some examples:
## Exhibit A
```
class Foo:
def __... |
How should I declare default values for instance variables in Python? | 2,681,243 | 43 | 2010-04-21T08:11:40Z | 2,681,507 | 62 | 2010-04-21T09:02:25Z | [
"python",
"class",
"oop"
] | Should I give my class members default values like this:
```
class Foo:
num = 1
```
or like this?
```
class Foo:
def __init__(self):
self.num = 1
```
In [this question](http://stackoverflow.com/questions/2424451/about-python-class-and-instance-variables) I discovered that in both cases,
```
bar = F... | Extending bp's answer, I wanted to show you what he meant by immutable types.
First, this is okay:
```
>>> class TestB():
... def __init__(self, attr=1):
... self.attr = attr
...
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1
```
However, this only works for immutable (unch... |
Django: Serving a Download in a Generic View | 2,681,338 | 5 | 2010-04-21T08:31:16Z | 2,681,440 | 14 | 2010-04-21T08:49:34Z | [
"python",
"django",
"file"
] | So I want to serve a couple of mp3s from a folder in `/home/username/music`. I didn't think this would be such a big deal but I am a bit confused on how to do it using generic views and my own url.
urls.py
```
url(r'^song/(?P<song_id>\d+)/download/$', song_download, name='song_download'),
```
The example I am follow... | Why do you want to do this with a generic view? It's very easy to do this without generic views:
```
def song_download(request, song_id):
song = Song.objects.get(id=song_id)
fsock = open('/path/to/file.mp3', 'r')
response = HttpResponse(fsock, mimetype='audio/mpeg')
response['Content-Disposition'] = "a... |
How to create simple web site with python? | 2,681,754 | 20 | 2010-04-21T09:40:15Z | 2,683,451 | 10 | 2010-04-21T13:48:20Z | [
"python",
"web-applications",
"website"
] | How to create simple web site with python?
I mean really simple, f.ex, you see text "Hello World", and there are button "submit", which (onClick) will show ajax box "submit successful".
I want to start develop some stuff with Python, and I don't know where to start ;) | I was hoping more elaborate answers would be given to this question, since it's a sensitive subject. Python web developing is split across lots of frameworks, each with its ups and downs and every developer using a different one. This is quite unfortunate. What you should know:
* Use WSGI. Don't use anything else, WSG... |
How to create simple web site with python? | 2,681,754 | 20 | 2010-04-21T09:40:15Z | 2,683,483 | 8 | 2010-04-21T13:52:50Z | [
"python",
"web-applications",
"website"
] | How to create simple web site with python?
I mean really simple, f.ex, you see text "Hello World", and there are button "submit", which (onClick) will show ajax box "submit successful".
I want to start develop some stuff with Python, and I don't know where to start ;) | I'd cast my vote for Django. Not just because it's what I use, but also because it has a great tutorial: <http://docs.djangoproject.com/en/dev/intro/tutorial01/> |
How to call same method for a list of objects? | 2,682,012 | 27 | 2010-04-21T10:20:36Z | 2,684,864 | 10 | 2010-04-21T16:48:28Z | [
"python"
] | Suppose code like this:
```
class Base:
def start(self):
pass
def stop(self)
pass
class A(Base):
def start(self):
... do something for A
def stop(self)
.... do something for A
class B(Base):
def start(self):
def stop(self):
a1 = A(); a2 = A()
b1 = B(); b2 = B... | The approach
```
for item in all:
item.start()
```
is simple, easy, readable, and concise. This is the main approach Python provides for this operation. You can certainly encapsulate it in a function if that helps something. Defining a special function for this for general use is likely to be less clear than just... |
How to call same method for a list of objects? | 2,682,012 | 27 | 2010-04-21T10:20:36Z | 6,588,258 | 12 | 2011-07-05T20:08:31Z | [
"python"
] | Suppose code like this:
```
class Base:
def start(self):
pass
def stop(self)
pass
class A(Base):
def start(self):
... do something for A
def stop(self)
.... do something for A
class B(Base):
def start(self):
def stop(self):
a1 = A(); a2 = A()
b1 = B(); b2 = B... | It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.
I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:
```
map(do_something, a_list_of_objects)
```
This replaces a bunch of code that looks like this:
```
do_something(a)
do_something... |
How to call same method for a list of objects? | 2,682,012 | 27 | 2010-04-21T10:20:36Z | 9,135,180 | 60 | 2012-02-03T20:38:49Z | [
"python"
] | Suppose code like this:
```
class Base:
def start(self):
pass
def stop(self)
pass
class A(Base):
def start(self):
... do something for A
def stop(self)
.... do something for A
class B(Base):
def start(self):
def stop(self):
a1 = A(); a2 = A()
b1 = B(); b2 = B... | **This will work**
```
all = [a1, b1, b2, a2,.....]
map(lambda x: x.start(),all)
```
simple example
```
all = ["MILK","BREAD","EGGS"]
map(lambda x:x.lower(),all)
>>>['milk','bread','eggs']
```
and in python3
```
all = ["MILK","BREAD","EGGS"]
list(map(lambda x:x.lower(),all))
>>>['milk','bread','eggs']
``` |
Feedback on availability with Google App Engine | 2,682,062 | 5 | 2010-04-21T10:27:25Z | 2,687,692 | 8 | 2010-04-22T01:34:37Z | [
"python",
"google-app-engine",
"google-apps"
] | We've had some good experiences building an app on Google App Engine, this first app's target audience are Google Apps users, so no issues there in terms of it being hosted on Google infrastructure.
We like it so much that we would like to investigate using it for another app, however this next project is for a client... | You are correct: you are not in as much control vs. traditional hosting. However, hopefully the gains outweight the negatives. App Engine is extremely scalable -- it runs on the same hardware that runs Google itself. How often have you visited <http://google.com> and had that page or a search result fail?
Although you... |
matplotlib analog of R's `pairs` | 2,682,144 | 15 | 2010-04-21T10:40:18Z | 12,956,923 | 18 | 2012-10-18T14:25:29Z | [
"python",
"matplotlib"
] | R has a useful function `pairs` that provides nice matrix of plots of pairwise connections between variables in a data set. The resulting plot looks similar to the following figure, copied from [this blog post](http://statisticsr.blogspot.com/2009/12/r-pairs-plot.html):
 has a built in function `scatter_matrix` ([source code](https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#L28)) which is something like this.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randn(1000, 4)... |
How to create a constant in Python | 2,682,745 | 419 | 2010-04-21T12:20:18Z | 2,682,752 | 413 | 2010-04-21T12:21:54Z | [
"python"
] | Is there a way to declare a constant in Python. In Java we can create constant in this manner:
```
public static final String CONST_NAME = "Name";
```
What is the equivalent of the above Java constant declaration in Python? | No there is not. You cannot declare a variable or value as constant in Python. Just don't change it.
If you are in a class, the equivalent would be:
```
class Foo(object):
CONST_NAME = "Name"
```
if not, it is just
```
CONST_NAME = "Name"
```
But you might want to have a look at the code snippet [Constants in ... |
How to create a constant in Python | 2,682,745 | 419 | 2010-04-21T12:20:18Z | 2,683,099 | 50 | 2010-04-21T13:06:32Z | [
"python"
] | Is there a way to declare a constant in Python. In Java we can create constant in this manner:
```
public static final String CONST_NAME = "Name";
```
What is the equivalent of the above Java constant declaration in Python? | In Python instead of language enforcing something, people use naming conventions e.g `__method` for private methods and using `_method` for protected methods.
So in same manner you can simply declare the constant as all caps e.g.
```
MY_CONSTANT = "one"
```
If you want that this constant never changes, you can hook ... |
How to create a constant in Python | 2,682,745 | 419 | 2010-04-21T12:20:18Z | 2,688,086 | 195 | 2010-04-22T03:39:39Z | [
"python"
] | Is there a way to declare a constant in Python. In Java we can create constant in this manner:
```
public static final String CONST_NAME = "Name";
```
What is the equivalent of the above Java constant declaration in Python? | There's no `const` keyword as in other languages, however it is possible to create a Property that **has a "getter function"** to read the data, but **no "setter function"** to re-write the data. **This essentially protects the identifier from being changed.**
Here is an alternative implementation using class property... |
How to create a constant in Python | 2,682,745 | 419 | 2010-04-21T12:20:18Z | 19,306,516 | 9 | 2013-10-10T21:25:47Z | [
"python"
] | Is there a way to declare a constant in Python. In Java we can create constant in this manner:
```
public static final String CONST_NAME = "Name";
```
What is the equivalent of the above Java constant declaration in Python? | In addition to the two top answers (just use variables with UPPERCASE names, or use properties to make the values read-only), I want to mention that it's possible to use metaclasses in order to implement *named* constants. I provide a very simple solution using metaclasses at [GitHub](https://github.com/hmeine/named_co... |
How to create a constant in Python | 2,682,745 | 419 | 2010-04-21T12:20:18Z | 23,274,028 | 16 | 2014-04-24T16:00:20Z | [
"python"
] | Is there a way to declare a constant in Python. In Java we can create constant in this manner:
```
public static final String CONST_NAME = "Name";
```
What is the equivalent of the above Java constant declaration in Python? | I'm probably missing a trick here, but this seems to work for me:
```
class CONST(object):
FOO = 1234
def __setattr__(self, *_):
pass
CONST = CONST()
#----------
print CONST.FOO # 1234
CONST.FOO = 4321
CONST.BAR = 5678
print CONST.FOO # Still 1234!
print CONST.BAR # Oops AttributeError
`... |
python: find and replace numbers < 1 in text file | 2,685,015 | 5 | 2010-04-21T17:09:56Z | 2,685,098 | 7 | 2010-04-21T17:22:12Z | [
"python",
"replace"
] | I'm pretty new to Python programming and would appreciate some help to a problem I have...
Basically I have multiple text files which contain velocity values as such:
0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00
etc for many lines..... | I think when you are beginning programming, it's useful to see some examples; and I assume you've tried this problem on your own first!
Here is a break-down of how you could approach this:
```
contents='0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+0... |
Syntax error when using "with open" in Python (python newbie) | 2,685,097 | 12 | 2010-04-21T17:22:11Z | 2,685,184 | 8 | 2010-04-21T17:33:56Z | [
"python",
"syntax-error"
] | ```
[root@234571-app2 git]# ./test.py
File "./test.py", line 4
with open("/home/git/post-receive-email.log",'a') as log_file:
^
SyntaxError: invalid syntax
```
The code looks like this:
```
[root@234571-app2 git]# more test.py
#!/usr/bin/python
from __future__ import with_statement
with open("/ho... | What you have should be correct. Python 2.5 introduced the with statement as something you can import from `__future__`. Since your code is correct, the only explanation I can think of is that your python version is not what you think it is. There's a good chance you have multiple versions of python installed on the sy... |
Google app engine How to count SUM from datestore? | 2,686,361 | 6 | 2010-04-21T20:35:05Z | 2,686,540 | 12 | 2010-04-21T21:02:41Z | [
"python",
"google-app-engine",
"gql"
] | Hey,
Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)?
should i:
```
ratingsum = 0
for rating in ratings:
ratingsum + rating
print ratingsum
```
? | Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no `SUM` in GQL.
If what you're trying to accomplish is to find the average rating for an entity, there's a better way.
```
class RateableThing(db.Model):
num_ratings = db.IntegerProperty()
avg_rating = d... |
Encoding in python with lxml - complex solution | 2,686,709 | 9 | 2010-04-21T21:30:02Z | 2,688,617 | 17 | 2010-04-22T06:21:11Z | [
"python",
"lxml"
] | I need to download and parse webpage with lxml and build UTF-8 xml output. I thing schema in pseudocode is more illustrative:
```
from lxml import etree
webfile = urllib2.urlopen(url)
root = etree.parse(webfile.read(), parser=etree.HTMLParser(recover=True))
txt = my_process_text(etree.tostring(root.xpath('/html/body... | lxml can be a little wonky about input encodings. It is best to send UTF8 in and get UTF8 out.
You might want to use the [chardet](http://pypi.python.org/pypi/chardet) module or [UnicodeDammit](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit) to decode... |
Writing a blocking wrapper around twisted's IRC client | 2,687,656 | 3 | 2010-04-22T01:21:08Z | 2,688,271 | 10 | 2010-04-22T04:35:43Z | [
"python",
"asynchronous",
"twisted"
] | I'm trying to write a dead-simple interface for an IRC library, like so:
```
import simpleirc
connection = simpleirc.Connect('irc.freenode.net', 6667)
channel = connection.join('foo')
find_command = re.compile(r'google ([a-z]+)').findall
for msg in channel:
for t in find_command(msg):
channel.say("http:/... | In general, if you're trying to use Twisted in a "blocking" way, you're going to run into a lot of difficulties, because that's neither the way it's intended to be used, nor the way in which most people use it.
Going with the flow is generally a lot easier, and in this case, that means embracing callbacks. The callbac... |
Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time | 2,687,724 | 37 | 2010-04-22T01:44:21Z | 2,712,401 | 54 | 2010-04-26T09:44:15Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] | In a Python Google App Engine app I'm writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), and then put this entity back in.
How should I do this? In particular, are there any caveats or tricks I need to be aware of when doing this so that... | Here you go:
```
def clone_entity(e, **extra_args):
"""Clones an entity, adding or overriding constructor attributes.
The cloned entity will have exactly the same property values as the original
entity, except where overridden. By default it will have no parent entity or
key name, unless supplied.
Args:
... |
Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time | 2,687,724 | 37 | 2010-04-22T01:44:21Z | 7,532,887 | 13 | 2011-09-23T17:43:23Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] | In a Python Google App Engine app I'm writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), and then put this entity back in.
How should I do this? In particular, are there any caveats or tricks I need to be aware of when doing this so that... | This is just an extension to [Nick Johnson's excellent code](http://stackoverflow.com/questions/2687724/copy-an-entity-in-google-app-engine-datastore-in-python-without-knowing-property/2712401#2712401) to address the problems highlighted by Amir in the comments:
1. The db.Key value of the ReferenceProperty is no longe... |
Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time | 2,687,724 | 37 | 2010-04-22T01:44:21Z | 9,935,803 | 19 | 2012-03-30T01:18:31Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] | In a Python Google App Engine app I'm writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), and then put this entity back in.
How should I do this? In particular, are there any caveats or tricks I need to be aware of when doing this so that... | If you're using the NDB you can simply copy with:
`new_entity.populate(**old_entity.to_dict())` |
Python hash() can't handle long integer? | 2,687,829 | 8 | 2010-04-22T02:14:33Z | 2,687,856 | 10 | 2010-04-22T02:23:50Z | [
"python",
"hash",
"integer"
] | I defined a class:
```
class A:
''' hash test class
>>> a = A(9, 1196833379, 1, 1773396906)
>>> hash(a)
-340004569
This is weird, 12544897317L expected.
'''
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __hash__(self):
... | It appears to be limited to 32-bits. By reading [this question](http://stackoverflow.com/questions/793761/built-in-python-hash-function), it looks like your code might have produced the expected result on a 64-bit machine (with those particular values, since the result fits in 64 bits).
The results of the built-in `ha... |
Python hash() can't handle long integer? | 2,687,829 | 8 | 2010-04-22T02:14:33Z | 2,688,025 | 7 | 2010-04-22T03:19:44Z | [
"python",
"hash",
"integer"
] | I defined a class:
```
class A:
''' hash test class
>>> a = A(9, 1196833379, 1, 1773396906)
>>> hash(a)
-340004569
This is weird, 12544897317L expected.
'''
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __hash__(self):
... | See [`object.__hash__`](http://docs.python.org/reference/datamodel.html#object.__hash__)
Notice that
> Changed in version 2.5: `__hash__()` may
> now also return a long integer object;
> the 32-bit integer is then derived
> from the hash of that object.
In your case, expected 12544897317L is a long integer object,
... |
Django: Serving Media Behind Custom URL | 2,687,957 | 10 | 2010-04-22T02:53:35Z | 2,690,263 | 12 | 2010-04-22T11:20:17Z | [
"python",
"django",
"url-rewriting",
"nginx"
] | So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the file using Django. <http://stackoverflow.com/questions/2681338/django-serving-a-download-in-a-generic-view> but the answer I accepted seems to be the ... | To expand on the previous answers you should be able to modify the following code and have nginx directly serve your download files whilst still having the files protected.
First of all add a location such as :
```
location /files/ {
alias /true/path/to/mp3/files/;
internal;
}
```
to your nginx.conf file (the ... |
How to iterate over the first n elements of a list? | 2,688,079 | 34 | 2010-04-22T03:37:14Z | 2,688,091 | 16 | 2010-04-22T03:41:03Z | [
"python",
"list",
"slice"
] | Say I want I've got a list and I want to iterate over the first `n` of them. What's the most best way to write this in Python? | I'd probably use [`itertools.islice`](http://docs.python.org/library/itertools.html#itertools.islice) (<- follow the link for the docs), which has the benefit of working with any iterable object. |
How to iterate over the first n elements of a list? | 2,688,079 | 34 | 2010-04-22T03:37:14Z | 2,688,103 | 64 | 2010-04-22T03:45:51Z | [
"python",
"list",
"slice"
] | Say I want I've got a list and I want to iterate over the first `n` of them. What's the most best way to write this in Python? | The normal way would be [slicing](http://docs.python.org/tutorial/introduction.html#strings):
```
for item in your_list[:n]:
...
``` |
How to iterate over the first n elements of a list? | 2,688,079 | 34 | 2010-04-22T03:37:14Z | 2,688,104 | 10 | 2010-04-22T03:46:06Z | [
"python",
"list",
"slice"
] | Say I want I've got a list and I want to iterate over the first `n` of them. What's the most best way to write this in Python? | You can just slice the list:
```
>>> l = [1, 2, 3, 4, 5]
>>> n = 3
>>> l[:n]
[1, 2, 3]
```
and then iterate on the slice as with any iterable. |
get average from set of objects in django | 2,689,664 | 8 | 2010-04-22T09:38:07Z | 2,689,737 | 18 | 2010-04-22T09:50:54Z | [
"python",
"django",
"average"
] | Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this
```
def Property(models.Model)
# stuff here
def Rating(models.Model)
property = models.ForeignKey(Property)
stars = models.IntegerField()
```
What i want to do is get a property, find ... | You should use [Aggregation(doc)](https://docs.djangoproject.com/en/1.9/topics/db/aggregation/):
```
from django.db.models import Avg
p = Property.objects.get(...)
stars_average = p.rating_set.aggregate(Avg('stars')).values()[0]
```
A little bit unsure about my example though. |
What is it in Java standard library that Python's lacks? | 2,690,147 | 7 | 2010-04-22T10:58:48Z | 2,690,215 | 8 | 2010-04-22T11:12:27Z | [
"java",
"python"
] | I hear that the Java standard library is larger than that of Python. That makes me curious about what is missing in Python's? | The one flaw in Python imho is that Python lacks one real canonical method of deployment. (Yes there are good ones out there, but nothing that's really rock solid).
Which can hamper its adoption in some Enterprise environments. |
List Directories and get the name of the Directory | 2,690,324 | 14 | 2010-04-22T11:29:29Z | 2,690,368 | 19 | 2010-04-22T11:36:18Z | [
"python",
"directory"
] | I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
```
import os
for directories in os.listdir(os.getcwd()):
di... | This will print all the subdirectories of the current directory:
```
print [name for name in os.listdir(".") if os.path.isdir(name)]
```
I'm not sure what you're doing with `split("-")`, but perhaps this code will help you find a solution?
If you want the full pathnames of the directories, use `abspath`:
```
print ... |
List Directories and get the name of the Directory | 2,690,324 | 14 | 2010-04-22T11:29:29Z | 2,690,390 | 9 | 2010-04-22T11:39:48Z | [
"python",
"directory"
] | I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
```
import os
for directories in os.listdir(os.getcwd()):
di... | ```
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
```
Walk is a good built-in for what you are doing |
Django check for any exists for a query | 2,690,521 | 31 | 2010-04-22T11:58:38Z | 2,690,573 | 32 | 2010-04-22T12:07:16Z | [
"python",
"django",
"django-views"
] | In django how to check whether any entry exists for a query
```
sc=scorm.objects.filter(Header__id=qp.id)
```
This was how it was done in php
```
if(mysql_num_rows($resultn)) {
// True condition
}
else {
// False condition
}
``` | Use [`count()`](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#count):
```
sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
```
The advantage over e.g. `len()` is, that the QuerySet is not yet evaluated:
> `count()` performs a `SELECT COUNT(*)` behind the scenes, so you should always... |
Django check for any exists for a query | 2,690,521 | 31 | 2010-04-22T11:58:38Z | 9,089,028 | 72 | 2012-02-01T00:17:30Z | [
"python",
"django",
"django-views"
] | In django how to check whether any entry exists for a query
```
sc=scorm.objects.filter(Header__id=qp.id)
```
This was how it was done in php
```
if(mysql_num_rows($resultn)) {
// True condition
}
else {
// False condition
}
``` | As of Django 1.2, you can use `exists()`:
<https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists>
```
if some_queryset.filter(pk=entity_id).exists():
print("Entry contained in queryset")
``` |
a simple smtp server | 2,690,965 | 9 | 2010-04-22T13:02:53Z | 2,691,224 | 12 | 2010-04-22T13:32:24Z | [
"python",
"smtp"
] | Could you please suggest a simple SMTP server with the very basic APIs(by very basic I mean, to read,write,delete email) that could be run on a linux box?
I just need to convert the crux of the email into XML format and FTP it to another machine. | There are really 2 things required to send an email:
* An SMTP Server - This can either be the [Python SMTP Server](http://docs.python.org/library/smtpd.html) or you can use GMail or your ISP's server. Chances are you don't need to run your own.
* An SMTP Library - Something that will send an email request to the SMTP... |
a simple smtp server | 2,690,965 | 9 | 2010-04-22T13:02:53Z | 2,691,249 | 17 | 2010-04-22T13:35:21Z | [
"python",
"smtp"
] | Could you please suggest a simple SMTP server with the very basic APIs(by very basic I mean, to read,write,delete email) that could be run on a linux box?
I just need to convert the crux of the email into XML format and FTP it to another machine. | Take a look at this [SMTP sink server](http://www.djangosnippets.org/snippets/96/)
It uses `smtpd.SMTPServer` to dump emails to files. |
How to add a Facebook Event with new Graph API | 2,690,971 | 5 | 2010-04-22T13:03:51Z | 2,747,233 | 7 | 2010-04-30T19:47:13Z | [
"python",
"django",
"facebook",
"facebook-graph-api"
] | I am trying to create an event using Facebooks api. (From a django app) Has anyone created an event with the new graph api? | Check here:
<http://developers.facebook.com/docs/api#publishing>
Make a POST call to /PROFILE\_ID/events with the required informations. Unfortunately they don't have all the possible arguments listed, but they can be found in the REST API docs under [Events.create](https://developers.facebook.com/docs/reference/rest/... |
Can I find the path of the executable running a python script from within the python script? | 2,691,655 | 7 | 2010-04-22T14:24:19Z | 2,691,679 | 8 | 2010-04-22T14:27:36Z | [
"python",
"introspection"
] | Is there a way to retreive the path of the executable that is running the current python script (from within the python script)? | That should do what you want
```
>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> import os
>>> os.path.dirname(sys.executable)
'C:\\Python26'
``` |
Python text file processing speed issues | 2,691,818 | 9 | 2010-04-22T14:45:23Z | 2,692,221 | 9 | 2010-04-22T15:35:11Z | [
"python",
"perl",
"file-io"
] | I'm having a problem with processing a largeish file in Python. All I'm doing is
```
f = gzip.open(pathToLog, 'r')
for line in f:
counter = counter + 1
if (counter % 1000000 == 0):
print counter
f.close
```
This takes around 10m25s just to open the file, read the lines and increment th... | In Python (at least <= 2.6.x), gzip format parsing is implemented in Python (over zlib). More, it appears to be doing some strange things, namely, decompress **to the end of file** to memory and then discard everything beyond the requested read size (then do it again for next read). **DISCLAIMER**: I've just looked at ... |
use python glob to find a folder that is a 14 digit number | 2,692,706 | 4 | 2010-04-22T16:37:03Z | 2,692,751 | 8 | 2010-04-22T16:43:13Z | [
"python",
"glob"
] | I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp).
I want to use glob to only select the folders that match that pattern. | Since [`glob`](http://docs.python.org/library/glob.html) doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in `[]` are expanded:
```
C:\temp\py>mkdir 12345678901234
C:\temp\py>C:\Python26\python.exe
Python 2.6.2 St... |
How to add columns to sqlite3 python? | 2,693,278 | 5 | 2010-04-22T18:08:36Z | 2,693,299 | 9 | 2010-04-22T18:11:29Z | [
"python",
"sqlite",
"sqlite3"
] | I know this is simple but I can't get it working! I have no probs with insert,update or select commands, Lets say I have a dictionary and I want to populate a table with the column names in the dictionary what is wrong with my one line where I add a column?
```
##create
con = sqlite3.connect('linksauthor.db')
c = con.... | Your paren is misplaced. You probably meant this:
```
c.execute("alter table linksauthor add column '%s' 'float'" % author)
``` |
Prototyping Qt/C++ in Python | 2,693,558 | 24 | 2010-04-22T18:49:26Z | 2,693,823 | 34 | 2010-04-22T19:26:41Z | [
"c++",
"python",
"qt",
"pyqt",
"pyside"
] | I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++.
Is this the right approach, and what tools (bindings, binding generators, IDE) should I use?
Ideally, everything should be available in the Ubuntu repositories so I wouldn't have t... | > I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++. Is this the right approach?
That depends on your goals. Having done both, I'd recommend you stay with Python wherever possible and reasonable. Although it takes a bit of discipline... |
Extract images from PDF without resampling, in python? | 2,693,820 | 20 | 2010-04-22T19:26:14Z | 2,695,387 | 10 | 2010-04-23T00:08:43Z | [
"python",
"image",
"pdf",
"extract",
"pypdf"
] | How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page.
I'm using python 2.7 but can use 3.x if required. | Often in a PDF, the image is simply stored as-is. For example, a PDF with a jpg inserted will have a range of bytes somewhere in the middle that when extracted is a valid jpg file. You can use this to very simply extract byte ranges from the PDF. I wrote about this some time ago, with sample code: [Extracting JPGs from... |
Dynamic function docstring | 2,693,883 | 6 | 2010-04-22T19:36:10Z | 2,694,358 | 7 | 2010-04-22T20:49:17Z | [
"python"
] | I'd like to write a python function that has a dynamically created docstring. In essence for a function `func()` I want `func.__doc__` to be a descriptor that calls a custom `__get__` function create the docstring on request. Then `help(func)` should return the dynamically generated docstring.
The context here is to w... | You can't do what you're looking to do, in the way you want to do it.
From your description it seems like you could do something like this:
```
for tool in find_tools():
def __tool(*arg):
validate_args(tool, args)
return execute_tool(tool, args)
__tool.__name__ = tool.name
__tool.__doc__ =... |
Socket set source port number | 2,694,212 | 6 | 2010-04-22T20:25:24Z | 2,694,244 | 11 | 2010-04-22T20:30:02Z | [
"python",
"sockets",
"port"
] | I'd like to send a specific UDP broadcast packet.. unfortunatly i need to send the udp packet **from** a very specific port for all packet I send.
Let say I broadcast via UDP "BLABLAH", the server will only answer if my incoming packet source port was 1444, if not the packet is discarded.
My broadcast socket setup lo... | You need to `bind` the socket to the specific port you want to send from. The `bind` method takes an address tuple, much like `connect`, though you can use the wildcard address. For example:
```
s.bind(('0.0.0.0', 1444))
``` |
Socket set source port number | 2,694,212 | 6 | 2010-04-22T20:25:24Z | 2,694,251 | 7 | 2010-04-22T20:30:56Z | [
"python",
"sockets",
"port"
] | I'd like to send a specific UDP broadcast packet.. unfortunatly i need to send the udp packet **from** a very specific port for all packet I send.
Let say I broadcast via UDP "BLABLAH", the server will only answer if my incoming packet source port was 1444, if not the packet is discarded.
My broadcast socket setup lo... | Use `s.bind(('', port))`. |
In Python, how do I decode GZIP encoding? | 2,695,152 | 22 | 2010-04-22T23:10:11Z | 2,695,466 | 21 | 2010-04-23T00:38:44Z | [
"python",
"http",
"text",
"encoding",
"ascii"
] | I downloaded a webpage in my python script.
In most cases, this works fine.
However, this one had a response header: GZIP encoding, and when I tried to print the source code of this web page, it had all symbols in my putty.
How do decode this to regular text? | Decompress your byte stream using the built-in gzip module.
If you have any problems, do show the exact minimal code that you used, the exact error message and traceback, together with the result of `print repr(your_byte_stream[:100])`
**Further information**
**1.** For an explanation of the gzip/zlib/deflate confus... |
In Python, how do I decode GZIP encoding? | 2,695,152 | 22 | 2010-04-22T23:10:11Z | 2,695,575 | 51 | 2010-04-23T01:10:51Z | [
"python",
"http",
"text",
"encoding",
"ascii"
] | I downloaded a webpage in my python script.
In most cases, this works fine.
However, this one had a response header: GZIP encoding, and when I tried to print the source code of this web page, it had all symbols in my putty.
How do decode this to regular text? | I use zlib to decompress gzipped content from web.
```
import zlib
...
# f=urllib2.urlopen(url)
decompressed_data=zlib.decompress(f.read(), 16+zlib.MAX_WBITS)
``` |
In Python, how do I decode GZIP encoding? | 2,695,152 | 22 | 2010-04-22T23:10:11Z | 2,696,477 | 7 | 2010-04-23T05:50:06Z | [
"python",
"http",
"text",
"encoding",
"ascii"
] | I downloaded a webpage in my python script.
In most cases, this works fine.
However, this one had a response header: GZIP encoding, and when I tried to print the source code of this web page, it had all symbols in my putty.
How do decode this to regular text? | I use something like that:
```
f = urllib2.urlopen(request)
data = f.read()
try:
from cStringIO import StringIO
from gzip import GzipFile
data2 = GzipFile('', 'r', 0, StringIO(data)).read()
data = data2
except:
#print "decompress error %s" % err
pass
return data
``` |
Jinja2 returns "None" string for Google App Engine models | 2,695,180 | 2 | 2010-04-22T23:15:57Z | 4,425,654 | 14 | 2010-12-13T03:44:47Z | [
"python",
"google-app-engine",
"jinja2"
] | Google App Engine models, likeso:
```
from google.appengine.ext.db import Model
class M(Model):
name = db.StringProperty()
```
Then in a Jinja2 template called from a Django view with an in instance of `M` passed in as `m`:
```
The name of this M is {{ m.name }}.
```
When `m` is initialized without `name` bein... | You might also want to consider using Jinja2's "or"...
```
The name of this M is {{ m.name or ''}}.
```
If `bool(m.name) == False`, this will show `The name of this M is .`
---
If `m.name == False` and you want to display it as the string "False", you can use Jinja2's "default" filter:
```
The name of this M is {{... |
`strip`ing the results of a split in python | 2,695,464 | 2 | 2010-04-23T00:37:32Z | 2,695,485 | 7 | 2010-04-23T00:44:45Z | [
"python",
"parsing"
] | i'm trying to do something pretty simple:
```
line = "name : bob"
k, v = line.lower().split(':')
k = k.strip()
v = v.strip()
```
is there a way to combine this into one line somehow? i found myself writing this over and over again when making parsers, and sometimes this involves way more than just two variabl... | ```
k, v = [x.strip() for x in line.lower().split(':')]
``` |
Convert a list of strings [ '3', '1', '2' ] to a list of sorted integers [1, 2, 3] | 2,695,472 | 4 | 2010-04-23T00:40:33Z | 2,695,489 | 19 | 2010-04-23T00:45:51Z | [
"python",
"string",
"list",
"sorting",
"integer"
] | I have a list of integers in string representation, similar to the following:
```
L1 = ['11', '10', '13', '12',
'15', '14', '1', '3',
'2', '5', '4', '7',
'6', '9', '8']
```
I need to make it a list of integers like:
```
L2 = [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
```
Finally... | You could do it in one step like this:
```
L3 = sorted(map(int, L1))
```
In more detail, here are the steps:
```
>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> L1
['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> map(int, L1)
[11, 10... |
removing pairs of elements from numpy arrays that are NaN (or another value) in Python | 2,695,503 | 10 | 2010-04-23T00:49:58Z | 2,699,169 | 27 | 2010-04-23T14:06:25Z | [
"python",
"arrays",
"numpy",
"scipy"
] | I have an array with two columns in numpy. For example:
```
a = array([[1, 5, nan, 6],
[10, 6, 6, nan]])
a = transpose(a)
```
I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs that meet a certain condition, in this case if they are NaN. The obvious way I can th... | If you want to take only the rows that have no NANs, this is the expression you need:
```
>>> import numpy as np
>>> a[~np.isnan(a).any(1)]
array([[ 1., 10.],
[ 5., 6.]])
```
If you want the rows that do not have a specific number among its elements, e.g. 5:
```
>>> a[~(a == 5).any(1)]
array([[ 1., 10.... |
Python: list and string matching | 2,696,880 | 8 | 2010-04-23T07:26:06Z | 2,696,887 | 13 | 2010-04-23T07:27:22Z | [
"python",
"match"
] | I have following:
```
temp = "aaaab123xyz@+"
lists = ["abc", "123.35", "xyz", "AND+"]
for list in lists
if re.match(list, temp, re.I):
print "The %s is within %s." % (list,temp)
```
The re.match is only match the beginning of the string, How to I match substring in between too. | You can use `re.search` instead of `re.match`.
It also seems like you don't really need regular expressions here. Your regular expression `123.35` probably doesn't do what you expect because the dot matches anything.
If this is the case then you can do simple string containment using `x in s`. |
Python: list and string matching | 2,696,880 | 8 | 2010-04-23T07:26:06Z | 2,696,888 | 11 | 2010-04-23T07:27:27Z | [
"python",
"match"
] | I have following:
```
temp = "aaaab123xyz@+"
lists = ["abc", "123.35", "xyz", "AND+"]
for list in lists
if re.match(list, temp, re.I):
print "The %s is within %s." % (list,temp)
```
The re.match is only match the beginning of the string, How to I match substring in between too. | Use [`re.search`](http://docs.python.org/library/re.html#re.search) or just use in `if l in temp:`
**Note**: built-in type `list` should not be shadowed, so `for l in lists:` is better |
Python Equivalent of setInterval()? | 2,697,039 | 12 | 2010-04-23T08:02:29Z | 14,035,296 | 14 | 2012-12-26T01:59:27Z | [
"python",
"setinterval"
] | Does Python have a function similar to JavaScript's `setInterval()`?
Thanks | This might be the correct snippet you were looking for:
```
import threading
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
``` |
Cython Speed Boost vs. Usability | 2,697,275 | 30 | 2010-04-23T08:48:52Z | 2,697,744 | 14 | 2010-04-23T10:17:46Z | [
"python",
"performance",
"cython"
] | I just came across Cython, while I was looking out for ways to optimize Python code. I read various posts on stackoverflow, the python wiki and read the article "General Rules for Optimization".
Cython is something which grasps my interest the most; instead of writing C-code for yourself, you can choose to have other ... | Cython is not another interpreter. It generates c-extensions for python, from python(-like) code. `cython test.pyx` will only generate a 'test.c' file, which (once compiled) can be used by python just like a normal python library.
That means that you are only measuring the time it takes for cython to translate your py... |
Cython Speed Boost vs. Usability | 2,697,275 | 30 | 2010-04-23T08:48:52Z | 2,699,348 | 8 | 2010-04-23T14:30:57Z | [
"python",
"performance",
"cython"
] | I just came across Cython, while I was looking out for ways to optimize Python code. I read various posts on stackoverflow, the python wiki and read the article "General Rules for Optimization".
Cython is something which grasps my interest the most; instead of writing C-code for yourself, you can choose to have other ... | * `cython test.pyx` doesn't actually run your program. The `cython` binary is for processing your Cython code into a Python extension module. You would have to import it in Python to run it.
* `#!/usr/bin/python` isn't the best shebang line for Python scripts. `#!/usr/bin/env python` is generally preferred, which runs ... |
Cython Speed Boost vs. Usability | 2,697,275 | 30 | 2010-04-23T08:48:52Z | 2,700,143 | 35 | 2010-04-23T16:11:12Z | [
"python",
"performance",
"cython"
] | I just came across Cython, while I was looking out for ways to optimize Python code. I read various posts on stackoverflow, the python wiki and read the article "General Rules for Optimization".
Cython is something which grasps my interest the most; instead of writing C-code for yourself, you can choose to have other ... | The other answers have already explained how you were just compiling the Cython code, not executing it. However, I thought that you might want to know how much faster Cython can make your code. When I compiled the code you have (though I ran the function from from a different module) with [`distutils`](http://docs.pyth... |
Cython Speed Boost vs. Usability | 2,697,275 | 30 | 2010-04-23T08:48:52Z | 2,994,088 | 7 | 2010-06-08T00:29:51Z | [
"python",
"performance",
"cython"
] | I just came across Cython, while I was looking out for ways to optimize Python code. I read various posts on stackoverflow, the python wiki and read the article "General Rules for Optimization".
Cython is something which grasps my interest the most; instead of writing C-code for yourself, you can choose to have other ... | A big point that seems to be missing: Cython is not a strict superset of Python. There are some features that Python supports, but Cython does not. Most notably, generators and lambdas (but they are coming). |
Python syntax error: can't assign to operator in module but works in interpreter | 2,697,610 | 8 | 2010-04-23T09:52:12Z | 2,697,635 | 12 | 2010-04-23T09:56:57Z | [
"python",
"syntax"
] | I have a string `a` and I would like to split it in half depending on its length, so I have
```
a-front = len(a) / 2 + len(a) % 2
```
this works fine in the interpreter but when i run the module from the command line python gives me a `SyntaxError: can't assign to operator`. What could be the issue here. | You might mistype hyphen and underscore, try
```
a_front = len(a) / 2 + len(a) % 2
``` |
Multiprocessing Bomb | 2,697,640 | 32 | 2010-04-23T09:57:54Z | 2,697,679 | 43 | 2010-04-23T10:03:35Z | [
"python",
"multiprocessing"
] | I was working the following example from [Doug Hellmann](http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html) tutorial on multiprocessing:
```
import multiprocessing
def worker():
"""worker function"""
print 'Worker'
return
if __name__ == '__main__':
jobs = []
for i in range(5):
... | On Windows there is no `fork()` routine, so `multiprocessing` imports the current module to get access to the `worker` function. Without the `if` statement the child process starts its own children and so on. |
cx_Oracle and output variables | 2,698,008 | 7 | 2010-04-23T11:09:04Z | 2,699,478 | 7 | 2010-04-23T14:48:29Z | [
"python",
"oracle",
"oracle10g",
"cx-oracle"
] | I'm trying to do this again an Oracle 10 database:
```
cursor = connection.cursor()
lOutput = cursor.var(cx_Oracle.STRING)
cursor.execute("""
BEGIN
%(out)s := 'N';
END;""",
{'out' : lOutput})
print lOutput.value
```
but I'm getting
```
DatabaseError: ORA-01036: ill... | Yes, you can do anonymous PL/SQL blocks. Your bind variable for the output parameter is not in the correct format. It should be `:out` instead of `%(out)s`
```
cursor = connection.cursor()
lOutput = cursor.var(cx_Oracle.STRING)
cursor.execute("""
BEGIN
:out := 'N';
END;""",
... |
How to start a program with Python? | 2,698,331 | 2 | 2010-04-23T12:11:25Z | 2,698,347 | 8 | 2010-04-23T12:15:10Z | [
"python",
"load"
] | How to start a program with Python?
I thougt this would be very easy like:
```
open(r"C:\Program Files\Mozilla Firefox\Firefox.exe")
```
But nothing happens.
How to do this?
Thanks in advance. | You are opening the file to read its content, instead try subprocess module
<http://docs.python.org/library/subprocess.html>
```
import subprocess
subprocess.Popen([r"C:\Program Files\Mozilla Firefox\Firefox.exe"])
``` |
How to start a program with Python? | 2,698,331 | 2 | 2010-04-23T12:11:25Z | 2,698,366 | 13 | 2010-04-23T12:17:59Z | [
"python",
"load"
] | How to start a program with Python?
I thougt this would be very easy like:
```
open(r"C:\Program Files\Mozilla Firefox\Firefox.exe")
```
But nothing happens.
How to do this?
Thanks in advance. | In general you can do that using `subprocess.call`
```
>>> from subprocess import call
>>> call(r"C:\Program Files\Mozilla Firefox\Firefox.exe")
```
But if all you want to do is open a page in a browser you can do:
```
>>> import webbrowser
>>> webbrowser.open('http://stackoverflow.com/')
True
```
See <http://docs.... |
What is __path__ useful for? | 2,699,287 | 36 | 2010-04-23T14:22:27Z | 2,699,333 | 25 | 2010-04-23T14:28:46Z | [
"python",
"path",
"module"
] | I had never noticed the `__path__` attribute that gets defined on some of my packages before today. According to the documentation:
> Packages support one more special
> attribute, `__path__`. This is
> initialized to be a list containing
> the name of the directory holding the
> packageâs `__init__.py` before the c... | If you change `__path__`, you can force the interpreter to look in a different directory for modules belonging to that package.
This would allow you to, e.g., load different versions of the same module based on runtime conditions. You might do this if you wanted to use different implementations of the same functionali... |
What is __path__ useful for? | 2,699,287 | 36 | 2010-04-23T14:22:27Z | 2,700,358 | 7 | 2010-04-23T16:45:54Z | [
"python",
"path",
"module"
] | I had never noticed the `__path__` attribute that gets defined on some of my packages before today. According to the documentation:
> Packages support one more special
> attribute, `__path__`. This is
> initialized to be a list containing
> the name of the directory holding the
> packageâs `__init__.py` before the c... | In addition to selecting different versions of a module based on runtime conditions as Syntactic says, this functionality also would allow you to break up your package into multiple pieces / downloads / installs while maintaining the appearance of a single logical package.
Consider the following.
* I have two package... |
What is __path__ useful for? | 2,699,287 | 36 | 2010-04-23T14:22:27Z | 2,700,924 | 18 | 2010-04-23T18:12:04Z | [
"python",
"path",
"module"
] | I had never noticed the `__path__` attribute that gets defined on some of my packages before today. According to the documentation:
> Packages support one more special
> attribute, `__path__`. This is
> initialized to be a list containing
> the name of the directory holding the
> packageâs `__init__.py` before the c... | This is usually used with [pkgutil](http://docs.python.org/library/pkgutil.html) to let a package be laid out across the disk. E.g., zope.interface and zope.schema are separate distributions (`zope` is a "namespace package"). You might have zope.interface installed in `/usr/lib/python2.6/site-packages/zope/interface/`,... |
Dropping Root Permissions In Python | 2,699,907 | 35 | 2010-04-23T15:40:55Z | 2,699,996 | 47 | 2010-04-23T15:53:50Z | [
"python",
"linux",
"unix",
"permissions",
"root"
] | I'd like to have a Python program start listening on port 80, but after that execute without root permissions. Is there a way to drop root or to get port 80 without it? | You won't be able to open a server on port 80 without root privileges, this is a restriction on the OS level. So the only solution is to drop root privileges after you have opened the port.
Here is a possible solution to drop root privileges in Python: [Dropping privileges in Python](http://antonym.org/2005/12/droppin... |
Dropping Root Permissions In Python | 2,699,907 | 35 | 2010-04-23T15:40:55Z | 8,186,927 | 10 | 2011-11-18T18:05:35Z | [
"python",
"linux",
"unix",
"permissions",
"root"
] | I'd like to have a Python program start listening on port 80, but after that execute without root permissions. Is there a way to drop root or to get port 80 without it? | I recommend using `authbind` to start your Python program, so none of it has to run as root.
<https://en.wikipedia.org/wiki/Authbind> |
How to replace unicode characters by ascii characters in Python (perl script given)? | 2,700,859 | 19 | 2010-04-23T18:01:36Z | 2,701,386 | 13 | 2010-04-23T19:23:45Z | [
"python",
"perl",
"unicode",
"diacritics"
] | I am trying to learn python and couldn't figure out how to translate the following perl script to python:
```
#!/usr/bin/perl -w
use open qw(:std :utf8);
while(<>) {
s/\x{00E4}/ae/;
s/\x{00F6}/oe/;
s/\x{00FC}/ue/;
print;
}
```
The script just changes unicode umlauts to alternative ascii... | * Use the [`fileinput`](http://docs.python.org/library/fileinput.html) module to loop over standard input or a list of files,
* decode the lines you read from UTF-8 to unicode objects
* then map any unicode characters you desire with the [`translate`](https://docs.python.org/2/library/stdtypes.html#str.translate) metho... |
How to replace unicode characters by ascii characters in Python (perl script given)? | 2,700,859 | 19 | 2010-04-23T18:01:36Z | 2,701,901 | 31 | 2010-04-23T20:50:33Z | [
"python",
"perl",
"unicode",
"diacritics"
] | I am trying to learn python and couldn't figure out how to translate the following perl script to python:
```
#!/usr/bin/perl -w
use open qw(:std :utf8);
while(<>) {
s/\x{00E4}/ae/;
s/\x{00F6}/oe/;
s/\x{00FC}/ue/;
print;
}
```
The script just changes unicode umlauts to alternative ascii... | For converting to ASCII you might want to try [ASCII, Dammit](http://www.crummy.com/cgi-bin/msm/map.cgi/ASCII,+Dammit) or [this recipe](http://www.peterbe.com/plog/unicode-to-ascii), which boils down to:
```
>>> title = u"Klüft skräms inför pÃ¥ fédéral électoral groÃe"
>>> import unicodedata
>>> unicodedata.nor... |
Multiply with find and replace | 2,701,063 | 3 | 2010-04-23T18:31:48Z | 2,701,178 | 8 | 2010-04-23T18:49:39Z | [
"python",
"regex",
"sed"
] | Can regular expressions be used to perform arithmetic? Such as find all numbers in a file and multiply them by a scalar value. | You can achieve this using [`re.sub()`](http://docs.python.org/library/re.html#re.sub) with a callback:
```
import re
def repl(matchobj):
i = int(matchobj.group(0))
return str(i * 2)
print re.sub(r'\d+', repl, '1 a20 300c')
```
Output:
```
2 a40 600c
```
From the docs:
> re.sub(pattern, repl, string[,
> coun... |
Most efficient way for a lookup/search in a huge list (python) | 2,701,173 | 21 | 2010-04-23T18:47:52Z | 2,701,189 | 37 | 2010-04-23T18:51:30Z | [
"python",
"search",
"list",
"performance"
] | -- I just parsed a big file and I created a list containing 42.000 strings/words. I want to query [against this list] to check if a given word/string belongs to it. So my question is:
What is the most efficient way for such a lookup?
A first approach is to sort the list (`list.sort()`) and then just use
```
>> if wo... | Don't create a `list`, create a `set`. It does lookups in constant time.
If you don't want the memory overhead of a set then keep a sorted list and search through it with the [`bisect`](http://docs.python.org/library/bisect.html) module.
```
from bisect import bisect_left
def bi_contains(lst, item):
""" efficient... |
Using Python functions in Tkinter.Tcl() | 2,701,909 | 3 | 2010-04-23T20:51:20Z | 2,708,398 | 7 | 2010-04-25T13:36:07Z | [
"python",
"integration",
"tcl",
"dsl"
] | 1. I have a bunch of Python functions. Let's call them `foo`, `bar` and `baz`. They accept variable number of string arguments and does other sophisticated things (like accessing the network).
2. I want the "user" (let's assume he is only familiar with Tcl) to write scripts in Tcl using those functions.
Here's an exam... | With a little experimentation I discovered you can do something like this to create a tcl interpreter, register a python command, and call it from Tcl:
```
import Tkinter
# create the tcl interpreter
tcl = Tkinter.Tcl()
# define a python function
def pycommand(*args):
print "pycommand args:", ", ".join(args)
# ... |
Sphinx autodoc is not automatic enough | 2,701,998 | 92 | 2010-04-23T21:11:53Z | 2,702,067 | 10 | 2010-04-23T21:24:15Z | [
"python",
"python-sphinx"
] | I'm trying to use Sphinx to document a 5,000+ line project in Python. It has about 7 base modules. As far as I know, In order to use autodoc I need to write code like this for each file in my project:
```
.. automodule:: mods.set.tests
:members:
:show-inheritance:
```
This is way too tedious because I have ma... | In each package, the `__init__.py` file can have `.. automodule:: package.module` components for each part of the package.
Then you can `.. automodule:: package` and it mostly does what you want. |
Sphinx autodoc is not automatic enough | 2,701,998 | 92 | 2010-04-23T21:11:53Z | 2,703,173 | 98 | 2010-04-24T04:03:35Z | [
"python",
"python-sphinx"
] | I'm trying to use Sphinx to document a 5,000+ line project in Python. It has about 7 base modules. As far as I know, In order to use autodoc I need to write code like this for each file in my project:
```
.. automodule:: mods.set.tests
:members:
:show-inheritance:
```
This is way too tedious because I have ma... | You can check this [script](http://www.bitbucket.org/etienned/sphinx-autopackage-script/src) that I've made. I think it can help you.
This script parses a directory tree looking for python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. It also creates a modules inde... |
Sphinx autodoc is not automatic enough | 2,701,998 | 92 | 2010-04-23T21:11:53Z | 21,665,947 | 16 | 2014-02-09T22:29:57Z | [
"python",
"python-sphinx"
] | I'm trying to use Sphinx to document a 5,000+ line project in Python. It has about 7 base modules. As far as I know, In order to use autodoc I need to write code like this for each file in my project:
```
.. automodule:: mods.set.tests
:members:
:show-inheritance:
```
This is way too tedious because I have ma... | I do not know whether Sphinx had had [`autosummary`](http://sphinx-doc.org/latest/ext/autosummary.html) extension at the time original question was asked, but for now it is quite possible to set up automatic generation of that kind without using `sphinx-apidoc` or similar script. Below there are settings which work for... |
Fast iterating over first n items of an iterable (not a list) in python | 2,702,158 | 10 | 2010-04-23T21:47:09Z | 2,702,225 | 13 | 2010-04-23T22:00:43Z | [
"iterator",
"performance",
"python",
"generator"
] | I'm looking for a pythonic way of iterating over first `n` items of an iterable (**upd**: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now:
```
count = 0
for item in iterable:
do_something(item)
count += 1
if count >= n: ... | `for item in itertools.islice(iterable, n):` is the most obvious, easy way to do it. It works for arbitrary iterables and is O(n), like would be any sane solution.
It's conceivable that another solution could have better performance; we wouldn't know without timing. I wouldn't recommend bothering with timing unless yo... |
'int' object is not callable | 2,702,344 | 2 | 2010-04-23T22:29:35Z | 2,702,352 | 16 | 2010-04-23T22:31:25Z | [
"python"
] | I'm trying to define a simply `Fraction` class
And I'm getting this error:
```
python fraction.py
Traceback (most recent call last):
File "fraction.py", line 20, in <module>
f.numerator(2)
TypeError: 'int' object is not callable
```
The code follows:
```
class Fraction(object):
def __init__( self, n=0, d=0... | You're using `numerator` as both a method name (`def numerator(...)`) and member variable name (`self.numerator = n`). Use `set_numerator` and `set_denominator` for the method names and it will work.
By the way, Python 2.6 has a built-in [fraction class](http://docs.python.org/library/fractions.html). |
'int' object is not callable | 2,702,344 | 2 | 2010-04-23T22:29:35Z | 2,702,354 | 8 | 2010-04-23T22:32:20Z | [
"python"
] | I'm trying to define a simply `Fraction` class
And I'm getting this error:
```
python fraction.py
Traceback (most recent call last):
File "fraction.py", line 20, in <module>
f.numerator(2)
TypeError: 'int' object is not callable
```
The code follows:
```
class Fraction(object):
def __init__( self, n=0, d=0... | You can't overload the name `numerator` to refer to both the member variable and the method. When you set `self.numerator = n`, you're overwriting the reference to the method, and so when you call `f.numerator(2)`, it's trying to do a method call on the member variable, which is an `int`, and Python doesn't let you do ... |
'int' object is not callable | 2,702,344 | 2 | 2010-04-23T22:29:35Z | 2,702,435 | 7 | 2010-04-23T23:00:03Z | [
"python"
] | I'm trying to define a simply `Fraction` class
And I'm getting this error:
```
python fraction.py
Traceback (most recent call last):
File "fraction.py", line 20, in <module>
f.numerator(2)
TypeError: 'int' object is not callable
```
The code follows:
```
class Fraction(object):
def __init__( self, n=0, d=0... | * You are using `numerator` as both a method name and a name for an instance attribute. Since methods are stored on the class, when you lookup that attribute you get the number, not the method. (Python will look up attributes on the instance before looking at the class.)
That is to say that on the line where you say... |
Operations on Python hashes | 2,702,751 | 10 | 2010-04-24T00:49:12Z | 2,702,761 | 21 | 2010-04-24T00:52:48Z | [
"python",
"math",
"hash",
"dht",
"hashlib"
] | I've got a rather strange problem. For a Distributed Hash Table I need to be able to do some simple math operations on MD5 hashes. These include a sum (numeric sum represented by the hash) and a modulo operation. Now I'm wondering what the best way to implement these operations is.
I'm using hashlib to calculate the ha... | You can use the `hexdigest()` method to get hexadecimal digits, and then convert them to a number:
```
>>> h = hashlib.md5('data')
>>> int(h.hexdigest(), 16)
188041611063492600696317361555123480284L
```
If you already have the output of `digest()`, you can convert it to hexadecimal digits:
```
>>> hexDig = ''.join('... |
Check if the internet cannot be accessed in Python | 2,702,802 | 3 | 2010-04-24T01:11:44Z | 2,702,824 | 8 | 2010-04-24T01:21:48Z | [
"python",
"exception",
"networking",
"urllib2"
] | I have an app that makes a HTTP GET request to a particular URL on the internet. But when the network is down (say, no public wifi - or my ISP is down, or some such thing), I get the following traceback at `urllib2.urlopen`:
```
70, in get
u = urllib2.urlopen(req)
File "/Library/Frameworks/Python.framework/Versi... | You should wrap the request in a try/except statement so that you catch the fault and then let them know.
```
try:
u = urllib2.urlopen(req)
except HTTPError as e:
#inform them of the specific error here (based off the error code)
except URLError as e:
#inform them of the specific error here
except Exception a... |
How can I make this timer run forever? | 2,702,890 | 4 | 2010-04-24T01:54:02Z | 2,702,904 | 7 | 2010-04-24T02:01:16Z | [
"python",
"multithreading",
"timer"
] | ```
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
```
This code only fires the timer once.
How can I make the timer run forever?
Thanks,
**updated**
this is right :
```
import time,sys
def hello():
while True:
print "Hello, Word!"
sys.std... | A `threading.Timer` executes a function *once*. That function can "run forever" if you wish, for example:
```
import time
def hello():
while True:
print "Hello, Word!"
time.sleep(30.0)
```
Using multiple `Timer` instances would consume substantial resources with no real added value. If you want t... |
How can I make this timer run forever? | 2,702,890 | 4 | 2010-04-24T01:54:02Z | 2,702,906 | 7 | 2010-04-24T02:01:51Z | [
"python",
"multithreading",
"timer"
] | ```
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
```
This code only fires the timer once.
How can I make the timer run forever?
Thanks,
**updated**
this is right :
```
import time,sys
def hello():
while True:
print "Hello, Word!"
sys.std... | Just restart (or recreate) the timer within the function:
```
#!/usr/bin/python
from threading import Timer
def hello():
print "hello, world"
t = Timer(2.0, hello)
t.start()
t = Timer(2.0, hello)
t.start()
``` |
Why regular expression's "non-capturing" group is not working | 2,703,029 | 12 | 2010-04-24T02:48:14Z | 2,703,039 | 15 | 2010-04-24T02:54:43Z | [
"python",
"regex"
] | In my snippet below, the non-capturing group `"(?:aaa)"` should be ignored in matching result,
so the result should be `"_bbb"` only.
However, I get `"aaa_bbb"` in matching result; only when I specify group(2) does it show `"_bbb"`.
```
import re
string1 = "aaa_bbb"
print(re.match(r"(?:aaa)(_bbb)", string1).group()... | `group()` and `group(0)` will return the entire match. Subsequent groups are actual capture groups.
```
>>> print (re.match(r"(?:aaa)(_bbb)", string1).group(0))
aaa_bbb
>>> print (re.match(r"(?:aaa)(_bbb)", string1).group(1))
_bbb
>>> print (re.match(r"(?:aaa)(_bbb)", string1).group(2))
Traceback (most recent call las... |
Why regular expression's "non-capturing" group is not working | 2,703,029 | 12 | 2010-04-24T02:48:14Z | 2,703,139 | 33 | 2010-04-24T03:43:52Z | [
"python",
"regex"
] | In my snippet below, the non-capturing group `"(?:aaa)"` should be ignored in matching result,
so the result should be `"_bbb"` only.
However, I get `"aaa_bbb"` in matching result; only when I specify group(2) does it show `"_bbb"`.
```
import re
string1 = "aaa_bbb"
print(re.match(r"(?:aaa)(_bbb)", string1).group()... | I think you're misunderstanding the concept of a "non-capturing group". The text matched by a non-capturing group still becomes part of the overall regex match.
Both the regex `(?:aaa)(_bbb)` and the regex `(aaa)(_bbb)` return `aaa_bbb` as the overall match. The difference is that the first regex has one capturing gro... |
List comprehension, map, and numpy.vectorize performance | 2,703,310 | 8 | 2010-04-24T05:16:33Z | 2,703,327 | 7 | 2010-04-24T05:21:05Z | [
"python",
"performance",
"numpy",
"list-comprehension"
] | I have a function foo(i) that takes an integer and takes a significant amount of time to execute. Will there be a significant performance difference between any of the following ways of initializing *a*:
```
a = [foo(i) for i in xrange(100)]
a = map(foo, range(100))
vfoo = numpy.vectorize(foo)
a = vfoo(range(100))
`... | If the function itself takes a significant amount of time to execute, it's irrelevant how you map its output to an array. Once you start getting into arrays of millions of numbers, though, numpy can save you a significant amount of memory. |
List comprehension, map, and numpy.vectorize performance | 2,703,310 | 8 | 2010-04-24T05:16:33Z | 2,703,428 | 9 | 2010-04-24T06:10:33Z | [
"python",
"performance",
"numpy",
"list-comprehension"
] | I have a function foo(i) that takes an integer and takes a significant amount of time to execute. Will there be a significant performance difference between any of the following ways of initializing *a*:
```
a = [foo(i) for i in xrange(100)]
a = map(foo, range(100))
vfoo = numpy.vectorize(foo)
a = vfoo(range(100))
`... | the first comment i have is that you should use `xrange(`) or `range()` in all of your examples. if you mix them, then you're comparing apples and oranges.
i second @Gabe's notion that if you have a lot of data structures and they are large, then numpy should win overall... just keep in mind most of the time C is fast... |
List comprehension, map, and numpy.vectorize performance | 2,703,310 | 8 | 2010-04-24T05:16:33Z | 2,704,693 | 16 | 2010-04-24T13:55:41Z | [
"python",
"performance",
"numpy",
"list-comprehension"
] | I have a function foo(i) that takes an integer and takes a significant amount of time to execute. Will there be a significant performance difference between any of the following ways of initializing *a*:
```
a = [foo(i) for i in xrange(100)]
a = map(foo, range(100))
vfoo = numpy.vectorize(foo)
a = vfoo(range(100))
`... | * Why are you optimizing this? Have you written working, tested code, then examined your algorithm [profiled](http://docs.python.org/library/profile.html) your code and found that optimizing this will have an effect? Are you doing this in a deep inner loop where you found you are spending your time? If not, don't bothe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.