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:
Red hat enterprise 5 Linux with Python 2.5
I have to deploy a Django project on Red hat enterprise linux 5, the project has been developed on Python 2.5 but the server environment has Python 2.4 which is causing some issues. I googled a lot over internet to get the Python 2.5 built rpm for the server but there are... | Red hat enterprise 5 Linux with Python 2.5 | I have to deploy a Django project on Red hat enterprise linux 5, the project has been developed on Python 2.5 but the server environment has Python 2.4 which is causing some issues. I googled a lot over internet to get the Python 2.5 built rpm for the server but there are only src rpm available for the mentioned Linux ... | [
"I would recommend ActivePython, it's pretty brain dead easy to install and it works pretty well with redhat in my experience.\n",
"Install the python package from http://iuscommunity.org/\n",
"This would help you with finding a linux distro with specifications DistroWatch\nSpecifically Ubuntu 8.10 \"intrepid\"... | [
2,
1,
0
] | [] | [] | [
"django",
"linux",
"python"
] | stackoverflow_0003069842_django_linux_python.txt |
Q:
How to substitute module.Class() to locally defined Class() when loading with Python's Pickle?
I have a pickle dump which has an array of foo.Bar() objects. I am trying to unpickle it, but the Bar() class definition is in the same file that's trying to unpickle, and not in the foo module. So, pickle complains that... | How to substitute module.Class() to locally defined Class() when loading with Python's Pickle? | I have a pickle dump which has an array of foo.Bar() objects. I am trying to unpickle it, but the Bar() class definition is in the same file that's trying to unpickle, and not in the foo module. So, pickle complains that it couldn't find module foo.
I tried to inject foo module doing something similar to:
import im... | [
"class Bar:\n pass\n\nclass MyUnpickler(pickle.Unpickler):\n def find_class(self, module, name):\n if module == \"foo\" and name == \"Bar\":\n return Bar\n else:\n return pickle.Unpickler.find_class(self, module, name)\n\nbars = MyUnpickler(open(\"objects.pkl\")).load()\n\n... | [
4
] | [] | [] | [
"import",
"pickle",
"python"
] | stackoverflow_0003073211_import_pickle_python.txt |
Q:
Query crashes MS Access
THE TASK:
I am in the process of migrating a DB from MS Access to Maximizer. In order to do this I must take 64 tables in MS ACCESS and merge them into one. The output must be in the form of a TAB or CSV file. Which will then be imported into Maximizer.
THE PROBLEM:
Access is unable to perf... | Query crashes MS Access | THE TASK:
I am in the process of migrating a DB from MS Access to Maximizer. In order to do this I must take 64 tables in MS ACCESS and merge them into one. The output must be in the form of a TAB or CSV file. Which will then be imported into Maximizer.
THE PROBLEM:
Access is unable to perform a query that is so comple... | [
"I agree with FrustratedWithFormsDesigner. #2 seems the simplest method. \nHere is some tested code if you decide to go that route (requires pyodbc):\nimport csv\nimport pyodbc\n\nMDB = 'c:/path/to/my.mdb'\nDRV = '{Microsoft Access Driver (*.mdb)}'\nPWD = 'mypassword'\n\nconn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD... | [
6,
2,
1,
0
] | [] | [] | [
"crm",
"ms_access",
"python",
"sql"
] | stackoverflow_0003064830_crm_ms_access_python_sql.txt |
Q:
Can I use the google chat image on google app engine?
I am writing an app using python on GAE. I figure since I'm using google logins as the authentication for my users, why can't I use each users google chat picture as their user portrait? However I haven't found a way to access that info. Maybe I've been using f... | Can I use the google chat image on google app engine? | I am writing an app using python on GAE. I figure since I'm using google logins as the authentication for my users, why can't I use each users google chat picture as their user portrait? However I haven't found a way to access that info. Maybe I've been using facebook api's for too long, but is there any way to access ... | [
"There is a separate API for retrieving a user's profile information, which unfortunately does not currently support profile pictures.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"google_talk",
"python"
] | stackoverflow_0003073267_google_app_engine_google_talk_python.txt |
Q:
Need a way to determine if a file is done being written to
The situation I'm in is this - there's a process that's writing to a file, sometimes the file is rather large say 400 - 500MB. I need to know when it's done writing. How can I determine this? If I look in the directory I'll see it there but it might not... | Need a way to determine if a file is done being written to | The situation I'm in is this - there's a process that's writing to a file, sometimes the file is rather large say 400 - 500MB. I need to know when it's done writing. How can I determine this? If I look in the directory I'll see it there but it might not be done being written. Plus this needs to be done remotely - as... | [
"There are probably many approaches you can take. I would try to open the file with write access. If that succeeds then no-one else is writing to that file.\nBuild a web service around this concept if you don't have direct access to the file between machines.\n",
"I ended up resolving it for our situation. As it... | [
8,
1
] | [] | [] | [
"file_io",
"linux",
"pdf",
"python",
"windows"
] | stackoverflow_0003070210_file_io_linux_pdf_python_windows.txt |
Q:
How to download data to b.csv that like a.csv format from gae localhost server
My a.csv is:
001,哈哈大学
002,拉拉大学
003,啊啊啊大学
004,文网文大学
005,卡卡卡大学
006,请求权大学
007,凤飞飞大学
And my str_loader.py is:
class College(db.Model):
cid = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class CollegeLoa... | How to download data to b.csv that like a.csv format from gae localhost server | My a.csv is:
001,哈哈大学
002,拉拉大学
003,啊啊啊大学
004,文网文大学
005,卡卡卡大学
006,请求权大学
007,凤飞飞大学
And my str_loader.py is:
class College(db.Model):
cid = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class CollegeLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(s... | [
"As per http://appengine-cookbook.appspot.com/recipe/using-the-python-bulk-exporter-tool-with-a-java-application/ , first add the following to your str_loader.py:\nclass CollegeExporter(bulkloader.Exporter):\n def __init__(self):\n bulkloader.Exporter.__init__(self, 'College',\n ... | [
1,
0
] | [
"by loading the data into an sqlite db and then dumping that via the python csv module.\n"
] | [
-2
] | [
"format",
"google_app_engine",
"python"
] | stackoverflow_0003074172_format_google_app_engine_python.txt |
Q:
How to override equals() in google app engine data model type?
I'm using the Python libraries for Google App Engine. How can I override the equals() method on a class so that it judges equality on the user_id field of the following class:
class UserAccount(db.Model):
# compare all equality tests on user_id
... | How to override equals() in google app engine data model type? | I'm using the Python libraries for Google App Engine. How can I override the equals() method on a class so that it judges equality on the user_id field of the following class:
class UserAccount(db.Model):
# compare all equality tests on user_id
user = db.UserProperty(required=True)
user_id = db.StringPrope... | [
"Override operators __eq__ (==) and __ne__ (!=)\ne.g.\nclass UserAccount(db.Model):\n\n def __eq__(self, other):\n if isinstance(other, UserAccount):\n return self.user_id == other.user_id\n return NotImplemented\n\n def __ne__(self, other):\n result = self.__eq__(other)\n ... | [
14
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0003074275_google_app_engine_python_web_applications.txt |
Q:
How can I iterate over only the first variable of a tuple
In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then:
for x,y,z in points:
pass
# do something with x y or z
What if you only want to use the first variable, or the first and the third. Is t... | How can I iterate over only the first variable of a tuple | In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then:
for x,y,z in points:
pass
# do something with x y or z
What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python?
| [
"Is something preventing you from not touching variables that you're not interested in? There is a conventional use of underscore in Python to indicate variable that you're not interested. E.g.:\nfor x, _,_ in points:\n print(x)\n\nYou need to understand that this is just a convention and has no bearing on perfo... | [
8,
7,
5,
4,
2
] | [] | [] | [
"loops",
"python",
"tuples"
] | stackoverflow_0003061336_loops_python_tuples.txt |
Q:
is a decorator in python exactly the same as calling a function on a function?
I thought that doing
@f
def g():
print 'hello'
is exactly the same as
def g():
print 'hello'
g=f(g)
But, I had this code, that uses contextlib.contextmanager:
@contextlib.contextmanager
def f():
print 1
yield
print ... | is a decorator in python exactly the same as calling a function on a function? | I thought that doing
@f
def g():
print 'hello'
is exactly the same as
def g():
print 'hello'
g=f(g)
But, I had this code, that uses contextlib.contextmanager:
@contextlib.contextmanager
def f():
print 1
yield
print 2
with f:
print 3
which works and yields 1 3 2
And when I tried to change it in... | [
"Yes, decorator is exactly same as calling a function and assigning to returned value\nIn this case error comes because you are not calling function, so correct code would be\ndef f():\n print 1\n yield\n print 2\n\nf=contextlib.contextmanager(f)\nwith f():\n print 3\n\nalso I am not sure if you tested ... | [
5
] | [] | [] | [
"contextmanager",
"decorator",
"python"
] | stackoverflow_0003074672_contextmanager_decorator_python.txt |
Q:
Python IRC Client
import socket, sys, string
if len(sys.argv) !=4 :
print "Usage: ./supabot.py <host> <port> <channel>"
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
chan = sys.argv[3]
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sc... | Python IRC Client | import socket, sys, string
if len(sys.argv) !=4 :
print "Usage: ./supabot.py <host> <port> <channel>"
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
chan = sys.argv[3]
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT su... | [
"nick = data.split('!')[ 0 ].replace(':',' ') \n\nThat's going to replace the : with a space (), and thus the resulting string will be \"s0urd \", not \"s0urd\". You probably meant this instead:\nnick = data.split('!')[ 0 ].replace(':','')\n\nNote the lack of space between the '' being passed as the replacement str... | [
1
] | [] | [] | [
"irc",
"python",
"sockets"
] | stackoverflow_0003074734_irc_python_sockets.txt |
Q:
Python | How to create complex dictionary
I want to create a data structure that will be parse as a JSON object. The out put must look like this and this should be a dynamic data structure.
{"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876},
{"type": "poi", "lat": -34.96615974838191... | Python | How to create complex dictionary | I want to create a data structure that will be parse as a JSON object. The out put must look like this and this should be a dynamic data structure.
{"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876},
{"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126},
{"type": "locale"... | [
"As response to the comment on Mathiasdm answer:\nYou mean how to create dictionary with a list of dictionaries?\nThat can be done like this:\ndict = {}\ndict[\"data\"] = []\ndict[\"data\"].append({'type': 'poi', 'lat': 123})\ndict[\"data\"].append({'type': 'locale', 'lat': 321})\n\nAnd so on.\nBut if this was real... | [
6,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003075021_python.txt |
Q:
Timeout with Ajaxterm
I have a similar question to this: PHP session timeout callback?
Basically, I want to run some code once a user has been inactive for a certain amount of time. However my case is a little more tricky than the above question. This is because I am using Ajaxterm: http://antony.lesuisse.org/soft... | Timeout with Ajaxterm | I have a similar question to this: PHP session timeout callback?
Basically, I want to run some code once a user has been inactive for a certain amount of time. However my case is a little more tricky than the above question. This is because I am using Ajaxterm: http://antony.lesuisse.org/software/ajaxterm/
My php scrip... | [
"The question you've posted is not only similar to what you want, it's pretty much the same. I guess you're asking how to do the cleanup task, which consists of killing ajaxterm.\nThere way I describe here works for Linux, but is portable with a little effort. To identify and kill a process you need to know the pro... | [
0
] | [] | [] | [
"apache",
"php",
"python"
] | stackoverflow_0003075037_apache_php_python.txt |
Q:
python - Which is the better way to enable/disable logging?
Which is better way to enable/disable logging?
1) Changing log levels,
logging.disable(logging.CRITICAL)
2)
log = None
And logging messages this way,
if log:
log.info("log message")
So that we can avoid unnecessary string constructions in case of l... | python - Which is the better way to enable/disable logging? | Which is better way to enable/disable logging?
1) Changing log levels,
logging.disable(logging.CRITICAL)
2)
log = None
And logging messages this way,
if log:
log.info("log message")
So that we can avoid unnecessary string constructions in case of logging disabled...
| [
"1 is best, ideally via a configuration file or command line argument (--quiet)\n2 will just clutter up your code\nIf you want to avoid expensive string construction (this is probably worthwhile about 0.001% of the time in my experience), use:\nif logger.isEnabledFor(logging.DEBUG):\n logger.debug(\"Message with... | [
15
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0003075202_logging_python.txt |
Q:
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases.
Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is ... | From the web to games | I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases.
Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I alre... | [
"Python's Pygame is certainly a good choice as others have said. If you want to get in to deep video game programming though.. move on to something like C++ or another lower level language.. from experience, most higher level languages tend to put artificial hurdles up in regards to decent video games. Though for a... | [
3,
2,
1,
0,
0,
0
] | [] | [] | [
"javascript",
"php",
"python"
] | stackoverflow_0003074103_javascript_php_python.txt |
Q:
unusual django admin behavior when storing string values
Using django trunk r13359 and django piston, I created a small restful service that stores string values.
This is the model I am using to store strings:
class DataStore(models.Model):
data = models.CharField(max_length=200)
url = models.URLField(def... | unusual django admin behavior when storing string values | Using django trunk r13359 and django piston, I created a small restful service that stores string values.
This is the model I am using to store strings:
class DataStore(models.Model):
data = models.CharField(max_length=200)
url = models.URLField(default = '', verify_exists=False, blank = True)
I used curl to ... | [
"Actually your response is also not what should be expected, note the [] around your strings, those shouldn't be there.\nYour error is adding the comma after these two lines: \nstore.url = request.POST.get('url',\"\"),\nstore.data = request.POST['data'],\n\nPython will interprete you want to store a tuple in url an... | [
1
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0003075326_django_django_piston_python.txt |
Q:
In a pylons web app, should a cookie be set from a model class or a controller?
Trying to figure out the best way to do this:
Should I do something like:
def index(self):
if request.POST:
u = User(id)
u.setCookie() #All session logic in def setCookie()
Or set the cookie in the controller like:... | In a pylons web app, should a cookie be set from a model class or a controller? | Trying to figure out the best way to do this:
Should I do something like:
def index(self):
if request.POST:
u = User(id)
u.setCookie() #All session logic in def setCookie()
Or set the cookie in the controller like:
def index(self):
if request.POST:
u = User(id)
response.set_cook... | [
"I think traditionally you would want the model to be concerned with data persistence and validation but not http related stuff like cookies. Which leaves the controller to be the more appropriate place in my opinion. \nA reason(not the only one) I can think of for this is that it might be required someday that you... | [
2,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002396804_pylons_python.txt |
Q:
(python) recursively remove capitalisation from directory structure?
uppercase letters - what's the point of them? all they give you is rsi.
i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python?
it should recursively parse a specified di... | (python) recursively remove capitalisation from directory structure? | uppercase letters - what's the point of them? all they give you is rsi.
i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python?
it should recursively parse a specified directory, identify the file/folder names with capital letters and rename th... | [
"os.walk is great for doing recursive stuff with the filesystem.\nimport os\n\ndef lowercase_rename( dir ):\n # renames all subforders of dir, not including dir itself\n def rename_all( root, items):\n for name in items:\n try:\n os.rename( os.path.join(root, name), \n ... | [
16,
2
] | [] | [] | [
"python",
"uppercase"
] | stackoverflow_0003075443_python_uppercase.txt |
Q:
How do I override a Python import?
I'm working on pypreprocessor which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports.
The problem is: The prepr... | How do I override a Python import? | I'm working on pypreprocessor which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports.
The problem is: The preprocessor runs through the file, processes... | [
"Does this answer your question? The second import does the trick.\nMod_1.py\ndef test_function():\n print \"Test Function -- Mod 1\"\n\nMod_2.py\ndef test_function():\n print \"Test Function -- Mod 2\"\n\nTest.py\n#!/usr/bin/python\n\nimport sys\n\nimport Mod_1\n\nMod_1.test_function()\n\ndel sys.modules['M... | [
44,
14,
0
] | [] | [] | [
"import",
"overriding",
"preprocessor",
"python"
] | stackoverflow_0003012473_import_overriding_preprocessor_python.txt |
Q:
Python multiprocessing/threading with shared variables that only will be read
Considering the code below. I would like to run 3 experiments at a time. The experiments are independent, the only thing they share is the Model object which they only read.
As there are seemingly no hard things in threading this out, ho... | Python multiprocessing/threading with shared variables that only will be read | Considering the code below. I would like to run 3 experiments at a time. The experiments are independent, the only thing they share is the Model object which they only read.
As there are seemingly no hard things in threading this out, how can I best do this in Python? I would like to use a pool or so to make sure that ... | [
"Check the docs, specifically:\nhttp://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool\nThere really are a lot of examples there that should get you on your way. For instance, I could come up with:\n#!/usr/bin/env python2.6\nimport time\nimport multiprocessing\n\nclass Model:\n name = \"... | [
3,
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0003071602_multiprocessing_multithreading_python.txt |
Q:
Reboot windows machines at a certain time of day and automatically login with Python
I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and ... | Reboot windows machines at a certain time of day and automatically login with Python | I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and go home, or shutdown their computers, whatever, python or some combination of python + win... | [
"You probably want to consider running whatever program you're considering as a Windows service, unless you absolute need a desktop. There are a couple of questions concerning that, e.g. here and here, as well as recipes on Active State. That involves no real need to start up or login to the computer.\nThere's also... | [
3,
1,
0
] | [] | [] | [
"authentication",
"boot",
"python",
"restart"
] | stackoverflow_0003066438_authentication_boot_python_restart.txt |
Q:
HTTP Banner Grabbing with Python
I am interested in making an HTTP Banner Grabber, but when i connect to a server on port 80 and i send something (e.g. "HEAD / HTTP/1.1") recv doesn't return anything to me like when i do it in let's say netcat..
How would i go about this?
Thanks!
A:
Are you sending a "\r\n\r\n" ... | HTTP Banner Grabbing with Python | I am interested in making an HTTP Banner Grabber, but when i connect to a server on port 80 and i send something (e.g. "HEAD / HTTP/1.1") recv doesn't return anything to me like when i do it in let's say netcat..
How would i go about this?
Thanks!
| [
"Are you sending a \"\\r\\n\\r\\n\" to indicate the end of the request? If you're not, the server's still waiting for the rest of the request.\n",
"Try using the urllib2 module.\n>>> data = urllib2.urlopen('http://www.example.com').read()\n>>> print data\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional... | [
2,
2
] | [] | [] | [
"netcat",
"python"
] | stackoverflow_0003076263_netcat_python.txt |
Q:
Pylons: Proper Way to Establish Per-Thread/Per-Request Resource?
I have a connection to an external resource that I need to make for my Pylons app (think along the lines of a database connection.) There is a modest amount of overhead involved in establishing the connection.
I could setup a piece of middleware that... | Pylons: Proper Way to Establish Per-Thread/Per-Request Resource? | I have a connection to an external resource that I need to make for my Pylons app (think along the lines of a database connection.) There is a modest amount of overhead involved in establishing the connection.
I could setup a piece of middleware that opens and closes the connection with every request but that seems was... | [
"Do the connections have to belong to a single thread for their lifetime? \nIf not, you could consider implementing your own connection pool for this resource. The pool would be responsible for initializing connections and each thread would acquire and release the connections as they are needed. \nIf you want to... | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003076348_pylons_python.txt |
Q:
How to update data to gae localhost server from MySQL?
I follow this article to update data to gae localhost server from MySQL.
This is my str_loader.py is:
class College(db.Model):
cid = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class MySQLLoader(bulkloader.Loader):
def... | How to update data to gae localhost server from MySQL? | I follow this article to update data to gae localhost server from MySQL.
This is my str_loader.py is:
class College(db.Model):
cid = db.StringProperty(required=True)
name = db.StringProperty(required=True)
class MySQLLoader(bulkloader.Loader):
def generate_records(self, filename):
"""Generates reco... | [
"Your Mysql_update class needs to subclass MySQLLoader, not bulkloader.Loader.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"mysql",
"python"
] | stackoverflow_0003074918_google_app_engine_mysql_python.txt |
Q:
Virtual classes: doing it right?
I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some m... | Virtual classes: doing it right? | I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the p... | [
"I agree with TooAngel, but I'd use the __new__ method.\nclass Shape(object):\n def __new__(cls, *args, **kwargs):\n if cls is Shape: # <-- required because Line's\n description, args = args[0], args[1:] # __new__ method is the\n if description == \"I... | [
18,
15,
1,
0
] | [] | [] | [
"abstract",
"class",
"inheritance",
"python",
"virtual"
] | stackoverflow_0003076537_abstract_class_inheritance_python_virtual.txt |
Q:
how to introspect a couchdb document for its set of fields via couchdb-python
How can I get the fields for a couchdb document? I'm thinking of how to use couchdb-python, and often will not know the complete set of fields for a document. I haven't seen anything about how to introspect a document in the docs. What... | how to introspect a couchdb document for its set of fields via couchdb-python | How can I get the fields for a couchdb document? I'm thinking of how to use couchdb-python, and often will not know the complete set of fields for a document. I haven't seen anything about how to introspect a document in the docs. What's the best way? If the document was a python object I would query object.__dict__... | [
".keys() returns a list of field names.\ndb = server['test']\nfor doc in db:\n print doc\n for key in db[doc].keys():\n print key\n\nYou should get the doc id, followed by the fields.\n"
] | [
0
] | [] | [] | [
"couchdb",
"python"
] | stackoverflow_0003076438_couchdb_python.txt |
Q:
Optimizing operations on lists
I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python.
The main ways I've come up with are using:
- List comprehensions
- generator expressions
- functional style operations (map,filter etc.)
I know generally list comp... | Optimizing operations on lists | I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python.
The main ways I've come up with are using:
- List comprehensions
- generator expressions
- functional style operations (map,filter etc.)
I know generally list comprehensions are probably the most "Py... | [
"Inspired by this answer: Python List Comprehension Vs. Map , I've tweaked the questions to allow generator expressions to be compared:\nFor built-ins:\n$ python -mtimeit -s 'import math;xs=range(10)' 'sum(map(math.sqrt, xs))'\n100000 loops, best of 3: 2.96 usec per loop\n$ python -mtimeit -s 'import math;xs=range(... | [
1
] | [] | [] | [
"list",
"performance",
"python"
] | stackoverflow_0003075375_list_performance_python.txt |
Q:
Python ctypes - how to handle arrays of strings
I'm trying to call an external library function that returns a NULL-terminated array of NULL-terminated strings.
kernel32 = ctypes.windll.kernel32
buf = ctypes.create_unicode_buffer(1024)
length = ctypes.c_int32()
if kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c... | Python ctypes - how to handle arrays of strings | I'm trying to call an external library function that returns a NULL-terminated array of NULL-terminated strings.
kernel32 = ctypes.windll.kernel32
buf = ctypes.create_unicode_buffer(1024)
length = ctypes.c_int32()
if kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume),
buf, ctypes.sizeof(buf), ctypes... | [
"After discovering ctypes.wstring_at() and ctypes.addressof(), I got this:\ndef wszarray_to_list(array):\n offset = 0\n while offset < ctypes.sizeof(array):\n sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)\n if sz:\n yield sz\n offset += len(sz)+1\n else:... | [
6,
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003073478_ctypes_python.txt |
Q:
Start nano as a subprocess from python, capture input
I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the subprocess module before, nor pipes, so I don't know what to try next.
So far I have this ... | Start nano as a subprocess from python, capture input | I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the subprocess module before, nor pipes, so I don't know what to try next.
So far I have this code:
a = subprocess.Popen('nano', stdout=subprocess.PIPE, ... | [
"Control-O in Nano writes to the file being edited, i.e., not to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac:\n>>> import tempfile\n>>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\n>>> n = f.name\n>>> f... | [
10,
4
] | [] | [] | [
"pipe",
"popen",
"python",
"subprocess"
] | stackoverflow_0003076798_pipe_popen_python_subprocess.txt |
Q:
Google App Engine Unittest: Difficulty with AssertEquals
I have a unit test for my GAE app:
def test_getNeighborhoodKeys_twoCourses(self):
cs1110, cs2110 = testutils.setUpSimpleCourses()
foo = getFooResult()
bar = getBarResult()
self.assertEquals(foo, bar) # fails
This is... | Google App Engine Unittest: Difficulty with AssertEquals | I have a unit test for my GAE app:
def test_getNeighborhoodKeys_twoCourses(self):
cs1110, cs2110 = testutils.setUpSimpleCourses()
foo = getFooResult()
bar = getBarResult()
self.assertEquals(foo, bar) # fails
This is the failure:
AssertionError: set([CS 1110: Untitled, CS 2110:... | [
"Looks like the items belonging to sets foo and bar are of some extremely funky type which overrides __repr__ -- otherwise, with normal types, there would be quotes to clarify exactly what's inside those brackets. Thus, that type must also override __eq__ to determine equality conditions (otherwise, by default, tw... | [
5
] | [] | [] | [
"google_app_engine",
"python",
"unit_testing"
] | stackoverflow_0003076856_google_app_engine_python_unit_testing.txt |
Q:
What is the difference between these two solutions - lambda or loop - Python
I want to calculate the sum of even numbers within a domain. I have two solutions, but I'm not sure of the advantages/disadvantages of each. Which is the optimal solution?
import sys
domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Cal1 = sum(fil... | What is the difference between these two solutions - lambda or loop - Python | I want to calculate the sum of even numbers within a domain. I have two solutions, but I'm not sure of the advantages/disadvantages of each. Which is the optimal solution?
import sys
domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Cal1 = sum(filter(lambda n : n % 2 == 0, domain))
Cal2 = sum([n for n in domain if n % 2 == 0])
... | [
"The second really should be just a generator, not a list comprehension (since you don't actually need to create a list to be able to sum the output of a generator):\nCal2 = sum(n for n in domain if n % 2 == 0)\n\nIt's the now-preferred (\"pythonic\") way for accomplishing this task.\n\nUsing a list comprehension (... | [
13,
7,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003076692_python.txt |
Q:
Python: Is this an ok way of overriding __eq__ and __hash__?
I'm new to Python, and I wanted to make sure that I overrode __eq__ and __hash__ correctly, so as not to cause painful errors later:
(I'm using Google App Engine.)
class Course(db.Model):
dept_code = db.StringProperty()
number = db.IntegerPropert... | Python: Is this an ok way of overriding __eq__ and __hash__? | I'm new to Python, and I wanted to make sure that I overrode __eq__ and __hash__ correctly, so as not to cause painful errors later:
(I'm using Google App Engine.)
class Course(db.Model):
dept_code = db.StringProperty()
number = db.IntegerProperty()
title = db.StringProperty()
raw_pre_reqs = db.StringPr... | [
"The first one is fine. The second one is problematic for two reasons:\n\nthere might be duplicates in .courses\ntwo entities with identical .courses but different .forwardLinks would compare equal but have different hashes\n\nI would fix the second one by making equality depend on both courses and forward links, ... | [
17
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0003076967_hash_python.txt |
Q:
Quoting long strings without newlines in Python
I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string ... | Quoting long strings without newlines in Python | I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string is displayed when the code is run. For example, I wa... | [
"You can concatenate string literals just like in C, so \"foo\" \"bar\" is the same as \"foobar\", meaning this should do what you want:\nparser.add_option(\"--my-option\", dest=\"my_option\", nargs=2, default=None, \n help=\"Here is a long description of my option. It does many things \"\n \"but... | [
22,
10,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003076979_python.txt |
Q:
How to Exporter gae data to MySQL?
I have a 'College' model data.
My str_loader.py is:
class MySQLExporter(bulkloader.Exporter):
def output_entities(self, entity_generator):
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8")
c = conn.cursor()
for... | How to Exporter gae data to MySQL? | I have a 'College' model data.
My str_loader.py is:
class MySQLExporter(bulkloader.Exporter):
def output_entities(self, entity_generator):
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8")
c = conn.cursor()
for entity in entity_generator:
c... | [
"Try calling .commit() on the connection after loading the entities.\n"
] | [
1
] | [] | [] | [
"download",
"google_app_engine",
"mysql",
"python"
] | stackoverflow_0003076933_download_google_app_engine_mysql_python.txt |
Q:
Node.TEXT_NODE has the value, but I need the Attribute
I have an xml file like so:
<host name='ip-10-196-55-2.ec2.internal'>
<hostvalue name='arch_string'>lx24-x86</hostvalue>
<hostvalue name='num_proc'>1</hostvalue>
<hostvalue name='load_avg'>0.01</hostvalue>
</host>
I can get get out the Node.data fro... | Node.TEXT_NODE has the value, but I need the Attribute | I have an xml file like so:
<host name='ip-10-196-55-2.ec2.internal'>
<hostvalue name='arch_string'>lx24-x86</hostvalue>
<hostvalue name='num_proc'>1</hostvalue>
<hostvalue name='load_avg'>0.01</hostvalue>
</host>
I can get get out the Node.data from a Node.TEXT_NODE, but I also need the Attribute name, like... | [
"here's a short example of what you could achieve:\nfrom xml.dom import minidom\n\nxmldoc = minidom.parse(\"so.xml\")\n\nvalues = {}\n\nfor stat in xmldoc.getElementsByTagName(\"hostvalue\"):\n attr = stat.attributes[\"name\"].value\n value = \"\\n\".join([x.data for x in stat.childNodes])\n values[attr] =... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003073471_python_xml.txt |
Q:
Fastest way of deleting certain keys from dict in Python
I'm looking for most fastest/effective way of deleting certain keys in a python dict
Here are some options
for k in somedict.keys():
if k.startswith("someprefix"):
del somedict[k]
or
dict((k, v) for (k, v) in somedict.iteritems() if not k.star... | Fastest way of deleting certain keys from dict in Python | I'm looking for most fastest/effective way of deleting certain keys in a python dict
Here are some options
for k in somedict.keys():
if k.startswith("someprefix"):
del somedict[k]
or
dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))
Logically first snippet should be faste... | [
"Not only is del more easily understood, but it seems slightly faster than pop():\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"for k in d.keys():\" \" if k.startswith('f'):\" \" del d[k]\"\n1000000 loops, best of 3: 0.733 usec per loop\n\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"for k... | [
18,
9
] | [] | [] | [
"dictionary",
"filter",
"python"
] | stackoverflow_0003077145_dictionary_filter_python.txt |
Q:
Instrumentation for numerical linear algebra in Python
I use numpy for numerical linear algebra. I suspect that I can get much better performance if I make small modifications in how I carry out certain computations so that they are more memory efficient, for example.
I was wondering if there is any form of instru... | Instrumentation for numerical linear algebra in Python | I use numpy for numerical linear algebra. I suspect that I can get much better performance if I make small modifications in how I carry out certain computations so that they are more memory efficient, for example.
I was wondering if there is any form of instrumentation available in python to detect cache and TLB misses... | [
"Maybe one of the provided profilers might help you find the hotspots? \nsee profiling python\nThese will probably not give enough detail to trigger direct action, but should indicate where to look for improvement and help to determine the point of diminishing returns.\n",
"Robert Kern (one of the NumPy devs) wro... | [
1,
1
] | [] | [] | [
"instrumentation",
"linear_algebra",
"numpy",
"python",
"scipy"
] | stackoverflow_0003077061_instrumentation_linear_algebra_numpy_python_scipy.txt |
Q:
Mercurial/Python - What Does The Underscore Function Do?
In Mercurial, many of the extensions wrap their help/syntax string in a call to an underscore function, like so:
_('[OPTION] [QUEUE]')
This confuses me, because it does not seem necessary (the Writing Extensions instructions don't mention it) and there doe... | Mercurial/Python - What Does The Underscore Function Do? | In Mercurial, many of the extensions wrap their help/syntax string in a call to an underscore function, like so:
_('[OPTION] [QUEUE]')
This confuses me, because it does not seem necessary (the Writing Extensions instructions don't mention it) and there doesn't seem to be a _ defined in the class, so I'm wondering if ... | [
"Look on line 45:\nfrom mercurial.i18n import _\n\nThis is the usual abbreviation in the internationalization package gettext, and possibly other packages too, for the function that returns a translation of its argument to the language the program is currently running in. It's abbreviated to _ for convenience, sinc... | [
8,
7
] | [] | [] | [
"magic_function",
"mercurial",
"python"
] | stackoverflow_0003077227_magic_function_mercurial_python.txt |
Q:
Invoke Django template renderer in memory without any files from strings?
I have built a Macro language for my users that is based upon the Django template language. Users enter into UITextFields their template/macro snippets that can be rendered in the context of larger documents. So I have large multi-line str... | Invoke Django template renderer in memory without any files from strings? | I have built a Macro language for my users that is based upon the Django template language. Users enter into UITextFields their template/macro snippets that can be rendered in the context of larger documents. So I have large multi-line string snippets of django template code that should be populated with variables th... | [
"from django.template import Context, Template\n\ntemplate = Template(\"this is a template string! {{ foo }}\")\nc = Context({\"foo\": \"barbarbar\"})\nprint template.render(c)\n\n"
] | [
8
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003077272_django_django_templates_python.txt |
Q:
Python Apache local/internal server error?
I am creating HTML form and using Python to code it. I have installed Apache version2.2 and Python version 2.6. Here is the code:
#!C:\Python26\Python.exe -u
#import cgi modules
import cgi
#create instances of field storage
form = cgi.FieldStorage()
#get data from the ... | Python Apache local/internal server error? | I am creating HTML form and using Python to code it. I have installed Apache version2.2 and Python version 2.6. Here is the code:
#!C:\Python26\Python.exe -u
#import cgi modules
import cgi
#create instances of field storage
form = cgi.FieldStorage()
#get data from the fields
first_name = form.getvalue('first_name')
... | [
"Something is definitely wrong is you subtracted those lines, and it still ran. print \"<h2>Hello %s %s</h2>\" % (first_name, last_name) in your HTML body should raise an exception, given that they are not defined yet.\nPlease post the bits of your error.log for the Internal Server Error.\n"
] | [
0
] | [] | [] | [
"apache2",
"apache2.2",
"cgi_bin",
"html",
"python"
] | stackoverflow_0003077312_apache2_apache2.2_cgi_bin_html_python.txt |
Q:
I can't connect to socket from the outside
I am trying to make a simple server/client program pair.
On LAN they work fine, but when i try to connect from the "outside" it says connection refused. I shut down firewalls on both machines but i am still unable to connect, and i double checked the ip.
What am i doing ... | I can't connect to socket from the outside | I am trying to make a simple server/client program pair.
On LAN they work fine, but when i try to connect from the "outside" it says connection refused. I shut down firewalls on both machines but i am still unable to connect, and i double checked the ip.
What am i doing wrong?
Thanks
Jake
Code:
import socket
host = '... | [
"You have one of two possible issues. \n\nErroneous network configuration\nBug(s) in code\n\nThe way to debug this is to try and rule one out. If we can get rid of the Code issue then we know it is a network issue.\nGet a Socket Server and client that you know works and then try them as standalone programs. inside... | [
3,
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003077390_python_sockets.txt |
Q:
Python: Run WSGI server from inetd?
As the title suggests, is it possible to run a WSGI server from (x)inetd?
A:
Yes, but don't do it.
| Python: Run WSGI server from inetd? | As the title suggests, is it possible to run a WSGI server from (x)inetd?
| [
"Yes, but don't do it.\n"
] | [
1
] | [] | [] | [
"inetd",
"python",
"wsgi"
] | stackoverflow_0003077557_inetd_python_wsgi.txt |
Q:
Error in creating HTML form using Python-CGI
I have to create a HTML form and get the data using python-cgi. HTML form requires user to submit firstname and lastname and then the python script is supposed to get the data generated in the form. I have read up tutorials and tried playing with it to make it work, but... | Error in creating HTML form using Python-CGI | I have to create a HTML form and get the data using python-cgi. HTML form requires user to submit firstname and lastname and then the python script is supposed to get the data generated in the form. I have read up tutorials and tried playing with it to make it work, but it does not seem to happen.
HTML code:
<form met... | [
"At least in what you just showed, there are syntax errors:\nif form.has_key(\"firstname\") amd form[\"firstname\"].value !=\"\":\nprint \"<h1>Hello\", form[\"firstname\"].value, \"</h1>\"\nelse:\nprint \"<h1> Error!Wrong!</h1>\n\namd should be and, and both print statements should be indented deeper than the if an... | [
0
] | [] | [] | [
"apache",
"cgi",
"forms",
"python"
] | stackoverflow_0003077724_apache_cgi_forms_python.txt |
Q:
MySQL_Python on Snow Leopard
I've tried to solve this myself searching and searching but I can't get it to work. :( I'm in Snow Leopard 10.6.4 and tried to setup my Django environment, first I upgraded my python to 2.6.5, installed django and then mysql_python. All seems to be smooth until I to connect to mysql us... | MySQL_Python on Snow Leopard | I've tried to solve this myself searching and searching but I can't get it to work. :( I'm in Snow Leopard 10.6.4 and tried to setup my Django environment, first I upgraded my python to 2.6.5, installed django and then mysql_python. All seems to be smooth until I to connect to mysql using syncdb.
Got this error/trace m... | [
"type:\nwhich python\n\nfigure out where it is pulling python 2.6.5 (which is not the current python as distributed by Apple). You might be able to symlink /usr/bin/python to your 2.6.5 installation, but, that just seems like you're asking for trouble.\nYou could install your mysqldb within your virtual environmen... | [
0,
0,
0
] | [] | [] | [
"django",
"macos",
"mysql",
"osx_snow_leopard",
"python"
] | stackoverflow_0003076746_django_macos_mysql_osx_snow_leopard_python.txt |
Q:
Broken Link On Django Admin Interface
I'm currently reading Practical Django Projects and in the Django admin interface there is an option to "View on site" when entering information.
But after finishing chapter 5 of the book I started to tinker with the admin interface and found that clicking this link with my ca... | Broken Link On Django Admin Interface | I'm currently reading Practical Django Projects and in the Django admin interface there is an option to "View on site" when entering information.
But after finishing chapter 5 of the book I started to tinker with the admin interface and found that clicking this link with my categories app doesn't work as it isn't appen... | [
"It uses the get_absolute_url() method on the model. Change that and it should work :)\n[edit]\nFor the edited question.\nIn your category model you are using a hardcoded link while you are using a permalink at the entries model. I suggest you use permalinks at both locations to solve the problem.\nHere's the docum... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_urls",
"python"
] | stackoverflow_0003077909_django_django_admin_django_urls_python.txt |
Q:
Does GQL automatically add an "ID" Property
I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically?
regards,
A:
An object has a Key, part of which is either an automati... | Does GQL automatically add an "ID" Property | I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically?
regards,
| [
"An object has a Key, part of which is either an automatically-generated numeric ID, or an assigned key name. IDs are not guaranteed to be increasing, and they're almost never going to be consecutive because they're allocated to an instance in big chunks, and IDs unused by the instance to which they're allocated w... | [
4,
3,
2
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0003077156_google_app_engine_gql_python.txt |
Q:
Optimization: Python String Repetition
I have a piece of code that will take a string and repeat it such that the length of the string is x.
>>> import math
>>> def repeat(data, length):
return (data * int(math.ceil(float(length) / len(data))))[:length]
>>> repeat("Hello World", 22)
'Hello WorldHello World... | Optimization: Python String Repetition | I have a piece of code that will take a string and repeat it such that the length of the string is x.
>>> import math
>>> def repeat(data, length):
return (data * int(math.ceil(float(length) / len(data))))[:length]
>>> repeat("Hello World", 22)
'Hello WorldHello World'
>>> repeat("Hello World", 20)
'Hello World... | [
"This might be marginally faster:\ndef repeat(string, length):\n L = len(string)\n return string * (length // L) + string[:length % L]\n\nI say \"might\" because a LOT depends on the typical string and length! With 'Hello World' and 61, I've timed this (on an old Mac laptop) at 1 microsecond vs 1.66 microseconds... | [
3,
0,
0,
0
] | [] | [] | [
"python",
"repeat",
"string"
] | stackoverflow_0003077899_python_repeat_string.txt |
Q:
How does the right-shift operator work in a python print statement?
I've seen someone using "print" with ">>" to write stuffs into a file:
In [7]: with open('text', 'w') as f:
...: print >> f, "Hello, world!"
...:
In [8]: !type text
Hello, world!
How does it work? When should I use this instead of just... | How does the right-shift operator work in a python print statement? | I've seen someone using "print" with ">>" to write stuffs into a file:
In [7]: with open('text', 'w') as f:
...: print >> f, "Hello, world!"
...:
In [8]: !type text
Hello, world!
How does it work? When should I use this instead of just using the "write" method?
| [
"From https://docs.python.org/2/reference/simple_stmts.html#the-print-statement\n\nprint also has an extended form,\n defined by the second portion of the\n syntax described above. This form is\n sometimes referred to as “print\n chevron.” In this form, the first\n expression after the >> must evaluate\n to a... | [
16
] | [] | [] | [
"grammar",
"python"
] | stackoverflow_0003078042_grammar_python.txt |
Q:
Python output out of order
I needed some really simple XML output so I decided to write my own functions. This was just the first step, but something has gone terribly wrong. While I would expect the output to look like this:
<A>
<D>
<I></I>
<J></J>
<K></K>
</D>
<E>
<I>... | Python output out of order | I needed some really simple XML output so I decided to write my own functions. This was just the first step, but something has gone terribly wrong. While I would expect the output to look like this:
<A>
<D>
<I></I>
<J></J>
<K></K>
</D>
<E>
<I></I>
<J></J>
<K>... | [
"You're not returning the result, but rather printing it directly. Therefore it will be outputted in the order that the functions execute. Your code is equivalent to the following, which clarifies the order in which the functions are called:\na = XMLChild(list3, 2)\nb = XMLParent(list2, 1, a)\nXMLParent(list1, 0, b... | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003078044_python_xml.txt |
Q:
Is there an open-source eMail message (headers, attachments, etc.) parser?
Is there a free open-source solution taking raw e-mail message (as a piece of text) and returning each header field, each attachment and the message body as separate fields?
A:
Yes... For each language you pointed out, I've used the one i... | Is there an open-source eMail message (headers, attachments, etc.) parser? | Is there a free open-source solution taking raw e-mail message (as a piece of text) and returning each header field, each attachment and the message body as separate fields?
| [
"Yes... For each language you pointed out, I've used the one in Python myself. Try perusing the library documentation for your chosen library.\n(Note: You may be expecting a \"nice\", high-level library for this parsing... That's a tricky area, email has evolved and grown without much design, there are a lot of d... | [
2,
1,
0
] | [] | [] | [
"email",
"java",
"parsing",
"php",
"python"
] | stackoverflow_0003078189_email_java_parsing_php_python.txt |
Q:
easy, straightforward way to package a python program for debian?
i'm having trouble navigating the maze of distribution tools for python and debian; cdbs, debhelper, python-support, python-central, blah blah blah ..
my application is a fairly straightforward one - a single python package (directory containing mod... | easy, straightforward way to package a python program for debian? | i'm having trouble navigating the maze of distribution tools for python and debian; cdbs, debhelper, python-support, python-central, blah blah blah ..
my application is a fairly straightforward one - a single python package (directory containing modules and a __init__.py), a script for running the program (script.py) a... | [
"python-stdeb should work for you. It's on Debian testing/unstable and Ubuntu (Lucid onwards). apt-get install python-stdeb\nIt is less a shortcut method than a tool that tries to generate as much of the source package as possible. It can actualy build a package that both works properly and is almost standards comp... | [
5,
3
] | [] | [] | [
"cdbs",
"deb",
"debhelper",
"debian",
"python"
] | stackoverflow_0002927615_cdbs_deb_debhelper_debian_python.txt |
Q:
How to make a cost effective but scalable site?
Portal Technology Assessment in which we will be creating a placement portal for the campuses and industry to help place students. The portal will handle large volumes of data and people logging in, approximately 1000 users/day in a concurrent mode.
What technology s... | How to make a cost effective but scalable site? | Portal Technology Assessment in which we will be creating a placement portal for the campuses and industry to help place students. The portal will handle large volumes of data and people logging in, approximately 1000 users/day in a concurrent mode.
What technology should i use? PHP with CakePHP as a framework, Ruby on... | [
"Any of those will do, it really depends on what you know. If you're comfortable with Python, use Django. If you like Ruby go with ROR. These modern frameworks are built to scale, assuming you're not going to be developing something on the scale of facebook then they should suffice.\nI personally recommend nginx as... | [
2,
1
] | [] | [] | [
"lamp",
"python"
] | stackoverflow_0003078364_lamp_python.txt |
Q:
Save PyML.classifiers.multi.OneAgainstRest(SVM()) object?
I'm using PYML to construct a multiclass linear support vector machine (SVM). After training the SVM, I would like to be able to save the classifier, so that on subsequent runs I can use the classifier right away without retraining. Unfortunately, the .save... | Save PyML.classifiers.multi.OneAgainstRest(SVM()) object? | I'm using PYML to construct a multiclass linear support vector machine (SVM). After training the SVM, I would like to be able to save the classifier, so that on subsequent runs I can use the classifier right away without retraining. Unfortunately, the .save() function is not implemented for that classifier, and attempt... | [
"In multi.py on line 96 \"self.classifiers[i].train(datai)\" is called without passing \"**args\", so that if you call \"mc.train(data, saveSpace=False)\", this saveSpace-Argument gets lost. This is why you get an error message if you try to save the classifiers in your multiclass-classifier individually. But if yo... | [
2,
0
] | [] | [] | [
"libsvm",
"pickle",
"pyml",
"python",
"svm"
] | stackoverflow_0002674123_libsvm_pickle_pyml_python_svm.txt |
Q:
how to check if an ip address or proxy is working or not
How can I check if a specific ip address or proxy is alive or dead
A:
Because there may be any level of filtering or translation between you and the remote host, the only way to determine whether you can connect to a specific host is to actually try to con... | how to check if an ip address or proxy is working or not | How can I check if a specific ip address or proxy is alive or dead
| [
"Because there may be any level of filtering or translation between you and the remote host, the only way to determine whether you can connect to a specific host is to actually try to connect. If the connection succeeds, then you can, else you can't.\nPinging isn't sufficient because ICMP ECHO requests may be block... | [
3,
0,
0
] | [] | [] | [
"proxy",
"python",
"sockets"
] | stackoverflow_0003078704_proxy_python_sockets.txt |
Q:
Adding printf to the starting of all functions in a file
I have some very large C files, having lots of functions. I need to trace the execution path at run time. There is no way I can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translations.
Can anyone... | Adding printf to the starting of all functions in a file | I have some very large C files, having lots of functions. I need to trace the execution path at run time. There is no way I can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translations.
Can anyone point me to some script in Perl or Python which can add a pri... | [
"Just pass -finstrument-functions to gcc when compiling. See the gcc(1) man page for details.\n",
"Here is a nice example of what you want.\n"
] | [
24,
2
] | [] | [] | [
"c",
"perl",
"python"
] | stackoverflow_0003078680_c_perl_python.txt |
Q:
Tornado handler thinks POST is missing argument when Firebug shows the argument being sent
I have a simple form using a POST method, consisting of a text box and a file. After hitting submit, I can see the post in Firebug as follows:
Parts multipart/form-data
posttext Some text
image BlahJFIFBlahExifBla... | Tornado handler thinks POST is missing argument when Firebug shows the argument being sent | I have a simple form using a POST method, consisting of a text box and a file. After hitting submit, I can see the post in Firebug as follows:
Parts multipart/form-data
posttext Some text
image BlahJFIFBlahExifBlahPhotoshopBlahBinaryStuff etc...
The Tornado handler that receives it looks like:
class NewPost... | [
"For file uploads you should use self.request.files instead of self.get_argument().\n"
] | [
4
] | [] | [] | [
"handler",
"post",
"python",
"tornado"
] | stackoverflow_0003073462_handler_post_python_tornado.txt |
Q:
Python urllib2 HTTPBasicAuthHandler
Here is the code:
import urllib2 as URL
def get_unread_msgs(user, passwd):
auth = URL.HTTPBasicAuthHandler()
auth.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s'%user,
passwd=passwd
... | Python urllib2 HTTPBasicAuthHandler | Here is the code:
import urllib2 as URL
def get_unread_msgs(user, passwd):
auth = URL.HTTPBasicAuthHandler()
auth.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s'%user,
passwd=passwd
)
opener = URL.build_opener(auth)
... | [
"It should throw an error, more precisely an urllib2.HTTPError, with the code field set to 401, you can see some adapted code below. I left your general try/except structure, but really, do not use general except statements, catch only what you expect that could happen!\ndef get_unread_msgs(user, passwd):\n auth... | [
3
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003078638_python_urllib2.txt |
Q:
Call the Python interactive interpreter from within a Python script
Is there any way to start up the Python interpreter from within a script , in a manner similar to just using python -i so that the objects/namespace, etc. from the current script are retained? The reason for not using python -i is that the script ... | Call the Python interactive interpreter from within a Python script | Is there any way to start up the Python interpreter from within a script , in a manner similar to just using python -i so that the objects/namespace, etc. from the current script are retained? The reason for not using python -i is that the script initializes a connection to an XML-RPC server, and I need to be able to s... | [
"Have you tried reading the error message? :)\n= is assignment, you want the comparison operator == instead.\n",
"Well, I finally got it to work.\nBasically, I put the entire try/except/else clause in a while True: loop, with the else suite being a break statement and the end of the except suite being a continue ... | [
2,
0
] | [] | [] | [
"python",
"python_interactive",
"while_loop",
"xmlrpclib"
] | stackoverflow_0003075827_python_python_interactive_while_loop_xmlrpclib.txt |
Q:
Override DEFINEs in setup.cfg in source eggs
The source egg of PySQLite 2.6.0 contains a file setup.cfg that looks like this:
[build_ext]
#define=
#include_dirs=/usr/local/include
#library_dirs=/usr/local/lib
libraries=sqlite3
define=SQLITE_OMIT_LOAD_EXTENSION
I'd like to build the egg with the SQLITE_OMIT_LOAD_E... | Override DEFINEs in setup.cfg in source eggs | The source egg of PySQLite 2.6.0 contains a file setup.cfg that looks like this:
[build_ext]
#define=
#include_dirs=/usr/local/include
#library_dirs=/usr/local/lib
libraries=sqlite3
define=SQLITE_OMIT_LOAD_EXTENSION
I'd like to build the egg with the SQLITE_OMIT_LOAD_EXTENSION define disabled (not set). I could do tha... | [
"Yes, there is:\n[buildout]\nparts = pysql\n\n[pysql]\nrecipe = zc.recipe.egg:custom\negg = PySQLite\nundef=SQLITE_OMIT_LOAD_EXTENSION\n\n"
] | [
4
] | [] | [] | [
"buildout",
"egg",
"pysqlite",
"python"
] | stackoverflow_0003013075_buildout_egg_pysqlite_python.txt |
Q:
Python: How to access variable declared in parent module
Using the structure from the Python docs:
sound/
__init__.py
effects/
__init__.py
echo.py
surround.py
reverse.py
Say I want to import sound.effects and get a list of available effects. I could do this by declarin... | Python: How to access variable declared in parent module | Using the structure from the Python docs:
sound/
__init__.py
effects/
__init__.py
echo.py
surround.py
reverse.py
Say I want to import sound.effects and get a list of available effects. I could do this by declaring a module-level variable in sound.effects and then appending ... | [
"What people commonly do in this situation is create a common.py file in the module.\nsound/\n __init__.py\n effect/\n __init__.py\n common.py\n echo.py\n surround.py\n reverse.py\n\nThen you move the code from __init__.py to common.py:\neffectList = []\nimport echo\ni... | [
8,
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003078927_import_python.txt |
Q:
Upload a file with python using httplib
conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/")
conn.request("POST", path, chunk, headers)
Above is the site "www.encodable.com/uploaddemo/" where I want to upload an image.
I am better versed in php so I am unable to understand the meaning of path and heade... | Upload a file with python using httplib | conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/")
conn.request("POST", path, chunk, headers)
Above is the site "www.encodable.com/uploaddemo/" where I want to upload an image.
I am better versed in php so I am unable to understand the meaning of path and headers here. In the code above, chunk is an objec... | [
"Currently, you aren't using the headers you've declared earlier in the code. You should provide them as the fourth argument to conn.request:\nconn.request(\"POST\", \"/uploaddemo/files/\", chunk, headers)\n\nAlso, side note: you can pass open(\"h1.jpg\", \"rb\") directly into conn.request without reading it fully... | [
5
] | [] | [] | [
"httplib",
"python"
] | stackoverflow_0003079562_httplib_python.txt |
Q:
doesn't python uses copy by reference?why is the following code not working then?
class x:
def __init__(self):
self.y=None
self.sillyFunc(self.y)
def sillyFunc(self,argument):
if argument is None:
argument='my_name_as_argument'
self.printy()
def printy(self):... | doesn't python uses copy by reference?why is the following code not working then? | class x:
def __init__(self):
self.y=None
self.sillyFunc(self.y)
def sillyFunc(self,argument):
if argument is None:
argument='my_name_as_argument'
self.printy()
def printy(self):
print self.y
According to me the above code should print >my_name_as_argument... | [
"The assigment\nargument='my_name_as_argument'\n\nonly affects the local variable argument. It doesn't change what self.y points to.\n",
"In Python everything is an object and variables contain references to objects. When you make a function call it makes copies of the references. Some people including Guido van ... | [
5,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003079533_python.txt |
Q:
socket.error: [Errno 10054]
import socket, sys
if len(sys.argv) !=3 :
print "Usage: ./supabot.py <host> <port>"
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBO... | socket.error: [Errno 10054] | import socket, sys
if len(sys.argv) !=3 :
print "Usage: ./supabot.py <host> <port>"
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send(... | [
"You need to check the IRC protocol a little it more; your IRC session is not considered conncted (by the server) until certain actions have been completed which the server will inform your client about using IRC protocol codes. And if the server or network is busy when you are connecting it will take longer for t... | [
4,
1,
1
] | [] | [] | [
"irc",
"network_protocols",
"python",
"sockets"
] | stackoverflow_0003058932_irc_network_protocols_python_sockets.txt |
Q:
how to make a chat room on gae ,has any audio python-framework to do this?
i want to make a chat room on gae ,(audio chat)
has any framework to do this ?
thanks
A:
App Engine doesn't directly support audio chat of any sort, and since it's based around a request-response system with (primarily) HTTP requests, yo... | how to make a chat room on gae ,has any audio python-framework to do this? | i want to make a chat room on gae ,(audio chat)
has any framework to do this ?
thanks
| [
"App Engine doesn't directly support audio chat of any sort, and since it's based around a request-response system with (primarily) HTTP requests, you can't implement it yourself.\n",
"Try Adobe Stratus (it works with p2p connections) and you could use Google App Engine only for exchanging peer ids.\n",
"If you... | [
1,
1,
0,
0
] | [] | [] | [
"audio",
"chat",
"google_app_engine",
"python"
] | stackoverflow_0003012661_audio_chat_google_app_engine_python.txt |
Q:
GAEUnit: Trouble with long strings in assert statements?
I'm having an odd error where GAEUnit seems to be hung on assertion statements that have error strings that are too long.
I'm running these tests on the GAE Dev server 1.3.3.
This works just fine:
self.assertEquals(2 + 2, 5, "[2, 3, 4]") # works
However, if... | GAEUnit: Trouble with long strings in assert statements? | I'm having an odd error where GAEUnit seems to be hung on assertion statements that have error strings that are too long.
I'm running these tests on the GAE Dev server 1.3.3.
This works just fine:
self.assertEquals(2 + 2, 5, "[2, 3, 4]") # works
However, if I defined a longer string, and try to print that out:
jso... | [
"Workaround: the ?format=plain option returns plaintext results that seem to work just fine.\n"
] | [
0
] | [] | [] | [
"gaeunit",
"google_app_engine",
"python",
"unit_testing"
] | stackoverflow_0003077576_gaeunit_google_app_engine_python_unit_testing.txt |
Q:
customizing basic existing Django apps that already have "nice looking" CSS/HTML templates?
I am looking for a basic Django application that "looks good" and has basic menus etc. that I could adapt for my own use. I am not doing any fancy processing of user input, but I do want to reuse an existing templates so t... | customizing basic existing Django apps that already have "nice looking" CSS/HTML templates? | I am looking for a basic Django application that "looks good" and has basic menus etc. that I could adapt for my own use. I am not doing any fancy processing of user input, but I do want to reuse an existing templates so that I don't have to worry about writing my own CSS/HTML to get clean, valid good looking webpages... | [
"In my opinion this is really in no way django-specific. I think you would be better suited if you search for something like \"web templates download\" in your favourite search engine. Find a layout that you like, pay for it (if you can't find anything gratis) and use it.\nOh, and no, there is regrettably no such a... | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003080194_django_django_templates_python.txt |
Q:
Some questions about Django localisation
I intend to localise my Django application and began reading up on localisation on the Django site. This put a few questions in my mind:
It seems that when you run the 'django-admin.py makemessages' command, it scans the files for embedded strings and generates a message f... | Some questions about Django localisation | I intend to localise my Django application and began reading up on localisation on the Django site. This put a few questions in my mind:
It seems that when you run the 'django-admin.py makemessages' command, it scans the files for embedded strings and generates a message file that contains the translations. These tran... | [
"\nIt very probably would, in some cases 'similar' strings can be detected and your translation will be marked with fuzzy. But it depends on the type of string, I don't know what adding an apostrophe would do. Read the GNU gettext docs for more information about this.\nHowever, an easy solution for your problem wou... | [
2
] | [] | [] | [
"django",
"localization",
"python"
] | stackoverflow_0003080331_django_localization_python.txt |
Q:
How do you create a python package with a built in "test/main.py" main function?
Desired directory tree:
Fibo
|-- src
| `-- Fibo.py
`-- test
`-- main.py
What I want is to call python main.py after cd'ing into test and executing main.py will run all the unit tests for this package.
Currently if I do:
import ... | How do you create a python package with a built in "test/main.py" main function? | Desired directory tree:
Fibo
|-- src
| `-- Fibo.py
`-- test
`-- main.py
What I want is to call python main.py after cd'ing into test and executing main.py will run all the unit tests for this package.
Currently if I do:
import Fibo
def main():
Fibo.fib(100)
if __name__ == "__main__":
main()
I get an e... | [
"If I want to import a module that lives at a fixed, relative location to the file I'm evaluating, I often do something like this:\ntry:\n import Fibo\nexcept ImportError:\n import sys\n from os.path import join, abspath, dirname\n parentpath = abspath(join(dirname(__file__), '..'))\n srcpath = join(... | [
1,
0,
0
] | [] | [] | [
"module",
"package",
"python",
"unit_testing"
] | stackoverflow_0003079670_module_package_python_unit_testing.txt |
Q:
Dealing with multi-language directories (Python)
I'm trying to open a file and I just realized that py is having trouble with my username (It's in Russian). Any suggestions on how to properly decode/encode this to make idle happy?
I'm using py 2.6.5
xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r")
Tra... | Dealing with multi-language directories (Python) | I'm trying to open a file and I just realized that py is having trouble with my username (It's in Russian). Any suggestions on how to properly decode/encode this to make idle happy?
I'm using py 2.6.5
xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r")
Traceback (most recent call last):
File "<pyshell#23>",... | [
"The first problem is that the parser tries to interpret backslashes in strings unless you use the r\"raw quote\" prefix. In 2.6.5, you needn't treat your Unicode string specially, but you may need a file encoding declaration in your source code like:\n# -*- coding: utf-8 -*-\n\nas defined in PEP 263. Here is an ex... | [
0,
0
] | [] | [] | [
"decode",
"python",
"unicode"
] | stackoverflow_0003080373_decode_python_unicode.txt |
Q:
Reconstituting Strings in Python
I would like to do something like:
temp=a.split()
#do some stuff with this new list
b=" ".join(temp)
where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do... | Reconstituting Strings in Python | I would like to do something like:
temp=a.split()
#do some stuff with this new list
b=" ".join(temp)
where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlines?
| [
"I assume in your third line you mean join(temp), not join(a).\nTo split and yet keep the exact \"splitters\", you need the re.split function (or split method of RE objects) with a capturing group:\n>>> import re\n>>> f='tanto va\\nla gatta al lardo'\n>>> re.split(r'(\\s+)', f)\n['tanto', ' ', 'va', '\\n', 'la', ' ... | [
7,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003081184_python.txt |
Q:
Can I use Ruby and Python together?
Is there something like JRuby but for Ruby and Python?
Not that it would actually be useful to me, but just wondering.
A:
If you develop for the .NET Framework Version 4.0, you can write code in IronRuby that calls methods that were written in IronPython and vice versa.
A:
J... | Can I use Ruby and Python together? | Is there something like JRuby but for Ruby and Python?
Not that it would actually be useful to me, but just wondering.
| [
"If you develop for the .NET Framework Version 4.0, you can write code in IronRuby that calls methods that were written in IronPython and vice versa.\n",
"Jython\n",
"Parrot aims. Not quite sure about its progress, though.\n",
"_why was working on something called unholy, which converted ruby to Python byteco... | [
8,
2,
1,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0003079531_python_ruby.txt |
Q:
Find previous calendar day in python
Possible Duplicate:
How can I subtract a day from a python date?
I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text file for some processing. How do I find the previous day's date in python?
A:
Here you go:
>>>... | Find previous calendar day in python |
Possible Duplicate:
How can I subtract a day from a python date?
I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text file for some processing. How do I find the previous day's date in python?
| [
"Here you go:\n>>> print datetime.date.today()-datetime.timedelta(1)\n>>> 2010-06-19\n\n",
"Say you start with a string '2010_05_1'. Then the similar string for the previous day is:\n>>> import datetime\n>>> s = '2010_05_1'\n>>> theday = datetime.date(*map(int, s.split('_')))\n>>> prevday = theday - datetime.tim... | [
44,
7,
5,
0
] | [] | [] | [
"calendar",
"date",
"datetime",
"file",
"python"
] | stackoverflow_0003081339_calendar_date_datetime_file_python.txt |
Q:
Python: Any way to declare constant parameters?
I have a method:
def foo(bar):
# ...
Is there a way to mark bar as constant? Such as "The value in bar cannot change" or "The object pointed to by bar cannot change".
A:
If bar is an inmutable object, bar won't change during the function.
You can also create yo... | Python: Any way to declare constant parameters? | I have a method:
def foo(bar):
# ...
Is there a way to mark bar as constant? Such as "The value in bar cannot change" or "The object pointed to by bar cannot change".
| [
"If bar is an inmutable object, bar won't change during the function.\nYou can also create your own constant object.\nThe recipe here.\n"
] | [
6
] | [
"No.\nWhat's the point? If you're writing the function, isn't it up to you to make sure bar doesn't change? Or if you're calling the function, who cares?\n"
] | [
-6
] | [
"constants",
"language_construct",
"python"
] | stackoverflow_0003081464_constants_language_construct_python.txt |
Q:
is mac good for python programming?
I am programming a django based website. I actually use a small computer under Ubuntu 10.04.
I would like to buy something more professional, so I am wondering whether an iMac is good for that, because :
Is there a free IDE as good as eclipse on MacOS ?
Is there a remote python... | is mac good for python programming? | I am programming a django based website. I actually use a small computer under Ubuntu 10.04.
I would like to buy something more professional, so I am wondering whether an iMac is good for that, because :
Is there a free IDE as good as eclipse on MacOS ?
Is there a remote python debugger like pydev for eclipse ?
Is the... | [
"Why do you consider iMac to be more or less professional than anything else? Hardware? System?\nNote: I'm myself a MacOSX and Linux user.\nUnless it's a requisite, most times I'd say it's only a matter of personal taste.\nAs said by others earlier, everything you cited works fine on MacOSX.\nHowever, you should co... | [
6,
5,
4,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003080019_macos_python.txt |
Q:
Python CGI-based frameworks for web development and templates?
What are my choices for frameworks for doing Python web development and having a nice language for writing templates for CSS/HTML? A key goal for me is not to have to run a server or install many extra dependencies -- I'd like something that works jus... | Python CGI-based frameworks for web development and templates? | What are my choices for frameworks for doing Python web development and having a nice language for writing templates for CSS/HTML? A key goal for me is not to have to run a server or install many extra dependencies -- I'd like something that works just by using CGI and hopefully does not force me to do any fancy recon... | [
"There's some docs, some tools, and some more tools. Plus, flup can turn any WSGI framework into a CGI app. And there's Pygments for syntax highlighting.\n",
"Well, you're probably not going to find a framework with templates like that included, simply because that's out of most frameworks' scopes. The page struc... | [
2,
2
] | [] | [] | [
"cgi",
"css",
"html",
"python"
] | stackoverflow_0003078114_cgi_css_html_python.txt |
Q:
virtualenv yolk problem
yolk -l gives me information that I've got 114 packages installed on my Ubuntu 10.04. After creating new virtualenv directory using
virtualenv virt_env/virt1 --no-site-packages --clear
I switched to that, my prompt changed and then yolk -l gives me again the same 114 packages.
What is goi... | virtualenv yolk problem | yolk -l gives me information that I've got 114 packages installed on my Ubuntu 10.04. After creating new virtualenv directory using
virtualenv virt_env/virt1 --no-site-packages --clear
I switched to that, my prompt changed and then yolk -l gives me again the same 114 packages.
What is going on there?
| [
"Activating a virtualenv works by changing your shell PATH so the virtualenv's bin/ directory is first. This is all it does. This means that when you run \"python\" it runs the virtualenv's copy of the Python binary instead of your global system python.\nIf you have yolk installed globally, however, the only \"yolk... | [
18,
0
] | [] | [] | [
"python",
"virtualenv",
"yolk"
] | stackoverflow_0002742980_python_virtualenv_yolk.txt |
Q:
python win32com Causes Program crash
I wrote program to control iTunes by monitoring keystrokes from with pyHooks and then interfaceing with the iTunes COM interface.
The program works fine, the only problem I have is when I try to compile it with py2exe. The program always crashes with this traceback:
Traceback (... | python win32com Causes Program crash | I wrote program to control iTunes by monitoring keystrokes from with pyHooks and then interfaceing with the iTunes COM interface.
The program works fine, the only problem I have is when I try to compile it with py2exe. The program always crashes with this traceback:
Traceback (most recent call last):
File "threading.... | [
"The problem is probably that the py2exe version isn't able to access the cache of wrappers generated by win32com.\nHere's a recipe for dealing with this problem.\n"
] | [
4
] | [] | [] | [
"com",
"itunes",
"py2exe",
"python"
] | stackoverflow_0003081822_com_itunes_py2exe_python.txt |
Q:
using 'variable.xyz' format in Python
This is a silly question, but I can't figure it out so I had to ask.
I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False.
Variable Car has not been defined in this situation. I kno... | using 'variable.xyz' format in Python | This is a silly question, but I can't figure it out so I had to ask.
I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False.
Variable Car has not been defined in this situation. I know I can do dicts (Car['store'] = False) etc... | [
"I think the closest you can get to what you want is by adding one extra line (assuming you have defined a class called Car):\ncar = Car()\ncar.store = False\n\nWithout the first line you will get an error.\nIf you want brevity you could set store to False in __init__ so that only the first line is necessary.\n",
... | [
2,
0
] | [
"Maybe you can try whith this:\ntry:\n car.store = False\nexcept NameError:\n #This means that car doesn't exists\n pass\nexcept AttributeError:\n #This means that car.store doesn't exists\n pass\n\n",
"car, car.store = car if \"car\" in locals() else lambda:1, False\n\n"
] | [
-1,
-1
] | [
"python"
] | stackoverflow_0003081500_python.txt |
Q:
question regarding postgresql sequences
I have a question regarding postgresql sequences.
For instance, for bigserial datatype, is it true that the sequence is advanced, then the number is retrieved and even if the insertion/committing is not successful, the sequence doesn't backtracks. Which means the next time I... | question regarding postgresql sequences | I have a question regarding postgresql sequences.
For instance, for bigserial datatype, is it true that the sequence is advanced, then the number is retrieved and even if the insertion/committing is not successful, the sequence doesn't backtracks. Which means the next time I might be doing insertion to the table, that ... | [
"\neven if the insertion/committing is\n not successful, the sequence doesn't\n backtracks. Which means the next time I might be doing insertion to the table, that might be a gap in the sequence number.\n\nYes, that's true, And that's fine.\nOne usually wants a sequence to get values in a table that are unique (t... | [
4,
3
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0003081899_postgresql_psycopg2_python.txt |
Q:
python multiprocessing - text processing
I am trying to create a multiprocessing version of text categorization code i found here (amongst other cool things). I've appended the full code below.
I've tried a couple of things - tried a lambda function first, but it complained of not being serializable (!?), so atte... | python multiprocessing - text processing | I am trying to create a multiprocessing version of text categorization code i found here (amongst other cool things). I've appended the full code below.
I've tried a couple of things - tried a lambda function first, but it complained of not being serializable (!?), so attempted a stripped down version of the original ... | [
"Are you trying to parallelize the classification, the training, or both? You can probably make the word counting and scoring parallel fairly easily, but I'm not sure about the feature extraction & training. For the classification, I'd recommend execnet. I've had good results using it for parallel/distributed part-... | [
1,
1
] | [] | [] | [
"multicore",
"multithreading",
"python"
] | stackoverflow_0003081044_multicore_multithreading_python.txt |
Q:
Python out params?
Is it possible to do something like this:
def foo(bar, success)
success = True
# ...
>>> success = False
>>> foo(bar1, success)
>>> success
True
Does Python have out params, or an easy way to simulate them? (Aside from messing with parent's stack frames.)
A:
You have multiple return ... | Python out params? | Is it possible to do something like this:
def foo(bar, success)
success = True
# ...
>>> success = False
>>> foo(bar1, success)
>>> success
True
Does Python have out params, or an easy way to simulate them? (Aside from messing with parent's stack frames.)
| [
"You have multiple return values.\ndef foo(bar)\n return 1, 2, True\n\nx, y, success = foo(bar1)\n\n",
"Yes, put them in a dict as pass the dict as a parameter. I think it's somewhere in the main python official tutorial.\n",
"In python you can not update an immutable type from inside a function (like the bo... | [
6,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003081807_python.txt |
Q:
Python Module Initialization Order?
I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask:
Under C++, there is a well known problem called global/static variable initia... | Python Module Initialization Order? | I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask:
Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inabi... | [
"Python import executes new Python modules from beginning to end. Subsequent imports only result in a copy of the existing reference in sys.modules, even if still in the middle of importing the module due to a circular import. Module attributes (\"global variables\" are actually at the module scope) that have been ... | [
12,
11
] | [] | [] | [
"initialization",
"python"
] | stackoverflow_0003082015_initialization_python.txt |
Q:
The book about integration Django and Flex
There is a remarkable book "Flexible Rails" http://www.manning.com/armstrong/ about how to use Ruby on Rails and Adobe Flex to build next-generation rich Internet applications (RIAs). Does anybody know any similar resource about integrating Django and Flex?
A:
I'm not a... | The book about integration Django and Flex | There is a remarkable book "Flexible Rails" http://www.manning.com/armstrong/ about how to use Ruby on Rails and Adobe Flex to build next-generation rich Internet applications (RIAs). Does anybody know any similar resource about integrating Django and Flex?
| [
"I'm not aware of any similar books, but all you really need is an API integration from your flex app to your django app.\nI've used the following 2 methods with success:\n\nREST API with simple HTTP access on the flex side. See django-piston and flex's mx.rpc.http.HTTPService/built-in XML deserializer.\nAMF proto... | [
1
] | [] | [] | [
"apache_flex",
"django",
"python"
] | stackoverflow_0003082272_apache_flex_django_python.txt |
Q:
Accessing the Microphone in Python
My laptop has a microphone in it. Is there any method of obtaining numbers in Python from it? For example pitch, volume, or the duration of a noise. I'm trying to use ambient noise to create random numbers.
A:
Accessing the amplitude is easy. Depending on the plattform your ap... | Accessing the Microphone in Python | My laptop has a microphone in it. Is there any method of obtaining numbers in Python from it? For example pitch, volume, or the duration of a noise. I'm trying to use ambient noise to create random numbers.
| [
"Accessing the amplitude is easy. Depending on the plattform your app is running on you can use \na framework like http://people.csail.mit.edu/hubert/pyaudio/ or http://pyalsaaudio.sourceforge.net/pyalsaaudio.html \nto access the the pitch you will need a framework that performs a fft-analysis like the scipy/numpy ... | [
1
] | [] | [] | [
"microphone",
"python"
] | stackoverflow_0003082635_microphone_python.txt |
Q:
Where can I read about import _{module name} in Python?
I've notice this. Example:
create an empty text file called for example ast.py
$ touch ast.py
run Python
$ python
>>> from ast import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> from _ast import *
>>> dir()
['AST', 'Add', 'And', 'A... | Where can I read about import _{module name} in Python? | I've notice this. Example:
create an empty text file called for example ast.py
$ touch ast.py
run Python
$ python
>>> from ast import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> from _ast import *
>>> dir()
['AST', 'Add', 'And', 'Assert', 'Assign', ...]
ast is a python module. So... what's ... | [
"There's nothing special with _xxx modules except they are private (e.g. _abcoll) or low-level (e.g. _thread) and not intended to be used in general.\nThe _ast module is special, e.g.\n$ touch _ast.py\n$ python -c 'from _ast import *; print(dir())'\n['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute ...\n\nBut th... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003082889_python.txt |
Q:
Is there a tool to do ast 2 python source code for Python 2.x?
I've seen codegen http://dev.pocoo.org/hg/sandbox/file/868ea20c2c1d/ast/ but doent works with all the files and ast2src which only works with Python 3.1.
A:
Ive patched codegen con make it work with my sources: http://svn.juanjoconti.com.ar/dyntaint/... | Is there a tool to do ast 2 python source code for Python 2.x? | I've seen codegen http://dev.pocoo.org/hg/sandbox/file/868ea20c2c1d/ast/ but doent works with all the files and ast2src which only works with Python 3.1.
| [
"Ive patched codegen con make it work with my sources: http://svn.juanjoconti.com.ar/dyntaint/trunk/wrapstrings/gen/\n",
"You could convert the 3.1 source to 2x using 3to2.\nIt's a utility for back-porting python3 scripts back to python2.\nNote: 3to2 isn't the standard user-submitted PYPI project. It has been vet... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003082921_python.txt |
Q:
python solutions for managing scientific data dependency graph by specification values
I have a scientific data management problem which seems general, but I can't find an existing solution or even a description of it, which I have long puzzled over. I am about to embark on a major rewrite (python) but I thought ... | python solutions for managing scientific data dependency graph by specification values | I have a scientific data management problem which seems general, but I can't find an existing solution or even a description of it, which I have long puzzled over. I am about to embark on a major rewrite (python) but I thought I'd cast about one last time for existing solutions, so I can scrap my own and get back to t... | [
"I don't have specific python-related suggestions for you, but here are a few thoughts:\nYou're encountering a common challenge in bioinformatics. The data is large, heterogeneous, and comes in constantly changing formats as new technologies are introduced. My advice is to not overthink your pipelines, as they're ... | [
2,
2
] | [] | [] | [
"aop",
"bioinformatics",
"nosql",
"python",
"scientific_computing"
] | stackoverflow_0003076953_aop_bioinformatics_nosql_python_scientific_computing.txt |
Q:
How C# use python program?
If it doesn't use ironpython, how C# use cpython program(py file)?
Because there are some bugs that ironpython load cpython code.
A:
If you need strict CPython behavior and do not want to change Python program I am afraid that in this case you should spawn separate CPython process and ... | How C# use python program? | If it doesn't use ironpython, how C# use cpython program(py file)?
Because there are some bugs that ironpython load cpython code.
| [
"If you need strict CPython behavior and do not want to change Python program I am afraid that in this case you should spawn separate CPython process and interact with it via some RPC protocol (there are plenty to choose from) via pipe or network connection to localhost.\nAs alternative to \"serialized\" RPC you m... | [
0
] | [] | [] | [
"c#",
"cpython",
"python"
] | stackoverflow_0003083167_c#_cpython_python.txt |
Q:
Use python to get friendslists on facebook
How can i use python to login to facebook,
grab a friendlist from my friends and use the data to see
if my friends are facebook buddies ?
Thanks for your help :-)
A:
First off, you won't be able to get access to your friends' friends list unless they themselves authoriz... | Use python to get friendslists on facebook | How can i use python to login to facebook,
grab a friendlist from my friends and use the data to see
if my friends are facebook buddies ?
Thanks for your help :-)
| [
"First off, you won't be able to get access to your friends' friends list unless they themselves authorize your application.\nThis being said, you can try the pyfacebook library with the friends.get() method or the new graph API.\nhttps://graph.facebook.com/me/friends will get a list of your friends then\nhttps://g... | [
4
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0003083401_facebook_python.txt |
Q:
python help django navigation
I would like to understand how I can access and navigate Python and Django help.
in Django I cd to my directory and entered the following command to access help of the manage.py:
python manage.py help
And I would like to get info on the commands. Here I have to type:
Type 'manage.p... | python help django navigation | I would like to understand how I can access and navigate Python and Django help.
in Django I cd to my directory and entered the following command to access help of the manage.py:
python manage.py help
And I would like to get info on the commands. Here I have to type:
Type 'manage.py help ' for help on a specific sub... | [
"you have to do \npython manage.py --help\n\nHere is the django admin.py/manage.py doc http://docs.djangoproject.com/en/dev/ref/django-admin/\nTo getting help in general in python you can use builtin help function e.g.\n>>> help('help')\n\nWelcome to Python 2.5! This is the online help utility.\n....\n\n"
] | [
1
] | [] | [] | [
"django",
"navigation",
"python"
] | stackoverflow_0003083583_django_navigation_python.txt |
Q:
Clear sqlalchemy reflection cache
I'm using sqlalchemy's reflection tools to get a Table object. I do this because these tables are dynamic and tables/columns can change. Here's the code I'm using:
def getTableByReflection(self, tableName, metadata, engine):
return Table(tableName, metadata, autoload = True, ... | Clear sqlalchemy reflection cache | I'm using sqlalchemy's reflection tools to get a Table object. I do this because these tables are dynamic and tables/columns can change. Here's the code I'm using:
def getTableByReflection(self, tableName, metadata, engine):
return Table(tableName, metadata, autoload = True, autoload_with = engine)
The problem is... | [
"Pass in a newly created, fresh metadata instance.\n",
"With thanks to codeape's comment above I was able to fix the problem by changing the syntax to:\ndef getTableByReflection(self, tableName, metadata, engine):\n\n return Table(tableName, MetaData(), autoload = True, autoload_with = engine)\n\nSo passing in... | [
6,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003068408_python_sqlalchemy.txt |
Q:
Forcing scons to use older compiler?
I have a C++ project which is using boost. The whole project is built using scons + Visual Studio 2008. We've installed Visual Studio 2010 and it turned out scons was attempting to use the later compiler instead of the old one - and failed to build the project as boost and visu... | Forcing scons to use older compiler? | I have a C++ project which is using boost. The whole project is built using scons + Visual Studio 2008. We've installed Visual Studio 2010 and it turned out scons was attempting to use the later compiler instead of the old one - and failed to build the project as boost and visual studio 2010 don't like each other very ... | [
"You can modify the scons Environment() by just choosing\nthe version you want:\nenv = Environment(MSVC_VERSION=<someversion>)\nFrom the scons manpage:\n\nMSVC_VERSION Sets the preferred \n version of Microsoft Visual C/C++ to\n use.\nIf $MSVC_VERSION is not set, SCons\n will (by default) select the latest\n ... | [
17,
2
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0003079344_python_scons.txt |
Q:
Multiple in same file
I have a multiple html files in one file:
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
and the result is that I get a messed up html file. How to correct this without removing tags fro... | Multiple in same file | I have a multiple html files in one file:
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
and the result is that I get a messed up html file. How to correct this without removing tags from the rest. I am using python... | [
"Have one HTML file per file. Anything else is invalid and won’t be processed properly.\nIf you’re not sure if your HTML files are valid, the W3C’s validator will tell you.\n"
] | [
3
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003083711_html_python.txt |
Q:
Starting multiple instances of a python script at once from linux command line
I'd like to start a piece of python script a thousand times! instead of trying to start them one-by-one how can I do that from linux command line?
Right now, I am doing it like this:
nohup python test.py &
nohup python test.py &
nohup p... | Starting multiple instances of a python script at once from linux command line | I'd like to start a piece of python script a thousand times! instead of trying to start them one-by-one how can I do that from linux command line?
Right now, I am doing it like this:
nohup python test.py &
nohup python test.py &
nohup python test.py &
nohup python test.py &
nohup python test.py &
...
Thanks in advance... | [
"As a one-liner, in Bash:\nfor i in {1..1000}; do nohup python test.py & done\n\n",
"I would recommend that you keep the spawning logic in a Python program. Perhaps use the multiprocessing library to do the processes. It'll be hard to manage all of these without some non-trivial scaffolding if you're going to spa... | [
7,
4,
2
] | [] | [] | [
"command_line",
"console",
"linux",
"python",
"shell"
] | stackoverflow_0003083922_command_line_console_linux_python_shell.txt |
Q:
What's a good document standard to use programmatically?
I'm writing a program that requires input in the form of a document, it needs to replace a few values, insert a table, and convert it to PDF. It's written in Python + Qt (PyQt). Is there any well known document standard which can be easily used programmatica... | What's a good document standard to use programmatically? | I'm writing a program that requires input in the form of a document, it needs to replace a few values, insert a table, and convert it to PDF. It's written in Python + Qt (PyQt). Is there any well known document standard which can be easily used programmatically? It must be cross platform, and preferably open.
I have l... | [
"Have you looked into using LaTeX documents?\nThey are perfect to use programatically (compiling documents? You gotta love that...), and you have several Python frameworks you can use such as plasTeX and PyTex.\nExporting a LaTeX documents to PDF is almost immediate.\n",
"Since you're already using PyQt anyway, i... | [
9,
2,
1,
0,
0
] | [] | [] | [
"document",
"pyqt",
"python"
] | stackoverflow_0003082502_document_pyqt_python.txt |
Q:
can someone help me with tags in canvas?
i tried to figure out what tags were in canvas however i am having a hard time understanding it. can someone explain what tags do and how to use them in canvas when using python.
A:
Every object in a canvas has an id. You can reference that object by that id to delete it,... | can someone help me with tags in canvas? | i tried to figure out what tags were in canvas however i am having a hard time understanding it. can someone explain what tags do and how to use them in canvas when using python.
| [
"Every object in a canvas has an id. You can reference that object by that id to delete it, modify it, move it, etc.\nObjects can also have one or more tags. A tag can be associated with a single object, in which case it is just another name for that object. For example, if you draw a red rectangle and a blue recta... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003081749_python_tkinter.txt |
Q:
Facebook Python-SDK VS. PyFacebook?
I'm starting to develop a facebook application using Django.
I'm trying to choose the appropriate API wrapper for my application and I can't decide whether to use PyFacebook (very well documented but no official release) or the official Facebook Python SDK (which is surprisingly... | Facebook Python-SDK VS. PyFacebook? | I'm starting to develop a facebook application using Django.
I'm trying to choose the appropriate API wrapper for my application and I can't decide whether to use PyFacebook (very well documented but no official release) or the official Facebook Python SDK (which is surprisingly poorly documented).
Are there any major... | [
"I believe PyFacebook was made for the old Facebook API (used to be the way to go) while the Facebook Platform Python SDK is a new official library from facebook and is aimed towards the new Graph API\nSo I suggest you start using the latter. And yeah the documentation totally sucks in both cases, took me a while t... | [
11
] | [] | [] | [
"facebook",
"pyfacebook",
"python"
] | stackoverflow_0003084230_facebook_pyfacebook_python.txt |
Q:
Using class/static methods as default parameter values within methods of the same class
I'd like to do something like this:
class SillyWalk(object):
@staticmethod
def is_silly_enough(walk):
return (False, "It's never silly enough")
def walk(self, appraisal_method=is_silly_enough):
self.... | Using class/static methods as default parameter values within methods of the same class | I'd like to do something like this:
class SillyWalk(object):
@staticmethod
def is_silly_enough(walk):
return (False, "It's never silly enough")
def walk(self, appraisal_method=is_silly_enough):
self.do_stuff()
(was_good_enough, reason) = appraisal_method(self)
if not was_good... | [
"I ended up writing an (un)wrapper function, to be used within function definition headers, eg\ndef walk(self, appraisal_method=unstaticmethod(is_silly_enough)):\n\nThis actually seems to work, at least it makes my doctests that break without it pass.\nHere it is:\ndef unstaticmethod(static):\n \"\"\"Retrieve th... | [
2,
2,
1
] | [] | [] | [
"class_method",
"decorator",
"default_value",
"python",
"static_methods"
] | stackoverflow_0003083692_class_method_decorator_default_value_python_static_methods.txt |
Q:
How to use float ** in Python with Swig?
I am writing swig bindings for some c functions. One of these functions takes a float**. I am already using cpointer.i for the normal pointers and looked into carrays.i, but I did not find a way to declare a float**. What do you recommend?
interface file:
extern int read_d... | How to use float ** in Python with Swig? | I am writing swig bindings for some c functions. One of these functions takes a float**. I am already using cpointer.i for the normal pointers and looked into carrays.i, but I did not find a way to declare a float**. What do you recommend?
interface file:
extern int read_data(const char
*file,int *n_,int *m_,float *... | [
"This answer is a repost of one to a related question Framester posted about using ctypes instead of swig. I've included it here in case any web-searches turn up a link to his original question.\n\nI've used ctypes for several projects\n now and have been quite happy with the\n results. I don't think I've persona... | [
1
] | [] | [] | [
"c",
"pointers",
"python",
"swig"
] | stackoverflow_0003068317_c_pointers_python_swig.txt |
Q:
closing a connection with twisted
Various connections - e.g. those created with twisted.web.client.getPage() seem to leak - they hang around indefinitely, since the OS time-out is measured in hours - if the server doesn't respond timely. And putting a time-out on the deferred you get back is deprecated.
How can y... | closing a connection with twisted | Various connections - e.g. those created with twisted.web.client.getPage() seem to leak - they hang around indefinitely, since the OS time-out is measured in hours - if the server doesn't respond timely. And putting a time-out on the deferred you get back is deprecated.
How can you track the requests you have open, an... | [
"getPage accepts a timeout parameter. If you pass a value for it and the response is not fully received within that number of seconds, the connection will be closed and the Deferred returned by getPage will errback.\n"
] | [
2
] | [] | [] | [
"python",
"tcp",
"twisted"
] | stackoverflow_0003084369_python_tcp_twisted.txt |
Q:
Force download of files on App Engine
How would I go about forcing the browser to download media files instead of attempting to stream them? These are static files in my application directory.
A:
You need to modify app.yaml in your project, setting application/octect-stream as mime_type.
Check this example:
- u... | Force download of files on App Engine | How would I go about forcing the browser to download media files instead of attempting to stream them? These are static files in my application directory.
| [
"You need to modify app.yaml in your project, setting application/octect-stream as mime_type.\nCheck this example:\n- url: /download\n static_dir: static/download\n mime_type : application/octect-stream\n\nAs correctly stated in comment, it is not a good idea to force a certain mime_type on download.\nIf your use... | [
0,
0
] | [] | [] | [
"content_disposition",
"download",
"google_app_engine",
"python"
] | stackoverflow_0003076045_content_disposition_download_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.