content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python: Memory usage and optimization when modifying lists
The problem
My concern is the following: I am storing a relativity large dataset in a classical python list and in order to process the data I must iterate over the list several times, perform some operations on the elements, and often pop an item out of t... | Python: Memory usage and optimization when modifying lists | The problem
My concern is the following: I am storing a relativity large dataset in a classical python list and in order to process the data I must iterate over the list several times, perform some operations on the elements, and often pop an item out of the list.
It seems that deleting one item out of a Python list co... | [
"Without knowing the specifics of what you're doing with this list, it's hard to know exactly what would be best in this case. If your processing stage depends on the current index of the list element, this won't work, but if not, it appears you've left off the most Pythonic (and in many ways, easiest) approach: g... | [
6,
4,
3,
3,
2,
2
] | [] | [] | [
"iteration",
"list",
"memory",
"optimization",
"python"
] | stackoverflow_0002631053_iteration_list_memory_optimization_python.txt |
Q:
Convert list to sequence of variables
I was wondering if this was possible...
I have a sequence of variables that have to be assigned to a do.something (a, b) a and b variables accordingly.
Something like this:
# # Have a list of sequenced variables.
list = 2:90 , 1:140 , 3:-40 , 4:60
# # "Template" on where to a... | Convert list to sequence of variables | I was wondering if this was possible...
I have a sequence of variables that have to be assigned to a do.something (a, b) a and b variables accordingly.
Something like this:
# # Have a list of sequenced variables.
list = 2:90 , 1:140 , 3:-40 , 4:60
# # "Template" on where to assign the variables from the list.
do.s... | [
"arglist = [(2, 90), (1, 140), (3, -40), (4, 60)]\nfor args in arglist:\n do.something(*args)\n time.sleep(1)\n print \"Did something (%d,%d)\" % args\n\nThe * means \"use the values in this tuple as the arguments\". Hint: you can do the same with keyword arguments by using ** and a dict.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0002633609_python.txt |
Q:
Python calling class methods with the wrong number of parameters
I'm just beginning to learn python. I wrote an example script to test OOP in python, but something very odd has happened. When I call a class method, Python is calling the function with one more parameter than given.
Here is the code:
1. class Ba... | Python calling class methods with the wrong number of parameters | I'm just beginning to learn python. I wrote an example script to test OOP in python, but something very odd has happened. When I call a class method, Python is calling the function with one more parameter than given.
Here is the code:
1. class Bar:
2. num1,num2 = 0,0
3. def __init__(num1,num2):
4. num1,num2 ... | [
"The first argument passed to an instance method is the instance itself. Typically this is called self when defining the function:\n def __init__(self, num1, num2):\n\nConsider reading the tutorial.\n",
"Couple things:\n\nYour class is named Bar but you're calling it as bar(a, b). Change that to Bar(a, b) to so... | [
7,
5,
3,
1,
1
] | [] | [] | [
"methods",
"oop",
"parameters",
"python"
] | stackoverflow_0002633775_methods_oop_parameters_python.txt |
Q:
XCode 3.2 Ruby and Python templates
Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.
Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get th... | XCode 3.2 Ruby and Python templates | Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.
Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again?
I found som... | [
"The folder for application templates in 3.2 is:\n/Developer/Library/Xcode/Project Templates/Application\nTemplates for python are at:\nhttp://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/Project%20Templates/\nuse:\n$svn co <address of template you want> /Developer/Library/Xcode/Project Templates/Application/<... | [
6,
5,
3,
1,
0
] | [] | [] | [
"cocoa",
"pyobjc",
"python",
"ruby",
"xcode"
] | stackoverflow_0001382252_cocoa_pyobjc_python_ruby_xcode.txt |
Q:
Efficient JSON encoding for data that may be binary, but is often text
I need to send a JSON packet across the wire with the contents of an arbitrary file. This may be a binary file (like a ZIP file), but most often it will be plain ASCII text.
I'm currently using base64 encoding, which handles all files, but it i... | Efficient JSON encoding for data that may be binary, but is often text | I need to send a JSON packet across the wire with the contents of an arbitrary file. This may be a binary file (like a ZIP file), but most often it will be plain ASCII text.
I'm currently using base64 encoding, which handles all files, but it increases the size of the data significantly - even if the file is ASCII to b... | [
"Use quoted-printable encoding. Any language should support that.\nhttp://en.wikipedia.org/wiki/Quoted-printable\n"
] | [
2
] | [] | [] | [
"c++",
"encoding",
"java",
"json",
"python"
] | stackoverflow_0002634135_c++_encoding_java_json_python.txt |
Q:
Annoying Twisted Python problem
I'm trying to answer the following question out of personal interest:
What is the fastest way to send 100,000 HTTP requests in Python?
And this is what I have came up so far, but I'm experiencing something very stange.
When installSignalHandlers is True, it just hangs. I can see tha... | Annoying Twisted Python problem | I'm trying to answer the following question out of personal interest:
What is the fastest way to send 100,000 HTTP requests in Python?
And this is what I have came up so far, but I'm experiencing something very stange.
When installSignalHandlers is True, it just hangs. I can see that the DelayedCall instances are in re... | [
"You're using waaaaay too much \"reactor calls\" (for example, there's a good chance that agent.request calls into the reactor) from the main thread. I'm not sure if that's your problem, but it's still not supported -- the only reactor calls to make from the non-reactor thread is reactor.callFromThread.\nAlso, the ... | [
6
] | [] | [] | [
"python",
"reactor",
"twisted"
] | stackoverflow_0002634272_python_reactor_twisted.txt |
Q:
Google App Engine : PolyModel + SelfReferenceProperty
Is a PolyModel-based class able to be used as a SelfReferenceProperty ?
I have the below code :
class BaseClass(polymodel.PolyModel):
attribute1 = db.IntegerProperty()
attribute2 = db.StringProperty()
class ParentClass(BaseClass):
attribute3 = db.S... | Google App Engine : PolyModel + SelfReferenceProperty | Is a PolyModel-based class able to be used as a SelfReferenceProperty ?
I have the below code :
class BaseClass(polymodel.PolyModel):
attribute1 = db.IntegerProperty()
attribute2 = db.StringProperty()
class ParentClass(BaseClass):
attribute3 = db.StringProperty()
class ChildClass(BaseClass):
parent = ... | [
"It's a lie to say I changed nothing here. I actually had to change \"parent\" attribute to \"parent_ref\". Also the references didn't work as I expected until I changed from SelfReferenceProperty to ReferenceProperty(Parent, collection_name = 'children')\nBut the end result is that polymorphic self-referencing do... | [
0
] | [] | [] | [
"google_app_engine",
"polymodel",
"python"
] | stackoverflow_0002634101_google_app_engine_polymodel_python.txt |
Q:
python webbrowser.open(url)
httpd = make_server('', 80, server)
webbrowser.open(url)
httpd.serve_forever()
This works cross platform except when I launch it on a putty ssh terminal.
How can i trick the console in opening the w3m browser in a separate process so it can continue to launch the server?
Or if it is no... | python webbrowser.open(url) | httpd = make_server('', 80, server)
webbrowser.open(url)
httpd.serve_forever()
This works cross platform except when I launch it on a putty ssh terminal.
How can i trick the console in opening the w3m browser in a separate process so it can continue to launch the server?
Or if it is not possible to skip webbrowser.ope... | [
"Maybe use threads? Either put the server setup separate from the main thread or the browsweropen instead as in:\nimport threading\nimport webbrowser\n\ndef start_browser(server_ready_event, url):\n print \"[Browser Thread] Waiting for server to start\"\n server_ready_event.wait()\n print \"[Browser Thread... | [
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002634235_python.txt |
Q:
Using __str__ representation for printing objects in containers
I've noticed that when an instance with an overloaded __str__ method is passed to the print function as an argument, it prints as intended. However, when passing a container that contains one of those instances to print, it uses the __repr__ method in... | Using __str__ representation for printing objects in containers | I've noticed that when an instance with an overloaded __str__ method is passed to the print function as an argument, it prints as intended. However, when passing a container that contains one of those instances to print, it uses the __repr__ method instead. That is to say, print(x) displays the correct string represent... | [
"The problem with the container using the objects' __str__ would be the total ambiguity -- what would it mean, say, if print L showed [1, 2]? L could be ['1, 2'] (a single item list whose string item contains a comma) or any of four 2-item lists (since each item can be a string or int). The ambiguity of type is c... | [
13,
5,
1
] | [] | [] | [
"operator_overloading",
"python"
] | stackoverflow_0002634552_operator_overloading_python.txt |
Q:
How can I run a GAE application on a private server?
I want to develop a GAE application using python, but I fear that Google will be the only company able to host the code. Is it possible to run a GAE app on a private server or other host?
(Note that a previous version of the question incorrectly referred to GWT)... | How can I run a GAE application on a private server? | I want to develop a GAE application using python, but I fear that Google will be the only company able to host the code. Is it possible to run a GAE app on a private server or other host?
(Note that a previous version of the question incorrectly referred to GWT).
| [
"Assuming that by GWT you mean GAE (GWT is for Java and anybody can serve it), appscale is probably the best way to host GAE applications anywhere you'd like (including on Amazon EC2 and in your own data center). Anybody can also start a business providing GAE service with AppScale (on Amazon, their own data cente... | [
9,
1
] | [] | [] | [
"google_app_engine",
"hosting",
"python"
] | stackoverflow_0002634543_google_app_engine_hosting_python.txt |
Q:
Easiest way to automatically download required modules in Python?
I would like to release a python module I wrote which depends on several packages. What's the easiest way to make it so these packages are programmatically downloaded just in case they are not available on the system that's being run? Most of these... | Easiest way to automatically download required modules in Python? | I would like to release a python module I wrote which depends on several packages. What's the easiest way to make it so these packages are programmatically downloaded just in case they are not available on the system that's being run? Most of these modules should be available by easy_install or pip or something like t... | [
"pip uses requirements files, which have a very straightforward format.\nFor more Python packaging tooling recommendations, see the latest from the Python Packaging Authority (PyPA).\n",
"See the setuptools docs on how to declare your dependencies -- this will allow easy_install to find, download and install all ... | [
21,
4
] | [] | [] | [
"module",
"python",
"python_module",
"setuptools"
] | stackoverflow_0002634874_module_python_python_module_setuptools.txt |
Q:
Django exclude(**kwargs) help
I had a question for you, something that I can't seem to find the solution for... Basically, I have a model called Environment, and I am passing all of them to a view, and there are particular environments that I would like to exclude. Now, I know there is a exclude function on a quer... | Django exclude(**kwargs) help | I had a question for you, something that I can't seem to find the solution for... Basically, I have a model called Environment, and I am passing all of them to a view, and there are particular environments that I would like to exclude. Now, I know there is a exclude function on a queryset, but I can't seem to figure ou... | [
"The way to do this would be:\nEnviroment.objects.exclude(name=\"env1\").exclude(name=\"env2\")\n\nor\nEnviroment.objects.exclude(Q(name=\"env1\") | Q(name=\"env2\"))\n\n",
"Enviroment.objects.exclude(name__in=[\"env1\",\"env2\"])\n"
] | [
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002634071_django_python.txt |
Q:
mount command pid
Trying to mount a device and get the pid of mount command.
cmd="/bin/mount /dev/sda1 /mnt"
os.system(cmd)
Now how to obtain the pid of mount command? There plenty of mounted device available on my system, something like ps | grep mount won't work.
A:
As the comments suggest I'm not sure how... | mount command pid | Trying to mount a device and get the pid of mount command.
cmd="/bin/mount /dev/sda1 /mnt"
os.system(cmd)
Now how to obtain the pid of mount command? There plenty of mounted device available on my system, something like ps | grep mount won't work.
| [
"As the comments suggest I'm not sure how useful it is to get the mount pid, but if you use the subprocess module you can easily get the pid.\n>>> import subprocess\n>>> p = subprocess.Popen(\"ls\", shell=True)\n>>> p.pid\n4136\n>>>\n\n"
] | [
2
] | [] | [] | [
"mount",
"pid",
"python"
] | stackoverflow_0002635210_mount_pid_python.txt |
Q:
Extending Python’s int type to accept only values within a given range
I would like to create a custom data type which basically behaves like an ordinary int, but with the value restricted to be within a given range. I guess I need some kind of factory function, but I cannot figure out how to do it.
myType = MyCu... | Extending Python’s int type to accept only values within a given range | I would like to create a custom data type which basically behaves like an ordinary int, but with the value restricted to be within a given range. I guess I need some kind of factory function, but I cannot figure out how to do it.
myType = MyCustomInt(minimum=7, maximum=49, default=10)
i = myType(16) # OK
i = myType... | [
"Use __new__ to override the construction of immutable types:\ndef makeLimitedInt(minimum, maximum, default):\n class LimitedInt(int):\n def __new__(cls, x= default, *args, **kwargs):\n instance= int.__new__(cls, x, *args, **kwargs)\n if not minimum<=instance<=maximum:\n ... | [
6,
1,
1,
0
] | [] | [] | [
"python",
"types"
] | stackoverflow_0002635148_python_types.txt |
Q:
How to read pdf, ppt, xl, doc files content into a string in php/python
Pls suggest me any inbuilt command or package?
A:
well, it shouldn't be too hard to find something from the net. Here's one for Python called pyPDF. Check PyPi also for such modules. As for reading doc,ppt,xls files, one way is to use COM.
... | How to read pdf, ppt, xl, doc files content into a string in php/python | Pls suggest me any inbuilt command or package?
| [
"well, it shouldn't be too hard to find something from the net. Here's one for Python called pyPDF. Check PyPi also for such modules. As for reading doc,ppt,xls files, one way is to use COM.\n",
"The content as in \"binary\" or the actual text?\nTo read the file as \"binary\" in php:\nhttp://php.net/manual/en/fun... | [
2,
1,
0
] | [] | [] | [
"file",
"php",
"python"
] | stackoverflow_0002635757_file_php_python.txt |
Q:
Google appengine authentication on iPhone web app on the home screen
I'm using Google appengine for developing an web application that is meant to be used on both the browser and iphone. I have purchased a domain name for this application, so that I have a pretty URL. I've used the User API for authentication. Thi... | Google appengine authentication on iPhone web app on the home screen | I'm using Google appengine for developing an web application that is meant to be used on both the browser and iphone. I have purchased a domain name for this application, so that I have a pretty URL. I've used the User API for authentication. This works just fine on desktop browsers and iPhone Safari.
The user could ad... | [
"Solved this, and just wanted to post the solution here.\nThe fix was as simple as setting the link href=\"javascript:window.location.href=\\\"whatever\\\";\".\nThe weirdest thing! No idea why I'd be forced to use JS for this.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"iphone",
"iphone_web_app",
"python"
] | stackoverflow_0002612780_google_app_engine_iphone_iphone_web_app_python.txt |
Q:
Python: some newbie questions on sys.stderr and using function as argument
I'm just starting on Python and maybe I'm worrying too much too soon, but anyways...
log = "/tmp/trefnoc.log"
def logThis (text, display=""):
msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
if display != None:
... | Python: some newbie questions on sys.stderr and using function as argument | I'm just starting on Python and maybe I'm worrying too much too soon, but anyways...
log = "/tmp/trefnoc.log"
def logThis (text, display=""):
msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
if display != None:
print msg + display
logfile = open(log, "a")
logfile.write(msg + "\n"... | [
"There's no reason for \"logThisAndExit\", it doesn't save you much typing over\nsys.exit(logThis(text)+display)\n\n(compare logThisAndExit(text, display))\nor\nsys.exit(logThis(text))\n\n(compare logThisAndExit(text))\nNot that I'm entirely sure why you like your exit messages formatted as log lines.\nIn answer to... | [
2,
2,
1,
1,
0
] | [] | [] | [
"function_pointers",
"python",
"stderr"
] | stackoverflow_0002634091_function_pointers_python_stderr.txt |
Q:
django + xmppy: send a message to two recipients
I'm trying to use xmpppy for sending jabber-messages from a django-website. This works entirely fine.
However, the message only gets sent to the -first- of the recipients in the list. This happens when I run the following function from django, and also if I run it f... | django + xmppy: send a message to two recipients | I'm trying to use xmpppy for sending jabber-messages from a django-website. This works entirely fine.
However, the message only gets sent to the -first- of the recipients in the list. This happens when I run the following function from django, and also if I run it from an interactive python-shell. The weird part though... | [
"Activate the debug options in xmpppy to see what does the xmpp client.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"xmpppy"
] | stackoverflow_0002635754_django_python_xmpppy.txt |
Q:
Installing a Python program on Linux
I wrote a Python program. I would like to add to it an installation script that will set up everything necessary - like desktop icon, entry in the menu, home directory file, etc.
I'm working on Linux (ubuntu). When a Python program is installed, what needs to happen in general... | Installing a Python program on Linux | I wrote a Python program. I would like to add to it an installation script that will set up everything necessary - like desktop icon, entry in the menu, home directory file, etc.
I'm working on Linux (ubuntu). When a Python program is installed, what needs to happen in general? I know that it probably depends on the n... | [
"If it's a Python program you're trying to package, you should consider using its 'standard' distribution framework distutils. I can't replicate the entire document here but I'd recommend that you read it. Once you're done with that, check out the Hitchhikers guide to packaging which contains details on distribute ... | [
4,
1,
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0002635433_linux_python.txt |
Q:
Why does TheyWorkForYou (TWFY) web API always returns '{}'
I'm calling a web API exposed by TheyWorkForYou (TWFI).
http://www.theyworkforyou.com/api/
I'm using the Python bindings provided by twfython:
http://code.google.com/p/twfython/
I wrote some code to call this API a few months ago, at which time it worked f... | Why does TheyWorkForYou (TWFY) web API always returns '{}' | I'm calling a web API exposed by TheyWorkForYou (TWFI).
http://www.theyworkforyou.com/api/
I'm using the Python bindings provided by twfython:
http://code.google.com/p/twfython/
I wrote some code to call this API a few months ago, at which time it worked fine. But now I dig it out to run it again, no matter what query ... | [
"You can run the getMPs call on their website directly, and it also produces no output. So you're probably right about there actually being no MPs at the moment.\nDo you get the same output if you call getMSPs? This one seems like it should return data.\n",
"From the horse's mouth, MAtthew Somerville at ORG:\nThe... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0002634055_python.txt |
Q:
Where can I find a good tutorial for py2exe?
Can somebody point me at a good tutorial for py2exe? I've read over the official tutorial but it is rather light on details, compared to all the options one can use when building an executable out of a python script. For the record, my python script uses Python 2.5.2,... | Where can I find a good tutorial for py2exe? | Can somebody point me at a good tutorial for py2exe? I've read over the official tutorial but it is rather light on details, compared to all the options one can use when building an executable out of a python script. For the record, my python script uses Python 2.5.2, wxPython/wxWidgets 2.8 and MySQLdb 1.2.2; so if y... | [
"Regarding \"Py2EXE and wxPython\", the page mentions the import statement \"from wxPython.wx import *\". This is the old wxPython (several years old, I think). In my app, I just do \"import wx\", and I don't have any major troubles.\nI have one tip for wxPython and py2exe: you need a manifest if you want your ap... | [
4,
2,
1,
1
] | [] | [] | [
"py2exe",
"python",
"wxpython"
] | stackoverflow_0000176322_py2exe_python_wxpython.txt |
Q:
Optimizing code using PIL
Firstly sorry for the long piece of code pasted below.
This is my first time actually having to worry about performance of an application so I haven't really ever worried about performance.
This piece of code pretty much searches for an image inside another image, it takes 30 seconds to r... | Optimizing code using PIL | Firstly sorry for the long piece of code pasted below.
This is my first time actually having to worry about performance of an application so I haven't really ever worried about performance.
This piece of code pretty much searches for an image inside another image, it takes 30 seconds to run on my computer, converting t... | [
"while not directly performance related you could do some things to improve your code:\nif not Found:\n return \"Not Found\"\n\nis idiomatic way to write condition in Python. You don't need this clause, however, since this return statement could be reached only if image wasn't found.\nin GetImage you should crea... | [
1,
1
] | [] | [] | [
"image",
"performance",
"python"
] | stackoverflow_0002636450_image_performance_python.txt |
Q:
PGU Tiles collision detection
I've been using PGU(Phil's Pygame Utilities) for a while. It has a dictionary called tdata, which is passed as an argument while loading tiles
tdata = { tileno:(agroup, hit_handler, config)}
I'm making a pacman clone in which I have 2 groups : player and ghost, for which I want to col... | PGU Tiles collision detection | I've been using PGU(Phil's Pygame Utilities) for a while. It has a dictionary called tdata, which is passed as an argument while loading tiles
tdata = { tileno:(agroup, hit_handler, config)}
I'm making a pacman clone in which I have 2 groups : player and ghost, for which I want to collision detection with the same type... | [
"I've had a look at the source code at: http://code.google.com/p/pgu/\nIn vid.py (http://code.google.com/p/pgu/source/browse/trunk/pgu/vid.py) there is code for loading tdata information.\nLine 300: def tga_load_tiles(self,fname,size,tdata={}):\nThen on lines 324 and 325:\nagroups,hit,config = tdata[n]\ntile.agroup... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0002611839_pygame_python.txt |
Q:
Python3k ctypes printf
printf returns 1 instead of "Hello World!" which is the desired result.
I googled it and think its because of the changes in the way sequences are treated.
How do I modify the code to print "Hello World!"?
www.mail-archive.com/python-3000@python.org/msg15119.html
import ctypes
msvcrt=ctypes... | Python3k ctypes printf | printf returns 1 instead of "Hello World!" which is the desired result.
I googled it and think its because of the changes in the way sequences are treated.
How do I modify the code to print "Hello World!"?
www.mail-archive.com/python-3000@python.org/msg15119.html
import ctypes
msvcrt=ctypes.cdll.msvcrt
string=b"Hello ... | [
"The first argument needs to be a byte string as well:\nmsvcrt.printf(b\"%s\", string)\n\nThe return value of printf is the number of characters printed, which should be 12 in this case.\nEdit:\nIf you want the string to be returned instead of printed, you can use sprintf instead. This is dangerous and NOT recommen... | [
4
] | [] | [] | [
"ctypes",
"printf",
"python"
] | stackoverflow_0002636597_ctypes_printf_python.txt |
Q:
boost python version
I'm trying to use boost.python library in a C++ project (Windows + VS9) but it always tries to link against pyton25.lib.
Is it possible to link with version 2.6.x of python?
thanks
A:
You need to recompile boost-python library pointing Boost.Build to needed python version.
P.S. This heals a ... | boost python version | I'm trying to use boost.python library in a C++ project (Windows + VS9) but it always tries to link against pyton25.lib.
Is it possible to link with version 2.6.x of python?
thanks
| [
"You need to recompile boost-python library pointing Boost.Build to needed python version.\nP.S. This heals a problem of undefined references while linking with library needed. I beleive you've already turned of autolinking.\n",
"You could try putting -lpython26 when linking\n"
] | [
1,
0
] | [] | [] | [
"boost",
"python"
] | stackoverflow_0002635933_boost_python.txt |
Q:
python bind a type to a variable
I am a Python noob.
I create a class as follows:
class t1:
x = ''
def __init__(self, x):
self.x = x
class t2:
y = ''
z = ''
def __init__(self, x, y, z):
self.y = t1.__init__(x)
self.z = z
Now contrary to C++ or Java, I do not bind the d... | python bind a type to a variable | I am a Python noob.
I create a class as follows:
class t1:
x = ''
def __init__(self, x):
self.x = x
class t2:
y = ''
z = ''
def __init__(self, x, y, z):
self.y = t1.__init__(x)
self.z = z
Now contrary to C++ or Java, I do not bind the data type to y while writing the class ... | [
"No. Variables in Python do not have types - y does not have a type. At any moment in time, y refers to an object, and that object has a type. This:\ny = ''\n\nbinds y to an object of type str. You can change it later to refer to an object of a different type. y itself has no intrinsic type.\nSee Fredrik Lundh... | [
6,
3
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0002636491_python_variables.txt |
Q:
convert a list of booleans to string
How do I convert this:
[True, True, False, True, True, False, True]
Into this:
'AB DE G'
Note: C and F are missing in the output because the corresponding items in the input list are False.
A:
Assuming your list of booleans is not too long:
bools = [True, True, False, True,... | convert a list of booleans to string | How do I convert this:
[True, True, False, True, True, False, True]
Into this:
'AB DE G'
Note: C and F are missing in the output because the corresponding items in the input list are False.
| [
"Assuming your list of booleans is not too long:\nbools = [True, True, False, True, True, False, True]\n\nprint ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools))\n\n",
"You can use string.uppercase instead of chr/ord. This will give you locale-dependent results. For ascii you can use string.as... | [
11,
9,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002635964_python.txt |
Q:
django + south + python: strange behavior when using a text string received as a parameter in a function
this is my first question.
I'm trying to execute a SQL query in django (south migration):
from django.db import connection
# ...
class Migration(SchemaMigration):
# ...
def transform_id_to_pk(self, tabl... | django + south + python: strange behavior when using a text string received as a parameter in a function | this is my first question.
I'm trying to execute a SQL query in django (south migration):
from django.db import connection
# ...
class Migration(SchemaMigration):
# ...
def transform_id_to_pk(self, table):
try:
db.delete_primary_key(table)
except:
pass
finally:
... | [
"The problem is that you're using DB-API parameterization for things that are not SQL data. When you do something like:\ncursor.execute('INSERT INTO table_foo VALUES (%s, %s)', (col1, col2))\n\nthe DB-API module (django's frontend for whatever database you are using, in this case) will know to escape the contents o... | [
4
] | [] | [] | [
"django",
"django_south",
"python",
"string"
] | stackoverflow_0002636839_django_django_south_python_string.txt |
Q:
Using memcache to store obj's in google app engine
I'm trying to use memcache to cache data retrevied from the datastore. Storing stings works fine. But can't one store an object? I get an error "TypeError: 'str' object is not callable" when trying to store with this:
pageData = StandardPage(page)
memcache.add... | Using memcache to store obj's in google app engine | I'm trying to use memcache to cache data retrevied from the datastore. Storing stings works fine. But can't one store an object? I get an error "TypeError: 'str' object is not callable" when trying to store with this:
pageData = StandardPage(page)
memcache.add(memcacheid, pageData, 60)
I've read in the documentati... | [
"You can use db.model_to_protobuf to turn your object into something that can be stored in memcache. Similarly, db.model_from_protobuf will get your object back.\nResource:\nDatastore Functions\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"memcached",
"python"
] | stackoverflow_0002636931_google_app_engine_memcached_python.txt |
Q:
Python file - Want to change it to a function or a class
I have a python program/file that I want to run repeatedly and calculate the averages of some variables over these runs. To do so, I thought it might be convenient to convert this program into a function or a class. One way I can think of is to add a
def Ma... | Python file - Want to change it to a function or a class | I have a python program/file that I want to run repeatedly and calculate the averages of some variables over these runs. To do so, I thought it might be convenient to convert this program into a function or a class. One way I can think of is to add a
def Main():
line at the top and indent every line manually within i... | [
"Yes you are on the right track.\nAdd the def Main(): line\nThen in pydev select all the other code and then hit tab which will indent all the code\nTo make the code runnable from the command line ie let it call the Main function you will need to add some code that is executed when the module is loaded. So at the e... | [
3,
1,
0,
0,
0,
0
] | [] | [] | [
"pydev",
"python"
] | stackoverflow_0002636808_pydev_python.txt |
Q:
Django model manager didn't work with related object when I do aggregated query
I'm having trouble doing an aggregation query on a many-to-many related field.
Here are my models:
class SortedTagManager(models.Manager):
use_for_related_fields = True
def get_query_set(self):
orig_query_set = super(S... | Django model manager didn't work with related object when I do aggregated query | I'm having trouble doing an aggregation query on a many-to-many related field.
Here are my models:
class SortedTagManager(models.Manager):
use_for_related_fields = True
def get_query_set(self):
orig_query_set = super(SortedTagManager, self).get_query_set()
# FIXME `used` is wrongly counted
... | [
"I have figured out what's wrong and how to fix it now :)\n\nAs stated in the Django doc:\n\n\nDjango interprets the first Manager defined in a class as the \"default\" Manager, and several parts of Django will use that Manager exclusively for that model. \n\nIn my case, I should make sure that SortedTagManager is ... | [
2
] | [] | [] | [
"django",
"django_aggregation",
"django_models",
"python"
] | stackoverflow_0002635587_django_django_aggregation_django_models_python.txt |
Q:
Redhat | How to compile Python 2.6 for 64bit
I'm trying to compile Python 2.6 for 64bit, I tried various compile commands but not sure whether those are correct
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
What is the correct syntax ... ?
A:
What exactly doesn't work? Do ... | Redhat | How to compile Python 2.6 for 64bit | I'm trying to compile Python 2.6 for 64bit, I tried various compile commands but not sure whether those are correct
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
What is the correct syntax ... ?
| [
"What exactly doesn't work? Do you get any error message? \nTry simple compilation without installing first:\n$ cd path/to/python/source\n$ ./configure\n$ make all\n... wait for some time ...\n$ make test # this runs python's test suite, you can usually skip this\n$ ./python # note the ./ runs the just installed... | [
1
] | [] | [] | [
"python",
"redhat"
] | stackoverflow_0002637166_python_redhat.txt |
Q:
extract specific element from nested elements using lxml html
Hi all I am having some problems that I think can be attributed to xpath problems. I am using the html module from the lxml package to try and get at some data. I am providing the most simplified situation below, but keep in mind the html I am working w... | extract specific element from nested elements using lxml html | Hi all I am having some problems that I think can be attributed to xpath problems. I am using the html module from the lxml package to try and get at some data. I am providing the most simplified situation below, but keep in mind the html I am working with is much uglier.
<table>
<tr>
<td>
<table>
... | [
"Use:\n//td[text() = 'Header1']/ancestor::table[1]\n\n",
"Find the header you are interested in and then pull out its table.\n\n//u[b = 'Header1']/ancestor::table[1]\n\nor \n\n//td[not(.//table) and .//b = 'Header1']/ancestor::table[1]\n\nNote that // always starts at the document root (!). You can't do:\n\n//tab... | [
3,
2,
0,
0
] | [] | [] | [
"html",
"lxml",
"parsing",
"python",
"xpath"
] | stackoverflow_0002634931_html_lxml_parsing_python_xpath.txt |
Q:
Displaying a Forecast Widget on a website
I am looking for displaying Forecast information in my Django Website.
Do you have any idea of how I can do that ?
I looked at https://registration.weather.com/ursa/wow/ but it is in english and I didn't find anyway to put it in French.
I looked at libgweather, but it didn... | Displaying a Forecast Widget on a website | I am looking for displaying Forecast information in my Django Website.
Do you have any idea of how I can do that ?
I looked at https://registration.weather.com/ursa/wow/ but it is in english and I didn't find anyway to put it in French.
I looked at libgweather, but it didn't helps me a lot.
Do you know how I can do tha... | [
"Here it is : http://france.meteofrance.com/france/accueil/partenaire\n"
] | [
2
] | [] | [] | [
"forecasting",
"python",
"web",
"widget"
] | stackoverflow_0002637690_forecasting_python_web_widget.txt |
Q:
parsing list in python
I have list in python which has following entries
name-1
name-2
name-3
name-4
name-1
name-2
name-3
name-4
name-1
name-2
name-3
name-4
I would like remove name-1 from list except its first appearance -- resultant list should look like
name-1
name-2
name-3
name-4
name-2
name-3
name-4
name-2... | parsing list in python | I have list in python which has following entries
name-1
name-2
name-3
name-4
name-1
name-2
name-3
name-4
name-1
name-2
name-3
name-4
I would like remove name-1 from list except its first appearance -- resultant list should look like
name-1
name-2
name-3
name-4
name-2
name-3
name-4
name-2
name-3
name-4
How to achie... | [
"def remove_but_first( lst, it):\n first = lst.index( it )\n # everything up to the first occurance of it, then the rest of the list without all it\n return lst[:first+1] + [ x for x in lst[first:] if x != it ]\n\ns = [1,2,3,4,1,5,6]\nprint remove_but_first( s, 1)\n\n",
"Assuming name-1 denotes \"the fir... | [
3,
2,
2,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002637480_list_python.txt |
Q:
How do I match contents of an element in XPath (lxml)?
I want to parse HTML with lxml using XPath expressions. My problem is matching for the contents of a tag:
For example given the
<a href="http://something">Example</a>
element I can match the href attribute using
.//a[@href='http://something']
but the given... | How do I match contents of an element in XPath (lxml)? | I want to parse HTML with lxml using XPath expressions. My problem is matching for the contents of a tag:
For example given the
<a href="http://something">Example</a>
element I can match the href attribute using
.//a[@href='http://something']
but the given the expression
.//a[.='Example']
or even
.//a[contains(.,'... | [
"I would try with:\n.//a[text()='Example']\nusing xpath() method:\ntree.xpath(\".//a[text()='Example']\")[0].tag\n\nIf case you would like to use iterfind(), findall(), find(), findtext(), keep in mind that advanced features like value comparison and functions are not available in ElementPath.\n\nlxml.etree support... | [
21
] | [] | [] | [
"lxml",
"predicate",
"python",
"xpath"
] | stackoverflow_0002637760_lxml_predicate_python_xpath.txt |
Q:
Running py.test from emacs
What I would like is for C-c C-c to run py.test and display the output in the other buffer if the name of the file being edited begins with test_, and to normally run py-execute-buffer otherwise. How would I do this? I am using emacs 23.1.1 with python-mode and can access py.test from th... | Running py.test from emacs | What I would like is for C-c C-c to run py.test and display the output in the other buffer if the name of the file being edited begins with test_, and to normally run py-execute-buffer otherwise. How would I do this? I am using emacs 23.1.1 with python-mode and can access py.test from the command line.
| [
"This isn't particularly well-tested; it's just a rough idea.\n(defun py-do-it ()\n (interactive)\n (if (string-match\n (rx bos \"test_\")\n (file-name-nondirectory (buffer-file-name)))\n (compile \"py.test\")\n (py-execute-buffer)))\n\n(add-hook 'python-mode-hook\n (lambda ()\n ... | [
8
] | [] | [] | [
"emacs",
"pytest",
"python"
] | stackoverflow_0002635523_emacs_pytest_python.txt |
Q:
SQL Alchemy related Objects Error
from sqlalchemy.orm import relation, backref
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Date, Sequence
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class GUI_SCENARIO(Base):
__tablename__ = 'GUI_SCENARIO'
... | SQL Alchemy related Objects Error | from sqlalchemy.orm import relation, backref
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Date, Sequence
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class GUI_SCENARIO(Base):
__tablename__ = 'GUI_SCENARIO'
Scenario_ID = Column(Integer, prima... | [
"I believe you should not call mapper(). When you use declarative_base, you define the table, the class and the mapping at once, in a shorthand style.\nI suggest you remove the call to mapper().\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002637705_python_sqlalchemy.txt |
Q:
add a custom RFC822 header via IMAP?
Is there an easy way to add a custom RFC822 header to a message on an IMAP server with imaplib?
I am writing a python-based program that filters my IMAP mail store. When I did this with Procmail I had the option of adding headers. But there doesn't seem to be a way to do that w... | add a custom RFC822 header via IMAP? | Is there an easy way to add a custom RFC822 header to a message on an IMAP server with imaplib?
I am writing a python-based program that filters my IMAP mail store. When I did this with Procmail I had the option of adding headers. But there doesn't seem to be a way to do that with the Python imap implementation.
Specif... | [
"Better option would be to use custom server flags called keywords.\nA keyword is defined by the server implementation. Keywords do not begin with \"\\\". Servers MAY permit the client to define new keywords in the mailbox.\nTo add myflag to the message you can use \nSTORE number +FLAGS (myflag) \n\nto search:\nSE... | [
1,
0
] | [] | [] | [
"imap",
"imaplib",
"python"
] | stackoverflow_0002575805_imap_imaplib_python.txt |
Q:
Python and C++ Sockets converting packet data
First of all, to clarify my goal: There exist two programs written in C in our laboratory. I am working on a Proxy Server (bidirectional) for them (which will also mainpulate the data). And I want to write that proxy server in Python. It is important to know that I kno... | Python and C++ Sockets converting packet data | First of all, to clarify my goal: There exist two programs written in C in our laboratory. I am working on a Proxy Server (bidirectional) for them (which will also mainpulate the data). And I want to write that proxy server in Python. It is important to know that I know close to nothing about these two programs, I only... | [
"You can receive the packet's 50 bytes with a .recv call on a properly connected socked (it might actually take more than one call in the unlikely event the TCP packet gets fragmented, so check incoming length until you have exactly 50 bytes in hand;-).\nAfter that, understanding that C code is puzzling. The assig... | [
4,
3
] | [] | [] | [
"binary",
"c++",
"networking",
"python",
"sockets"
] | stackoverflow_0002637546_binary_c++_networking_python_sockets.txt |
Q:
Porting Python algorithm to C++ - different solution
Thank you all for helping. Below this post I put the corrected version's of both scripts which now produce the equal output.
Hello,
I have written a little brute string generation script in python to generate all possible combinations of an alphabet within a g... | Porting Python algorithm to C++ - different solution | Thank you all for helping. Below this post I put the corrected version's of both scripts which now produce the equal output.
Hello,
I have written a little brute string generation script in python to generate all possible combinations of an alphabet within a given length. It works quite nice, but for the reason I wan... | [
"I think the Python code is also broken but maybe you don't notice because the print is indented by one space too many (hey, now I've seen a Python program with a one-off error!)\nShouldn't the output only happen in the else case? And the reason why the output happens more often is that you call print/cout 4 times.... | [
1,
1,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002638361_c++_python.txt |
Q:
What is faster: multiple `send`s or using buffering?
I'm playing around with sockets in C/Python and I wonder what is the most efficient way to send headers from a Python dictionary to the client socket.
My ideas:
use a send call for every header. Pros: No memory allocation needed. Cons: many send calls -- probab... | What is faster: multiple `send`s or using buffering? | I'm playing around with sockets in C/Python and I wonder what is the most efficient way to send headers from a Python dictionary to the client socket.
My ideas:
use a send call for every header. Pros: No memory allocation needed. Cons: many send calls -- probably error prone; error management should be rather complica... | [
"Because of the way TCP congestion control works, it's more efficient to send data all at once. TCP maintains a window of how much data it will allow to be \"in the air\" (sent but not yet acknowledged). TCP measures the acknowledgments coming back to figure out how much data it can have \"in the air\" without ca... | [
3,
0,
0
] | [] | [] | [
"buffer",
"c",
"python",
"send",
"sockets"
] | stackoverflow_0002638490_buffer_c_python_send_sockets.txt |
Q:
mod_python with Python 2.6 on Windows
How do I install mod_python to run with Python 2.6 on a Windows machine? I could not find an installer for Python 2.6.
I downloaded this installer for (mod_python on Python 2.5): mod_python-3.3.1.win32-py2.5-Apache2.2.exe and extracted it to get PLATLIB and SCRIPTS folders. W... | mod_python with Python 2.6 on Windows | How do I install mod_python to run with Python 2.6 on a Windows machine? I could not find an installer for Python 2.6.
I downloaded this installer for (mod_python on Python 2.5): mod_python-3.3.1.win32-py2.5-Apache2.2.exe and extracted it to get PLATLIB and SCRIPTS folders. Where do I go from here?
| [
"You don't. That's the install for Python 2.5 and will not work. You can try the instructions here or use mod_wsgi instead as they suggest.\n",
"Nowhere. That is for Python 2.5. You'll need to build from source if you want it to work with 2.6, or wait for them to get around to it.\n"
] | [
3,
2
] | [] | [] | [
"apache",
"mod_python",
"python"
] | stackoverflow_0002639089_apache_mod_python_python.txt |
Q:
Can SQLAlchemy's reflection tools output python source?
I want to reflect a schema using SQLAlchemy's MetaData.reflect() method, so that I can have a cache of the current schema. How can I do this?
A:
A simple and supported way to cache the result of reflection is to just pickle the MetaData object. If you prefe... | Can SQLAlchemy's reflection tools output python source? | I want to reflect a schema using SQLAlchemy's MetaData.reflect() method, so that I can have a cache of the current schema. How can I do this?
| [
"A simple and supported way to cache the result of reflection is to just pickle the MetaData object. If you prefer to generate Python code that initializes the metadata, then there's a tool called sqlautocode.\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002638717_python_sqlalchemy.txt |
Q:
Is there any free Python to C translator?
Is there any free Python to C translator? for example capable to translate such lib as lib for Fast content-aware image resizing (which already depends on some C libs) to C files?
A:
Shedskin translates Python code to C++.
A:
I think that cython is what you're looking ... | Is there any free Python to C translator? | Is there any free Python to C translator? for example capable to translate such lib as lib for Fast content-aware image resizing (which already depends on some C libs) to C files?
| [
"Shedskin translates Python code to C++.\n",
"I think that cython is what you're looking for http://www.cython.org/\n",
"The fantastic PyPy project which aims to: \"translate a Python-level description of the Python language itself to lower level languages\", has a C backend. That is one of the lower level lang... | [
7,
5,
2
] | [] | [] | [
"c",
"code_translation",
"python"
] | stackoverflow_0002639195_c_code_translation_python.txt |
Q:
Create two separate windows in terminal
Picture a terminal. There are two windows inside that terminal. One on top, one on bottom. The top one is much bigger. The top one receives asynchronous updates. The bottom one is for user input.
It would work almost exactly the same as vim - the text editor.
I'm writing t... | Create two separate windows in terminal | Picture a terminal. There are two windows inside that terminal. One on top, one on bottom. The top one is much bigger. The top one receives asynchronous updates. The bottom one is for user input.
It would work almost exactly the same as vim - the text editor.
I'm writing this in Python. I'm guessing you would do this... | [
"Yes, you want the python standard library implementation of ncurses for this.\n",
"http://docs.python.org/library/curses.html\nYes, curses + some code that will do parallel stuff\n"
] | [
2,
1
] | [] | [] | [
"curses",
"python",
"terminal"
] | stackoverflow_0002639853_curses_python_terminal.txt |
Q:
Preserving the dimensions of a slice from a Numpy 3d array
I have a 3d array, a, of shape say a.shape = (10, 10, 10)
When slicing, the dimensions are squeezed automatically i.e.
a[:,:,5].shape = (10, 10)
I'd like to preserve the number of dimensions but also ensure that the dimension that was squeezed is the one t... | Preserving the dimensions of a slice from a Numpy 3d array | I have a 3d array, a, of shape say a.shape = (10, 10, 10)
When slicing, the dimensions are squeezed automatically i.e.
a[:,:,5].shape = (10, 10)
I'd like to preserve the number of dimensions but also ensure that the dimension that was squeezed is the one that shows 1 i.e.
a[:,:,5].shape = (10, 10, 1)
I have thought of ... | [
"a[:,:,[5]].shape\n# (10,10,1)\n\n\na[:,:,5] is an example of basic slicing.\na[:,:,[5]] is an example of integer array indexing -- combined with basic slicing. When using integer array indexing the resultant shape is always \"identical to the (broadcast) indexing array shapes\". Since [5] (as an array) has shape (... | [
13
] | [] | [] | [
"numpy",
"python",
"slice"
] | stackoverflow_0002640147_numpy_python_slice.txt |
Q:
Sending data from one Protocol to another Protocol in Twisted?
One of my protocols is connected to a server, and with the output of that I'd like to send it to the other protocol.
I need to access the 'msg' method in ClassA from ClassB but I keep getting: exceptions.AttributeError: 'NoneType' object has no attrib... | Sending data from one Protocol to another Protocol in Twisted? | One of my protocols is connected to a server, and with the output of that I'd like to send it to the other protocol.
I need to access the 'msg' method in ClassA from ClassB but I keep getting: exceptions.AttributeError: 'NoneType' object has no attribute 'write'
Actual code:
from twisted.words.protocols import irc
fro... | [
"Twisted FAQ: \n\nHow do I make input on one connection\n result in output on another?\nThis seems like it's a Twisted\n question, but actually it's a Python\n question. Each Protocol object\n represents one connection; you can\n call its transport.write to write some\n data to it. These are regular Python\n ... | [
4
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0002634494_python_twisted.txt |
Q:
Recognizing a file
I have no idea how this works or if it is even possible but what I want to do is for example create a file type (lets imagine .test (in which a random file name would be random.test)). Now before I continue, its obviously easy to do this using for example:
filename = "random.test"
file = open(fi... | Recognizing a file | I have no idea how this works or if it is even possible but what I want to do is for example create a file type (lets imagine .test (in which a random file name would be random.test)). Now before I continue, its obviously easy to do this using for example:
filename = "random.test"
file = open(filename, 'w')
file.write(... | [
"How this works varies by operating system, but, AFAIK, the general rule is that if you register your application with the operating system as recognizing that file type, then clicking on one or more files of that type causes the operating system to invoke your program with the names of the files as parameters, so ... | [
2
] | [] | [] | [
"file",
"python"
] | stackoverflow_0002640138_file_python.txt |
Q:
Django/Python: Save an HTML table to Excel
I have an HTML table that I'd like to be able to export to an Excel file. I already have an option to export the table into an IQY file, but I'd prefer something that didn't allow the user to refresh the data via Excel. I just want a feature that takes a snapshot of the t... | Django/Python: Save an HTML table to Excel | I have an HTML table that I'd like to be able to export to an Excel file. I already have an option to export the table into an IQY file, but I'd prefer something that didn't allow the user to refresh the data via Excel. I just want a feature that takes a snapshot of the table at the time the user clicks the link/button... | [
"You can use the excellent xlwt module.\nIt is very easy to use, and creates files in xls format (Excel 2003).\nHere is an (untested!) example of use for a Django view:\nfrom django.http import HttpResponse\nimport xlwt\n\ndef excel_view(request):\n normal_style = xlwt.easyxf(\"\"\"\n font:\n name Verd... | [
7,
2,
0
] | [] | [] | [
"django",
"excel",
"html_table",
"python"
] | stackoverflow_0002640072_django_excel_html_table_python.txt |
Q:
How do I use Regex to find the ID in a YouTube link?
when I try to extract this video ID (AIiMa2Fe-ZQ) with a regex expression, I can't get the dash an all the letters after.
>>> id = re.search('(?<=\?v\=)\w+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ')
>>> print id.group(0)
>>> AIiMa2Fe
A:
Intead of \w+ use ... | How do I use Regex to find the ID in a YouTube link? | when I try to extract this video ID (AIiMa2Fe-ZQ) with a regex expression, I can't get the dash an all the letters after.
>>> id = re.search('(?<=\?v\=)\w+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ')
>>> print id.group(0)
>>> AIiMa2Fe
| [
"Intead of \\w+ use below. Word character (\\w) doesn't include a dash. It only includes [a-zA-Z_0-9].\n[\\w-]+\n\n",
">>> re.search('(?<=v=)[\\w-]+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ').group()\n'AIiMa2Fe-ZQ'\n\n\\w is a short-hand for [a-zA-Z0-9_] in python2.x, you'll have to use re.A flag in py3k. Yo... | [
2,
1,
1,
1,
1,
0
] | [] | [] | [
"python",
"regex",
"youtube"
] | stackoverflow_0002639582_python_regex_youtube.txt |
Q:
Why the "mutable default argument fix" syntax is so ugly, asks python newbie
Now following my series of "python newbie questions" and based on another question.
Prerogative
Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Paramet... | Why the "mutable default argument fix" syntax is so ugly, asks python newbie | Now following my series of "python newbie questions" and based on another question.
Prerogative
Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Parameter Values". There you can find the following:
def bad_append(new_item, a_list=[]):... | [
"This is called the 'mutable defaults trap'. See: http://www.ferg.org/projects/python_gotchas.html#contents_item_6\nBasically, a_list is initialized when the program is first interpreted, not each time you call the function (as you might expect from other languages). So you're not getting a new list each time you c... | [
11,
6,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"mutable",
"names",
"python"
] | stackoverflow_0002639915_mutable_names_python.txt |
Q:
Python string formatting too slow
I use the following code to log a map, it is fast when it only contains zeroes, but as soon as there is actual data in the map it becomes unbearably slow... Is there any way to do this faster?
log_file = open('testfile', 'w')
for i, x in ((i, start + i * interval) for i in range(l... | Python string formatting too slow | I use the following code to log a map, it is fast when it only contains zeroes, but as soon as there is actual data in the map it becomes unbearably slow... Is there any way to do this faster?
log_file = open('testfile', 'w')
for i, x in ((i, start + i * interval) for i in range(length)):
log_file.write('%-5d %8.3f... | [
"I suggest you run your code using the cProfile module and postprocess the results as described on http://docs.python.org/library/profile.html . This will let you know exactly how much time is spent in the call to str.__mod__ for the string formatting and how much is spent doing other things, like writing the file ... | [
3,
2,
0
] | [] | [] | [
"formatting",
"python",
"string"
] | stackoverflow_0002637530_formatting_python_string.txt |
Q:
Include empty directory with python setup.py sdist
I have a Python package where I want to include an empty directory as part of the source distribution. I tried adding
include empty_directory
to the MANIFEST.in file, but when I run
python setup.py sdist
The empty directory is still not included. Any tips on how... | Include empty directory with python setup.py sdist | I have a Python package where I want to include an empty directory as part of the source distribution. I tried adding
include empty_directory
to the MANIFEST.in file, but when I run
python setup.py sdist
The empty directory is still not included. Any tips on how to do this?
| [
"According to the docs:\n\n\ninclude pat1 pat2 - include all\n files matching any of the listed\n patterns\nexclude pat1 pat2 -\n exclude all files matching any of the listed patterns\nrecursive-include dir pat1 pat2 - include all files\n under dir matching any of the listed\n patterns\nrecursive-exclude dir p... | [
12
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0002640378_installation_python.txt |
Q:
How can I conditionally only log something if it's a certain Class?
Something like this:
if self.__class__ == "User":
logging.debug("%s non_pks were found" % (str(len(non_pks))) )
In [2]: user = User.objects.get(pk=1)
In [3]: user.__class__
Out[3]: <class 'django.contrib.auth.models.User'>
In [... | How can I conditionally only log something if it's a certain Class? | Something like this:
if self.__class__ == "User":
logging.debug("%s non_pks were found" % (str(len(non_pks))) )
In [2]: user = User.objects.get(pk=1)
In [3]: user.__class__
Out[3]: <class 'django.contrib.auth.models.User'>
In [4]: if user.__class__ == 'django.contrib.auth.models.User': print "yes"
... | [
"Classes are first class objects in Python:\n>>> class Foo(object):\n... pass\n... \n>>> a = Foo()\n>>> a.__class__ == Foo\nTrue\n\nNote: they're not strings, they're objects. Don't compare to \"Foo\" but to Foo\n",
"This should work:\nif user.__class__.__name__ == 'User':\n\n"
] | [
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002641113_django_python.txt |
Q:
Populating Models from other Models in Django?
This is somewhat related to the question posed in this question but I'm trying to do this with an abstract base class.
For the purposes of this example lets use these models:
class Comic(models.Model):
name = models.CharField(max_length=20)
desc = models.CharF... | Populating Models from other Models in Django? | This is somewhat related to the question posed in this question but I'm trying to do this with an abstract base class.
For the purposes of this example lets use these models:
class Comic(models.Model):
name = models.CharField(max_length=20)
desc = models.CharField(max_length=100)
volume = models.IntegerFiel... | [
"What about a static method on the class to handle this?\ncolored = ColoredComic.create_from_Inked(pk=ink_id)\ncolored.colored = True\ncolored.save()\n\nUntested, but something to this effect (using your code from above)\nclass ColoredComic(Comic):\n colored = models.BooleanField(default=False)\n\n @staticmet... | [
3,
0
] | [] | [] | [
"django",
"django_models",
"inheritance",
"python"
] | stackoverflow_0002640896_django_django_models_inheritance_python.txt |
Q:
Pylons user authentication roll our own or openid or alternatives?
what is the current state of user authentication? is it good to go with openid or another alternative, or we still have to write our own user/password?
A:
Take a look at: Pylons authentication?
But, the direct answer to your question:
You could... | Pylons user authentication roll our own or openid or alternatives? | what is the current state of user authentication? is it good to go with openid or another alternative, or we still have to write our own user/password?
| [
"Take a look at: Pylons authentication?\nBut, the direct answer to your question:\nYou could use RPX along with openid as mentioned on Tony Landis' blog\n"
] | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002639046_pylons_python.txt |
Q:
How to use FFmpeg
I'm trying to extract frames from a video and I've picked ffmpeg ( tell me if you know something better ) for this task.
I've downloaded its source and don't know how to use it ?? how can I compile it?
What is the recommended language for it ? I know Python and C++.
Please note that my operating ... | How to use FFmpeg | I'm trying to extract frames from a video and I've picked ffmpeg ( tell me if you know something better ) for this task.
I've downloaded its source and don't know how to use it ?? how can I compile it?
What is the recommended language for it ? I know Python and C++.
Please note that my operating system is Windows Vista... | [
"If you know C++, you can modify sample from article using ffmpeg.\n",
"If you just want to extract the frames from a video and save them to file, you can just use ffmpeg at the command line:\nffmpeg -i video.avi image%d.jpg\n\nFor this method, you do not need to build ffmpeg as there should be a windows binary a... | [
8,
6,
1
] | [] | [] | [
"c++",
"ffmpeg",
"python"
] | stackoverflow_0001908411_c++_ffmpeg_python.txt |
Q:
class, dict, self, init, args?
class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
print a.x, a.y
b = attrdict()
b.x, b.y = 1, 2
print b.x, b.y
Could somebody explain the first four lines in words? I rea... | class, dict, self, init, args? | class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
print a.x, a.y
b = attrdict()
b.x, b.y = 1, 2
print b.x, b.y
Could somebody explain the first four lines in words? I read about classes and methods. But her... | [
"My shot at a line-by-line explanation:\nclass attrdict(dict):\n\nThis line declares a class attrdict as a subclass of the built-in dict class.\ndef __init__(self, *args, **kwargs): \n dict.__init__(self, *args, **kwargs)\n\nThis is your standard __init__ method. The call to dict.__init__(...) is to utilize the... | [
7,
5,
4
] | [] | [] | [
"arguments",
"class",
"python",
"self"
] | stackoverflow_0002641484_arguments_class_python_self.txt |
Q:
Django Querysets -- need a less expensive way to do this
I have a problem with some code and I believe it is because of the expense of the queryset. I am looking for a much less expensive (in terms of time) way to to this..
log.info("Getting Users")
employees = Employee.objects.filter(is_active = True)
log.info("... | Django Querysets -- need a less expensive way to do this | I have a problem with some code and I believe it is because of the expense of the queryset. I am looking for a much less expensive (in terms of time) way to to this..
log.info("Getting Users")
employees = Employee.objects.filter(is_active = True)
log.info("Have Users")
if opt.supervisor:
if opt.hierarchical:
... | [
"\nOr Q objects together instead of QuerySets.\nQuerySet.select_related()\nQuerySet.iterator()\nUse QuerySet.extra() to add IS NULL fields instead of the three len() calls in the loop.\n\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002641655_django_django_models_python.txt |
Q:
pyinstaller: 2 instances of my cherrypy app exe get executed
I have a cherrypy app that I've made an exe with pyinstaller.
now when I run the exe it loads itself twice into memory. Watching the taskmanager shows the first instance load into about 1k, then a second later a second instance of hte exe loads into abo... | pyinstaller: 2 instances of my cherrypy app exe get executed | I have a cherrypy app that I've made an exe with pyinstaller.
now when I run the exe it loads itself twice into memory. Watching the taskmanager shows the first instance load into about 1k, then a second later a second instance of hte exe loads into about 3k ram. If I close the bigger one both processes die. If I clos... | [
"PyInstaller spawns a subprocess during its boot process. This is explained in a section of its manual.\n",
"It would be important to know what version of CherryPy you are using. The 2.x line had an unfortunate design: the autoreloader feature always started a second instance of CherryPy, so the first could respa... | [
6,
1
] | [] | [] | [
"cherrypy",
"pyinstaller",
"python"
] | stackoverflow_0002124603_cherrypy_pyinstaller_python.txt |
Q:
get_or_create generic relations in Django & python debugging in general
I ran the code to create the generically related objects from this demo:
http://www.djangoproject.com/documentation/models/generic_relations/
Everything is good intially:
>>> bacon.tags.create(tag="fatty")
<TaggedItem: fatty>
>>> tag, newtag =... | get_or_create generic relations in Django & python debugging in general | I ran the code to create the generically related objects from this demo:
http://www.djangoproject.com/documentation/models/generic_relations/
Everything is good intially:
>>> bacon.tags.create(tag="fatty")
<TaggedItem: fatty>
>>> tag, newtag = bacon.tags.get_or_create(tag="fatty")
>>> tag
<TaggedItem: fatty>
>>> newtag... | [
"ContentType.objects.get_for_model() will give you the appropriate ContentType for a model. Pass the returned object as content_type.\nAnd don't worry too much about \"getting it\" when it comes to Django. Django is mostly insane to begin with, and experimentation and heavy reading of both documentation and source ... | [
10,
2
] | [] | [] | [
"debugging",
"django",
"generic_relationship",
"python"
] | stackoverflow_0002641780_debugging_django_generic_relationship_python.txt |
Q:
Migrating data from Plone to Liferay, or how could I retrieve information from Plone's Data.fs
I need to migrate data from a Plone-based portal to Liferay. Has anyone some idea on how to do it?
Anyway, I am trying to retrieve data from Data.fs and store it in a representation easier to work, such as JSON. To do it... | Migrating data from Plone to Liferay, or how could I retrieve information from Plone's Data.fs | I need to migrate data from a Plone-based portal to Liferay. Has anyone some idea on how to do it?
Anyway, I am trying to retrieve data from Data.fs and store it in a representation easier to work, such as JSON. To do it, I need to know which objects I should get from Plone's Data.fs. I already got the Products.CMFPlon... | [
"Once you've got ahold of the Plone site object, you can do a catalog query to find all content items in the site:\n >>> brains = site.portal_catalog.unrestrictedSearchResults()\n\nThis returns a list of \"catalog brains\", each of which contains some metadata about the item. You can get the full item from the bra... | [
3
] | [] | [] | [
"liferay",
"plone",
"python",
"zodb",
"zope"
] | stackoverflow_0002394493_liferay_plone_python_zodb_zope.txt |
Q:
storing record arrays in object arrays
I'd like to convert a list of record arrays -- dtype is (uint32, float32) -- into a numpy array of dtype np.object:
X = np.array(instances, dtype = np.object)
where instances is a list of arrays with data type np.dtype([('f0', '<u4'), ('f1', '<f4')]).
However, the above st... | storing record arrays in object arrays | I'd like to convert a list of record arrays -- dtype is (uint32, float32) -- into a numpy array of dtype np.object:
X = np.array(instances, dtype = np.object)
where instances is a list of arrays with data type np.dtype([('f0', '<u4'), ('f1', '<f4')]).
However, the above statement results in an array whose elements a... | [
"Stéfan van der Walt (a numpy developer) explains:\n\nThe ndarray constructor does its best\n to guess what kind of data you are\n feeding it, but sometimes it needs a\n bit of help....\nI prefer to construct arrays\n explicitly, so there is no doubt what\n is happening under the hood:\n\nWhen you say somethin... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002641701_numpy_python.txt |
Q:
Python stream http client with keep-alive
I need a python http client that can reuse connections and that supports consuming the stream as it comes in. It will be used to parse xml streams, sax style.
I came up with a solution, but I'm not sure it is the best one (there are quite a few ways of writing an http clie... | Python stream http client with keep-alive | I need a python http client that can reuse connections and that supports consuming the stream as it comes in. It will be used to parse xml streams, sax style.
I came up with a solution, but I'm not sure it is the best one (there are quite a few ways of writing an http client in python)
class Downloader():
def __in... | [
"urlgrabber supports keepalive and can return a file-like object.\n",
"There is also pycurl. By default keepalive is turned on and you can write to a file for output.\nFollow the examples, they are quite helpful\n"
] | [
1,
1
] | [] | [] | [
"client",
"http",
"keep_alive",
"python",
"streaming"
] | stackoverflow_0002370692_client_http_keep_alive_python_streaming.txt |
Q:
Google App Engine: How to disable cache on 'static' files, or make cache smart
I'm using the app engine locally, and sometimes the JS files are being cached between page refreshes, and it drives me crazy because I don't know if there's a bug in the javascript code I'm trying to write, or if the cache is acting up... | Google App Engine: How to disable cache on 'static' files, or make cache smart | I'm using the app engine locally, and sometimes the JS files are being cached between page refreshes, and it drives me crazy because I don't know if there's a bug in the javascript code I'm trying to write, or if the cache is acting up.
How do I completely disable cache for *.js files? Or maybe the question is, how to... | [
"A common practice used by the major sites is to cache documents forever but include a unique identifier based on the release version or date into the url for the .js or .css call. For example:\n<script type=\"text/javascript\" src=\"static/util.js?version=20100310\"></script>\n\nThis way you get optimum caching as... | [
15,
13
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002642432_google_app_engine_python.txt |
Q:
Python - multiple copies of output when using multiprocessing
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
Module run via python myscript.py (not shell input)
import uuid
import time
import multiprocessing
def sleep_then_write(content):
time.sleep(5)
print(content)
if _... | Python - multiple copies of output when using multiprocessing |
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
Module run via python myscript.py (not shell input)
import uuid
import time
import multiprocessing
def sleep_then_write(content):
time.sleep(5)
print(content)
if __name__ == '__main__':
for i in range(15):
p = multip... | [
"multiprocessing works by starting several processes. Each process loads a copy of your script (that way it has access to the \"target\" function), and then runs the target function.\nYou get the bottom print statement 16 times because the statement is sitting out there by itself and gets printed when you load the ... | [
4,
2
] | [] | [] | [
"multiprocessing",
"python",
"windows"
] | stackoverflow_0002641080_multiprocessing_python_windows.txt |
Q:
Queuing methods to be run on an object by different threads in Python
Let's say I have an object who's class definition looks like:
class Command:
foo = 5
def run(self, bar):
time.sleep(1)
self.foo = bar
return self.foo
If this class is instantiated once, but different threads are hitting its run ... | Queuing methods to be run on an object by different threads in Python | Let's say I have an object who's class definition looks like:
class Command:
foo = 5
def run(self, bar):
time.sleep(1)
self.foo = bar
return self.foo
If this class is instantiated once, but different threads are hitting its run method (via an HTTP request, handled separately) passing in different args,... | [
"Here's a relatively simple approach (ignores exceptions, attribute-access, special methods, etc):\nimport Queue\nimport threading\n\ndef serialize(q):\n \"\"\"runs a serializer on queue q: put [-1]*4 on q to terminate.\"\"\"\n while True:\n # get output-queue for result, a callable, its args and kwds\n out... | [
2,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002642515_multithreading_python.txt |
Q:
A web framework where AJAX was not an after thought
AJAX is a pain in the ass because it essentially means you'll have to write two sets of similarish code: one for browsers with JavaScript enabled and those without.
Not only this, but you have to connect JavaScript events to hook into your models and display the ... | A web framework where AJAX was not an after thought | AJAX is a pain in the ass because it essentially means you'll have to write two sets of similarish code: one for browsers with JavaScript enabled and those without.
Not only this, but you have to connect JavaScript events to hook into your models and display the results.
And if all that weren't bad enough, you need to ... | [
"Have you given a look to Pyjamas\nQuoted from the site\n\nWhy should I use it?\nYou can write web applications in\n python - a readable programming\n language - instead of in HTML and\n Javascript, both of which become\n quickly unreadable for even\n medium-sized applications. Your\n application's design can... | [
3,
0,
0,
0
] | [] | [] | [
".net",
"ajax",
"frameworks",
"php",
"python"
] | stackoverflow_0002642364_.net_ajax_frameworks_php_python.txt |
Q:
How to evaluate a custom math expression in Python
I'm writing a custom dice rolling parser (snicker if you must) in python. Basically, I want to use standard math evaluation but add the 'd' operator:
#xdy
sum = 0
for each in range(x):
sum += randInt(1, y)
return sum
So that, for example, 1d6+2d6+2d6-72+4d100... | How to evaluate a custom math expression in Python | I'm writing a custom dice rolling parser (snicker if you must) in python. Basically, I want to use standard math evaluation but add the 'd' operator:
#xdy
sum = 0
for each in range(x):
sum += randInt(1, y)
return sum
So that, for example, 1d6+2d6+2d6-72+4d100 = (5)+(1+1)+(6+2)-72+(5+39+38+59) = 84
I was using rege... | [
"You could use a callback function with re.sub. When you follow the link, search down to the paragraph beginning with \"If repl is a function...\"\nimport re\nimport random\n\ndef xdy(matchobj):\n x,y=map(int,matchobj.groups())\n s = 0\n for each in range(x):\n s += random.randint(1, y)\n return ... | [
6,
5,
2,
0,
0
] | [] | [] | [
"eval",
"math",
"python"
] | stackoverflow_0002642650_eval_math_python.txt |
Q:
Java's equivalence to Python's "Got value: %s" % variable?
Java's equivalence to Python's "Got value: %s" % variable?
A:
String.format("Got value: %s", variable);
A:
System.out.format("%s", aString)
See Format and all its various incarnations.
| Java's equivalence to Python's "Got value: %s" % variable? | Java's equivalence to Python's "Got value: %s" % variable?
| [
"String.format(\"Got value: %s\", variable);\n\n",
"System.out.format(\"%s\", aString)\n\nSee Format and all its various incarnations.\n"
] | [
6,
3
] | [] | [] | [
"formatting",
"java",
"python",
"string"
] | stackoverflow_0002642908_formatting_java_python_string.txt |
Q:
What is the best way to create a running integer id on the AppEngine data storage?
For various reasons, I need a unique running integer id for my entities stored on the Google AppEngine. The automatically generated key sort of has this behaviour, but it doesn't start from 1 (or 0) and doesn't guarantee that the ge... | What is the best way to create a running integer id on the AppEngine data storage? | For various reasons, I need a unique running integer id for my entities stored on the Google AppEngine. The automatically generated key sort of has this behaviour, but it doesn't start from 1 (or 0) and doesn't guarantee that the generated integer part will come from a continuous sequence.
What would be the best way t... | [
"If you could live without the integer part, try the uuid module (from\nthe standard library): http://docs.python.org/library/uuid.html\nThat would typically give you a 36-character string, though, maybee\nthat's to far from what you need. But it's unique.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002640907_google_app_engine_python.txt |
Q:
Extending a series of nonuniform netcdf data in a numpy array
I am new to python, apologies if this has been asked already.
Using python and numpy, I am trying to gather data across many netcdf files into a single array by iteratively calling append().
Naively, I am trying to do something like this:
from numpy imp... | Extending a series of nonuniform netcdf data in a numpy array | I am new to python, apologies if this has been asked already.
Using python and numpy, I am trying to gather data across many netcdf files into a single array by iteratively calling append().
Naively, I am trying to do something like this:
from numpy import *
from pupynere import netcdf_file
x = array([])
y = [...some ... | [
"You can solve the two problems by first loading the arrays from the files files into a list of arrays, and then using concatenate to join all the arrays. Something like this:\nx = [] # a normal python list, not np.array\ny = [...some list of files...]\n\nfor file in y:\n ncfile = netcdf_file(file,'r')\n xFra... | [
1
] | [] | [] | [
"arrays",
"netcdf",
"numpy",
"python"
] | stackoverflow_0002642951_arrays_netcdf_numpy_python.txt |
Q:
Python list comprehension to return edge values of a list
If I have a list in python such as:
stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with length n (in this case 9) and I am interested in creating lists of length n/2 (in this case 4). I want all possible sets of n/2 values in the original list, for example:
[1, 2... | Python list comprehension to return edge values of a list | If I have a list in python such as:
stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with length n (in this case 9) and I am interested in creating lists of length n/2 (in this case 4). I want all possible sets of n/2 values in the original list, for example:
[1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3]
is there some list ... | [
"What you need is combinations function from itertools\n(EDIT: use permutation if the order is important)\nNote that this function is not available at Python 2.5. In that case you can copy the code from the above link:\ndef combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD\n # combi... | [
5,
5,
3
] | [] | [] | [
"data_structures",
"iteration",
"list_comprehension",
"python"
] | stackoverflow_0002643209_data_structures_iteration_list_comprehension_python.txt |
Q:
How to store an arbitrarily long int to a binary file in python?
How can I store and retrieve the number 2**10000 in a binary file in python without converting it to a string? Can it be stored as 10,000 bits?
A:
The built-in pickle module can do it if you pass in protocol version 2 ("new binary protocol"):
impo... | How to store an arbitrarily long int to a binary file in python? | How can I store and retrieve the number 2**10000 in a binary file in python without converting it to a string? Can it be stored as 10,000 bits?
| [
"The built-in pickle module can do it if you pass in protocol version 2 (\"new binary protocol\"):\nimport pickle\npickle.dumps(2**10000, 2)\n\nThat returns a string of 1259 bytes. Of course, you'd want to write it to a file normally, so use pickle.dump(2**10000, file, 2)\n",
"It's not clear to me if you are aski... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002641695_python.txt |
Q:
Can Microsoft Visual C++ 2008 Redistributable Package be freely redistributed
I am planning to use py2exe to make an application developped with Python 2.6.
It seems that my app need the VC redistribuables : http://www.py2exe.org/index.cgi/Tutorial#Step5
I've read this tutorial and the redistribuables license agre... | Can Microsoft Visual C++ 2008 Redistributable Package be freely redistributed | I am planning to use py2exe to make an application developped with Python 2.6.
It seems that my app need the VC redistribuables : http://www.py2exe.org/index.cgi/Tutorial#Step5
I've read this tutorial and the redistribuables license agreement and I am not sure if I can freely redistribute these files with my program. (... | [
"I think you should be fine if you simply include the installation of vcredist_x86.exe into your installation procedure (according to the document you linked to):\n\nEither you can instruct your users to\n download and run this themselves, or\n you could create an installer for your\n application (see Step 6 bel... | [
3
] | [] | [] | [
"py2exe",
"python",
"redistributable",
"visual_studio_2008"
] | stackoverflow_0002643760_py2exe_python_redistributable_visual_studio_2008.txt |
Q:
Embed a Python persistance layer into a C++ application - good idea?
say I'm about to write an application with a thin GUI layer, a really fat calculation layer (doing computationally heavy calibrations and other long-running stuff) and fairly simple persistance layer. I'm looking at building the GUI + calculation... | Embed a Python persistance layer into a C++ application - good idea? | say I'm about to write an application with a thin GUI layer, a really fat calculation layer (doing computationally heavy calibrations and other long-running stuff) and fairly simple persistance layer. I'm looking at building the GUI + calculation layer in C++ (using Qt for the gui parts).
Now - would it be a crazy idea... | [
"I would go with the 'alternative' approach:\nWrite as much as possible in Python (you can use the GUI bindings PyQt or PySide) and then only write the computationally intensive parts (when proven critical for performance) in C++ (have a look at Boost.Python).\nDeveloping in Python should be faster, easier and less... | [
10
] | [] | [] | [
"c++",
"embedded_language",
"orm",
"python"
] | stackoverflow_0002643863_c++_embedded_language_orm_python.txt |
Q:
What's the simplest way to get the highest and lowest keys from a dictionary?
self.mood_scale = {
'-30':"Panic",
'-20':'Fear',
'-10':'Concern',
'0':'Normal',
'10':'Satisfaction',
'20':'Happiness',
'30':'Euphoria'}
I need to set two variables: max_mood and min_mood, so I can put some li... | What's the simplest way to get the highest and lowest keys from a dictionary? | self.mood_scale = {
'-30':"Panic",
'-20':'Fear',
'-10':'Concern',
'0':'Normal',
'10':'Satisfaction',
'20':'Happiness',
'30':'Euphoria'}
I need to set two variables: max_mood and min_mood, so I can put some limits on a ticker.
What's the easiest way to get the lowest and the highest keys?
| [
">>> min(self.mood_scale, key=int)\n'-30'\n>>> max(self.mood_scale, key=int)\n'30'\n\n",
"This should do it:\nmax_mood = max(self.mood_scale)\nmin_mood = min(self.mood_scale)\n\nPerhaps not the most efficient (since it has to get and traverse the list of keys twice), but certainly very obvious and clear.\nUPDATE:... | [
12,
9,
7
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002644039_dictionary_python.txt |
Q:
object won't die (still references to it that I can't find)
I'm using parallel-python and start a new job server in a function. after the functions ends it still exists even though I didn't return it out of the function (I used weakref to test this). I guess there's still some references to this object somewhere. ... | object won't die (still references to it that I can't find) | I'm using parallel-python and start a new job server in a function. after the functions ends it still exists even though I didn't return it out of the function (I used weakref to test this). I guess there's still some references to this object somewhere.
My two theories: It starts threads and it logs to root logger.
M... | [
"You can use gc.get_referrers(obj) to find out what is referencing the object. Because you'll most likely get a bunch of dicts as the response, you'll have to go up a couple of levels to make any sense of it.\n"
] | [
1
] | [] | [] | [
"garbage_collection",
"logging",
"parallel_python",
"python",
"reference"
] | stackoverflow_0002644103_garbage_collection_logging_parallel_python_python_reference.txt |
Q:
Constructing an if statement from the client data in python
I need to construct an if statement from the data coming from the client as below:
conditions: condition1, condition2, condition3, condition4
logical operators: lo1, lo2, lo3 (Possible values: "and" "or")
Eg.
if condition1 lo1 condition2 lo3 condition4:
... | Constructing an if statement from the client data in python | I need to construct an if statement from the data coming from the client as below:
conditions: condition1, condition2, condition3, condition4
logical operators: lo1, lo2, lo3 (Possible values: "and" "or")
Eg.
if condition1 lo1 condition2 lo3 condition4:
# Do something
I can think of eval/exec but not sure how saf... | [
"Don't use eval. It's a huge security risk. If your conditions are relatively simple, I would consider giving the user a decent flex GUI in which to enter them, not just a raw text area, but a real expression creation tool. Look at the \"advanced search\" features in any reasonably sophisticate search application... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002630493_python.txt |
Q:
How can I convert this string to list of lists?
If a user types in [[0,0,0], [0,0,1], [1,1,0]] and press enter,
the program should convert this string to several lists;
one list holding [0][0][0], other for [0][0][1], and the last list for [1][1][0]
Does python have a good way to handle this?
A:
>>> import ast... | How can I convert this string to list of lists? | If a user types in [[0,0,0], [0,0,1], [1,1,0]] and press enter,
the program should convert this string to several lists;
one list holding [0][0][0], other for [0][0][1], and the last list for [1][1][0]
Does python have a good way to handle this?
| [
">>> import ast\n>>> ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')\n[[0, 0, 0], [0, 0, 1], [1, 1, 0]]\n\nFor tuples\n>>> ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')\n[(0, 0, 0), (0, 0, 1), (1, 1, 0)]\n\n",
">>> import json\n>>> json.loads('[[0,0,0], [0,0,1], [1,1,0]]')\n[[0, 0, 0], [0, 0, 1], [1, 1, 0]]\n\n... | [
47,
23,
10,
3,
0
] | [
">>> string='[[0,0,0], [0,0,1], [1,1,0]]'\n>>> eval(string)\n[[0, 0, 0], [0, 0, 1], [1, 1, 0]]\n>>> a=eval(string)\n>>> a\n[[0, 0, 0], [0, 0, 1], [1, 1, 0]]\n\nbefore passing your string to eval(), do the necessary sanitization first.\n"
] | [
-3
] | [
"list",
"python",
"tuples"
] | stackoverflow_0002644221_list_python_tuples.txt |
Q:
Google Bot information?
Does anyone know any more details about google's web-crawler (aka GoogleBot)? I was curious about what it was written in (I've made a few crawlers myself and am about to make another) and if it parses images and such. I'm assuming it does somewhere along the line, b/c the images in images... | Google Bot information? | Does anyone know any more details about google's web-crawler (aka GoogleBot)? I was curious about what it was written in (I've made a few crawlers myself and am about to make another) and if it parses images and such. I'm assuming it does somewhere along the line, b/c the images in images.google.com are all resized. ... | [
"you can find a bit about how googlebot works here:\nhttp://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=158587\nfor example the \"fetch as googlebot\" tool lets you see a page as Googlebot sees it. \n",
"The crawler is very likely written in C or C++, at least backrub's crawler was written in one... | [
1,
1,
0
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0002633302_c_c++_python.txt |
Q:
Fastest way to find the closest point to a given point in 3D, in Python
So lets say I have 10,000 points in A and 10,000 points in B and want to find out the closest point in A for every B point.
Currently, I simply loop through every point in B and A to find which one is closest in distance. ie.
B = [(.5, 1, 1), ... | Fastest way to find the closest point to a given point in 3D, in Python | So lets say I have 10,000 points in A and 10,000 points in B and want to find out the closest point in A for every B point.
Currently, I simply loop through every point in B and A to find which one is closest in distance. ie.
B = [(.5, 1, 1), (1, .1, 1), (1, 1, .2)]
A = [(1, 1, .3), (1, 0, 1), (.4, 1, 1)]
C = {}
for bp... | [
"I typically use a kd-tree in such situations.\nThere is a C++ implementation wrapped with SWIG and bundled with BioPython that's easy to use.\n",
"You could use some spatial lookup structure. A simple option is an octree; fancier ones include the BSP tree.\n",
"You could use numpy broadcasting. For example,\nf... | [
4,
1,
1
] | [] | [] | [
"closest",
"distance",
"points",
"python"
] | stackoverflow_0002641206_closest_distance_points_python.txt |
Q:
python extract from switch output
I have some info back from a LAN switch as below
Vlan 1 is administratively down, line protocol is down
Vlan 2 is up, line protocol is up
Helper address is 192.168.0.2
Vlan 3 is up, line protocol is up
Helper address is not set
Vlan 4 is up, line protocol is up
... | python extract from switch output | I have some info back from a LAN switch as below
Vlan 1 is administratively down, line protocol is down
Vlan 2 is up, line protocol is up
Helper address is 192.168.0.2
Vlan 3 is up, line protocol is up
Helper address is not set
Vlan 4 is up, line protocol is up
Helper address is 192.168.0.2
Vlan 5... | [
"import re\n\nx=\"\"\"\nVlan 1 is administratively down, line protocol is down \nVlan 2 is up, line protocol is up \n Helper address is 192.168.0.2 \nVlan 3 is up, line protocol is up \n Helper address is not set \nVlan 4 is up, line protocol is up \n Helper address is 192.168.0.2 \nVlan 5 is down, line p... | [
1,
0,
0,
0
] | [] | [] | [
"parsing",
"python",
"text"
] | stackoverflow_0002643532_parsing_python_text.txt |
Q:
Avoiding nesting two for loops
Please have a look at the code below:
import string
from collections import defaultdict
first_complex=open( "residue_a_chain_a_b_backup.txt", "r" )
first_complex_lines=first_complex.readlines()
first_complex_lines=map( string.strip, first_complex_lines )
first_complex.close()
secon... | Avoiding nesting two for loops | Please have a look at the code below:
import string
from collections import defaultdict
first_complex=open( "residue_a_chain_a_b_backup.txt", "r" )
first_complex_lines=first_complex.readlines()
first_complex_lines=map( string.strip, first_complex_lines )
first_complex.close()
second_complex=open( "residue_a_chain_a... | [
"You want to convert list_2 to a set, and check for membership:\nlist_1 = ['a', 'big', 'list']\nlist_2 = ['another', 'big', 'list']\n\ntarget_set = set(list_2)\n\nfor a in list_1:\n if a in target_set:\n print a\n\nOutputs:\nbig\nlist\n\nA set gives you the advantage of O(1) access time to determine memb... | [
8,
3,
2,
1
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0002364382_for_loop_python.txt |
Q:
Need help running Python app as service in Ubuntu with Upstart
I have written a logging application in Python that is meant to start at boot, but I've been unable to start the app with Ubuntu's Upstart init daemon. When run from the terminal with sudo /usr/local/greeenlog/main.pyw, the application works perfectly... | Need help running Python app as service in Ubuntu with Upstart | I have written a logging application in Python that is meant to start at boot, but I've been unable to start the app with Ubuntu's Upstart init daemon. When run from the terminal with sudo /usr/local/greeenlog/main.pyw, the application works perfectly. Here is what I've tried for the Upstart job:
/etc/init/greeenlog.... | [
"Thanks to unutbu's help, I have been able to correct my job. Apparently, these are the only environment variables that Upstart sets (retrieved in Python with os.environ):\n{'TERM': 'linux', 'PWD': '/', 'UPSTART_INSTANCE': '', 'UPSTART_JOB': 'greeenlog', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/... | [
12
] | [] | [] | [
"python",
"ubuntu",
"upstart"
] | stackoverflow_0002641136_python_ubuntu_upstart.txt |
Q:
Why urllib.urlopen doesn't (seem to) work with Stack Overflow?
I need to retrieve my info from Stack Overflow.
The web page that I want to retrieve is something like this.
http://stackoverflow.com/users/260127/prosseek
When I run the script, it doesn't seem return any results.
import urllib ... | Why urllib.urlopen doesn't (seem to) work with Stack Overflow? | I need to retrieve my info from Stack Overflow.
The web page that I want to retrieve is something like this.
http://stackoverflow.com/users/260127/prosseek
When I run the script, it doesn't seem return any results.
import urllib
sock = urllib.urlopen("http://stackoverflow.com/u... | [
"It \"works\" for me - the page returned is a 404 error. Try putting the URL https://stackoverflow.com/users/XXXXX/prosseek into your browser and see for yourself.\nI think you want to use https://stackoverflow.com/users/260127/prosseek instead.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002646880_python.txt |
Q:
Check if something is a list
What is the easiest way to check if something is a list?
A method doSomething has the parameters a and b. In the method, it will loop through the list a and do something. I'd like a way to make sure a is a list, before looping through - thus avoiding an error or the unfortunate circums... | Check if something is a list | What is the easiest way to check if something is a list?
A method doSomething has the parameters a and b. In the method, it will loop through the list a and do something. I'd like a way to make sure a is a list, before looping through - thus avoiding an error or the unfortunate circumstance of passing in a string then ... | [
"To enable more usecases, but still treat strings as scalars, don't check for a being a list, check that it isn't a string:\nif not isinstance(a, basestring):\n ...\n\n",
"Typechecking hurts the generality, simplicity, and maintainability of your code. It is seldom used in good, idiomatic Python programs.\nThe... | [
16,
10,
7,
5
] | [] | [] | [
"python",
"typechecking"
] | stackoverflow_0002645749_python_typechecking.txt |
Q:
Python - import error
I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way.
I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass.
/mydir/utils.py imports get_hash() from /mydir/__init__. ... | Python - import error | I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way.
I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass.
/mydir/utils.py imports get_hash() from /mydir/__init__.
/mydir/__init__.py imports... | [
"This is a pretty easy problem to encounter. What's happening is this that the interpreter evaluates your __init__.py file line-by line. When you have the following code:\n import mydir.utils\n def get_hash(): return 1\n\nThe interpreter will suspend processing __init__.py at the point of import mydir.utils until i... | [
2,
2,
1
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0002647088_python_python_import.txt |
Q:
Unique user ID in a Pylons web application
What is the best way to create a unique user ID in Python, using UUID?
A:
I'd go with uuid
from uuid import uuid4
def new_user_id():
return uuid4().hex
| Unique user ID in a Pylons web application | What is the best way to create a unique user ID in Python, using UUID?
| [
"I'd go with uuid\nfrom uuid import uuid4\ndef new_user_id():\n return uuid4().hex\n\n"
] | [
8
] | [] | [] | [
"cassandra",
"pylons",
"python",
"uuid"
] | stackoverflow_0002647080_cassandra_pylons_python_uuid.txt |
Q:
graphviz segmentation fault
I'm building a graph with many nodes, around 3000. I wrote a simple python program to do the trick with graphviz, but it gives me segmentation fault and I don't know why, if the graph is too big or if i'm missing something.
The code is:
#!/usr/bin/env python
# Import graphviz
import sy... | graphviz segmentation fault | I'm building a graph with many nodes, around 3000. I wrote a simple python program to do the trick with graphviz, but it gives me segmentation fault and I don't know why, if the graph is too big or if i'm missing something.
The code is:
#!/usr/bin/env python
# Import graphviz
import sys
sys.path.append('..')
sys.path.... | [
"I changed the layout type from dot to neato and that solved the problem.\nI searched a bit and it seems that the dot layout is a bit faulty on large graphs.\n"
] | [
6
] | [] | [] | [
"graphviz",
"python",
"segmentation_fault"
] | stackoverflow_0002628972_graphviz_python_segmentation_fault.txt |
Q:
Python List length as a string
Is there a preferred (not ugly) way of outputting a list length as a string? Currently I am nesting function calls like so:
print "Length: %s" % str(len(self.listOfThings))
This seems like a hack solution, is there a more graceful way of achieving the same result?
A:
You don't... | Python List length as a string | Is there a preferred (not ugly) way of outputting a list length as a string? Currently I am nesting function calls like so:
print "Length: %s" % str(len(self.listOfThings))
This seems like a hack solution, is there a more graceful way of achieving the same result?
| [
"You don't need the call to str:\nprint \"Length: %s\" % len(self.listOfThings)\n\nNote that using % is being deprecated, and you should prefer to use str.format if you are using Python 2.6 or newer:\nprint \"Length: {0}\".format(len(self.listOfThings)) \n\n",
"\"Length: %d\" % len(self.listOfThings) should work... | [
9,
2,
1
] | [] | [] | [
"conventions",
"python",
"string"
] | stackoverflow_0002647672_conventions_python_string.txt |
Q:
customizing Django look and feel in Python
I am learning Django and got it to work with wsgi. I'm following the tutorial here:
http://docs.djangoproject.com/en/1.1/intro/tutorial01/
My question is: how can I customize the look and feel of Django? Is there a repository of templates that "look good", kind of like... | customizing Django look and feel in Python | I am learning Django and got it to work with wsgi. I'm following the tutorial here:
http://docs.djangoproject.com/en/1.1/intro/tutorial01/
My question is: how can I customize the look and feel of Django? Is there a repository of templates that "look good", kind of like there are for Wordpress, that I can start from?... | [
"Search for generic CSS/HTML templates, and add in the Django template language where you need it. Because unless you are trying to skin a particular app (such as the admin system), there is nothing Django-specific about any of your HTML.\n",
"The fact that you're thinking in terms of Wordpress templates, and tha... | [
5,
2,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002647098_django_django_templates_python.txt |
Q:
How can I tell what directory an imported library comes from in python?
I'm trying to modify a python library that I downloaded and am using. But the changes I'm making aren't doing anything. So I suspect that python is importing a different copy of this library from somewhere else on the filesystem. So...
When... | How can I tell what directory an imported library comes from in python? | I'm trying to modify a python library that I downloaded and am using. But the changes I'm making aren't doing anything. So I suspect that python is importing a different copy of this library from somewhere else on the filesystem. So...
When I run import foolib in python, how can I tell where on the filesystem it's g... | [
"the correct answer is to use sys.modules... it works on everything, even sys. sys.modules is a dictionary where the keys are the imported names (modules or packages), and the values are their respective locations. here is some usage output from my Mac:\n$ python\nPython 2.5.1 (r251:54863, Feb 9 2009, 18:49:36) \n... | [
7,
6,
2
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002647862_import_python.txt |
Q:
What are 'len', 'dir', 'vars' named?
I was wondering what language to use when talking about a function that takes in a specific object, acts on it and returns something else. Clearly they're functions, but I was wondering if there's a more specific term.
A couple examples of Python built-in functions that fit thi... | What are 'len', 'dir', 'vars' named? | I was wondering what language to use when talking about a function that takes in a specific object, acts on it and returns something else. Clearly they're functions, but I was wondering if there's a more specific term.
A couple examples of Python built-in functions that fit this spec are: 'len', 'dir', 'vars'
I thought... | [
"There isn't really a generic term for these kinds of functions, although Python internally uses 'inquiry' for this kind of function. I rarely see them described as anything other than just plain 'function', though.\n",
"Call them functions. That's something everyone will understand. You could also call them subr... | [
6,
5,
2,
2,
1
] | [] | [] | [
"computer_science",
"python"
] | stackoverflow_0002648121_computer_science_python.txt |
Q:
Connecting to Python XML RPC from the Mac
I wrote an XML RPC server in python and a simple Test Client for it in python. The Server runs on a linux box. I tested it by running the python client on the same linux machine and it works.
I then tried to run the python client on a Mac and i get the following error
sock... | Connecting to Python XML RPC from the Mac | I wrote an XML RPC server in python and a simple Test Client for it in python. The Server runs on a linux box. I tested it by running the python client on the same linux machine and it works.
I then tried to run the python client on a Mac and i get the following error
socket.error: (61, 'Connection Refused')
I can pin... | [
"\"Connection Refused\" means the connection was REFUSED - the machine 143.252.249.141 is up, and in the network, but is not accepting connections on port 8000 - it is actively refusing them.\nSo maybe the server software isn't running on the server? Or is running in another port? Or is bound to a different IP addr... | [
1
] | [] | [] | [
"macos",
"python",
"xml_rpc"
] | stackoverflow_0002648212_macos_python_xml_rpc.txt |
Q:
how would i manage to install python's boto library on shared hosting?
how would i manage to install python's boto library on shared hosting?
A:
Why install virtualenv? I would try:
easy_install boto
or
pip install boto
pip and easy_install are python tools for installing other packages. Who is your hosting serv... | how would i manage to install python's boto library on shared hosting? | how would i manage to install python's boto library on shared hosting?
| [
"Why install virtualenv? I would try:\neasy_install boto\nor\npip install boto\npip and easy_install are python tools for installing other packages. Who is your hosting service? If they have these utilities, using them would be the easiest route.\nhttp://www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/\nThat... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002646002_python.txt |
Q:
Python unit test. How to add some sleeping time between test cases?
I am using python unit test module. I am wondering is there anyway to add some delay between every 2 test cases? Because my unit test is just making http request and I guess the server may block the frequent request from the same ip.
A:
Put a sl... | Python unit test. How to add some sleeping time between test cases? | I am using python unit test module. I am wondering is there anyway to add some delay between every 2 test cases? Because my unit test is just making http request and I guess the server may block the frequent request from the same ip.
| [
"Put a sleep inside the tearDown method of your TestCase\nimport time\n\nclass ExampleTestCase(unittest.TestCase):\n def tearDown(self):\n time.sleep(1) # sleep time in seconds\n\ntearDown() will be executed after every test within that TestCase class.\nThe modules documentation can be found here.\n",
... | [
21,
3
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002648329_python_unit_testing.txt |
Q:
virtual serial port on Arch linux
I am using Arch linux and I need to create virtual serial port on it. I tried everything but it seems doesnt work. All I want is to connect that virtual port to another virtual port over TCP and after that to use it in my python application to communicate with python application t... | virtual serial port on Arch linux | I am using Arch linux and I need to create virtual serial port on it. I tried everything but it seems doesnt work. All I want is to connect that virtual port to another virtual port over TCP and after that to use it in my python application to communicate with python application to other side. Is that posible? Please h... | [
"socat command is solution.\nFirst you need to install socat:\npacman -S socat\nJust insert this in console, but first you should be login as root:\nsocat PTY,link=/dev/ttyVirtualS0,echo=0 PTY,link=/dev/ttyVirtualS1,echo=0\nand now we have two virtual serial ports which are virtualy connected:\n/dev/ttyVirtualS0 <-... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0002119217_python.txt |
Q:
Python Pre-testing for exceptions when coverage fails
I recently came across a simple but nasty bug.
I had a list and I wanted to find the smallest member in it. I used Python's built-in min().
Everything worked great until in some strange scenario the list was empty (due to strange user input I could not have ant... | Python Pre-testing for exceptions when coverage fails | I recently came across a simple but nasty bug.
I had a list and I wanted to find the smallest member in it. I used Python's built-in min().
Everything worked great until in some strange scenario the list was empty (due to strange user input I could not have anticipated). My application crashed with a ValueError (BTW - ... | [
"The problem here is that malformed external input crashed your program. The solution is to exhaustively unit test possible input scenarios at the boundaries of your code. You say your unit tests are 'extensive', but you clearly hadn't tested for this possibility. Code coverage is a useful tool, but it's important ... | [
7,
4,
1,
0
] | [] | [] | [
"code_coverage",
"exception_handling",
"python",
"runtime_error",
"unit_testing"
] | stackoverflow_0002647790_code_coverage_exception_handling_python_runtime_error_unit_testing.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.