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:
what does this code snippet do?
can somebody give me an explanation about the following code?
from twisted.internet import protocol, reactor
from twisted.protocols import basic
class FingerProtocol(basic.LineReceiver):
def lineReceived(self, user):
self.transport.write(self.factory.getUser(user)+"\r\n... | what does this code snippet do? | can somebody give me an explanation about the following code?
from twisted.internet import protocol, reactor
from twisted.protocols import basic
class FingerProtocol(basic.LineReceiver):
def lineReceived(self, user):
self.transport.write(self.factory.getUser(user)+"\r\n")
self.transport.loseConnect... | [
"It's keyword argument notation.\n",
"The call to FingerFactory (a strange name, BTW) is instantiating a FingerFactory object. The parameters to that call are passed to the __init__ function of the class, where they are accepted by the **kwargs parameter as a dictionary: \n{'moshez': 'Happy and well'}\n\nSo this ... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002115578_python.txt |
Q:
Python 2.x vs 3.x Speed
I'm a PhD student and use Python to write the code I use for my research. My workflow often consists of making a small change to the code, running the program, seeing whether the results improved, and repeating the process. Because of this, I find myself spending more time waiting for my... | Python 2.x vs 3.x Speed | I'm a PhD student and use Python to write the code I use for my research. My workflow often consists of making a small change to the code, running the program, seeing whether the results improved, and repeating the process. Because of this, I find myself spending more time waiting for my program to run than I do act... | [
"This article (archive.org) said that there were a few points where Python 3.0 was actually slower than Python 2.6, though I think many of these issues were resolved. That being said, Numpy hasn't been brought over to Python 3.0 yet and that's where a lot of the high performance (written in c) number functionality... | [
23,
5,
3,
2,
2
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0002112298_performance_python.txt |
Q:
assigning value to shell variable using a function return value from Python
I have a Python function, fooPy() that returns some value. ( int / double or string)
I want to use this value and assign it in a shell script. For example following is the python function:
def fooPy():
return "some string"
#retur... | assigning value to shell variable using a function return value from Python | I have a Python function, fooPy() that returns some value. ( int / double or string)
I want to use this value and assign it in a shell script. For example following is the python function:
def fooPy():
return "some string"
#return 10 .. alternatively, it can be an int
fooPy()
In the shell script I tried th... | [
"You can print your value in Python, like this:\nprint fooPy()\n\nand in your shell script:\nfooShell=$(python fooPy.py)\n\nBe sure not to leave spaces around the = in the shell script.\n",
"In your Python code, you need to print the result.\nimport sys\ndef fooPy():\n return 10 # or whatever\n\nif __name__ ==... | [
34,
11,
5,
3
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0002115615_python_shell.txt |
Q:
Calling Python function in Django template
Inside a django template I'm trying to call the split function on one of the template variables and then get the last element, so I did something like this:
{{ newsletter.NewsletterPath.split('/').-1 }}
Unfortunately, it doesn't like the split. Some might suggest that I ... | Calling Python function in Django template | Inside a django template I'm trying to call the split function on one of the template variables and then get the last element, so I did something like this:
{{ newsletter.NewsletterPath.split('/').-1 }}
Unfortunately, it doesn't like the split. Some might suggest that I do the split in the view, but I'm not sure how t... | [
"From the django book:\n\nNote that you do not include parentheses in the method calls.\n Also, it’s not possible to pass arguments to the methods;\n you can only call methods that have no required arguments.\n\nSo, if you want to call a method without arguments from a template, it's fine.\n Otherwise, you hav... | [
9,
6,
5,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002115869_django_django_templates_python.txt |
Q:
How to download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine?
I have a python script running inside the Google App Engine with boto 1.9b that gets all keys inside a S3-Bucket. The output is formated as a HTML-Table.
bucket_instance = conn_s3.get_bucket(bucketname)
liste_keys ... | How to download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine? | I have a python script running inside the Google App Engine with boto 1.9b that gets all keys inside a S3-Bucket. The output is formated as a HTML-Table.
bucket_instance = conn_s3.get_bucket(bucketname)
liste_keys = bucket_instance.get_all_keys()
table = '<table>'
for i in range(laenge_liste_keys):
table = table + ... | [
"The solution is found.\ngenerate_url(expires_in, method='GET', headers=None, query_auth=True, force_http=False)\n\nThis makes it easy to create a link for every key which is valid for x seconds. \n",
"The public URL for the file would be something like: \nhttp://s3.amazonaws.com/bucket_name/key_name \n\nSo in y... | [
3,
2
] | [] | [] | [
"amazon_s3",
"boto",
"google_app_engine",
"html",
"python"
] | stackoverflow_0002113777_amazon_s3_boto_google_app_engine_html_python.txt |
Q:
XML to store system paths in Python with lxml
I'm using an xml file to store configurations for a software.
One of theese configurations would be a system path like
> set_value = "c:\\test\\3 tests\\test"
i can store it by using:
> setting = etree.SubElement(settings,
> "setting", name=tmp_set_name, type =
> set... | XML to store system paths in Python with lxml | I'm using an xml file to store configurations for a software.
One of theese configurations would be a system path like
> set_value = "c:\\test\\3 tests\\test"
i can store it by using:
> setting = etree.SubElement(settings,
> "setting", name=tmp_set_name, type =
> set_type , value= set_value)
If I use
doc.write(outpu... | [
"\nNow I read it again with the\n etree.parse method\nI obtain an etree child object with a\n string value, but the string contains\n the\n\\3\n\ncharacter and if i try to use it to\n write again to xml it will be\n interpreted !!!!!\n\nI just tried that, and it doesn't get \"interpreted\". The elements attrib... | [
1
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0002116121_lxml_python_xml.txt |
Q:
Python EVT_SET_FOCUS
When I run this code and focus on choice it is raise a error. I close
this message but it is come back again. I want to see only one time
this message. How can i do this? What is error in my code ?
#! -*- coding:utf-8 -*-
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, *args,... | Python EVT_SET_FOCUS | When I run this code and focus on choice it is raise a error. I close
this message but it is come back again. I want to see only one time
this message. How can i do this? What is error in my code ?
#! -*- coding:utf-8 -*-
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Pane... | [
"The error dialog gets the focus when it is shown. When you close the error dialog, the focus returns to the choice control, firing the event handler again, which pops up the error dialog again, et cetera.\nTo avoid the event handler from being invoked multiple times, one solution would be to unbind the wx.EVT_SET_... | [
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002107223_python_wxpython.txt |
Q:
Cannot solve mod_wsgi exception in Django setup
I'm working with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end.
I don't have direct access to the conf file but here's how its contents have been described to me:
<If... | Cannot solve mod_wsgi exception in Django setup | I'm working with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end.
I don't have direct access to the conf file but here's how its contents have been described to me:
<IfModule mod_wsgi.c>
WSGIScriptAlias /fredapp/ /home/fr... | [
"If the quoted configuration about is what you are using, the error is rather obvious actually. You have:\nWSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/\nWSGIProcessGroup scratchf\n\nIt should be:\nWSGIDaemonProcess fred threads=15 display-name=%{... | [
22,
1,
0
] | [] | [] | [
"apache",
"django",
"python",
"wsgi"
] | stackoverflow_0002113905_apache_django_python_wsgi.txt |
Q:
sum of bytes with unsigned long overflow in python
how to translate this piece of C code into Python >=2.6 ?
unsigned long memSum(unsigned char *p, unsigned long len)
{
unsigned long i, sum=0;
for(i=0; i<len; i++)
sum = sum + *p++;
return sum;
}
of course
f=open("file_to_sum",'rb')
m = f.read(... | sum of bytes with unsigned long overflow in python | how to translate this piece of C code into Python >=2.6 ?
unsigned long memSum(unsigned char *p, unsigned long len)
{
unsigned long i, sum=0;
for(i=0; i<len; i++)
sum = sum + *p++;
return sum;
}
of course
f=open("file_to_sum",'rb')
m = f.read()
f.close()
sum( array.array('B', m) )
does not work
| [
"If you need to wrap around on overflow, simply take your sum modulo MAX_LONG at the end.\n",
"A direct, Pythonic translation:\ndef memSum(data):\n return sum(ord(c) for c in data) & 0xFFFFFFFF\n\n",
"As I mentioned in my comment, you need to convert the string into a list of ints.\nThis probably what you wa... | [
3,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"byte",
"overflow",
"python",
"sum"
] | stackoverflow_0002113118_byte_overflow_python_sum.txt |
Q:
Create string(s) from list(s) items
I have a list, list = ['foo','bar'] and now i want to create a string from each item.
Each string is named as the item and has the value of the item
foo = 'foo'
bar = 'bar'
Thanks to all, i will use a dict instead
A:
Don't do that. Use a dict instead.
strings = dict((x, x) for... | Create string(s) from list(s) items | I have a list, list = ['foo','bar'] and now i want to create a string from each item.
Each string is named as the item and has the value of the item
foo = 'foo'
bar = 'bar'
Thanks to all, i will use a dict instead
| [
"Don't do that. Use a dict instead.\nstrings = dict((x, x) for x in L)\n\n",
"Ignacio Vazquez-Abrams is right, using a dict is better. But if you insist on having them available as variables, you can always do this:\nstrings = dict((x, x) for x in L)\nlocals().update(strings)\n\nPS: Edan Maor's version with exec ... | [
9,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002116597_python.txt |
Q:
Python XML Parsing Confusion
I'm using xml.dom.mindom in Python and have retrieved the book node in the below XML tree. I want to get a list of all children nodes. In this case, I would think there would only be one.
<Book>
<Title>Why is this so hard</Title>
</Book
When I call:
nodeList = bookNode.childNo... | Python XML Parsing Confusion | I'm using xml.dom.mindom in Python and have retrieved the book node in the below XML tree. I want to get a list of all children nodes. In this case, I would think there would only be one.
<Book>
<Title>Why is this so hard</Title>
</Book
When I call:
nodeList = bookNode.childNodes
print "nodeList has " + str(no... | [
"The first text node is the whitespace between <Book> and <Title>. The second is the whitespace between </Title> and </Book>\n",
"\nWhat are these random #text nodes?\n\nHardly random, they're text nodes representing the whitespace you put between tags. XML has to remember this, or the document would be all run t... | [
3,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002113917_python_xml.txt |
Q:
How can I check compilation errors in python?
#!/usr/bin/python
str = "this"
if(1):
print "Hi"
else:
print str.any_random_function()
This doesn't fail when I run the program. I tried py_compile but that didn't indicate the error in the else loop either. Now how can I compile the program and detect... | How can I check compilation errors in python? | #!/usr/bin/python
str = "this"
if(1):
print "Hi"
else:
print str.any_random_function()
This doesn't fail when I run the program. I tried py_compile but that didn't indicate the error in the else loop either. Now how can I compile the program and detect errors reliably in python code?
| [
"I think your best bet would be pylint.\n",
"Python is a dynamic language, so you can't simply check for compiling errors like in static languages (C/C++/Java). If you assign str.any_random_function, the above code would be correct (okay that's a bad example...).\nI'd suggest you to use PyDev for Eclipse which au... | [
9,
3
] | [] | [] | [
"compilation",
"python"
] | stackoverflow_0002117586_compilation_python.txt |
Q:
How can I query objects with a date field, using a specific month and year?
I need to make a gql query against a set of some objects which have a date field. I am very new to python and also the GAE so I am a bit igorant to this. I am looking in the documentation but cannot find quite what I am looking for. Bas... | How can I query objects with a date field, using a specific month and year? | I need to make a gql query against a set of some objects which have a date field. I am very new to python and also the GAE so I am a bit igorant to this. I am looking in the documentation but cannot find quite what I am looking for. Basically I have made the following class method
Event.getEventsForMonth(cls, month,... | [
"First, store your dates as DateProperty or DateTimeProperty instances in the datastore.\nThen, you can do your query something like this:\ndef getEventsForMonth(self, month, year):\n start_date = datetime.datetime(year, month, 1)\n if month == 12:\n end_date = datetime.datetime(year + 1, 1, 1)\n else:\n e... | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002117056_django_google_app_engine_python.txt |
Q:
Is there any metaprogramming patterns catalog for Python?
I have just read Python Cookbook. The book is amazing.
I think the best use of this book is that it provides lots of examples that show python in real problem applications. Many of the idioms include metaprogramming techniques.
I wonder if there is any cat... | Is there any metaprogramming patterns catalog for Python? | I have just read Python Cookbook. The book is amazing.
I think the best use of this book is that it provides lots of examples that show python in real problem applications. Many of the idioms include metaprogramming techniques.
I wonder if there is any catalog that summarizes metaprogramming idioms in Python?
Python C... | [
"\nA Primer on Python Metaclass Programming.\nhttp://www.ibm.com/developerworks/linux/library/l-pymeta.html\n\n"
] | [
4
] | [] | [] | [
"design_patterns",
"idioms",
"metaprogramming",
"python"
] | stackoverflow_0002117927_design_patterns_idioms_metaprogramming_python.txt |
Q:
Python List Exclusions
I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this
for y in myDict:
print(y+"\t"+myDict[y])
I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entrie... | Python List Exclusions | I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this
for y in myDict:
print(y+"\t"+myDict[y])
I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok li... | [
"Do you mean\nfor key in myDict:\n if key not in myList:\n print(key+\"\\t\"+myDict[key])\n\nOr one of many alternatives:\nfor key in (set(myDict)-set(myList)):\n print(key+\"\\t\"+myDict[key])\n\n",
"mySet = set(myList)\nmyNewDict = dict(((k, v) for k, v in myDict if k not in mySet))\n\nNote that us... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0002118503_python.txt |
Q:
Python :: How to open a page in the Non Default browser
I was trying to create a simple script to open a locally hosted web site for testing the css in 2 or more browsers. The default browser is IE7 and it opens the page fine but when I try to open a non default browser such as Firefox or Arora it just fails.
I a... | Python :: How to open a page in the Non Default browser | I was trying to create a simple script to open a locally hosted web site for testing the css in 2 or more browsers. The default browser is IE7 and it opens the page fine but when I try to open a non default browser such as Firefox or Arora it just fails.
I am using the webbrowser module and have tried this several way... | [
"Matt's right and it's a pretty useful module to know...\n18.1. subprocess\nIDLE 2.6.2 \n>>> import subprocess\n>>> chrome = 'C:\\Users\\Ted\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'\n>>> chrome_args = 'www.rit.edu'\n>>> spChrome = subprocess.Popen(chrome+' '+chrome_args)\n>>> print spChrome.pi... | [
3,
1,
0
] | [] | [] | [
"browser",
"python"
] | stackoverflow_0002117545_browser_python.txt |
Q:
SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0]? How?
I'm trying to help a colleague run SOATest (a web services client that makes testing SOAP services easy) on a WCF web service operation, and for "big" responses, we are seeing this error:
SOAP Message size it greater than allowed limit ... | SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0]? How? | I'm trying to help a colleague run SOATest (a web services client that makes testing SOAP services easy) on a WCF web service operation, and for "big" responses, we are seeing this error:
SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0]
This is perplexing, as the tool is actually able to get a ... | [
"We were able to get an answer to this error on the SOATest forums.\nSECURITY.MSGSIZE is one of the default SOAP Policy rule checks available to be added to a response. Here's a screenshot of the particular rule as it was being applied. This particular rule is located at:\nC:\\Program Files\\Parasoft\\SOAtest\\5.5.... | [
0
] | [] | [] | [
"policy",
"python",
"rule",
"soap"
] | stackoverflow_0002105037_policy_python_rule_soap.txt |
Q:
What are the cons of returning an Exception instance instead of raising it in Python?
I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following:... | What are the cons of returning an Exception instance instead of raising it in Python? | I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following:
def update(self, documents, **options):
"""Perform a bulk update or insertion of the g... | [
"I think it is ok to return the exceptions in this case, because some parts of the update function may succeed and some may fail. When you raise the exception, the API user has no control over what succeeded already.\n",
"Raising an Exception is a notification that something that was expected to work did not work... | [
4,
2,
1,
1
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0002116972_exception_python.txt |
Q:
os.listdir etc fails on shared windows path (Python 2.5)
I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds)
I am reading text file which contains directory paths which I want to process further. In order to do so I do as below:
def toWin(path):
return path... | os.listdir etc fails on shared windows path (Python 2.5) | I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds)
I am reading text file which contains directory paths which I want to process further. In order to do so I do as below:
def toWin(path):
return path.replace("\\", "\\\\")
for line in open(fileName):
l = to... | [
"This may not be your actual issue, but your UNC paths are actually not correct - they should start with a double backslash, but internally only use a single backslash as a divider.\nI'm not sure why the same thing would be working within the shell.\nUpdate:\nI suspect that what's happening is that in the shell, yo... | [
0,
0,
-1
] | [] | [] | [
"path",
"python"
] | stackoverflow_0002046912_path_python.txt |
Q:
python: convert UUID to a string which is a C unsigned char[16] initializer
(in case you're curious about motivation: this will be used in a scons build to generate a C file containing a GUID)
I found the question about generating a GUID in python. But I don't really know much about programming python. Could someo... | python: convert UUID to a string which is a C unsigned char[16] initializer | (in case you're curious about motivation: this will be used in a scons build to generate a C file containing a GUID)
I found the question about generating a GUID in python. But I don't really know much about programming python. Could someone help me convert this to a string of the form
"{0x**, 0x**, 0x**, 0x**, 0x**, 0... | [
"hex(ord(b))\n\n...\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002119500_python.txt |
Q:
Boost.Python - How to return by reference?
I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.
Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.
Specifying that the return by value s... | Boost.Python - How to return by reference? | I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.
Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.
Specifying that the return by value should be used was easy once I typedefed a signat... | [
"In Python, there's the concept of immutable types. An immutable type can't have its value changed. Examples of built-in immutable types are int, float and str.\nHaving said that, you can't do what you want with boost::python, because Python itself does not allow you to change the value of the float returned by the... | [
7,
3,
0,
0
] | [] | [] | [
"boost",
"boost_python",
"python"
] | stackoverflow_0001571054_boost_boost_python_python.txt |
Q:
Returning a c++ array (pointer) from boost python
I'm currently writing python bindings for a c++ library I'm working on. The library reads some binary file format and reading speed is very important. While optimizing the library for speed, I noticed that std::vector (used in the instances I'm reading) was eating ... | Returning a c++ array (pointer) from boost python | I'm currently writing python bindings for a c++ library I'm working on. The library reads some binary file format and reading speed is very important. While optimizing the library for speed, I noticed that std::vector (used in the instances I'm reading) was eating up a lot of processing time, so I replaced those with s... | [
"If you change your class to work with std::vector instances, take a look at the vector indexing suite (http://www.boost.org/doc/libs/1_41_0/libs/python/doc/v2/indexing.html), which allows you to expose vectors to python with a native list interface, without creating copies from/to python.\n",
"I will recomend a ... | [
4,
1
] | [] | [] | [
"binding",
"boost",
"boost_python",
"python"
] | stackoverflow_0001410272_binding_boost_boost_python_python.txt |
Q:
How to separate one list in two via list comprehension or otherwise
If have a list of dictionary items like so:
L = [{"a":1, "b":0}, {"a":3, "b":1}...]
I would like to split these entries based upon the value of "b", either 0 or 1.
A(b=0) = [{"a":1, "b":1}, ....]
B(b=1) = [{"a":3, "b":2}, .....]
I am comfortabl... | How to separate one list in two via list comprehension or otherwise | If have a list of dictionary items like so:
L = [{"a":1, "b":0}, {"a":3, "b":1}...]
I would like to split these entries based upon the value of "b", either 0 or 1.
A(b=0) = [{"a":1, "b":1}, ....]
B(b=1) = [{"a":3, "b":2}, .....]
I am comfortable with using simple list comprehensions, and i am currently looping throu... | [
"Don't use a list comprehension. List comprehensions are for when you want a single list result. You obviously don't :) Use a regular for loop:\nA = []\nB = []\nfor item in L:\n if item['b'] == 0:\n target = A\n else:\n target = B\n target.append(item)\n\nYou can shorten the snippet by doing,... | [
5,
3
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0002119112_list_list_comprehension_python.txt |
Q:
How do I create an extra RSS item element that contains HTML using PyRSS2Gen?
I'm using PyRSS2Gen to generate an RSS feed. I've succeeded in extending it to add an extra element to each item in the RSS feed:
class FullRSSItem(PyRSS2Gen.RSSItem):
def __init__(self, **kwargs):
if 'content' in kwargs:
... | How do I create an extra RSS item element that contains HTML using PyRSS2Gen? | I'm using PyRSS2Gen to generate an RSS feed. I've succeeded in extending it to add an extra element to each item in the RSS feed:
class FullRSSItem(PyRSS2Gen.RSSItem):
def __init__(self, **kwargs):
if 'content' in kwargs:
self.content = kwargs['content']
del kwargs['content']
... | [
"I eventually ditched the idea of using the CDATA wrapper and just had the full text be encoded. Seems to work.\n"
] | [
0
] | [] | [] | [
"cdata",
"python",
"rss"
] | stackoverflow_0002066423_cdata_python_rss.txt |
Q:
Is there a Python library for connecting to a PostgreSQL 8.4 server using certificate authentication?
We are in the process of upgrading from PostgreSQL 8.3 to PostgreSQL 8.4, in a large part so that we can start using certificate-based authentication.
We have some Python 2.x code that accesses the database that u... | Is there a Python library for connecting to a PostgreSQL 8.4 server using certificate authentication? | We are in the process of upgrading from PostgreSQL 8.3 to PostgreSQL 8.4, in a large part so that we can start using certificate-based authentication.
We have some Python 2.x code that accesses the database that uses PyGreSQL. Is there a way to get it or any other Python library to use a cert to access PostgreSQL?
Look... | [
"psycopg2 is based on libpq, so it should work there. I don't think there's a specific interface for it, so you'll have to use the environment variables (see the libpq documentation) to control it, but it should work. (disclaimer: I haven't actually tried it, but anything on top of libpq should work)\n"
] | [
2
] | [] | [] | [
"authentication",
"certificate",
"postgresql",
"python"
] | stackoverflow_0002118846_authentication_certificate_postgresql_python.txt |
Q:
Python extensions that can be used in all varieties of python (jython / IronPython / etc.)
In the 'old days' when there was just cpython, most extensions were written in c (as platform independent as possible) and compiled into pyd's (think PyCrypto for example). Now there is Jython, IronPython and PyPy and the p... | Python extensions that can be used in all varieties of python (jython / IronPython / etc.) | In the 'old days' when there was just cpython, most extensions were written in c (as platform independent as possible) and compiled into pyd's (think PyCrypto for example). Now there is Jython, IronPython and PyPy and the pyd’s do not work with any of them (Ironclad aside). It seems they all support ctypes and that t... | [
"Currently, it seems the ctypes is indeed the best approach. It works today, and it's so convenient that it's gonna conquer (most of) the world.\nFor performance-critical APIs (such as numpy), ctypes is indeed problematic. The cleanest approach would probably be to port Cython to produce native IronPython / Jytho... | [
2,
1
] | [] | [] | [
"ironpython",
"jython",
"python"
] | stackoverflow_0002114627_ironpython_jython_python.txt |
Q:
Django forms: how do I display the initial blank form?
I have this view function:
def search(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
last_name = form.cleaned_data['last_name']
first_name = form.cleaned_data['first_name']
... | Django forms: how do I display the initial blank form? | I have this view function:
def search(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
last_name = form.cleaned_data['last_name']
first_name = form.cleaned_data['first_name']
lawyers = Lawyer.objects.all()
[ othe... | [
"Every normal HTTP request (like when you go to http://stackoverflow.com) is a GET request. It is generally a good idea to use POST as the method of your forms when they change some data.\nYou should read: When do you use POST and when do you use GET?\n",
"When you post a form with method=GET you don't actually c... | [
2,
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0002119682_django_forms_python.txt |
Q:
What do square brackets, "[]", mean in function/class documentation?
I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.
From the docmentation:
class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[,... | What do square brackets, "[]", mean in function/class documentation? | I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify.
From the docmentation:
class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
I'd appreciate a summary of the arguments to the cla... | [
"The square brackets indicate that these arguments are optional. You can leave them out.\nSo, in this case you are only required to pass the csvfile argument to csv.DictReader. If you would pass a second parameter, it would be interpreted as the fieldnames arguments. The third would be restkey, etc.\nIf you only wa... | [
28,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001718903_python.txt |
Q:
Best F/OSS IDE for Python Web Development (Windows or Linux)?
Would like to know what is the best F/OSS IDE for Python Web development. I've always used vim myself, but I'm increasingly interested in having a tool that integrates syntax checking/highlighting, source control, debugging, and other IDE goodies.
I us... | Best F/OSS IDE for Python Web Development (Windows or Linux)? | Would like to know what is the best F/OSS IDE for Python Web development. I've always used vim myself, but I'm increasingly interested in having a tool that integrates syntax checking/highlighting, source control, debugging, and other IDE goodies.
I use both Windows and Linux as desktops, so recommendations for either... | [
"Might take some getting used to but Eclipse with the python extension - PyDev - works for me. It took a bit of getting-used-to though as Eclipse is generally meant for Java (or perhaps because I wasn't familiar with it). But it's a good open source option.\n",
"I am also working with mod_wsgi, python, apache sof... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0002097134_ide_python.txt |
Q:
ImportError: Model A references Model B, Model B references Model A
I think this is more a python question than Django.
But basically I'm doing at Model A:
from myproject.modelb.models import ModelB
and at Model B:
from myproject.modela.models import ModelA
Result:
cannot import name ModelA
Am I doing somethin... | ImportError: Model A references Model B, Model B references Model A | I think this is more a python question than Django.
But basically I'm doing at Model A:
from myproject.modelb.models import ModelB
and at Model B:
from myproject.modela.models import ModelA
Result:
cannot import name ModelA
Am I doing something forbidden? Thanks
| [
"A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the ModelA class because the i... | [
6,
2
] | [] | [] | [
"circular_dependency",
"django",
"python"
] | stackoverflow_0002120332_circular_dependency_django_python.txt |
Q:
Read XML with multiple top-level items using Python ElementTree?
How can I read an XML file using Python ElementTree, if the XML has multiple top-level items?
I have an XML file that I would like to read using Python ElementTree.
Unfortunately, it has multiple top-level tags. I would wrap <doc>...</doc> around the... | Read XML with multiple top-level items using Python ElementTree? | How can I read an XML file using Python ElementTree, if the XML has multiple top-level items?
I have an XML file that I would like to read using Python ElementTree.
Unfortunately, it has multiple top-level tags. I would wrap <doc>...</doc> around the XML, except I have to put the <doc> after the <?xml> and <!DOCTYPE> f... | [
"I wrote the following function to add a toplevel tag after the XML processing instructions. You can now find this code in my common Python library as common.myelementtree.add_toplevel_tag\nimport re\nxmlprocre = re.compile(\"(\\s*<[\\?\\!])\")\ndef add_toplevel_tag(string):\n \"\"\"\nAfter all the XML processin... | [
0
] | [] | [] | [
"elementtree",
"parsing",
"python",
"xml"
] | stackoverflow_0002113819_elementtree_parsing_python_xml.txt |
Q:
Why do Python function docs include the comma after the bracket for optional args?
The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets?
How they are:... | Why do Python function docs include the comma after the bracket for optional args? | The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets?
How they are:
RegexObject.match(string[, pos[, endpos]])
I would expect one of the following:
RegexO... | [
"The square bracket means that the contents are optional, but everything outside of square brackets is compulsory.\nWith your notation:\nRegexObject.match(string, [pos], [endpos])\n\nI would expect to have to write:\nr.match(\"foo\",,)\n\nThe nesting is required because if you supply the third parameter then you mu... | [
22,
2,
2,
0,
0
] | [] | [] | [
"documentation",
"notation",
"python"
] | stackoverflow_0002120507_documentation_notation_python.txt |
Q:
In wxPython, What is the Standard Process of Making an Application Slightly More Complex Than a Wizard?
I am attempting to create my first OS-level GUI using wxPython. I have the book wxPython in Action and have looked at the code demos. I have no experience with event-driven programming (aside from some Javascr... | In wxPython, What is the Standard Process of Making an Application Slightly More Complex Than a Wizard? | I am attempting to create my first OS-level GUI using wxPython. I have the book wxPython in Action and have looked at the code demos. I have no experience with event-driven programming (aside from some Javascript), sizers, and all of the typical GUI elements. The book is organized a little strangely and assumes I kn... | [
"I don't have a good understanding of your application, but trying to force wxWizard to suit your needs sounds like a bad idea.\nI suggest checking out the Demos available from the wxPython website. Go through each demo and I bet you'll find one that suits your needs.\nI've personally never used wxWizard as I find... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002119067_python_wxpython.txt |
Q:
Parse boolean arithmetic including parentheses with regex?
Is there a single regular expression that can parse a string (in Python and/or Javascript, does not need to be the same expression) that represents simple boolean arithmetic? For example I want to parse this string:
a and (b and c) and d or e and (f or g)
... | Parse boolean arithmetic including parentheses with regex? | Is there a single regular expression that can parse a string (in Python and/or Javascript, does not need to be the same expression) that represents simple boolean arithmetic? For example I want to parse this string:
a and (b and c) and d or e and (f or g)
Assuming that:
* parentheses do not nest
* the terms a, b, ...,... | [
"Normally you would use for example a recursive descent parser for this task, but you can grab all the parts (tokens) with a regex:\nx = 'a and (b and c) and d or e and (f or g)'\nimport re\n\nmatches = re.findall(r'\\(.*?\\)|\\w+', x)\nprint ','.join(matches)\n\nThe operators usually have different precedence. Par... | [
2,
1,
1
] | [] | [] | [
"javascript",
"python",
"regex"
] | stackoverflow_0002118261_javascript_python_regex.txt |
Q:
How do I get stacktraces from epydoc when it is loading my code?
When I load my code into epydoc and just load the top module it fails with:
Error: TypeError: 'NoneType' object is not callable (line 10)
Where the the NoneType that it is referring to is a submodule that I tried to load on line 9. How can I get ep... | How do I get stacktraces from epydoc when it is loading my code? | When I load my code into epydoc and just load the top module it fails with:
Error: TypeError: 'NoneType' object is not callable (line 10)
Where the the NoneType that it is referring to is a submodule that I tried to load on line 9. How can I get epydoc to explain why it couldn't load the module on line 9 instead of j... | [
"So if I understand correctly, the module you're running epydoc on imports a module that has an error in it (not the module you want to generate docs for)? \nIf all you need to accomplish is to see the line in the file which has the error so you can debug it, you can pass in this file as well and the line number w... | [
2
] | [] | [] | [
"epydoc",
"python"
] | stackoverflow_0002121268_epydoc_python.txt |
Q:
rstrip not removing newline char what am I doing wrong?
Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence.
def add_quotes( fpath ):
ifile = open( fpath, 'r' )
ofile = open( 'ofile.txt', 'w' )
... | rstrip not removing newline char what am I doing wrong? | Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence.
def add_quotes( fpath ):
ifile = open( fpath, 'r' )
ofile = open( 'ofile.txt', 'w' )
for line in ifile:
if line == '\n':
... | [
"The clue is in the signature of rstrip.\nIt returns a copy of the string, but with the desired characters stripped, thus you'll need to assign line the new value:\nline = line.rstrip('\\n')\n\nThis allows for the sometimes very handy chaining of operations:\n\"a string\".strip().upper()\n\nAs Max. S says in the co... | [
35,
3,
3
] | [] | [] | [
"newline",
"python"
] | stackoverflow_0002121839_newline_python.txt |
Q:
How to report a bug with Python's 'help()' function?
As a hobby/learning project, I'm writing a parser generator in Python. One of my code files is named "token.py" - which contains a couple of classes for turning plain strings into Token objects. I've just discovered that using the "help()" function from the cons... | How to report a bug with Python's 'help()' function? | As a hobby/learning project, I'm writing a parser generator in Python. One of my code files is named "token.py" - which contains a couple of classes for turning plain strings into Token objects. I've just discovered that using the "help()" function from the console in Python raises an error for any module defined in a ... | [
"The problem is that your local token.py is being imported by help() instead of Python's actual token.py. This will occur for any number of .py files whose names collide with built-in modules. For example, try creating a pydoc.py file in the CWD and then try help() in Python. The help() function is just a built-in ... | [
5,
3,
1,
0
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0002121715_namespaces_python.txt |
Q:
Inline parsing in BeautifulSoup in Python
I am writing an HTML document with BeautifulSoup, and I would like it to not split inline text (such as text within the <p> tag) into multiple lines. The issue that I get is that parsing the <p>a<span>b</span>c</p> with prettify gives me the output
<p>
a
<span>
b
</span... | Inline parsing in BeautifulSoup in Python | I am writing an HTML document with BeautifulSoup, and I would like it to not split inline text (such as text within the <p> tag) into multiple lines. The issue that I get is that parsing the <p>a<span>b</span>c</p> with prettify gives me the output
<p>
a
<span>
b
</span>
c
</p>
and now the HTML displays spaces betw... | [
"How about not using prettify at all?\nBeautifulSoup.BeautifulSoup('<p>a<span>b</span>c</p>').renderContents()\n\noutputs the original HTML with no extra spaces. You can use e.g. Firebug to have a closer look at the document's structure later with no need to 'prettify' it at construction time.\n",
"I'd just do:\n... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0002121036_beautifulsoup_html_python.txt |
Q:
What side effects should one expect when method decorator replaces self?
I want to execute a method with a copy of the original self passed while execution.
Here is the code I'm talking about:
def protect_self(func):
from copy import copy
from functools import wraps
@wraps(func)
def decorated(self,... | What side effects should one expect when method decorator replaces self? | I want to execute a method with a copy of the original self passed while execution.
Here is the code I'm talking about:
def protect_self(func):
from copy import copy
from functools import wraps
@wraps(func)
def decorated(self, *args, **kwargs):
self_copy = copy(self)
return func(self_cop... | [
"The copy makes it so the 'self' passed to the decorated function is a shallow copy of the original. The decorated function can't modify the original 'self' directly, although it can of course modify it through other means (if it has indirect access to it.) If any of the attributes of the object are mutable, it can... | [
2,
1
] | [] | [] | [
"decorator",
"python",
"self"
] | stackoverflow_0002120563_decorator_python_self.txt |
Q:
Problem allocating heap space over 4 GB when calling java "from Python"
I am using using os.system call from python to run jar file.
The jar file requires large heap space and thus i am allocating 4 Gb heap space using Xmx.
When i execute the command
"java -Xms4096m -Xmx4096m -jar camXnet.jar net.txt"
from comma... | Problem allocating heap space over 4 GB when calling java "from Python" | I am using using os.system call from python to run jar file.
The jar file requires large heap space and thus i am allocating 4 Gb heap space using Xmx.
When i execute the command
"java -Xms4096m -Xmx4096m -jar camXnet.jar net.txt"
from command line it executes properly, however when i call it from a python program vi... | [
"It's hard to be sure without knowing more detail - like which OS you're on - but my guess is that you're using a 32-bit version of Python which means that when you launch Java, you're also getting the 32-bit version which has a heap size limit of 4GB.\nTo test if this is the case, compare the output of java -versi... | [
2,
1,
0
] | [] | [] | [
"java",
"python",
"ram"
] | stackoverflow_0002000331_java_python_ram.txt |
Q:
Can Someone Explain Threads to Me?
I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or ... | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be c... | [
"This is a very broad topic. But here are the things I would want to know if I knew nothing about threads:\n\nThey are units of execution within a single process that happen \"in parallel\" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via differen... | [
32,
2,
1,
1,
1,
1,
1,
1,
1,
0
] | [] | [] | [
"c++",
"java",
"multithreading",
"perl",
"python"
] | stackoverflow_0002121617_c++_java_multithreading_perl_python.txt |
Q:
Can someone help clarify my confusion about syncdb and import loops, 'Do you have to be explicit on imports?'
I have been having a difficult time building the database with syncdb on Python2.5.
I think that some of this issue is because of the use of wildcard* for importing forum.models it seems to be creating a l... | Can someone help clarify my confusion about syncdb and import loops, 'Do you have to be explicit on imports?' | I have been having a difficult time building the database with syncdb on Python2.5.
I think that some of this issue is because of the use of wildcard* for importing forum.models it seems to be creating a loop.
>>> import settings
>>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, ... | [
"Would you happen to be using global_settings.py or local_settings.py in addition to settings.py?\nThe proper way to import Django's settings is to use the decoupled object from django.conf import settings, NOT to import settings. See the doc page about it here: Using settings in Python code\nI can't say for certa... | [
0
] | [] | [] | [
"django",
"django_syncdb",
"python"
] | stackoverflow_0002120870_django_django_syncdb_python.txt |
Q:
Is it acceptable to use tricks to save programmer when putting data in your code?
Example: It's really annoying to type a list of strings in python:
["January", "February", "March", "April", ...]
I often do something like this to save me having to type quotation marks all over the place:
"January February March A... | Is it acceptable to use tricks to save programmer when putting data in your code? | Example: It's really annoying to type a list of strings in python:
["January", "February", "March", "April", ...]
I often do something like this to save me having to type quotation marks all over the place:
"January February March April May June July August ...".split()
Those took the same amount of time, and I got 2... | [
"Code is usually read many times, and it is written only once.\nSaving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code.\nThe second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking abou... | [
33,
19,
6,
5,
3,
3,
1,
1,
1,
1,
0,
0
] | [
"I would find this acceptable, if a bit lazy, as long as what is being done isn't too performance critical. You could always go back and optimize it if you need more speed.\n"
] | [
-2
] | [
"coding_style",
"python"
] | stackoverflow_0001122691_coding_style_python.txt |
Q:
Python - uniquifying(!) dictionary keys
I have data coming in from a machine (via pexpect) and I parse it using regexes into a dictionary like this
for line in stream:
if '/' in line:
# some matching etc which results in getting the
# machine name, an interface and the data for that interface... | Python - uniquifying(!) dictionary keys | I have data coming in from a machine (via pexpect) and I parse it using regexes into a dictionary like this
for line in stream:
if '/' in line:
# some matching etc which results in getting the
# machine name, an interface and the data for that interface
key=str(hostname)+":"+r.groups()[0][... | [
"You can create a list for each key, holding all values for that key:\nd = collections.defaultdict(list)\nfor line in stream:\n if '/' in line:\n #.....\n key = str(hostname)+\":\"+r.groups()[0][0:2]+r.groups()[2]\n value = str(line[3])\n d[key].append(value)\n\nEdit: If you want the... | [
4,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002122880_dictionary_python.txt |
Q:
Trouble using python's gzip/"How do I know what compression is being used?"
Ok, so I've got an Open Source Java client/server program that uses packets to communicate. I'm trying to write a python client for said program, but the contents of the packet seem to be compressed. A quick perusal through the source code... | Trouble using python's gzip/"How do I know what compression is being used?" | Ok, so I've got an Open Source Java client/server program that uses packets to communicate. I'm trying to write a python client for said program, but the contents of the packet seem to be compressed. A quick perusal through the source code suggested gzip as the compression schema (since that was the only compression mo... | [
"You could try using standard library module zlib directly -- that's what gzip uses for the compress/decompress part. If the whole packet isn't liked by the decompress function, you can try using different values of wbits and/or slicing off a few bytes off the packet's front (if you could \"reverse engineer\" exac... | [
1,
1,
0
] | [] | [] | [
"compression",
"java",
"python",
"reverse_engineering"
] | stackoverflow_0002122190_compression_java_python_reverse_engineering.txt |
Q:
What is the method of doing nl2br in Genshi?
hiyas. I using Genshi+Pylons.
please teach me, how use \n to <br/>tag in Genshi?
I hope to obtain the same result as "nl2br" in php to change line.
Or, does not the solution exist?
i'm assign template to some text.
(genshi template)
<p>${c.message}</p>
Im tried.
case... | What is the method of doing nl2br in Genshi? | hiyas. I using Genshi+Pylons.
please teach me, how use \n to <br/>tag in Genshi?
I hope to obtain the same result as "nl2br" in php to change line.
Or, does not the solution exist?
i'm assign template to some text.
(genshi template)
<p>${c.message}</p>
Im tried.
case 1:
(python code)
c.message = """
foo
bar
"""
NG.... | [
"Try this:\n<py:for each=\"line in message.split('\\n')\">${line}<br /></py:for>\n\n"
] | [
2
] | [] | [] | [
"genshi",
"pylons",
"python"
] | stackoverflow_0002123162_genshi_pylons_python.txt |
Q:
What are some Pythonic ways to share variables with objects defined in a module?
I'm building a module where there are a whole lot of diverse objects which need to be controlled by several variables.
If this were C, I would pass the objects a pointer to the variable / object I want them to watch, have the applicat... | What are some Pythonic ways to share variables with objects defined in a module? | I'm building a module where there are a whole lot of diverse objects which need to be controlled by several variables.
If this were C, I would pass the objects a pointer to the variable / object I want them to watch, have the application change the variable as it needs to, and the objects in the module would "see" the ... | [
"How about putting the control variables in a separate module -- say, settings -- and doing a separate import settings? You could then have your objects watch settings.bar and settings.quux while still doing from foo import * to clutter up your main namespace. ;-) You could also use a global object to store your se... | [
3,
3,
3,
1,
1
] | [] | [] | [
"global_variables",
"module",
"python"
] | stackoverflow_0002122306_global_variables_module_python.txt |
Q:
Changing web service url in SUDS library
Using SUDS SOAP client how do I specify web service URL. I can see clearly that WSDL path is specified in Client constructor but what if I wan't to change web service url?
A:
Suds supports WSDL with multiple services or multiple ports (or both), and without having any det... | Changing web service url in SUDS library | Using SUDS SOAP client how do I specify web service URL. I can see clearly that WSDL path is specified in Client constructor but what if I wan't to change web service url?
| [
"Suds supports WSDL with multiple services or multiple ports (or both), and without having any detailed information on what you're working with, I am only guessing that this is what you are looking for. This question would be easier to answer if you provided more detail, such as what your Client instance looks like... | [
4,
4,
1
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0001670569_python_soap_suds.txt |
Q:
python : mysql : Return 0 when no rows found
Table structure - Data present for 5 min. slots -
data_point | point_date
12 | 00:00
14 | 00:05
23 | 00:10
10 | 00:15
43 | 00:25
10 | 00:40
When I run the query for say 30 mins. and if data is pres... | python : mysql : Return 0 when no rows found | Table structure - Data present for 5 min. slots -
data_point | point_date
12 | 00:00
14 | 00:05
23 | 00:10
10 | 00:15
43 | 00:25
10 | 00:40
When I run the query for say 30 mins. and if data is present I'll get 6 rows (one row for each 5 min. stamp... | [
"Yes, you can do that using SQL only. A solution would be to use a Stored Routine. The bellow Stored Procedure produces following output:\nstart cnt\n00:05:00 1\n00:10:00 0\n00:15:00 1\n00:20:00 0\n00:25:00 1\n00:30:00 0\n00:35:00 1\n00:40:00 0\n00:45:00 0\n00:50:00 0\n00:55:00 2\n\nThe tabl... | [
1,
0,
0
] | [] | [] | [
"mysql",
"null",
"python"
] | stackoverflow_0002119153_mysql_null_python.txt |
Q:
failed abstraction of variable in for loop
I'm trying to make a 4x4 sudoku solver in Python (I'm only a beginner!) and while trying to define a function to clean up my code somewhat, I ran across some strange behavior I don't really understand. Apparently, there's a difference between this:
sudoku = "0200140000230... | failed abstraction of variable in for loop | I'm trying to make a 4x4 sudoku solver in Python (I'm only a beginner!) and while trying to define a function to clean up my code somewhat, I ran across some strange behavior I don't really understand. Apparently, there's a difference between this:
sudoku = "0200140000230040"
sudoku = map(lambda x: '1234' if x=='0' el... | [
"There is a difference... they fail with two different errors!\nThe first gives me this error:\n File \"test.py\", line 9, in <module>\n sudoku[i/4*4+k] = sudoku[i/4*4+k].translate(None, str(j+1))\nTypeError: expected a character buffer object\n\nThe second gives me this error:\n File \"test.py\", line 12, in ... | [
2
] | [] | [] | [
"function",
"python",
"sudoku"
] | stackoverflow_0002123408_function_python_sudoku.txt |
Q:
Python: creating a grid
Is it possible to create a grid like below?
I didn't found anything in the forum.
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is ... | Python: creating a grid | Is it possible to create a grid like below?
I didn't found anything in the forum.
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of four ... | [
"You can define the numbers in a string and split it easily in row/columns:\nnums = \"\"\"\\\n1 2 3\n4 5 6\n7 8 9 10\n\"\"\"\nrows = [map(int, row.split()) for row in nums.splitlines()]\nprint rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]\n\n",
"Check out NumPy - specifically, the N-dimensional array object... | [
3,
2,
2,
0,
0
] | [] | [] | [
"datagrid",
"grid",
"python"
] | stackoverflow_0002112632_datagrid_grid_python.txt |
Q:
python threading/fork?
I'm making a python script that needs to do 3 things simultaneously.
What is a good way to achieve this as do to what i've heard about the GIL i'm not so lean into using threads anymore.
2 of the things that the script needs to do will be heavily active, they will have lots of work to do and... | python threading/fork? | I'm making a python script that needs to do 3 things simultaneously.
What is a good way to achieve this as do to what i've heard about the GIL i'm not so lean into using threads anymore.
2 of the things that the script needs to do will be heavily active, they will have lots of work to do and then i need to have the thi... | [
"I think you could use the multiprocessing package that has an API similar to the threading package and will allow you to get a better performance with multiple cores on a single CPU. \nTo view the gain of performance using multiprocessing instead threading, check on this link about the average time comparison of t... | [
4,
2
] | [] | [] | [
"multiprocess",
"multithreading",
"python"
] | stackoverflow_0002123269_multiprocess_multithreading_python.txt |
Q:
Python: multiple properties, one setter/getter
Consider the following class definitions
class of2010(object):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
def set_a(self,value):
print('setting a...')
self._a = value
def set_b(self,value):
prin... | Python: multiple properties, one setter/getter | Consider the following class definitions
class of2010(object):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
def set_a(self,value):
print('setting a...')
self._a = value
def set_b(self,value):
print('setting b...')
self._b = value
def se... | [
"def attrsetter(attr):\n def set_any(self, value):\n setattr(self, attr, value)\n return set_any\n\na = property(fset=attrsetter('_a'))\nb = property(fset=attrsetter('_b'))\nc = property(fset=attrsetter('_c'))\n\n",
"I see that your setters just log a message and then simply assign the value - in fact, your ... | [
21,
7,
3,
1
] | [] | [] | [
"getter_setter",
"properties",
"python",
"setter"
] | stackoverflow_0002123585_getter_setter_properties_python_setter.txt |
Q:
Google App Engine and Django templates: why do these two cases differ?
I'm new to Python, and I'm using Google App Engine to build a simple blog to help me learn it. I have the following test code:
entries = db.Query(Entry).order("-published").get()
comments = db.Query(Comment).order("published").get()
... | Google App Engine and Django templates: why do these two cases differ? | I'm new to Python, and I'm using Google App Engine to build a simple blog to help me learn it. I have the following test code:
entries = db.Query(Entry).order("-published").get()
comments = db.Query(Comment).order("published").get()
self.response.out.write(template.render(templatePath + 'test.django.htm... | [
"You want to use .fetch(), not get():\nentries = db.Query(Entry).order(\"-published\").fetch()\ncomments = db.Query(Comment).order(\"published\").fetch()\n\nget() returns only the first item that matches the query criteria, so instead of an iterable collection, you'll get one instance, and Entry object.\nI can not ... | [
2
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0002123695_django_templates_google_app_engine_python.txt |
Q:
How to prevent JPEG compression when uploading image through Picasa API?
I'm using the Python client library for the Picasa Web Albums API to upload some JPEG images to an album. But the photos appear very compressed once uploaded. In Picasa 3.6 there is an option to upload images in their original quality without... | How to prevent JPEG compression when uploading image through Picasa API? | I'm using the Python client library for the Picasa Web Albums API to upload some JPEG images to an album. But the photos appear very compressed once uploaded. In Picasa 3.6 there is an option to upload images in their original quality without any compression, but is there are similar option I can use from within the AP... | [
"I managed to solve this problem myself, and it turned out to be a weird one :-)\nI asked around on the Google Group for the Picasa data API and people there were saying that the API does not do any compression when uploading new images. That led me to look at the other code, namely the urlfetch.\nIt turned out tha... | [
3
] | [] | [] | [
"gdata_api",
"jpeg",
"picasa",
"python"
] | stackoverflow_0002100001_gdata_api_jpeg_picasa_python.txt |
Q:
Convert string in Class name (from appengine datastore to class)
Possible Duplicate:
Does python have an equivalent to Java Class.forName()?
I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this:
class Recipe(db.Model):
ingredients = db.ListPropert... | Convert string in Class name (from appengine datastore to class) |
Possible Duplicate:
Does python have an equivalent to Java Class.forName()?
I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this:
class Recipe(db.Model):
ingredients = db.ListProperty(type)
quantities = db.ListProperty(int)
However it seems that ... | [
"I suggest you make ingredient a list of strings, populate it with the pickle.dumps of the types you're saving, and, upon retrieval, use pickle.loads to get a type object back.\npickle serializes types \"by name\", so there are some constraints (essentially, the types must live at the top level of some module), but... | [
1,
0
] | [] | [] | [
"eval",
"google_app_engine",
"metaprogramming",
"python"
] | stackoverflow_0002122571_eval_google_app_engine_metaprogramming_python.txt |
Q:
Reading corrupted file in python
I've got a file, that looks like this alt text http://img40.imageshack.us/img40/4581/crapq.png
Now there are 5 lines shown. However running this script
with open('hello.txt', 'r') as hello:
for line in hello:
print line,
gives
num 1
ctl00$header1$Login1$txtUserName=ыют... | Reading corrupted file in python | I've got a file, that looks like this alt text http://img40.imageshack.us/img40/4581/crapq.png
Now there are 5 lines shown. However running this script
with open('hello.txt', 'r') as hello:
for line in hello:
print line,
gives
num 1
ctl00$header1$Login1$txtUserName=ыют;CBШ▌
and that's all. How can I read ... | [
"entire_file = open('hello.txt', 'rb').read()\n\nprint 'number of \\\\n: %d, number of bytes %d' % (\n entire_file.count('\\n'), len(entire_file))\n\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0002124238_python.txt |
Q:
Enabling overriding of app template in django?
I'm writing a simple site to display statistics for some data, and I've got an app called "stats", that I'd like to write default templates for (places in stats/templates/stats), but I'd like these to be overridable in the same way that the templates for the admin app... | Enabling overriding of app template in django? | I'm writing a simple site to display statistics for some data, and I've got an app called "stats", that I'd like to write default templates for (places in stats/templates/stats), but I'd like these to be overridable in the same way that the templates for the admin app are. IE: If I put a stats/view.html in my project'... | [
"You need to put filesystem loader before app_directories loader in your TEMPLATE_LOADERS setting.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source'\n)\n\nThe order of TEMPLATE_LOADERS matter.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0002124399_django_python_templates.txt |
Q:
Python3 http.server POST example
I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST request... | Python3 http.server POST example | I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manua... | [
"After poking and a few more hours of googling I've found the following works.\ndef do_POST(self):\n length = int(self.headers['Content-Length'])\n post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))\n # You now have a dictionary of the post data\n\n self.wfile.write(\"Lorem Ipsum... | [
25
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002121481_python_python_3.x.txt |
Q:
Paramiko equvalent of pipline controls and input/output pipes
I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as:
ssh server "cat remote_file" > local_file
with ... | Paramiko equvalent of pipline controls and input/output pipes | I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as:
ssh server "cat remote_file" > local_file
with paramiko channels?
Can paramiko.Transport.open_channel() or Message... | [
"If the limitation, as you say, is only in your client, you can easily implement a SFTP client directly with paramiko -- e.g., look at this example code.\n",
"pyfilesystem implements an sftp filesystem on top of paramiko. \n"
] | [
1,
1
] | [] | [] | [
"file",
"paramiko",
"python",
"transfer"
] | stackoverflow_0002123581_file_paramiko_python_transfer.txt |
Q:
How does Timer in Python work, regarding multithreading?
If I call
Timer(.1, some_function, [some_arguments]).start()
multiple times, what exactly happens behind the scenes?
The source of our problem is ...
We have a method that's essentially:
def move(target):
force = calculateForce(target-getCurrentPosition()... | How does Timer in Python work, regarding multithreading? | If I call
Timer(.1, some_function, [some_arguments]).start()
multiple times, what exactly happens behind the scenes?
The source of our problem is ...
We have a method that's essentially:
def move(target):
force = calculateForce(target-getCurrentPosition())
if(force != 0)
setForce(force)
Timer(.1, moveCursor, ... | [
"Right: each call to Timer does start a new thread. Indeed, class threading.Timer is documented as being \"a thread\". You can confirm this by reading the source code, line 707.\nA good alternative is to run a scheduler in a single thread, receiving requests through a Queue.Queue instance (intrinsically threadsaf... | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002124540_multithreading_python.txt |
Q:
Pythonic way of summing lists and lists of lists
I'm trying to find a neat way of summing a list and a list of lists in the same function, so far I've got:
import operator
"""
Fails late for item = ['a', 'b']
"""
def validate(item):
try:
return sum(item) == sum(range(1, 10))
except TypeError:
... | Pythonic way of summing lists and lists of lists | I'm trying to find a neat way of summing a list and a list of lists in the same function, so far I've got:
import operator
"""
Fails late for item = ['a', 'b']
"""
def validate(item):
try:
return sum(item) == sum(range(1, 10))
except TypeError:
return sum(reduce(operator.add, item)) == sum(r... | [
"Perhaps you'd find it easier to flatten the list first?\ndef flatten(xs):\n for x in xs:\n try:\n sub = iter(x)\n except TypeError:\n yield x\n else:\n for y in flatten(sub):\n yield y\n\nWith the above, you can do this:\nIn [4]: fs = flatten... | [
5,
3,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0002106996_algorithm_python.txt |
Q:
Renaming a file on a remote file server in C# / Python
I need to rename a whole heap of files on a Windows file server - I don't mind what language I use really as long it's quick and easy!
I know it's basic but just to clarify - in pseudo-code...
server = login (fileserver, creds)
foreach (file in server.navigat... | Renaming a file on a remote file server in C# / Python | I need to rename a whole heap of files on a Windows file server - I don't mind what language I use really as long it's quick and easy!
I know it's basic but just to clarify - in pseudo-code...
server = login (fileserver, creds)
foreach (file in server.navigateToDir(dir))
rename(file)
I know how to do this in Pyth... | [
"Use \\\\servername\\sharename\\somefile.foo for filenames - provided you have access to connect to it and are running on windows.\nYou could also map up a network drive and treat it as any other local drive (y:\\sharename\\somefile.foo)\n",
"You could also use PSEXEC to execute the code remotely on the server if... | [
1,
1,
1,
0
] | [] | [] | [
"c#",
"file",
"fileserver",
"python",
"rename"
] | stackoverflow_0002109988_c#_file_fileserver_python_rename.txt |
Q:
Pretty printing a list of list of floats?
Basically i have to dump a series of temperature readings, into a text file. This is a space delimited list of elements, where each row represents something (i don't know, and it just gets forced into a fortran model, shudder). I am more or less handling it from our groups... | Pretty printing a list of list of floats? | Basically i have to dump a series of temperature readings, into a text file. This is a space delimited list of elements, where each row represents something (i don't know, and it just gets forced into a fortran model, shudder). I am more or less handling it from our groups side, which is extracting those temperature re... | [
"you can right-pad like this:\nstr = '%-10f' % val\n\nto left pad:\nset = '%10f' % val\n\nor in combination pad and set the precision to 4 decimal places:\nstr = '%-10.4f' % val\n\n:\nimport sys\nrows = [[1.343, 348.222, 484844.3333], [12349.000002, -2.43333]]\nfor row in rows:\n for val in row:\n sys.stdout.wr... | [
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002124645_python.txt |
Q:
Why am I getting dups with random.shuffle in Python?
For a list of 10 ints, there are 10! possible orders or permutations. Why does random.shuffle give duplicates after only 5000 tries?
>>> L = range(10)
>>> rL = list()
>>> for i in range(5000):
... random.shuffle(L)
... rL.append(L[:])
...
>>> rL = [tup... | Why am I getting dups with random.shuffle in Python? | For a list of 10 ints, there are 10! possible orders or permutations. Why does random.shuffle give duplicates after only 5000 tries?
>>> L = range(10)
>>> rL = list()
>>> for i in range(5000):
... random.shuffle(L)
... rL.append(L[:])
...
>>> rL = [tuple(e) for e in rL]
>>> len(set(rL))
4997
>>> for i,t in en... | [
"It's called the Birthday Paradox.\nAccording to this formula from Wikipedia:\n\nbut replacing 365 with 10! you would only need about 2200 examples to have a 50% chance of a collision, and you are way above that.\n",
"Because it's... random! If you want all permutations just use itertools.permutations.\n",
"ma... | [
19,
6,
2
] | [] | [] | [
"birthday_paradox",
"probability",
"python",
"random"
] | stackoverflow_0002124748_birthday_paradox_probability_python_random.txt |
Q:
python imaplib ssl error using celeryd queue
I'm having a problem using imaplib on python 2.6 with the latest django svn. I want to download imap emails in a queue (using celeryd). I'm able to connect/download emails from the command line, but when i offload the task through django to celeryd i get this error: "SS... | python imaplib ssl error using celeryd queue | I'm having a problem using imaplib on python 2.6 with the latest django svn. I want to download imap emails in a queue (using celeryd). I'm able to connect/download emails from the command line, but when i offload the task through django to celeryd i get this error: "SSLError: [Errno 1] _ssl.c:1325: error:1408F10B:SSL ... | [
"If it only breaks when run inside the celery worker, there might be something with amqplib (which uses the ssl module) or it could be something with multiprocessing and forking (a global variable that was initialized before the fork that is no longer alive)\nCould you please include the task you're trying to run?\... | [
1,
1,
0
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0002016516_celery_django_python.txt |
Q:
(Py)GTK StatusIcon notifications on Windows
I'm currently writing a screen capture app for Windows and Linux using PyGTK, and I've hit a slight problem with displaying notifications. On Linux, I've been using the libnotify bindings to provide notifications, which has been working very well; however, this has no eq... | (Py)GTK StatusIcon notifications on Windows | I'm currently writing a screen capture app for Windows and Linux using PyGTK, and I've hit a slight problem with displaying notifications. On Linux, I've been using the libnotify bindings to provide notifications, which has been working very well; however, this has no equivalent on Windows.
I'd use the Win32 APIs direc... | [
"Looking at the GtkStatusIcon source code I don't see the NOTIFYICONDATA exposed anywhere. For X11 there is get_x11_window_id, which has no equivalent and just returns 0 in Windows. Perhaps you could file a bug to request similar functionality.\nFor now, you'll have to create your own tray icon. A quick search at c... | [
2
] | [] | [] | [
"gtk",
"notifications",
"pygtk",
"python",
"winapi"
] | stackoverflow_0002124683_gtk_notifications_pygtk_python_winapi.txt |
Q:
Network IPC With Authentication (in Python)
I am looking for a way to connect a frontend server (running Django) with a backend server.
I want to avoid inventing my own protocol on top of a socket, so my plan was to use SimpleHTTPServer + JSON or XML.
However, we also require some security (authentication + encryp... | Network IPC With Authentication (in Python) | I am looking for a way to connect a frontend server (running Django) with a backend server.
I want to avoid inventing my own protocol on top of a socket, so my plan was to use SimpleHTTPServer + JSON or XML.
However, we also require some security (authentication + encryption) for the connection, which isn't quite as si... | [
"Use a client side certificate for the connection. This is a good monetization technique to get more income for your client side app.\n"
] | [
1
] | [] | [] | [
"ipc",
"json",
"networking",
"python"
] | stackoverflow_0002125149_ipc_json_networking_python.txt |
Q:
Python: how so fast?
The period of the Mersenne Twister used in the module random is (I am told) 2**19937 - 1. As a binary number, that is 19937 '1's in a row (if I'm not mistaken). Python converts it to decimal pretty darned fast:
$ python -m timeit '2**19937'
10000000 loops, best of 3: 0.0271 usec per loop
$ ... | Python: how so fast? | The period of the Mersenne Twister used in the module random is (I am told) 2**19937 - 1. As a binary number, that is 19937 '1's in a row (if I'm not mistaken). Python converts it to decimal pretty darned fast:
$ python -m timeit '2**19937'
10000000 loops, best of 3: 0.0271 usec per loop
$ python -m timeit -s 'resul... | [
"Hate to rain on your parade, but the reason it's so fast is because the math module is actually not implemented in Python.\nPython supports loading shared libraries that export Python APIs, but are implemented in other languages. math.so, which provides the module you get from import math, happens to be one of tho... | [
6,
5,
4,
0
] | [] | [] | [
"computation",
"largenumber",
"python"
] | stackoverflow_0002125159_computation_largenumber_python.txt |
Q:
iPhone app with Google App Engine
I've prototyped an iPhone app that uses (internally) SQLite as its data base. The intent was to ultimately have it communicate with a server via PHP, which would use MySQL as the back-end database.
I just discovered Google App Engine, however, but know very little about it. I ... | iPhone app with Google App Engine | I've prototyped an iPhone app that uses (internally) SQLite as its data base. The intent was to ultimately have it communicate with a server via PHP, which would use MySQL as the back-end database.
I just discovered Google App Engine, however, but know very little about it. I think it'd be nice to use the Python in... | [
"True, Google App Engine is a very cool product, but the datastore is a different beast than a regular mySQL database. That's not to say that what you need can't be done with the GAE datastore; however it may take some reworking on your end. \nThe most prominent different that you notice right off the start is tha... | [
2,
2,
1,
1
] | [] | [] | [
"google_app_engine",
"gql",
"iphone",
"python"
] | stackoverflow_0002124688_google_app_engine_gql_iphone_python.txt |
Q:
Python, Source-Code Encoding Problem
I'm using Notepad++ editor on windows with format set to ASCII,
I've read "PEP 263: Source Code Encodings" and amended my code accordingly (I think), but there are characters still printing in hex...
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
a_munge = [ "A", "4... | Python, Source-Code Encoding Problem | I'm using Notepad++ editor on windows with format set to ASCII,
I've read "PEP 263: Source Code Encodings" and amended my code accordingly (I think), but there are characters still printing in hex...
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
a_munge = [ "A", "4", "/\\", "\@", "/-\\", "^", "aye", "?" ]
... | [
"Perhaps you should be using unicode literals (e.g. u'€') instead.\n",
"The line:\n# -*- coding: UTF-8 -*-\n\ndeclares that the source file is saved in UTF-8. Anything else is an error.\nWhen you declare byte strings in your source code:\ne_munge = [ \"E\", \"3\", \"&\", \"€\", \"£\", \"[-\", \"|=-\", \"?\" ]\n\... | [
2,
2,
1
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0002123283_character_encoding_python.txt |
Q:
Reassembling Python bytecode to the original code?
This might be a silly question, but, given the output of, say..
>>> from dis import dis
>>> def myfunc(x):
... print x ** 2
...
>>> dis(myfunc)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINAR... | Reassembling Python bytecode to the original code? | This might be a silly question, but, given the output of, say..
>>> from dis import dis
>>> def myfunc(x):
... print x ** 2
...
>>> dis(myfunc)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_POWER
7 PRINT_ITEM
... | [
"http://sourceforge.net/projects/decompyle/\n"
] | [
5
] | [] | [] | [
"bytecode",
"bytecode_manipulation",
"python"
] | stackoverflow_0002124202_bytecode_bytecode_manipulation_python.txt |
Q:
How can I see error logs of Django views
I'm coding a small application with Django. But I can't see any error logs in the console when an error (e.g. Python syntax error, etc.) occurs in one of my views -no action at all.
How can I see the error logs of my views? Debugging like a blind is really annoying.
A:
Dj... | How can I see error logs of Django views | I'm coding a small application with Django. But I can't see any error logs in the console when an error (e.g. Python syntax error, etc.) occurs in one of my views -no action at all.
How can I see the error logs of my views? Debugging like a blind is really annoying.
| [
"Django does not print any errors to the console by default. Instead it provides very helpful error pages that are displayed for any errors that occur in your views. Please check what your DEBUG setting is set to. In development this should be True which will give you the nice error pages for 404 and 500 errors.\nT... | [
5
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002125080_django_logging_python.txt |
Q:
Compress data before storage on Google App Engine
I im trying to store 30 second user mp3 recordings as Blobs in my app engine data store. However, in order to enable this feature (App Engine has a 1MB limit per upload) and to keep the costs down I would like to compress the file before upload and decompress the f... | Compress data before storage on Google App Engine | I im trying to store 30 second user mp3 recordings as Blobs in my app engine data store. However, in order to enable this feature (App Engine has a 1MB limit per upload) and to keep the costs down I would like to compress the file before upload and decompress the file every time it is requested. How would you suggest ... | [
"\"Compressing before upload\" implies doing it in the user's browser -- but no text in your question addresses that! It seems to be about compression in your GAE app, where of course the data will only be after the upload. You could do it with a Firefox extension (or other browsers' equivalents), if you can deve... | [
2,
2,
2,
0,
0
] | [] | [] | [
"compression",
"google_app_engine",
"gzip",
"python",
"zlib"
] | stackoverflow_0001739543_compression_google_app_engine_gzip_python_zlib.txt |
Q:
Hudson build failed using Python & Coverage
I completed this tutorial from Joe Heck to set up Hudson for Python. Everything worked perfectly except the Coverage section. My build failed with this output:
[workspace] $ /bin/sh -xe /tmp/hudson6222564272447222496.sh
+ coverage run tests/run.py --with-xunit
You must... | Hudson build failed using Python & Coverage | I completed this tutorial from Joe Heck to set up Hudson for Python. Everything worked perfectly except the Coverage section. My build failed with this output:
[workspace] $ /bin/sh -xe /tmp/hudson6222564272447222496.sh
+ coverage run tests/run.py --with-xunit
You must specify at least one of -e, -x, -c, -r, or -a.
... | [
"You have an old version of coverage.py, it looks like 2.x of some sort. \"coverage run\" is new syntax with coverage.py 3.x. Download the latest coverage.py at http://pypi.python.org/pypi/coverage, and you should be good to go.\n"
] | [
4
] | [] | [] | [
"code_coverage",
"continuous_integration",
"hudson",
"python",
"python_coverage"
] | stackoverflow_0002125164_code_coverage_continuous_integration_hudson_python_python_coverage.txt |
Q:
Good looking Python GUI toolkit for Snow Leopard(64 bit)
I'm looking for a GUI toolkit/framework to create applications that run on Mac Snow Leopard and preferably other systems(Windows, Linux).
Deal breakers:
X11 based
Non-native widgets
32 bit/Carbon
Bad Mac look and feel
As far as I know Tkinter runs X11 and ... | Good looking Python GUI toolkit for Snow Leopard(64 bit) | I'm looking for a GUI toolkit/framework to create applications that run on Mac Snow Leopard and preferably other systems(Windows, Linux).
Deal breakers:
X11 based
Non-native widgets
32 bit/Carbon
Bad Mac look and feel
As far as I know Tkinter runs X11 and wxWidgets and PyQT do not run 64 bit.
Is there anything usable... | [
"Maybe PyQt works on Snow Leopard 64 bits. Look at this link and try it.\n",
"Your list doesn't specifically rule out CocoaPython/PyObjC, which would be completely native on Mac OS X. It wouldn't run on anything else, though,\n",
"The Apple-supplied Tk, Aqua Tk, on OS X has not been X11-based since at least OS ... | [
2,
2,
1
] | [] | [] | [
"macos",
"osx_snow_leopard",
"python",
"user_interface"
] | stackoverflow_0002123335_macos_osx_snow_leopard_python_user_interface.txt |
Q:
how do I change 'username-password login' to 'email-password login' on django-registration
how do I change 'username-password login' to 'email-password login' on django-registration
A:
You can't easily store emails in django.contrib.auth.model.User's username field, so you'll need a different auth backend. Put t... | how do I change 'username-password login' to 'email-password login' on django-registration | how do I change 'username-password login' to 'email-password login' on django-registration
| [
"You can't easily store emails in django.contrib.auth.model.User's username field, so you'll need a different auth backend. Put the following somewhere and add its path to AUTHENTICATION_BACKENDS. See http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend\nfrom django.contrib.auth.model... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002125724_django_python.txt |
Q:
How to properly escape output (for XHTML) in mako?
Despite offering a nice way to escape output using filters, none of them do the right thing.
Taking the string:
x=u"&\u0092"
The filters do the following:
x Turns the & into an entity but not the \u0092 (valid XML but not XHTML)
h Exactly ... | How to properly escape output (for XHTML) in mako? | Despite offering a nice way to escape output using filters, none of them do the right thing.
Taking the string:
x=u"&\u0092"
The filters do the following:
x Turns the & into an entity but not the \u0092 (valid XML but not XHTML)
h Exactly the same
u Escapes both, but obviously uses ... | [
"It is not necessary to convert Unicode characters to the &#xxxx; form to work in HTML unless you're deliberately using the ASCII charset. It's simpler and more efficient to escape named entities, then encode the whole string to UTF-8 and write it out like that. You should probably declare the encoding being used i... | [
2,
1
] | [] | [] | [
"escaping",
"mako",
"python",
"unicode",
"xhtml"
] | stackoverflow_0002125788_escaping_mako_python_unicode_xhtml.txt |
Q:
After breaking a python program into functions, how do I make one the main function?
This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1,... | After breaking a python program into functions, how do I make one the main function? | This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "main" but I have no clue.
| [
"Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects.\nIf you put a print statement at the top or middle of your program, it will run normally without being in any function. What this ... | [
12,
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002125825_python.txt |
Q:
How to organize an app-engine application
I want to create a directory structure like the following. How can I get the account.py and game.py to handle the requests that go to \account\ and \game\ respectfully. All the app-engine examples I have seen have all the logic in on main.py that handle all urls.
app\a... | How to organize an app-engine application | I want to create a directory structure like the following. How can I get the account.py and game.py to handle the requests that go to \account\ and \game\ respectfully. All the app-engine examples I have seen have all the logic in on main.py that handle all urls.
app\account\
\account.py
\game\
... | [
"You need the following in your app.yaml:\n- url: /account\n script: account/account.py\n\n- url: /game\n script: game/game.py\n\n- url: .*\n script: main.py\n\nBTW, I suggest you try to forget backslashes (characters like this: \\ ) -- think normal slashes (characters like this: / ). Backslashes are a Windows ... | [
11,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002125951_google_app_engine_python.txt |
Q:
Python property
The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing?
class Base:
def __init__(self):
self.s = "BaseStr"
def getstr(self):
... | Python property | The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing?
class Base:
def __init__(self):
self.s = "BaseStr"
def getstr(self):
print "get in... | [
"You need to use new-style classes for properties to work correctly. To do so derive your class from object:\nclass Base(object):\n ...\n\n",
"Whenever creating a new class, derive it from the object type.\n"
] | [
18,
0
] | [] | [] | [
"properties",
"python"
] | stackoverflow_0002125166_properties_python.txt |
Q:
Python os.path is ntpath, how?
Can someone tell me how Python "aliases" os.path to ntpath?
>>> import os.path
>>> os.path
<module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'>
>>>
A:
Look at os.py, lines 55-67:
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt ... | Python os.path is ntpath, how? | Can someone tell me how Python "aliases" os.path to ntpath?
>>> import os.path
>>> os.path
<module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'>
>>>
| [
"Look at os.py, lines 55-67:\nelif 'nt' in _names:\n name = 'nt'\n linesep = '\\r\\n'\n from nt import *\n try:\n from nt import _exit\n except ImportError:\n pass\n import ntpath as path\n\n import nt\n __all__.extend(_get_exports_list(nt))\n del nt\n\nThe import ntpath as ... | [
13,
7
] | [] | [] | [
"alias",
"module",
"path",
"python"
] | stackoverflow_0002126301_alias_module_path_python.txt |
Q:
GAE Python optimization: Django filter for language support
I have a filter that I use for lang support in my webapp. But when I publish it to GAE it keeps telling me that it the usage of CPU is to high.
I think I located the problem to my filters I use for support. I use this in my templates:
<h1>{{ "collection.... | GAE Python optimization: Django filter for language support | I have a filter that I use for lang support in my webapp. But when I publish it to GAE it keeps telling me that it the usage of CPU is to high.
I think I located the problem to my filters I use for support. I use this in my templates:
<h1>{{ "collection.header"|translate:lang }}</h1>
The filter code looks like this:
... | [
"Your initial question is about high cpu usage, the answer i think is simple, with GAE and databases like BigTable (non-relational) the code with entries.count() is expensive and the for entry in entrie too if you have a lot of data.\nI think you must have to do a couple of things:\nin your utils.py\ndef GetDiction... | [
3,
2
] | [] | [] | [
"django",
"filter",
"google_app_engine",
"python"
] | stackoverflow_0001873704_django_filter_google_app_engine_python.txt |
Q:
Machine learning issue for negative instances
I had to build a concept analyzer for computer science field and I used for this machine learning, the orange library for Python. I have the examples of concepts, where the features are lemma and part of speech, like algorithm|NN|concept. The problem is that any other ... | Machine learning issue for negative instances | I had to build a concept analyzer for computer science field and I used for this machine learning, the orange library for Python. I have the examples of concepts, where the features are lemma and part of speech, like algorithm|NN|concept. The problem is that any other word, that in fact is not a concept, is classified ... | [
"The question is very unclear, but assuming what you mean is that your machine learning algorithm is not working without negative examples and you can't give it every possible negative example, then it's perfectly alright to give it some negative examples.\nThe point of data mining (a.k.a. machine learning) is to t... | [
2
] | [] | [] | [
"artificial_intelligence",
"data_mining",
"machine_learning",
"python"
] | stackoverflow_0002126383_artificial_intelligence_data_mining_machine_learning_python.txt |
Q:
Processing a simple workflow in Python
I am working on a code which takes a dataset and runs some algorithms on it.
User uploads a dataset, and then selects which algorithms will be run on this dataset and creates a workflow like this:
workflow =
{0: {'dataset': 'some dataset'},
1: {'algorithm1': "parameters"},
... | Processing a simple workflow in Python | I am working on a code which takes a dataset and runs some algorithms on it.
User uploads a dataset, and then selects which algorithms will be run on this dataset and creates a workflow like this:
workflow =
{0: {'dataset': 'some dataset'},
1: {'algorithm1': "parameters"},
2: {'algorithm2': "parameters"},
3: {'algo... | [
"You want to run a pipeline on some dataset. That sounds like a reduce operation (fold in some languages). No need for anything complicated:\nresult = reduce(lambda data, (aname, p): algo_by_name(aname)(p, data), workflow)\n\nThis assumes workflow looks like (text-oriented so you can load it with YAML/JSON):\nworkf... | [
10,
4,
2,
2,
1
] | [] | [] | [
"python",
"workflow"
] | stackoverflow_0002126811_python_workflow.txt |
Q:
How to play sound in Python WITHOUT interrupting music/other sounds from playing
I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code:
from wave import open as wave_open
from ossaudiodev import open as oss_open
def _play_chime():
"""
Play a sound fi... | How to play sound in Python WITHOUT interrupting music/other sounds from playing | I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code:
from wave import open as wave_open
from ossaudiodev import open as oss_open
def _play_chime():
"""
Play a sound file once.
"""
sound_file = wave_open('chime.wav','rb')
(nc,sw,fr,nf,compty... | [
"The easy answer is \"Switch from OSS to PulseAudio.\" (Or set up ALSA to use dmix, or get a soundcard with better Linux drivers...)\nThe more complicated answer is, your code already works the way you want it to... on some soundcards. OSS drivers can expose hardware mixers so that you can have multiple audio strea... | [
8,
1
] | [] | [] | [
"audio",
"linux",
"python",
"timer"
] | stackoverflow_0002125547_audio_linux_python_timer.txt |
Q:
Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py)
Django only allows you to use one database in settings.py.
Does that prevent you from scaling up? (millions of users)
A:
Django now has support for multiple databases.
A:
The database isn't your b... | Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py) | Django only allows you to use one database in settings.py.
Does that prevent you from scaling up? (millions of users)
| [
"Django now has support for multiple databases.\n",
"The database isn't your bottleneck.\nCheck your browser carefully.\nFor each page of HTML you're sending (on average) 8 other files, some of which may be quite large. These are your JS, CSS, graphics, etc.\nThe actual performance bottleneck is the browser requ... | [
11,
7,
3,
1,
1,
0
] | [] | [] | [
"django",
"python",
"scalability",
"web_services"
] | stackoverflow_0002127067_django_python_scalability_web_services.txt |
Q:
Set auto-incrementing attribute in XML node
I'm trying to set an attribute in one of the nodes for my XML as below:
rank = 1
for photo in s:
image = feed.createElement('Image')
images.appendChild(image)
image.setAttribute("rank", rank)
p = feed.createTextNode(str(main_url+photo.display.url))
image.append... | Set auto-incrementing attribute in XML node | I'm trying to set an attribute in one of the nodes for my XML as below:
rank = 1
for photo in s:
image = feed.createElement('Image')
images.appendChild(image)
image.setAttribute("rank", rank)
p = feed.createTextNode(str(main_url+photo.display.url))
image.appendChild(p)
rank += 1
This however results in the... | [
"The .setAttribute method expects a string, so you will have to convert it:\nimage.setAttribute(\"rank\", str(rank))\n\n"
] | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002127291_python_xml.txt |
Q:
How to resolve case problems for non-english languages in django admin panel?
I need to resolve problem with word endings in django admin panel. The language I'm using is russian (using utf-8 charset), so some problems occur, for example, there is a problem with the right endings on the "Add" button for some model... | How to resolve case problems for non-english languages in django admin panel? | I need to resolve problem with word endings in django admin panel. The language I'm using is russian (using utf-8 charset), so some problems occur, for example, there is a problem with the right endings on the "Add" button for some model names. The simplest thing I found is using jQuery to correct endings "on the fly",... | [
"If I understood the problem correctly, you should just add an appropriate attribute in the meta section of the class.\nEnglish example:\nclass Man(models.Model):\n [...your fields...]\n\n class Meta:\n verbose_name_plural = \"men\"\n\nMore info can be found in the documentation for Django model option... | [
1
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0002127362_django_internationalization_python.txt |
Q:
tricky string matching
I want to find the first index of substrings in a larger string. I only want it to match whole words and I'd like it to be case-insensitive, except that I want it to treat CamelCase as separate words.
The code below does the trick, but it's slow. I'd like to speed it up. Any suggestions? ... | tricky string matching | I want to find the first index of substrings in a larger string. I only want it to match whole words and I'd like it to be case-insensitive, except that I want it to treat CamelCase as separate words.
The code below does the trick, but it's slow. I'd like to speed it up. Any suggestions? I was trying some regex stu... | [
"word_emitter (below) takes a text string and yields lowercase \"words\" as they are found, one at a time (along with their positions). \nIt replaces all underscores with spaces. It then splits the text into a list. For example,\n\"a_foobar_FooBar baz golf_CART Foo\"\n\nbecomes\n['a', 'foobar', 'FooBar', 'baz', 'go... | [
3,
2,
1
] | [] | [] | [
"find",
"python",
"regex",
"string"
] | stackoverflow_0002127188_find_python_regex_string.txt |
Q:
Easy to use time-stamps in Python
I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal.
As of now, I use the time.ctime() function to generate time-stamps that are visually friendly. The jou... | Easy to use time-stamps in Python | I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal.
As of now, I use the time.ctime() function to generate time-stamps that are visually friendly. The journal entries thus look like:
Thu Jan 21... | [
"You might want to consider changing to ISO 8601. Will help with sorting for example, or transferring data between different systems.\n",
"Option 1: Don't change anything. Use time.strptime to parse your timestamps.\nOption 2: Change to datetime. You can format the timestamps the same way, and use datetime.strp... | [
9,
7
] | [] | [] | [
"datetime",
"python",
"time",
"timestamp"
] | stackoverflow_0002127447_datetime_python_time_timestamp.txt |
Q:
An equivalent to string.ascii_letters for unicode strings in python 2.x?
In the "string" module of the standard library,
string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase
is
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Is there a similar constant which would include ever... | An equivalent to string.ascii_letters for unicode strings in python 2.x? | In the "string" module of the standard library,
string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase
is
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Is there a similar constant which would include everything that is considered a letter in unicode?
| [
"You can construct your own constant of Unicode upper and lower case letters with:\nimport unicodedata as ud\nall_unicode = ''.join(unichr(i) for i in xrange(65536))\nunicode_letters = ''.join(c for c in all_unicode\n if ud.category(c)=='Lu' or ud.category(c)=='Ll')\n\nThis makes a string 2... | [
11,
7,
0
] | [
"As mentioned in previous answers, the string would indeed be way too long. So, you have to target (a) specific language(s).\n[EDIT: I realized it was the case for my original intended use, and for most uses, I guess. However, in the meantime, Mark Tolonen gave a good answer to the question as it was asked, so I ch... | [
-1
] | [
"python",
"python_2.x",
"unicode"
] | stackoverflow_0002126551_python_python_2.x_unicode.txt |
Q:
Finding fast default aliases in Python
Is there a faster way to do the following for much larger dicts?
aliases = {
'United States': 'USA',
'United Kingdom': 'UK',
'Russia': 'RUS',
}
if countryname in aliases: countryname = aliases[countryname]
A:
Your solution is fi... | Finding fast default aliases in Python | Is there a faster way to do the following for much larger dicts?
aliases = {
'United States': 'USA',
'United Kingdom': 'UK',
'Russia': 'RUS',
}
if countryname in aliases: countryname = aliases[countryname]
| [
"Your solution is fine, as \"in\" is 0(1) for dictionaries.\nYou could do something like this to save some typing:\ncountryname = aliases.get(countryname, countryname)\n\n(But I find your code a lot easier to read than that)\nWhen it comes to speed, what solution is best would depend on if there will be a majority ... | [
6,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002127202_python.txt |
Q:
Python Syntax Error but looks fine to me. Help?
Right now I'm working on a Tetris Game (sorta, I found a Tetris example for Python on a website, I've been copying it but adding some of my own stuff), and just finished writing all the code but have had a couple syntax errors. I've been able to fix all of them but t... | Python Syntax Error but looks fine to me. Help? | Right now I'm working on a Tetris Game (sorta, I found a Tetris example for Python on a website, I've been copying it but adding some of my own stuff), and just finished writing all the code but have had a couple syntax errors. I've been able to fix all of them but this last syntax error is confusing to me.
def pie... | [
"You didn't close the parenthesis of self.setShapeAt.\n",
"There's an extra whitespace on the last line - just ahead self.removeFullLines(). Its indenting is thus not the same as the for line's indenting. EDIT: Seems to be corrected now.\nAlways use the same indent sequence - choose either tabs, or n whitespaces.... | [
7,
0
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0002127735_python_syntax_error.txt |
Q:
Python sqlite3 "unable to open database file" on windows
I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts some rows into the db. However, at some point in the insertion process, the program d... | Python sqlite3 "unable to open database file" on windows | I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts some rows into the db. However, at some point in the insertion process, the program dies with this message:
sqlite3.OperationalError: unable to... | [
"SQLite does not have record locking; it uses a simple locking mechanism that locks the entire database file briefly during a write. It sounds like you are running into a lock that hasn't cleared yet.\nThe author of SQLite recommends that you create a transaction prior to doing your inserts, and then complete the ... | [
1,
0
] | [] | [] | [
"python",
"sqlite",
"windows_vista"
] | stackoverflow_0001529527_python_sqlite_windows_vista.txt |
Q:
Python - Moving entire text between two .doc files
I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target ... | Python - Moving entire text between two .doc files | I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target .doc file is not the only one but can be many of them. A... | [
"Openoffice ships with full python scripting support, have a look: http://wiki.services.openoffice.org/wiki/Python\nMight be easier than trying to mess around with MS Word and COM apis.\n",
"So you want to take the text from a doc file, and append it to the end of the text in another doc file. And the problem her... | [
3,
1
] | [] | [] | [
".doc",
"python",
"text"
] | stackoverflow_0002127410_.doc_python_text.txt |
Q:
Django, making a page activate for a fixed time
Greetings
I am hacking Django and trying to test something such as:
Like woot.com , I want to sell "an item per day", so only one item will be available for that day (say the default www.mysite.com will be redirected to that item),
Assume my urls for calling these i... | Django, making a page activate for a fixed time | Greetings
I am hacking Django and trying to test something such as:
Like woot.com , I want to sell "an item per day", so only one item will be available for that day (say the default www.mysite.com will be redirected to that item),
Assume my urls for calling these items will be such: www.mysite.com/item/<number>
my mo... | [
"It seems you've got the basics figured out, so I'm assuming you're asking for polishing suggestions... A few ideas in this vein:\n\nI think I'd have a separate URL like /items/today/ for this, or perhaps just /today/.\nYou'll want to use the date components of datime.datetime.now() only. The whole thing is an obje... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0002128093_django_django_models_django_views_python.txt |
Q:
Google App Engine: Add task to queue from a task
I need to track data from another website. Since it's spread over 60+ pages, I intend to use a daily cron job to add a task to the queue. This task then should take care of one page and depending on some checks, put another instance of itself on the queue for the ne... | Google App Engine: Add task to queue from a task | I need to track data from another website. Since it's spread over 60+ pages, I intend to use a daily cron job to add a task to the queue. This task then should take care of one page and depending on some checks, put another instance of itself on the queue for the next page.
Now a simple
taskqueue.add(url='/path/to_self... | [
"It's possible to add tasks from within tasks. I'm doing it in my application.\nIt's very useful when you want to migrate a large set of entities : one task processes a small chunk of entities then adds itself to the queue in order to process the rest until the migration is over.\nI am not sure what is the problem ... | [
6
] | [] | [] | [
"google_app_engine",
"python",
"task",
"task_queue"
] | stackoverflow_0002127981_google_app_engine_python_task_task_queue.txt |
Q:
python automate ffmpeg conversion from upload directory
I have a upload script done. But i need to figure out how to make a script that I can run as a daemon in python to handle the conversion part and moving the file thats converted to its final resting place. heres what I have so far for the directory watcher sc... | python automate ffmpeg conversion from upload directory | I have a upload script done. But i need to figure out how to make a script that I can run as a daemon in python to handle the conversion part and moving the file thats converted to its final resting place. heres what I have so far for the directory watcher script:
#!/usr/bin/python
import os
import pyinotify import W... | [
"I don't run on Linux and have never used the inotify capabilities you are using here. I'll describe how I would do things generically.\nIn the simplest case, you need to check if there's a new file in the upload directory and when there is one, start doing the conversion notification.\nTo check if there are new fi... | [
3
] | [] | [] | [
"ffmpeg",
"inotify",
"python"
] | stackoverflow_0002123435_ffmpeg_inotify_python.txt |
Q:
Preferred way to store/retrieve python data
I would like to include data files with a Python package. Is the best place to put them inside the actual package as suggested here, i.e.
setup.py
src/
mypkg/
__init__.py
module.py
data/
tables.dat
spoons.dat
... | Preferred way to store/retrieve python data | I would like to include data files with a Python package. Is the best place to put them inside the actual package as suggested here, i.e.
setup.py
src/
mypkg/
__init__.py
module.py
data/
tables.dat
spoons.dat
forks.dat
or is there a better way to do this?... | [
"pkgutil means you can load the data even if the package is installed in a ZIP file, so it's preferable if you want to support that. Storing it in a data directory like that is fine, I do that all the time. :)\n"
] | [
3
] | [
"You should store your data as a Python data structure vía the Pickle module. That way, when you call it (load it) the data is ready to be used, and you dont need to process it in every script. \nAs for the location, it makes sense that you store it in a way that is transparent and clear to the user, the following ... | [
-2
] | [
"python"
] | stackoverflow_0002128399_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.