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 is needed to add an paperprint-like effect to photos in python?
I want to transform photos in python to look like this:
taken from doctype.com
I will use it in django, PIL is installed.
How can I achieve this?
A:
This is a combination of several subtle effects. It starts by a nonlinear deformation, and the... | What is needed to add an paperprint-like effect to photos in python? | I want to transform photos in python to look like this:
taken from doctype.com
I will use it in django, PIL is installed.
How can I achieve this?
| [
"This is a combination of several subtle effects. It starts by a nonlinear deformation, and then a tasteful drop shadow is added. There's also a small border. I'd start by drawing one straight, vertical line on the above picture, and then seeing how you would transform to that from the original picture. Then, apply... | [
3,
2
] | [] | [] | [
"django",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0001546205_django_image_python_python_imaging_library.txt |
Q:
how to force python httplib library to use only A requests
The problem is that urllib using httplib is querying for AAAA records.
I would like to avoid that. Is there a nice way to do that?
>>> import socket
>>> socket.gethostbyname('www.python.org')
'82.94.164.162'
21:52:37.302028 IP 192.168.0.9.44992 > 192.168.... | how to force python httplib library to use only A requests | The problem is that urllib using httplib is querying for AAAA records.
I would like to avoid that. Is there a nice way to do that?
>>> import socket
>>> socket.gethostbyname('www.python.org')
'82.94.164.162'
21:52:37.302028 IP 192.168.0.9.44992 > 192.168.0.1.53: 27463+ A? www.python.org. (32)
21:52:37.312031 IP 192.1... | [
"The correct answer is:\nhttp://docs.python.org/library/socket.html\nThe Python socket library is using the following:\nsocket.socket([family[, type[, proto]]])\nCreate a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UN... | [
6,
0
] | [] | [] | [
"dns",
"ipv4",
"ipv6",
"python"
] | stackoverflow_0001540749_dns_ipv4_ipv6_python.txt |
Q:
Deploying Django: How do you do it?
I have tried following guides like this one but it just didnt work for me.
So my question is this: What is a good guide for deploying Django, and how do you deploy your Django.
I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what... | Deploying Django: How do you do it? | I have tried following guides like this one but it just didnt work for me.
So my question is this: What is a good guide for deploying Django, and how do you deploy your Django.
I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploy... | [
"mod_wsgi in combination with a virtualenv for all the dependencies, a mercurial checkout into the virtualenv and a fabric recipe to check out the changes on the server.\nI wrote an article about my usual workflow: Deploying Python Web Applications. Hope that helps.\n",
"I have had success with mod_wsgi\n",
"I... | [
7,
1,
1,
0,
0
] | [
"The easiest way would be to use one of the sites on http://djangofriendly.com/hosts/ that will provide the hosting and set up for you, but even if you're wanting to roll your own it will allow you to see what set up other sites are using.\n"
] | [
-2
] | [
"django_deployment",
"python"
] | stackoverflow_0000114112_django_deployment_python.txt |
Q:
Using enums in ctypes.Structure
I have a struct I'm accessing via ctypes:
struct attrl {
char *name;
char *resource;
char *value;
struct attrl *next;
enum batch_op op;
};
So far I have Python code like:
# struct attropl
class attropl(Structure):
pass
attrl._fields_ = [
("next", PO... | Using enums in ctypes.Structure | I have a struct I'm accessing via ctypes:
struct attrl {
char *name;
char *resource;
char *value;
struct attrl *next;
enum batch_op op;
};
So far I have Python code like:
# struct attropl
class attropl(Structure):
pass
attrl._fields_ = [
("next", POINTER(attropl)),
("name", c_c... | [
"At least for GCC enum is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed or unsigned. I guess it cannot exceed long long int, but practically you should check the range of your enums and choose something like c_uint.\nHere is an example... | [
13,
5
] | [] | [] | [
"ctypes",
"enums",
"python"
] | stackoverflow_0001546355_ctypes_enums_python.txt |
Q:
Str in Python's map and sum
Why do you need to use the function 'str' in the following code?
I am trying to count the sum of digits in a number.
My code
for i in number:
sum(map(int, str(i))
where number is the following array
[7,79,9]
I read my code as follows
loop though the array such that
count sum of t... | Str in Python's map and sum | Why do you need to use the function 'str' in the following code?
I am trying to count the sum of digits in a number.
My code
for i in number:
sum(map(int, str(i))
where number is the following array
[7,79,9]
I read my code as follows
loop though the array such that
count sum of the integer digits
by getting give... | [
"Given 79 you need to get [7, 9] in order to sum up this list.\nWhat does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base 10 in this case). E. g. 79 is 7 * 10**1 + 9 * 10**0.\nAnd what is the simplest (well, at least in this context) way to get such... | [
8,
2,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001546846_python_string.txt |
Q:
Prevent decorator from being used twice on the same function in python
I have a decorator:
from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
And I want to prevent it from decorating the same functio... | Prevent decorator from being used twice on the same function in python | I have a decorator:
from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
And I want to prevent it from decorating the same function twice, e.g prevent things such as:
@d
@d
def f():
print 2
Only possibl... | [
"I'd store the information in the function itself. There is a risk of a conflict if multiple decorators decide to use the same variable, but if it's only your own code, you should be able to avoid it.\ndef d(f):\n if getattr(f, '_decorated_with_d', False):\n raise SomeException('Already decorated')\n @... | [
3,
2,
0
] | [
"Look at f.func_code, it can tell you if f is a function or a wrapper.\n"
] | [
-1
] | [
"decorator",
"python"
] | stackoverflow_0001547222_decorator_python.txt |
Q:
Trace/BPT trap with Python threading module
The following code dies with Trace/BPT trap:
from tvdb_api import Tvdb
from threading import Thread
class GrabStuff(Thread):
def run(self):
t = Tvdb()
def main():
threads = [GrabStuff() for x in range(1)]
[x.start() for x in threads]
[x.join() f... | Trace/BPT trap with Python threading module | The following code dies with Trace/BPT trap:
from tvdb_api import Tvdb
from threading import Thread
class GrabStuff(Thread):
def run(self):
t = Tvdb()
def main():
threads = [GrabStuff() for x in range(1)]
[x.start() for x in threads]
[x.join() for x in threads]
if __name__ == '__main__':
... | [
"Bad things can happen when importing modules for the first time in a thread on OS X 10.6. See, for instance, this issue. As a workaround, try looking through Tvdb and add its complete chain of imports to the main module.\n"
] | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0001540835_multithreading_python.txt |
Q:
Forms in Django--cannot get past "cleaned_data"
I have a form that allows users to upload text AND a file. However, I'd like to make it valid even if the user doesn't upload the file (file is optional). However, in Django, it is not allowing me to get past "clean(self)". I just want it simple--if text box, pass. ... | Forms in Django--cannot get past "cleaned_data" | I have a form that allows users to upload text AND a file. However, I'd like to make it valid even if the user doesn't upload the file (file is optional). However, in Django, it is not allowing me to get past "clean(self)". I just want it simple--if text box, pass. If no text , return error.
class PieceForm(forms.Form... | [
"You must set required=False for the fields which are optional as noted in the documentation\nIn your case, the following line should do the trick:\n file = forms.FileField(required=False)\n\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001547412_django_python.txt |
Q:
Parallel Python: How do I supply arguments to 'submit'?
This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.
The following is the API (I think it's calle... | Parallel Python: How do I supply arguments to 'submit'? | This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.
The following is the API (I think it's called) that submits all pertinent info to pp.
def submit(self... | [
"interesting - are you doing genetics simulations? i ask because i see 'Chromosome' in there, and I once developed a population genetics simulation using parallel python.\nyour approach looks really complicated. in my parallel python program, i used the following call:\njob = jobServer.submit( doRun, (param,))\n\nh... | [
5,
0
] | [] | [] | [
"parallel_python",
"python"
] | stackoverflow_0001546429_parallel_python_python.txt |
Q:
A minimalist, non-enterprisey approach for a SOAP server in Python
I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X... | A minimalist, non-enterprisey approach for a SOAP server in Python | I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X?" answers)
I'd like to use stuff that's already in the basic python 2.... | [
"You could write a WSGI function (see wsgiref) and parse inside it an HTTP request body using the xml.etree.ElementTree module.\nSOAP is basically very simple, I'm not sure that it deserves a special module. Just use a standard XML processing library you like.\n",
"I wrote something like this in Boo, using a .Net... | [
3,
1
] | [] | [] | [
"http",
"python",
"soap"
] | stackoverflow_0001547520_http_python_soap.txt |
Q:
General printing raster and/or vector images
I'm looking for some API for printing.
Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).
What I think that would be minimum API is:
printer devices list
printer buffer w... | General printing raster and/or vector images | I'm looking for some API for printing.
Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).
What I think that would be minimum API is:
printer devices list
printer buffer where I could send my in-memory pixmap (ex. like wi... | [
"You might want to investigate wx python for printing. Learning the framework might be a bit of an overhead for you though! I've had success with that in the past, both on windows and linux.\nI've also used reportlab to make PDFs which are pretty easy to print using the minimum of OS interaction.\n",
"I would u... | [
0,
0,
0
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0001547621_c_c++_python.txt |
Q:
How to sort this list in Python?
[ {'time':33}, {'time':11}, {'time':66} ]
How to sort by the "time" element, DESC.
A:
Like this:
from operator import itemgetter
l = sorted(l, key=itemgetter('time'), reverse=True)
Or:
l = sorted(l, key=lambda a: a['time'], reverse=True)
output:
[{'time': 66}, {'time': 33},... | How to sort this list in Python? | [ {'time':33}, {'time':11}, {'time':66} ]
How to sort by the "time" element, DESC.
| [
"Like this:\nfrom operator import itemgetter\nl = sorted(l, key=itemgetter('time'), reverse=True)\n\nOr:\nl = sorted(l, key=lambda a: a['time'], reverse=True)\n\noutput: \n[{'time': 66}, {'time': 33}, {'time': 11}]\n\nIf you don't want to keep the original order you can use your_list.sort which modifies the orig... | [
27
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001547733_list_python.txt |
Q:
Crazy python behaviour
I have a little piece of python code in the server script for my website which looks a little bit like this:
console.append([str(x) for x in data])
console.append(str(max(data)))
quite simple, you might think, however the result it's outputting is this:
['3', '12', '3']
3
for some reason p... | Crazy python behaviour | I have a little piece of python code in the server script for my website which looks a little bit like this:
console.append([str(x) for x in data])
console.append(str(max(data)))
quite simple, you might think, however the result it's outputting is this:
['3', '12', '3']
3
for some reason python thinks 3 is the max of... | [
"Because the character '3' is higher in the ASCII table than '1'. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is max(data, key=int), but you might want to actually store numbers in the list.\n",
"I know very little Python, but you ar... | [
8,
1
] | [] | [] | [
"max",
"python"
] | stackoverflow_0001547856_max_python.txt |
Q:
How do I parse indents and dedents with pyparsing?
Here is a subset of the Python grammar:
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: pass_stmt
pass_stmt: 'pass'
compound_stmt: if_stmt
if_stmt:... | How do I parse indents and dedents with pyparsing? | Here is a subset of the Python grammar:
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: pass_stmt
pass_stmt: 'pass'
compound_stmt: if_stmt
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':... | [
"There are a couple of examples on the pyparsing wiki Examples page that could give you some insights:\n\npythonGrammarParser.py\nindentedGrammarExample.py\n\nTo use pyparsing's indentedBlock, I think you would define suite as:\nindentstack = [1]\nsuite = indentedBlock(stmt, indentstack, True)\n\nNote that indented... | [
11
] | [] | [] | [
"indentation",
"parser_generator",
"pyparsing",
"python"
] | stackoverflow_0001547944_indentation_parser_generator_pyparsing_python.txt |
Q:
Python library for syntax highlighting
Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc.
A:
I think pygments is the greatest choice. It supports a large number of languages and it'... | Python library for syntax highlighting | Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc.
| [
"I think pygments is the greatest choice. It supports a large number of languages and it's very mature.\n"
] | [
9
] | [] | [] | [
"pygments",
"python",
"syntax_highlighting"
] | stackoverflow_0001548276_pygments_python_syntax_highlighting.txt |
Q:
Python way to do crc32b
As i posted as title, there is a way to use the crc32b hash on python natively or through a library (i.e. chilkat)?
My intention is to "translate" a program from php to python, so output should be same as in php:
$hashedData= hash('crc32b',$data);
-> Edit: in a win32 system
Thanks to all ;)... | Python way to do crc32b | As i posted as title, there is a way to use the crc32b hash on python natively or through a library (i.e. chilkat)?
My intention is to "translate" a program from php to python, so output should be same as in php:
$hashedData= hash('crc32b',$data);
-> Edit: in a win32 system
Thanks to all ;)
| [
"python-mhash supplies many hashing functions including crc32b.\n"
] | [
2
] | [] | [] | [
"crc",
"hash",
"python"
] | stackoverflow_0001548366_crc_hash_python.txt |
Q:
Self contained classes with Qt
I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off...
Anyway, take this example:
class Main_Window (QtGui.QMainWindow):
def __init__ (self, parent=None... | Self contained classes with Qt | I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off...
Anyway, take this example:
class Main_Window (QtGui.QMainWindow):
def __init__ (self, parent=None):
QtGui.QWidget.__init__(se... | [
"I don't know Python so I can't give a good example here, but what I would probably do with Qt in C++ is define a signal of \"bookingAdded\" to your window object, and have one of your external objects (probably whichever invokes the UI) connect a slot to this signal, and then in your clickSubmitRecord you fire thi... | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0001548370_oop_python.txt |
Q:
Cart item management in python Turbogears 2.0
I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the add to cart method in my CartController.
def add(self, **... | Cart item management in python Turbogears 2.0 | I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the add to cart method in my CartController.
def add(self, **kw):
pid=kw['pid']
product = model.Product... | [
"Since you are modifying the item object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to?\nAs for making this more pythonic, you might consider something like this:\nitems_by_pid = dict([(item.product.pid, item) for item in cart.items])\nitem = ... | [
3
] | [] | [] | [
"python",
"turbogears2"
] | stackoverflow_0001545913_python_turbogears2.txt |
Q:
Why leading zero not possible in Python's Map and Str
What is the reason that you cannot use zero at the beginning of a number when converting the number to a sequence?
Code example
map(int,str(08978789787))
which gives Syntax error.
I would like to convert numbers which leading digit is zero to a sequence.
How c... | Why leading zero not possible in Python's Map and Str | What is the reason that you cannot use zero at the beginning of a number when converting the number to a sequence?
Code example
map(int,str(08978789787))
which gives Syntax error.
I would like to convert numbers which leading digit is zero to a sequence.
How can you convert such a number to a sequence?
| [
"This happens because the leading zero means you are writing an octal number and you can't have 9 or 8 in an octal number. See:\n>>> a = 0123\n>>> a\n83\n>>> a = 010\n>>> a\n8\n\nYou can just do:\n>>> map(int, '08978789787')\n[0, 8, 9, 7, 8, 7, 8, 9, 7, 8, 7]\n\n",
"The \"leading 0 in an integer means it's in oct... | [
14,
9,
4,
2
] | [] | [] | [
"python",
"sequence",
"string"
] | stackoverflow_0001548419_python_sequence_string.txt |
Q:
Workflow for maintaining different versions of codebase for different versions of Python
I'm developing an open source application called GarlicSim.
Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.
I decided it's important to produce versions of it that will support... | Workflow for maintaining different versions of codebase for different versions of Python | I'm developing an open source application called GarlicSim.
Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.
I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4.
So I h... | [
"You need separate branches for separate versions only in the rarest of cases. You mention context managers, and they are great, and it would suck not to use them, and you are right. But for Python 2.4 you will have to not use them. So that will suck. So therefore, if you want to support Python 2.4 you'll have to w... | [
3,
1,
1,
0
] | [] | [] | [
"git",
"merge",
"organization",
"python",
"version"
] | stackoverflow_0001546917_git_merge_organization_python_version.txt |
Q:
Python for C++ or Java Programmer
I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Ja... | Python for C++ or Java Programmer | I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show ... | [
"When you run a script through the Python interpreter (or import that script from another script), it actually executes all the code from beginning to end -- in that sense, there is no \"entry point\" to a Python script.\nSo to work around this, Python automatically creates a __name__ variable and fills it with the... | [
11,
7,
5,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001548620_python.txt |
Q:
Efficient storage of and access to web pages with Python
So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in c... | Efficient storage of and access to web pages with Python | So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). Bu... | [
"Why do you think solution (3), the Sphinx-based one, requires \"repeatedly crawling the site\"? Sphinx can accept and index many different data sources, including MySQL and PostgreSQL \"natively\" (there are contributed add-ons for other DBs such as Firebird) -- you can keep your HTML docs as columns in your DB i... | [
2,
1,
0
] | [] | [] | [
"database",
"mysql",
"python"
] | stackoverflow_0001548857_database_mysql_python.txt |
Q:
How to set an nonexistent field in Python ClientForm?
I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this?
The error is similar to the one you get if you... | How to set an nonexistent field in Python ClientForm? | I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this?
The error is similar to the one you get if you try to execute
from mechanize import Browser
br = Browser(... | [
"You need to first add the control to the form, and then fixup the form.\nbr.form.new_control('text','unexistent',{'value':''})\nbr.form.fixup()\nbr['unexistent'] = 'hello'\n\nThis really isn't very well documented, and in the source under fixup() there is the comment:\nThis method should only be called once, after... | [
17
] | [] | [] | [
"clientform",
"mechanize",
"python"
] | stackoverflow_0001548996_clientform_mechanize_python.txt |
Q:
how to define a widget in a model attribute
Simply, I write:
# forms.py
class NoteForm(ModelForm):
def __init__(self, *args, **kwargs):
super(NoteForm, self).__init__(*args, **kwargs)
#add attributes to html-field-tag:
self.fields['content'].widget.attrs['rows'] = 3
self.fields['title'].widget.att... | how to define a widget in a model attribute | Simply, I write:
# forms.py
class NoteForm(ModelForm):
def __init__(self, *args, **kwargs):
super(NoteForm, self).__init__(*args, **kwargs)
#add attributes to html-field-tag:
self.fields['content'].widget.attrs['rows'] = 3
self.fields['title'].widget.attrs['size'] = 20
class Meta:
model = Note
... | [
"No, you still do it in a form, but you just pass that form as a parameter to inlineformset_factory.\nNotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm)\n\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001549011_django_django_forms_python.txt |
Q:
Generate a string representation of a one-hot encoding
In Python, I need to generate a dict that maps a letter to a pre-defined "one-hot" representation of that letter. By way of illustration, the dict should look like this:
{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 ... | Generate a string representation of a one-hot encoding | In Python, I need to generate a dict that maps a letter to a pre-defined "one-hot" representation of that letter. By way of illustration, the dict should look like this:
{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}
There is one bit ... | [
"I find this to be more readable:\nfrom string import ascii_uppercase\n\none_hot = {}\nfor i, l in enumerate(ascii_uppercase):\n bits = ['0']*26; bits[i] = '1'\n one_hot[l] = ' '.join(bits)\n\nIf you need a more general alphabet, just enumerate over a string of the characters, and replace ['0']*26 with ['0']*... | [
7,
2,
1
] | [
"That seems pretty clear, concise, and Pythonic to me.\n"
] | [
-1
] | [
"data_generation",
"python"
] | stackoverflow_0001548984_data_generation_python.txt |
Q:
Help with JSON format
I'm using a JSON example off the web, as seen below.
{
"menu": "File",
"commands": [
{
"title": "New",
"action":"CreateDoc"
},
{
"title": "Open",
"action": "OpenDoc"
},
{
"title": "Close",
"act... | Help with JSON format | I'm using a JSON example off the web, as seen below.
{
"menu": "File",
"commands": [
{
"title": "New",
"action":"CreateDoc"
},
{
"title": "Open",
"action": "OpenDoc"
},
{
"title": "Close",
"action": "CloseDoc"
}
... | [
"Ok, after looking at jsoncpp's code, I realize my error. It wants the document as a string, not a file name.\n",
"It's your parser apparently. I can import correctly the file with simplejson parser in django\n>>> from django.utils import simplejson as sj\n>>> f=file(\"x.json\")\n>>> sj.load(f)\n{u'menu': u'File'... | [
11,
1,
1
] | [] | [] | [
"c++",
"json",
"python"
] | stackoverflow_0001549292_c++_json_python.txt |
Q:
Project Euler # 255
Project euler problem #255 is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?
def ceil(a, b):
return (a + b - 1) / b;
def f... | Project Euler # 255 | Project euler problem #255 is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?
def ceil(a, b):
return (a + b - 1) / b;
def func(a, b):
return (b + c... | [
"Don't use map. It generates a big list in memory.\nDon't use xrange. It is limited to short integers.\nUse generators instead.\n# No changes on `ceil()`, `func()` and `calculate()`\n\ndef generate_sequence(start, stop):\n while start < stop:\n yield start\n start += 1\n\nresult = sum(calculate(n)... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001427040_python.txt |
Q:
How to create a specific if condition templatetag with Django?
My problem is a if condition.
I would like somethings like that but cannot figure out how to do it.
{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo... | How to create a specific if condition templatetag with Django? | My problem is a if condition.
I would like somethings like that but cannot figure out how to do it.
{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png... | [
"Easiest way is to create a filter.\n@register.filter\ndef is_favourite_of(object, user):\n return Favourite.objects.is_favourite(user, object)\n\nand in the template:\n{% if restaurant|is_favourite_of:user %}\n\n",
"Maybe I could use the inclusion tag.\nCreate a tag like that :\n{% show_favorite_img user rest... | [
11,
2,
0
] | [] | [] | [
"django",
"django_templates",
"favorites",
"python"
] | stackoverflow_0001546816_django_django_templates_favorites_python.txt |
Q:
How do do this list manipulation in Python? This is tricky
Suppose I have this list:
[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
What is the MOST efficient way to turn it into this list?
[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
Notice, I grab the first from each. Then the 2nd element from each.
Of course, this func... | How do do this list manipulation in Python? This is tricky | Suppose I have this list:
[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
What is the MOST efficient way to turn it into this list?
[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.
I've tried it, but mine h... | [
">>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\n>>> L2 = []\n>>> map(L2.extend, zip(*L1))\n>>> L2\n[5, 7, 1, 44, 21, 32, 73, 99, 100]\n\n",
"import itertools\nlist(itertools.chain(*zip(*L1)))\n\nIf you need lists of varying length:\nimport itertools\n[x for x in itertools.chain(*itertools.izip_longest(*L1... | [
10,
8,
4,
2,
1,
0,
0,
-2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001549445_list_python.txt |
Q:
Why does this happen in my template for Django?
simple%20minds is displayed when do this:
{{ rec.artist_name }}
How do I remove the %20...and make it spaces?
When I put | safe as a fitler, the error is:
Could not parse the remainder: ' | safe' from 'active.artist_name | safe'
Thanks.
A:
I think you're being hit ... | Why does this happen in my template for Django? | simple%20minds is displayed when do this:
{{ rec.artist_name }}
How do I remove the %20...and make it spaces?
When I put | safe as a fitler, the error is:
Could not parse the remainder: ' | safe' from 'active.artist_name | safe'
Thanks.
| [
"I think you're being hit by Django's relatively-new autoescaping. What happens if you do \n{{ rec.artist_name | safe }}\n\nto avid the value being autoescaped?\n",
"Try removing the space between the rec.artist_name and the |. So you should have this: \n{{ rec.artist_name|safe }}\nThat'll fix the autoescaping, ... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001549606_django_python.txt |
Q:
How to do nested Django SELECT?
class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name='friend_set')
to_friend = models.ForeignKey(User, related_name='to_friend_set')
I'd like to SELECT all to_friends that have from_friend = a certain User.
Then, I'd like to pass to_friends to ... | How to do nested Django SELECT? | class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name='friend_set')
to_friend = models.ForeignKey(User, related_name='to_friend_set')
I'd like to SELECT all to_friends that have from_friend = a certain User.
Then, I'd like to pass to_friends to inside filter in another .objects.fil... | [
"\nI'd like to SELECT all to_friends that have from_friend = a certain User.\n\nYou could get all the Friendship objects for this step like so:\nfriendships = Friendship.objects.filter(from_friend=some_user)\n\nThen you can get all the to_friend fields into a flat list using the values_list method of a query set:\n... | [
3,
2,
2
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0001547494_django_mysql_python.txt |
Q:
Regex From .NET to Python
I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:
((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))
I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).
It is a lame quest... | Regex From .NET to Python | I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:
((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))
I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).
It is a lame question/request, but I have been st... | [
"There are some syntax incompatibilities between .NET regexps and PCRE/Python regexps :\n\n(?<name>...) is (?P<name>...)\n(?...) does not exist, and as I don't know what it is used for in .NET I can't guess any equivalent. A Google codesearch do not give me any pointer to what it could be used for.\n\nBesides, you ... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001549716_python_regex.txt |
Q:
Unexpected result on a simple example
# Barn yard example: counting heads and legs
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
... | Unexpected result on a simple example | # Barn yard example: counting heads and legs
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads... | [
"look at your indentation. return [None, None] is inside the loop. it returns [None, None] after the first iteration\n",
"In solve(), your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine.\ndef solve(numLegs, numHeads):\n for numChicks in range(0, n... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0001549795_python.txt |
Q:
Python 3.1.1 with --enable-shared : will not build any extensions
Summary: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems.
Please note that this question may seem to blur the line between programming and system adminis... | Python 3.1.1 with --enable-shared : will not build any extensions | Summary: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems.
Please note that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with ... | [
"Something is wrong with your build environment. It is picking up a libpython3.1.a from /usr/local/lib; this confuses the error messages. It tries linking with that library, which fails - however, it shouldn't have tried that in the first place, since it should have used the libpython that it just built. I recommen... | [
6,
0
] | [] | [] | [
"compilation",
"mod_wsgi",
"python",
"python_3.x"
] | stackoverflow_0001547310_compilation_mod_wsgi_python_python_3.x.txt |
Q:
Problem about python writing files
I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be... | Problem about python writing files | I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file.
In short, my problem is t... | [
"I guess it's caused by incorrect indentation. The break statement should be inside the if block. The loop as it is written will only try the first option from judge. Check if you don't have mixed spaces and tabs in the file.\n"
] | [
2
] | [] | [] | [
"file",
"python"
] | stackoverflow_0001550132_file_python.txt |
Q:
Adding to local namespace in Python?
Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?
Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print stateme... | Adding to local namespace in Python? | Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?
Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.
def A():
B(locals())... | [
"In Python 2.*, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function with exec ''; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization can easily speed code up... | [
4,
1
] | [] | [] | [
"class",
"methods",
"namespaces",
"python"
] | stackoverflow_0001549201_class_methods_namespaces_python.txt |
Q:
web2py - how to inject html
i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"
rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id
,db.member... | web2py - how to inject html | i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"
rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id
,db.member.first_name,db.member.middle_name... | [
"There are many HTML helpers you can use, for example:\nhtml_code = A('<click>', rows.xml(), _href='http://mylink')\nhtml_code = B('Results:', rows.xml(), _class='results', _id=1)\nhtml_page = HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1)))\n\nand so on.\nYou can even create a whole table automatical... | [
2,
0
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001550368_python_web2py.txt |
Q:
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line?
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
How do I make htmlSource in 1 line, instead of many lines?
A:
... | I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line? | urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
How do I make htmlSource in 1 line, instead of many lines?
| [
"You can't really do that, the only possible thing is put the response and the source on the same line. Or you could use ; between statements, but that's ugly.\nBut more importantly, why would you do that? Why is it better to have it all in on line?\n>>> import this\n\nThe Zen of Python, by Tim Peters\n\n...\nReada... | [
9,
6
] | [] | [] | [
"python"
] | stackoverflow_0001550406_python.txt |
Q:
Counting all the keys pressed and what they are (python)
I'd like to create a map of the number of presses for every key for a project I'm working on.
I'd like to do this with a Python module. Is it possible to do this in any way?
A:
On Windows, a possible solution is to install Python for Windows extensions and... | Counting all the keys pressed and what they are (python) | I'd like to create a map of the number of presses for every key for a project I'm working on.
I'd like to do this with a Python module. Is it possible to do this in any way?
| [
"On Windows, a possible solution is to install Python for Windows extensions and use the PyCWnd.HookAllKeyStrokes\n",
"As Nick D points out, on Windows, the PyHook library would work.\nOn Linux, the Python X Library gives you access to key-presses on the X-server.\nA good example of the use of both libraries is p... | [
1,
1
] | [] | [] | [
"counting",
"key",
"python"
] | stackoverflow_0001550273_counting_key_python.txt |
Q:
Django: how to include the file?
I have a Django Application.
I want to have all my models to be separated in files and lay in the specific directory, for instance:
/usr/project/models/myModel.py
Is it any possible?
Just importing through from myModel import * doesn't work, unfortunately.
Is there any specific wa... | Django: how to include the file? | I have a Django Application.
I want to have all my models to be separated in files and lay in the specific directory, for instance:
/usr/project/models/myModel.py
Is it any possible?
Just importing through from myModel import * doesn't work, unfortunately.
Is there any specific way to do this?
| [
"Create file /usr/project/models/__init__.py containing from myModel import *. __init__.py file is required to make directory a python package.\n",
"You can split your models into separate files, it's just Python code. \n"
] | [
1,
0
] | [] | [] | [
"django_urls",
"python"
] | stackoverflow_0001550601_django_urls_python.txt |
Q:
Difference between defining a member in __init__ to defining it in the class body in python?
What is the difference between doing
class a:
def __init__(self):
self.val=1
to doing
class a:
val=1
def __init__(self):
pass
A:
class a:
def __init__(self):
self.val=1
this creates a c... | Difference between defining a member in __init__ to defining it in the class body in python? | What is the difference between doing
class a:
def __init__(self):
self.val=1
to doing
class a:
val=1
def __init__(self):
pass
| [
"class a:\n def __init__(self):\n self.val=1\n\nthis creates a class (in Py2, a cruddy, legacy, old-style, don't do that! class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the **good* kind, which requires class a(object): in Py2) such tha... | [
10,
6,
5
] | [] | [] | [
"class",
"init",
"python"
] | stackoverflow_0001549722_class_init_python.txt |
Q:
web2py SQLTABLE - How can I transpose the table?
I am using:
rows = db(db.member.membership_id==request.args[0]).select(db.member.membership_id,
db.member.first_name,
db.member.middle_name,
db.member.last_name,
db.member.birthdate,
db.member.registration_date,
db.member.membership_end_date)... | web2py SQLTABLE - How can I transpose the table? | I am using:
rows = db(db.member.membership_id==request.args[0]).select(db.member.membership_id,
db.member.first_name,
db.member.middle_name,
db.member.last_name,
db.member.birthdate,
db.member.registration_date,
db.member.membership_end_date)
rows.colnames = ('Membership Id', 'First Name', 'Mid... | [
"Try this:\nrows=db(query).select(*fields).as_list()\nif rows:\n table=TABLE(*[TR(TH(field),*[TD(row[field]) for row in rows]) \\ \n for field in row[0].keys()])\nelse:\n table=\"nothing to see here\"\nreturn dict(table=table)\n\n"
] | [
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001550707_python_web2py.txt |
Q:
Dynamically importing modules in Python3.0?
I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an ImportError and tells me my module doesn't exist.
First I get the list of module filenames and chop off the ".py" suffixes, like so:
viable_plugins = filter(is_plu... | Dynamically importing modules in Python3.0? | I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an ImportError and tells me my module doesn't exist.
First I get the list of module filenames and chop off the ".py" suffixes, like so:
viable_plugins = filter(is_plugin, os.listdir(plugin_dir))
viable_plugins = map... | [
"It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path.\nWhat you need to do, instead of changing to the directory where the modules are located, is to insert that directory into sys.path.\nimport sys\nsys.path.insert(0, directo... | [
8
] | [] | [] | [
"import",
"python",
"python_3.x"
] | stackoverflow_0001551063_import_python_python_3.x.txt |
Q:
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows
I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash ver... | urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't ma... | [
"If it is really a resource problem (freeing os socket resources)\ntry this:\nrequest = urllib2.Request(file_remote_path)\nopener = urllib2.build_opener()\n\nretry = 3 # 3 tries\nwhile retry :\n try :\n datastream = opener.open(request)\n except urllib2.URLError, ue:\n if ue.reason.find('10048')... | [
5,
1,
1,
1,
1
] | [] | [] | [
"download",
"http",
"python",
"urllib2",
"windows"
] | stackoverflow_0001512057_download_http_python_urllib2_windows.txt |
Q:
python: parse HTTP POST request w/file upload and additional params
The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters.
I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chu... | python: parse HTTP POST request w/file upload and additional params | The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters.
I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk.
All methods I found are based on cgi.FieldStorage, which somehow only... | [
"As you suggested, I would (and have done before) override the make_file method of a FieldStorage object. Just return an object which has a write method that both accepts the data (into a file or memory or what-have-you) and tracks how much has been received for your progress indicator.\nDoing it this way you also ... | [
2,
1,
0
] | [] | [] | [
"python",
"upload",
"wsgi"
] | stackoverflow_0001551552_python_upload_wsgi.txt |
Q:
How can 2 Python dictionaries become 1?
Possible Duplicate:
Python “extend” for a dictionary
I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance:
basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'}
basket_two = {'dairy... | How can 2 Python dictionaries become 1? |
Possible Duplicate:
Python “extend” for a dictionary
I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance:
basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'}
basket_two = {'dairy': 'cheese', 'meat': 'turkey'}
I then want ... | [
"The \"oneliner way\", altering neither of the input dicts, is\nbasket = dict(basket_one, **basket_two)\n\nIn case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict tha... | [
65,
8
] | [] | [] | [
"dictionary",
"merge",
"python"
] | stackoverflow_0001551666_dictionary_merge_python.txt |
Q:
How to perform this RegExp in Python?
I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00
+33 is the indicatif it could be 2 or 3 digits length.
Digits after the . are the phone number. It could be 9 or 10 digits length.
I try like this :
p = re.compile( "\+[0-9]+\.([0-9]+)", re.V... | How to perform this RegExp in Python? | I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00
+33 is the indicatif it could be 2 or 3 digits length.
Digits after the . are the phone number. It could be 9 or 10 digits length.
I try like this :
p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE)
number = "+33.300000000"
p.sub("0\1... | [
"The simplest approach is a mix of RE and pure string manipulation, e.g.:\nimport re\n\ndef doitall(number):\n # get 9 or 10 digits, or None:\n mo = re.search(r'\\d{9,10}', number)\n if mo is None: return None\n # add a leading 0 if they were just 9\n digits = ('0' + mo.group())[-10:]\n # now put a dot after ... | [
3,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001552124_python_string.txt |
Q:
Why doesn't memcache work in my Django?
from django.core.cache import cache
def testcache():
cache.set('test','I am putting this message in',3333)
print cache.get('test')
It just prints "None"
This is in "ps aux":
dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u... | Why doesn't memcache work in my Django? | from django.core.cache import cache
def testcache():
cache.set('test','I am putting this message in',3333)
print cache.get('test')
It just prints "None"
This is in "ps aux":
dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211
dovr 2247 0.0 3... | [
"You can insure that you can reach memcached from your code by logging value returned from set() method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface.\n",
"Solved.\nDjango was talking to the server.\nI did \"nc IPADRESS 11211\" .\nAnd typed \"stats\"\nThen, I looke... | [
2,
0
] | [] | [] | [
"django",
"memcached",
"python"
] | stackoverflow_0001550180_django_memcached_python.txt |
Q:
How to transform Python 3 script to Mac OS application bundle?
Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated.
A:
There's always Platypus and PyObjC
http://ww... | How to transform Python 3 script to Mac OS application bundle? | Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated.
| [
"There's always Platypus and PyObjC\nhttp://www.sveinbjorn.org/platypus\nhttp://pyobjc.sourceforge.net\n",
"I have not checked if that's true, but cx_freeze 4.1 claims to support Python 3.1 (cx_freeze in general has long supported Mac OS X, as well as Windows and Linux, and I believe that also applies to the rece... | [
1,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0001534933_macos_python.txt |
Q:
Rules of thumb for when to use operator overloading in python
From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading + you probably also want to overload ++ and +=, and also ... | Rules of thumb for when to use operator overloading in python | From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading + you probably also want to overload ++ and +=, and also make sure to handle end cases like adding an object to itself etc.)... | [
"Operator overloading is mostly useful when you're making a new class that falls into an existing \"Abstract Base Class\" (ABC) -- indeed, many of the ABCs in standard library module collections rely on the presence of certain special methods (and special methods, one with names starting and ending with double unde... | [
24,
12,
6,
3
] | [] | [] | [
"operator_overloading",
"python"
] | stackoverflow_0001552260_operator_overloading_python.txt |
Q:
Is there a cleaner way to chain empty list checks in Python?
I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:
if a.get("key") and a["key"][0] and a... | Is there a cleaner way to chain empty list checks in Python? | I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:
if a.get("key") and a["key"][0] and a["key"][0][0] :
for b in a["key"][0][0] :
#Do somethin... | [
"try:\n bs = a[\"key\"][0][0]\n# Note: the syntax for catching exceptions is different in old versions\n# of Python. Use whichever one of these lines is appropriate to your version.\nexcept KeyError, IndexError, TypeError: # Python 3\nexcept (KeyError, IndexError, TypeError): # Python 2\n bs = []\nfor b in bs:\... | [
14,
3,
2
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0001552310_coding_style_python.txt |
Q:
Understanding an example
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads, legs):
pigs, c... | Understanding an example | def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads, legs):
pigs, chickens = solve(legs, heads)
... | [
"solve is computing how many chicks (1 head, 2 legs) and how many pigs (1 head, 4 legs) it takes to total up to the given numbers of heads and legs.\nIt uses a \"brute force\", that is, maximally simple, approach: \n\nit tries even possible number of\nchicks from none at all to as many as\nwas specified as number o... | [
8,
2,
1,
1,
1
] | [] | [] | [
"pseudocode",
"python"
] | stackoverflow_0001549828_pseudocode_python.txt |
Q:
Extracting text fields from HTML using Python?
what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" <email@email.com>... | Extracting text fields from HTML using Python? | what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" <email@email.com></td>
<td>1231231234</td>
... | [
"For extracting and general HTML munging look at\nhttp://www.crummy.com/software/BeautifulSoup/\n\nFor the MySQL I suggest googling on: MySQL tutorial python \n",
"Here is how you get the td contents into a python list using BeautifulSoup:\n#!/usr/bin/python\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\... | [
6,
1,
1,
1,
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0001551293_python_text.txt |
Q:
python adding gibberish when reading from a .rtf file?
I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that?... | python adding gibberish when reading from a .rtf file? | I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in this f... | [
"That's the nature of .RTF (i.e Rich Text files), they include extra data to define how the text is layed-out and formated.\nIt is not recommended to store data in such files lest you encounter the difficulties you noted. Would you go through the effort to parse this file and \"recover\" your one numeric value, y... | [
4,
4
] | [] | [] | [
"file_io",
"python",
"rtf"
] | stackoverflow_0001552886_file_io_python_rtf.txt |
Q:
Web Service client in Python using ZSI - "Classless struct didn't get dictionary"
I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsd... | Web Service client in Python using ZSI - "Classless struct didn't get dictionary" | I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/test/" xmlns:wsdl="http://schemas.xmlsoap.or... | [
"Finally, I have found the solution. \nI should run like this:\nfrom ZSI.ServiceProxy import ServiceProxy\nservice = ServiceProxy('test.wsdl')\nservice.NewOperation(NewOperationRequest='test')\n\nThe reason of the problem was that the name of the parameter was missing (sic!) - silly error ;-)\n"
] | [
3
] | [] | [] | [
"python",
"wsdl",
"zsi"
] | stackoverflow_0001496910_python_wsdl_zsi.txt |
Q:
Python sqlite3 version
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> sqlite3.version
'2.4.1'
Questions:
Why is the version of the sqlite3 module '2.4.1'
Whats the reason behind bu... | Python sqlite3 version | Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> sqlite3.version
'2.4.1'
Questions:
Why is the version of the sqlite3 module '2.4.1'
Whats the reason behind bundling such an old sqlite wi... | [
"Python 2.5.1\n>>> import sqlite3\n>>> sqlite3.version\n'2.3.2'\n>>> sqlite3.sqlite_version\n'3.3.4'\n\nversion - pysqlite version\nsqlite_version - sqlite version\n"
] | [
97
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0001553160_python_sqlite.txt |
Q:
How to strip a list of tuple with python?
I have an array with some flag for each case.
In order to use print the array in HTML and use colspan, I need to convert this :
[{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': Fa... | How to strip a list of tuple with python? | I have an array with some flag for each case.
In order to use print the array in HTML and use colspan, I need to convert this :
[{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': F... | [
"def cluster(dicts, key):\n current_value = None\n current_span = 0\n result = []\n\n for d in dicts:\n value = d[key]\n if current_value is None:\n current_value = value\n elif current_value != value:\n result.append({'colspan': current_span, key: current_valu... | [
4,
4
] | [] | [] | [
"dictionary",
"flags",
"list",
"python"
] | stackoverflow_0001553275_dictionary_flags_list_python.txt |
Q:
% operator in python over string
What does the following Python statement mean?
send_data=""
str_len = "%#04d" % (len(send_data)/2)
A:
This sets str_len to show half the length of send_data, padded with zeros to be four characters right. The % character is carrying out interpolation. See the printf-style String ... | % operator in python over string | What does the following Python statement mean?
send_data=""
str_len = "%#04d" % (len(send_data)/2)
| [
"This sets str_len to show half the length of send_data, padded with zeros to be four characters right. The % character is carrying out interpolation. See the printf-style String Formatting section of the documentation.\n"
] | [
4
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0001553434_python_string_formatting.txt |
Q:
After submitting form, the value is different due to encoding? (Python)
I am using Django.
In a regular form, the user enters "Gerry & Pacemakers".
(Notice the Ampersand sign.)
When I go views.py...
def myview(request):
q = request.GET.get('q','').strip()
print q
q is "Gerry"...but it's supposed to be "Ge... | After submitting form, the value is different due to encoding? (Python) | I am using Django.
In a regular form, the user enters "Gerry & Pacemakers".
(Notice the Ampersand sign.)
When I go views.py...
def myview(request):
q = request.GET.get('q','').strip()
print q
q is "Gerry"...but it's supposed to be "Gerry & Pacemakers"...encoded
Is the correct way doing this by using urllib??
H... | [
"Since you are pulling the data from request.GET, it looks like you're building the URL in the browser somehow. You need to use the Javascript escape() function to handle URL-significant characters properly.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001553564_django_python.txt |
Q:
Dynamic Finders and Method Missing in Python
I'm trying to implement something like Rails dynamic-finders in Python (for
webapp/GAE). The dynamic finders work like this:
Your Person has some fields: name, age and email.
Suppose you want to find all the users whose name is "Robot".
The Person class has a method ... | Dynamic Finders and Method Missing in Python | I'm trying to implement something like Rails dynamic-finders in Python (for
webapp/GAE). The dynamic finders work like this:
Your Person has some fields: name, age and email.
Suppose you want to find all the users whose name is "Robot".
The Person class has a method called "find_by_name" that receives the name
and r... | [
"There's really no need to use GQL here - it just complicates matters. Here's a simple implementation:\nclass FindableModel(db.Model):\n def __getattr__(self, name):\n if not name.startswith(\"find_by_\"):\n raise AttributeError(name)\n field = name[len(\"find_by_\"):]\n return lambda value: self.all... | [
8,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0000913020_google_app_engine_python_web_applications.txt |
Q:
reading midi input
is there a module to read midi input (live) with python?
A:
I used PyPortMidi successfully in 2006 to record Midi input in real time (on OS X). It should work on Windows, OS X, and Linux. It was very light on the processor side, which was great!
A:
I had this discussion like ages ago once,... | reading midi input | is there a module to read midi input (live) with python?
| [
"I used PyPortMidi successfully in 2006 to record Midi input in real time (on OS X). It should work on Windows, OS X, and Linux. It was very light on the processor side, which was great!\n",
"I had this discussion like ages ago once, and the consensus kinda ended up on using MidiShare, which has Python bindings... | [
3,
1
] | [] | [] | [
"input",
"midi",
"python"
] | stackoverflow_0001554362_input_midi_python.txt |
Q:
Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath)
I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the... | Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath) | I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less tag... | [
"If speed is a requirement have a look at lxml. lxml is a pythonic binding for the libxml2 and libxslt C libraries. Using the C libraries is much faster than any pure php or python version.\nThere are some impressive benchmarks from Ian Bicking:\n\nIn Conclusion\nI knew lxml was fast before I started these benchmar... | [
3,
2,
0
] | [] | [] | [
"html",
"php",
"python",
"regex",
"xpath"
] | stackoverflow_0001553511_html_php_python_regex_xpath.txt |
Q:
Python Clientform-can not get expexted result
I am trying to search through http://www.wegottickets.com/ with the keywords "Live music". But the returned result is still the main page, not the search result page including lots of live music information. Could anyone show me out what the problem is?
from urllib2 im... | Python Clientform-can not get expexted result | I am trying to search through http://www.wegottickets.com/ with the keywords "Live music". But the returned result is still the main page, not the search result page including lots of live music information. Could anyone show me out what the problem is?
from urllib2 import urlopen
from ClientForm import ParseResponse
... | [
"Never used it, but I've had success with the python mechanize module, if it turns out to be a fault in clientform.\nHowever, as a first step, I'd suggest removing your try...except wrapper. What you're basically doing is saying \"catch any error, then ignore the actual error and print 'Unsuccessful Query' instead... | [
0
] | [] | [] | [
"clientform",
"python"
] | stackoverflow_0001554534_clientform_python.txt |
Q:
Using Python locale or equivalent in web applications?
Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's... | Using Python locale or equivalent in web applications? | Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.
And there are warnings in the locale docs that make... | [
"locale is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, PyICU is a vastly superior solution -- top-quality i18n/L10n support, speed, flexibility (downside: while ICU's docs are good, PyICU... | [
14,
1,
0,
0
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0001551508_django_internationalization_python.txt |
Q:
Implementing "Starts with" and "Ends with" queries with Google App Engine
Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python?
In pseudo code, it would work something like...
Query for all entities A where property P star... | Implementing "Starts with" and "Ends with" queries with Google App Engine | Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python?
In pseudo code, it would work something like...
Query for all entities A where property P starts with X
or
Query for all entities B where property P ends with X
Thanks, Matt... | [
"You can do a 'starts with' query by using inequality filters:\nMyModel.all().filter('prop >=', prefix).filter('prop <', prefix + u'\\ufffd')\n\nDoing an 'ends with' query would require storing the reverse of the string, then applying the same tactic as above.\n",
"Seems you can't do it for the general case, but ... | [
16,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001554600_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I ask for an authenticated url directly with python
I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like:
urllib2.urlopen('http://username:pwd@server/page')
If not, how do I use authentication?
A:
It depends on the type of authentication used. ... | How do I ask for an authenticated url directly with python | I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like:
urllib2.urlopen('http://username:pwd@server/page')
If not, how do I use authentication?
| [
"It depends on the type of authentication used. \n\nA simple example is Http Authentication\nIf the site uses cookies for auth you need to add a cookiejar and login over http\nthere are many more auth schemes, so find out which you need.\n\n",
"AFAIK, there isn't a trivial way of doing this. Basically, you make a... | [
2,
1
] | [] | [] | [
"authentication",
"python",
"urllib2"
] | stackoverflow_0001554745_authentication_python_urllib2.txt |
Q:
Getting input from MIDI devices live (Python)
I've got a trigger finger (MIDI tablet) and I want to be able to read its input live and make python execute actions depending on the pressed key.
I need it for Windows, and preferably working with python 2.5 +
Thanks
A:
PyGame includes a built-in midi module, availa... | Getting input from MIDI devices live (Python) | I've got a trigger finger (MIDI tablet) and I want to be able to read its input live and make python execute actions depending on the pressed key.
I need it for Windows, and preferably working with python 2.5 +
Thanks
| [
"PyGame includes a built-in midi module, available for Linux, Windows and MacOS and is very well supported.\nFor example, here is the documentation for pygame.midi.Input:\n Input is used to get midi input from midi devices.\n Input(device_id)\n Input(device_id, buffer_size)\n Input.close - closes a midi s... | [
10
] | [] | [] | [
"midi",
"python"
] | stackoverflow_0001554896_midi_python.txt |
Q:
How do I know what's the realm and uri of a site
I want to use python's urllib2 with authentication and I need the realm and uri of a url. How do I get it?
thanks
A:
When you make a request for a resource that requires authentication, the server will respond with a 401 status code, and a header that contains the... | How do I know what's the realm and uri of a site | I want to use python's urllib2 with authentication and I need the realm and uri of a url. How do I get it?
thanks
| [
"When you make a request for a resource that requires authentication, the server will respond with a 401 status code, and a header that contains the realm:\nWWW-Authenticate: Basic realm=\"the realm\"\n\nThe URI is the URL you're trying to access.\n"
] | [
1
] | [] | [] | [
"authentication",
"python",
"urllib2"
] | stackoverflow_0001555018_authentication_python_urllib2.txt |
Q:
Problem to make an apache server run correctly under mod_python
We try to migrate our old server to a new one but we experienced some problems with mod_python.
The problem is under this web page:
http://auction.tinyerp.org/auction-in-europe.com/aie/
Here is our apache2 configuration:
NameVirtualHost *
<VirtualHo... | Problem to make an apache server run correctly under mod_python | We try to migrate our old server to a new one but we experienced some problems with mod_python.
The problem is under this web page:
http://auction.tinyerp.org/auction-in-europe.com/aie/
Here is our apache2 configuration:
NameVirtualHost *
<VirtualHost *>
DocumentRoot /var/www/
<Directory />
Options FollowSymLin... | [
"\n#!/usr/bin/python\nimport os, sys\nbase_dir = \"/home/www/auction-in-europe.com/aie/\"\nsys.path.insert(0, base_dir)\nimport albatross\nimport sql_db\nfrom albatross.apacheapp import Request\nfrom albatross import apacheapp\nfrom albatross.template import Content, EmptyTag, EnclosingTag\nimport string\nimport co... | [
0,
0
] | [] | [] | [
"apache2",
"mod_python",
"python"
] | stackoverflow_0001554673_apache2_mod_python_python.txt |
Q:
Worker/Timeslot permutation/constraint filtering algorithm
Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have.
If anyone knows of a good third-party ap... | Worker/Timeslot permutation/constraint filtering algorithm | Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have.
If anyone knows of a good third-party app which (certainly) automate this, that would almost as good. J... | [
"\nI've tried implementing this with a Genetic Algorithm, \n but can't seem to get it tuned quite right, so although \n the basic principle seems to work on single shifts, \n it can't solve even easy cases with a few shifts and a few workers.\n\nIn short, don't! Unless you have lots of experience with genetic al... | [
3,
1,
1
] | [] | [] | [
"permutation",
"python",
"scheduling",
"timeslots",
"timetable"
] | stackoverflow_0001554366_permutation_python_scheduling_timeslots_timetable.txt |
Q:
webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser"
I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac.
I'm testing a Python pr... | webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser" | I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac.
I'm testing a Python program (Crunchy Python) which sets up a web server then uses Firefox for the front end. It... | [
"Apple uses launch services to find applications. An application can be used by the open command - Apple developer man page for open\nThe python command you want is\nclient = webbrowser.get(\"open -a /Applications/Firefox.app %s\")\n\nFollowing Nicholas Riley 's comment\nIf Firefox is on the list of Applications th... | [
3,
3
] | [] | [] | [
"browser",
"firefox",
"macos",
"python"
] | stackoverflow_0001555283_browser_firefox_macos_python.txt |
Q:
In Django, How Do I Move Images When A Dynamic Path Changes?
I have a Django app with an image field (a custom ThumbnailImageField type) that auto-generates the file path for an image based on the title, type, and country of the item the image is attached to (upload_ to = get_ image_path). Here's how:
def get_im... | In Django, How Do I Move Images When A Dynamic Path Changes? | I have a Django app with an image field (a custom ThumbnailImageField type) that auto-generates the file path for an image based on the title, type, and country of the item the image is attached to (upload_ to = get_ image_path). Here's how:
def get_image_path(instance, filename):
dir = 'images'
subdir = inst... | [
"You probably want to look into signals:\nhttp://docs.djangoproject.com/en/dev/topics/signals/\nIn particular, the django.db.models.signals.pre_save signal:\nhttp://docs.djangoproject.com/en/dev/howto/custom-model-fields/#pre_save\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001556040_django_django_models_python.txt |
Q:
How to dereference a memory location from python ctypes?
I want to replicate the following c code in python ctypes:
main() {
long *ptr = (long *)0x7fff96000000;
printf("%lx",*ptr);
}
I can figure out how to call this memory location as a function pointer but not just do a normal dereference:
from ctypes impor... | How to dereference a memory location from python ctypes? | I want to replicate the following c code in python ctypes:
main() {
long *ptr = (long *)0x7fff96000000;
printf("%lx",*ptr);
}
I can figure out how to call this memory location as a function pointer but not just do a normal dereference:
from ctypes import *
"""
>>> fptr = CFUNCTYPE(None, None)
Traceback (most recen... | [
"ctypes.cast.\n>>> import ctypes\n>>> c_long_p = ctypes.POINTER(ctypes.c_long)\n>>> some_long = ctypes.c_long(42)\n>>> ctypes.addressof(some_long)\n4300833936\n>>> ctypes.cast(4300833936, c_long_p)\n<__main__.LP_c_long object at 0x1005983b0>\n>>> ctypes.cast(4300833936, c_long_p).contents\nc_long(42)\n\n"
] | [
32
] | [] | [] | [
"ctypes",
"ffi",
"python"
] | stackoverflow_0001555944_ctypes_ffi_python.txt |
Q:
Python "Task Server"
My question is: which python framework should I use to build my server?
Notes:
This server talks HTTP with it's clients: GET and POST (via pyAMF)
Clients "submit" "tasks" for processing and, then, sometime later, retrieve the associated "task_result"
submit and retrieve might be separated b... | Python "Task Server" | My question is: which python framework should I use to build my server?
Notes:
This server talks HTTP with it's clients: GET and POST (via pyAMF)
Clients "submit" "tasks" for processing and, then, sometime later, retrieve the associated "task_result"
submit and retrieve might be separated by days - different HTTP co... | [
"I'd recommend using an existing message queue. There are many to choose from (see below), and they vary in complexity and robustness. \nAlso, avoid threads: let your processing tasks run in a different process (why do they have to run in the webserver?)\nBy using an existing message queue, you only need to worry a... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000805120_python.txt |
Q:
Should you import all classes you use in Python?
Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?
Example
someclass.py
class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
somecli... | Should you import all classes you use in Python? | Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?
Example
someclass.py
class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
someclient.py
class SomeClient:
def __init__(self, some_c... | [
"Yes, it's completely ok. some_class_instance might be anything, it doesn't have to be an instance of SomeClass. You might want to pass an instance that looks just like SomeClass, but uses a different implementation for testing purposes, for example.\n",
"Importing SomeClass won't make any difference to how that ... | [
9,
6,
4,
1
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0001556766_coding_style_python.txt |
Q:
Executing a MySQL query on command line via os.system in Python
I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e
I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. ... | Executing a MySQL query on command line via os.system in Python | I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e
I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string befor... | [
"Code below might help you out. It isn't particularly exciting and is deliberately simple. This is not the way many programmers would tackle this problem, but without more info it seems to fulfil your requirements.\nI have also made an assumption that you are new to python; If I'm wrong, feel free to ignore this po... | [
3,
1,
0
] | [] | [] | [
"mysql",
"python",
"shell"
] | stackoverflow_0001221232_mysql_python_shell.txt |
Q:
How does AMF communication work?
How does Flash communicate with services / scripts on servers via AMF?
Regarding the AMF libraries for Python / Perl / PHP which are easier to develop than .NET / Java:
do they execute script files, whenever Flash sends an Remote Procedure Call?
or do they communicate via sockets,... | How does AMF communication work? | How does Flash communicate with services / scripts on servers via AMF?
Regarding the AMF libraries for Python / Perl / PHP which are easier to develop than .NET / Java:
do they execute script files, whenever Flash sends an Remote Procedure Call?
or do they communicate via sockets, to script classes that are running as... | [
"The only AMF library I'm familiar with is PyAMF, which has been great to work with so far. Here are the answers to your questions for PyAMF:\n\nI'd imagine you can run it as a script (do you mean like CGI?), but the easiest IMO is to set up an app server specifically for AMF requests\nthe easiest way is to define ... | [
8,
4
] | [] | [] | [
"actionscript_2",
"amf",
"flash",
"perl",
"python"
] | stackoverflow_0001422724_actionscript_2_amf_flash_perl_python.txt |
Q:
python: run a process with timeout and capture stdout, stderr and exit status
Possible Duplicate:
subprocess with timeout
What is the easiest way to do the following in Python:
Run an external process
Capture stdout in a string, stderr, and exit status
Set a timeout.
I would like something like this:
import pr... | python: run a process with timeout and capture stdout, stderr and exit status |
Possible Duplicate:
subprocess with timeout
What is the easiest way to do the following in Python:
Run an external process
Capture stdout in a string, stderr, and exit status
Set a timeout.
I would like something like this:
import proc
try:
status, stdout, stderr = proc.run(["ls", "-l"], timeout=10)
except pr... | [
"I hate doing the work by myself. Just copy this into your proc.py module.\nimport subprocess\nimport time\nimport sys\n\nclass Timeout(Exception):\n pass\n\ndef run(command, timeout=10):\n proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n poll_seconds = .250\n ... | [
13,
12
] | [] | [] | [
"external_process",
"process",
"python"
] | stackoverflow_0001556348_external_process_process_python.txt |
Q:
python/django for loop creating database populated with 0000-9999
Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.
def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:... | python/django for loop creating database populated with 0000-9999 | Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.
def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:
print 'The for loop is over'
what is the right way to do this, an... | [
"There may be positional default arguments, try using keywords:\nfrom django.db import transaction\n\n@transaction.commit_manually\ndef insert_serials(request):\n for i in range(0,10000):\n serial = Serial(serial=str(i),closed=False)\n serial.save()\n transaction.commit()\n print 'The for loo... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001541891_django_python.txt |
Q:
PyQt: Displaying QTextEdits over the window
I want to display some QTextEdits over my main window at arbitrary locations. Below is my first attempt. It doesn't quite work. If I create the text edits before I show the window, the text edits appear, but if I create them after I have shown the window they don't ap... | PyQt: Displaying QTextEdits over the window | I want to display some QTextEdits over my main window at arbitrary locations. Below is my first attempt. It doesn't quite work. If I create the text edits before I show the window, the text edits appear, but if I create them after I have shown the window they don't appear. What's up with that? How can I get the on... | [
"Oh, I got it. You have to call show on each widget before it appears. I guess QMainWindow.show recursively calls the method for all of its children. So just add text.show() to the end of the new_text function and it works.\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0001557864_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Getting proper code completion for Python on Vim?
I've gotten omnicompletion with Pysmell to work before, but I can't seem to do it again.
I tried following some steps online, but most, if not all, of them are to vague and assume too much that you know what you are doing to some extent.
Can someone post a full, s... | Getting proper code completion for Python on Vim? | I've gotten omnicompletion with Pysmell to work before, but I can't seem to do it again.
I tried following some steps online, but most, if not all, of them are to vague and assume too much that you know what you are doing to some extent.
Can someone post a full, step-by-step tutorial on how to get code completion work... | [
"There's also Ctrl+n in insert mode which will autocomplete based on the words it has seen in any of the open buffers (even in other tabs). \n",
"You may try Pydiction (Excerpt below)\n\nDescription Pydiction allows you to\n Tab-complete Python code in Vim,\n including: standard, custom and\n third-party modul... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0001520576_python_vim.txt |
Q:
relevant query to what is the best python method for encryption
I tried to use the gnupg.py module encryption decryption function named
" def test_encryption_and_decryption(self): "
Could i use this function by passing the key or fingerprint retrieved from public key server.
I am getting the key by this :
retk ... | relevant query to what is the best python method for encryption | I tried to use the gnupg.py module encryption decryption function named
" def test_encryption_and_decryption(self): "
Could i use this function by passing the key or fingerprint retrieved from public key server.
I am getting the key by this :
retk = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup
op=... | [
"Before you can encrypt with a key whose keyid you have, you need to import the key into the keyring. Use the import_keys function for that.\nEdit: that you cannot encrypt even after importing the key is because GPG does not trust it. This becomes apparent when you turn on verbose messages; you'll get\ngpg: <keyid>... | [
3
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0001558287_encryption_python.txt |
Q:
how do I get only the time in models
How do I format datetime to give me only the time in my model
A:
If you've got a datetime object in your template called foo, use:
{{ foo|time:"H:i" }}
Look at the time filter documentation. You're not limited to "H:i", there are lots of options around for formatting datetim... | how do I get only the time in models | How do I format datetime to give me only the time in my model
| [
"If you've got a datetime object in your template called foo, use:\n{{ foo|time:\"H:i\" }}\n\nLook at the time filter documentation. You're not limited to \"H:i\", there are lots of options around for formatting datetime objects.\nIf for some reason you're wanting to do this directly in your model (which is probabl... | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001558896_django_python.txt |
Q:
Convert from hex string to unicode
How can i convert the 'dead' string to an unicode string u'\xde\xad'?
Doing this:
from binascii import unhexlify
out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')])
creates a <type 'str'> string '\xde\xad'
Trying to use the Unicode.join() like this:
from binascii import... | Convert from hex string to unicode | How can i convert the 'dead' string to an unicode string u'\xde\xad'?
Doing this:
from binascii import unhexlify
out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')])
creates a <type 'str'> string '\xde\xad'
Trying to use the Unicode.join() like this:
from binascii import unhexlify
out = ''.join(x for x in [u''... | [
"Unicode is designed to be compatible with Latin-1, you can use that and simply decode the bytestring:\nIn [2]: unhexlify('dead').decode('latin1')\nOut[2]: u'\\xde\\xad'\n\n",
"See this Python unicode how-to, and use something akin to:\nunicode('\\x80abc', errors='replace')\n\nor\nunicode('\\x80abc', errors='igno... | [
5,
1
] | [] | [] | [
"decode",
"encode",
"python",
"unicode",
"utf_8"
] | stackoverflow_0001559065_decode_encode_python_unicode_utf_8.txt |
Q:
String arguments in Python multiprocessing
I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.
This is the code:
import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Proc... | String arguments in Python multiprocessing | I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.
This is the code:
import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start()
I ... | [
"This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element.\nTo fix this, just put a comma after the string, inside the brackets:\np = multi... | [
133,
16,
11
] | [] | [] | [
"arguments",
"multiprocessing",
"python",
"string"
] | stackoverflow_0001559125_arguments_multiprocessing_python_string.txt |
Q:
Regular Expression for HTML artifacts
I some text with HTML artifacts where the < and > of tags got dropped, so now I need something that will match a small p followed by a capital letter, like
pThe next day they....
And I also need something that will catch the trailing /p which is easier. These need to be strip... | Regular Expression for HTML artifacts | I some text with HTML artifacts where the < and > of tags got dropped, so now I need something that will match a small p followed by a capital letter, like
pThe next day they....
And I also need something that will catch the trailing /p which is easier. These need to be stripped, i.e. replaced with "" in python.
What ... | [
"Try this:\nre.sub(r\"(/?p)(?=[A-Z]|$)\", r\"<\\1>\", str)\n\nYou might want to extend the boundary assertion (here (?=[A-Z]|$)) with additional characters like whitespace.\n",
"I got is. You use backreferences,\nimport re\nsmallBig = re.compile(r'[a-z]([A-Z])')\n\n...\ncleanedString = smallBig.sub(r'\\1', dirtyS... | [
1,
1
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0001559375_html_python_regex.txt |
Q:
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools
Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.
In general, I used to ... | Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools | Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.
In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy_install|pip/cpan)
Now using pyth... | [
"The system python version and its libraries are often used by software in the distribution. As long as the software you are using are happy with the same versions of python and all the libraries as your distribution is, than using the distribution packages will work just fine.\nHowever, quite often you need develo... | [
17,
17
] | [] | [] | [
"distutils",
"pip",
"python",
"setuptools"
] | stackoverflow_0001559372_distutils_pip_python_setuptools.txt |
Q:
Embedded objects in MS Office documents using Python?
How could I create embedded objects in an MS office document using Python?
I don't need anything fancy, just what one used to do in the first version of OLE: doing a copy-paste from my application into e.g. MS Word should give me an object embedded in the Wor... | Embedded objects in MS Office documents using Python? | How could I create embedded objects in an MS office document using Python?
I don't need anything fancy, just what one used to do in the first version of OLE: doing a copy-paste from my application into e.g. MS Word should give me an object embedded in the Word document, which I can then double-click to open a copy o... | [
"OLE compound documents enable users working within a single application to manipulate data written in various formats and derived from multiple sources. A compound document object is essentially a COM object that can be embedded in, or linked to, an existing document. As a COM object, a compound document object ex... | [
1
] | [] | [] | [
"com",
"ms_office",
"ole",
"python",
"windows"
] | stackoverflow_0001559709_com_ms_office_ole_python_windows.txt |
Q:
"undefined symbol: TLSv1_method" error when import psycopg2
I installed psycopg2 by "easy_install psycopg2" on CentOS 5.3, no error was reported, but when I tried "import psycopg2", I got :
exceptions.ImportError: /usr/lib/python2.4/site-packages/psycopg2-2.0.9-py2.4-linux-i686.egg/psycopg2/_psycopg.so: undefined ... | "undefined symbol: TLSv1_method" error when import psycopg2 | I installed psycopg2 by "easy_install psycopg2" on CentOS 5.3, no error was reported, but when I tried "import psycopg2", I got :
exceptions.ImportError: /usr/lib/python2.4/site-packages/psycopg2-2.0.9-py2.4-linux-i686.egg/psycopg2/_psycopg.so: undefined symbol: TLSv1_method
What might cause the problem?
| [
"You might have to yum install openssl?\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001560066_python.txt |
Q:
Optparse library - callback action while storing arg
My code:
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs")
(options, args) = parser.parse_... | Optparse library - callback action while storing arg | My code:
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs")
(options, args) = parser.parse_args()
if x == 0:
print usage, " (-h or --help... | [
"The arguments are available through sys.argv.\n",
"Ended up passing the argument to the function that is being called.\n"
] | [
1,
0
] | [] | [] | [
"ironpython",
"optparse",
"python"
] | stackoverflow_0001560092_ironpython_optparse_python.txt |
Q:
Equivalent of GetCursorPos() in Mac's Carbon
Background
We're porting our PythonOgre-based games to Mac, and the publishers demand ability for mouse to leave the window. On Windows, we're going around OIS (Object-oriented Input System) for the purposes of mouse control; that is, we don't let OIS keep the mouse cap... | Equivalent of GetCursorPos() in Mac's Carbon | Background
We're porting our PythonOgre-based games to Mac, and the publishers demand ability for mouse to leave the window. On Windows, we're going around OIS (Object-oriented Input System) for the purposes of mouse control; that is, we don't let OIS keep the mouse captured inside window borders, and then track the mo... | [
"I believe that what you are looking for is GetMouse(). You can find an example in Apple's UIElementInspector sample code. This is in Obj-C not Python, though.\nEDIT: HIGetMousePosition() is the preferred method, according to NSD.\n"
] | [
1
] | [] | [] | [
"macos",
"macos_carbon",
"mouse",
"python"
] | stackoverflow_0001560472_macos_macos_carbon_mouse_python.txt |
Q:
Perform an action and redirecting to the same URL doesn't refresh the page
We are working on a new web site using Apache, Python and Django.
In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem.
We stand on :
http://website.fr/search/
When we want to change... | Perform an action and redirecting to the same URL doesn't refresh the page | We are working on a new web site using Apache, Python and Django.
In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem.
We stand on :
http://website.fr/search/
When we want to change the ordering of the research, we are sending the user to :
http://website.fr/se... | [
"What happens is, the browser asks for the new URL and via 302 gets redirected back to the previous one, which is in the cache and thus not refreshed. Adding a random integer, like Piotr is suggesting will solve the problem. For randomness you can use simple timestamp.\nImplication of performing forward as you are ... | [
5,
1,
0
] | [] | [] | [
"django",
"http",
"http_status_code_302",
"httpwebrequest",
"python"
] | stackoverflow_0001538994_django_http_http_status_code_302_httpwebrequest_python.txt |
Q:
Histogram in matplotlib gets cropped at top
I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where plt is matplotlib.pyplot and fig is matplotlib.figure:
plt.hist(grade... | Histogram in matplotlib gets cropped at top | I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where plt is matplotlib.pyplot and fig is matplotlib.figure:
plt.hist(grades, bins=min(20, maxScore), range=(0,maxScore), fi... | [
"File a bug report to the matplotlib's developers, and ask them to write a test case on it.\nYou should be able to set the y axis with the ylim function: is it what you are asking for? Can you show a screenshot of your problem?\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0001560734_matplotlib_python_python_imaging_library.txt |
Q:
Playing sounds with python and changing their tone during playback?
Is there a way to do this? Also, I need this to work with pygame, since I want audio in my game. I'm asking this because I didn't see any tone change function in pygame.. Anyone knows?
Update:
I need to do something like the noise of a car acceler... | Playing sounds with python and changing their tone during playback? | Is there a way to do this? Also, I need this to work with pygame, since I want audio in my game. I'm asking this because I didn't see any tone change function in pygame.. Anyone knows?
Update:
I need to do something like the noise of a car accelerating. I don't really know if it is timbre or tone.
| [
"Well, it depends on how you're doing your sounds: I'm not sure if this is possible with pygame, but SDL (which pygame is based off of) lets you have a callback to retrieve data for the sound buffer, and it's possible to change the frequency of the sine wave (or whatever) to get different tones in the callback, giv... | [
1
] | [] | [] | [
"pitch",
"pygame",
"python"
] | stackoverflow_0001561104_pitch_pygame_python.txt |
Q:
Grouping data points into series
I have a series of data points (tuples) in a list with a format like:
points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.
I need them group... | Grouping data points into series | I have a series of data points (tuples) in a list with a format like:
points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.
I need them grouped in lists by their first value in a ... | [
"One way to do it (no promises on speed):\nBreak your list of tuples into two lists:\n[1,2,2,3,4] and ['a','b','a','d','c']\nSince the first list is sorted, you can just keep iterating over it until you get to an element out of the range. Then, you know the indexes of the start and end elements so you can just slic... | [
2,
2,
2,
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"python",
"series"
] | stackoverflow_0001549412_algorithm_python_series.txt |
Q:
How do you make a shared network file read-only using Python?
Using Python, what's the correct way to set a file to be read-only when the file is located on a network share (being served from a Windows 2003 Server)?
I'm running Python 2.6.2 in OS X (10.6.1).
The following code throws an exception (as expected) whe... | How do you make a shared network file read-only using Python? | Using Python, what's the correct way to set a file to be read-only when the file is located on a network share (being served from a Windows 2003 Server)?
I'm running Python 2.6.2 in OS X (10.6.1).
The following code throws an exception (as expected) when path is local, but os.chmod appears to have no effect when path p... | [
"I am pretty sure you must have the proper settings on your local SAMBA server (/etc/samba/smb.conf) to make this behave the way you intend. There is many ways to go around permission checking if smb.conf isn't set correctly.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0001561482_python.txt |
Q:
Is it possible to use django Piston on Google AppEngine?
I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine)
I was wondering if anyone patched\forked piston to get it working... | Is it possible to use django Piston on Google AppEngine? | I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine)
I was wondering if anyone patched\forked piston to get it working on AppEngine?
| [
"http://bitbucket.org/gumptioncom/django-piston-app-engine/\n",
"It turns out the problem with Piston and AppEngine is mainly when it comes to the authentication code.\nSo, I managed to port Piston to AppEngine doing the following:\n\nI'm using the app-engine-patch project which integrates django's authentication... | [
5,
2,
1
] | [] | [] | [
"django",
"django_piston",
"google_app_engine",
"python"
] | stackoverflow_0001453909_django_django_piston_google_app_engine_python.txt |
Q:
View Windows file metadata in Python
I am writing a script to email the owner of a file when a separate process has finished. I have tried:
import os
FileInfo = os.stat("test.txt")
print (FileInfo.st_uid)
The output of this is the owner ID number. What I need is the Windows user name.
A:
Once I stopped searchi... | View Windows file metadata in Python | I am writing a script to email the owner of a file when a separate process has finished. I have tried:
import os
FileInfo = os.stat("test.txt")
print (FileInfo.st_uid)
The output of this is the owner ID number. What I need is the Windows user name.
| [
"Once I stopped searching for file meta data and started looking for file security I found exactly what I was looking for.\nimport tempfile\nimport win32api\nimport win32con\nimport win32security\n\nf = tempfile.NamedTemporaryFile ()\nFILENAME = f.name\ntry:\n sd = win32security.GetFileSecurity (FILENAME,win32secu... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0001561831_python.txt |
Q:
Using DPAPI with Python?
Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?
I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.
EDIT: I've taken the examp... | Using DPAPI with Python? | Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?
I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.
EDIT: I've taken the example code pointed to by "dF" and... | [
"I have been using CryptProtectData and CryptUnprotectData through ctypes, with the code from\nhttp://article.gmane.org/gmane.comp.python.ctypes/420\nand it has been working well.\n",
"Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module.\n",
"The easiest way would be to use... | [
10,
6,
2
] | [] | [] | [
"dpapi",
"encryption",
"python",
"security",
"windows"
] | stackoverflow_0000463832_dpapi_encryption_python_security_windows.txt |
Q:
handling db connection on daemonize threads
I have a problem handling database connections in a daemon I've been working on, I first connect to my postgres database with:
try:
psycopg2.apilevel = '2.0'
psycopg2.threadsafety = 3
cnx = psycopg2.connect( "host='192.168.10.36' dbname='db' user='vas' password='va... | handling db connection on daemonize threads | I have a problem handling database connections in a daemon I've been working on, I first connect to my postgres database with:
try:
psycopg2.apilevel = '2.0'
psycopg2.threadsafety = 3
cnx = psycopg2.connect( "host='192.168.10.36' dbname='db' user='vas' password='vas'")
except Exception, e:
print "Unable to co... | [
"Database handles don't survive across fork(). You'll need to open a new database handle in each subprocess, ie after you call daemonize() call psycopg2.connect.\nI've not used postgres but I know this to be definitely true for MySQL.\n"
] | [
1
] | [] | [] | [
"daemons",
"multithreading",
"psycopg2",
"python"
] | stackoverflow_0001561427_daemons_multithreading_psycopg2_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.