content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python List not getting in rendered in javascript
I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python
numbersvar = [0,1,2,3]
stringsvar = ['a','b','c']
The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not re... | Python List not getting in rendered in javascript | I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python
numbersvar = [0,1,2,3]
stringsvar = ['a','b','c']
The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.
| [
"Maybe it will be better to use a json module to create a javascript lists?\n>>> a = ['stste', 'setset', 'serthjsetj']\n>>> b = json.dumps(a)\n>>> b\n'[\"stste\", \"setset\", \"serthjsetj\"]'\n>>> json.loads(b)\n[u'stste', u'setset', u'serthjsetj']\n\n",
"What does stringsvar contain? The list, or the string repr... | [
3,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002100233_javascript_python.txt |
Q:
Is there a javascript equivalent to unpack sequences like in python?
Is there a javascript equivalent to unpack sequences like in python?
a, b = (1, 2)
A:
[a, b] = [1, 2]
Update:
Browser compatibility matrix:
Firefox: all versions
Opera: 9.x only
Chrome: 49 and higher
MSIE: no
EdgeHTML: 14 (Browser version 31,... | Is there a javascript equivalent to unpack sequences like in python? | Is there a javascript equivalent to unpack sequences like in python?
a, b = (1, 2)
| [
"[a, b] = [1, 2]\n\nUpdate:\nBrowser compatibility matrix:\n\nFirefox: all versions\nOpera: 9.x only\nChrome: 49 and higher\nMSIE: no\nEdgeHTML: 14 (Browser version 31, released Feb. 2016)\nSafari: 7.1 (8 for Safari Mobile)\n\n",
"There isn't. JavaScript doesn't have such syntax sugar.\n"
] | [
15,
8
] | [
"An object cannot contain a reference to an integer, only its value. So I can't see any way to do what you ask in javascript.\n"
] | [
-4
] | [
"iterable_unpacking",
"javascript",
"python"
] | stackoverflow_0002100731_iterable_unpacking_javascript_python.txt |
Q:
Python sockets, how to escape from infinite loop and handle exceptions
I have a script that connects to a remote server. The code is below
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_host,remote_port))
s.setblocking(False)
while True:
try:
data = s.recv(1024)
if no... | Python sockets, how to escape from infinite loop and handle exceptions | I have a script that connects to a remote server. The code is below
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_host,remote_port))
s.setblocking(False)
while True:
try:
data = s.recv(1024)
if not data:
break
pkt_type = ord(data[2]) # get pkt type
... | [
"A Finite State Machine (FSM) is pretty much the canonical way to do this sort of thing. A good reference for doing FSMs in Python is this: http://wiki.python.org/moin/FiniteStateMachine\n",
"EDIT:\nLooks like a FSM should be handy here.\nActually, I suggest you take a look at Twisted Reactor - haven't used it m... | [
1,
0,
0
] | [] | [] | [
"communication_protocol",
"python",
"sockets"
] | stackoverflow_0002100224_communication_protocol_python_sockets.txt |
Q:
Making a web interface to a script that takes 30 minutes to execute
I wrote a python script to process some data from CSV files. The script takes between 3 to 30 minutes to complete, depending on the size of the CSV.
Now I want to put in a web interface to this, so I can upload the CSV data files from anywhere. I ... | Making a web interface to a script that takes 30 minutes to execute | I wrote a python script to process some data from CSV files. The script takes between 3 to 30 minutes to complete, depending on the size of the CSV.
Now I want to put in a web interface to this, so I can upload the CSV data files from anywhere. I wrote a basic HTTP POST upload page and used Python's CGI module - but th... | [
"I would separate the work like this:\n\nA web app URL that accept the POSTed CSV file. The web app puts the CSV content into an off line queue, for instance a database table. The web app's response should be an unique ID for the queued item (use an auto-incremented ID column, for instance). The client must store t... | [
12,
5,
4,
2,
2,
1
] | [] | [] | [
"http_headers",
"http_status_code_504",
"python",
"timeout"
] | stackoverflow_0002101052_http_headers_http_status_code_504_python_timeout.txt |
Q:
tips on creating RSS/XML easily in python
I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?
A:
I suggest you use a template and feed the list of items to t... | tips on creating RSS/XML easily in python | I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?
| [
"I suggest you use a template and feed the list of items to the template.\nExample Jinja2 template (Atom, not RSS, but you get the idea), assuming that the items are 3-tuples (title, link, html):\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n <author>Author's name</au... | [
12,
2,
1
] | [] | [] | [
"python",
"rss",
"xml"
] | stackoverflow_0002099666_python_rss_xml.txt |
Q:
How to call a function and change a variable
I am calling a function several times as I am testing several responses. I am asking on how I call a function earlier in the program, changing a variable in this function and then calling it. Below is a snippet of the code.
class AbsoluteMove(unittest.TestCase):
d... | How to call a function and change a variable | I am calling a function several times as I am testing several responses. I am asking on how I call a function earlier in the program, changing a variable in this function and then calling it. Below is a snippet of the code.
class AbsoluteMove(unittest.TestCase):
def Ssh(self):
p=pexpect.spawn('ssh user@1... | [
"is it doable to add another parameter to Absolute Move?\n",
"You'll need to have a wrapper for the runTest function. Notice that I commented the self.command='./ptzpanposition -c 0 -u degx10' in runTest\nclass VerifyTilt(AbsoluteMove):\n def testWrapper(self):\n self.command = './ptzpanposition -c 0 -u degx1... | [
1,
0,
0,
0
] | [] | [] | [
"inheritance",
"python",
"variables"
] | stackoverflow_0002100847_inheritance_python_variables.txt |
Q:
Parsing a stdout in Python
In Python I need to get the version of an external binary I need to call in my script.
Let's say that I want to use Wget in Python and I want to know its version.
I will call
os.system( "wget --version | grep Wget" )
and then I will parse the outputted string.
How to redirect the stdo... | Parsing a stdout in Python | In Python I need to get the version of an external binary I need to call in my script.
Let's say that I want to use Wget in Python and I want to know its version.
I will call
os.system( "wget --version | grep Wget" )
and then I will parse the outputted string.
How to redirect the stdout of the os.command in a string... | [
"One \"old\" way is:\nfin,fout=os.popen4(\"wget --version | grep Wget\")\nprint fout.read()\n\nThe other modern way is to use a subprocess module:\nimport subprocess\ncmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE)\nfor line in cmd.stdout:\n if \"Wget\" in line:\n print line\n... | [
42,
10
] | [
"Use subprocess instead.\n",
"If you are on *nix, I would recommend you to use commands module.\nimport commands\n\nstatus, res = commands.getstatusoutput(\"wget --version | grep Wget\")\n\nprint status # Should be zero in case of of success, otherwise would have an error code\nprint res # Contains stdout\n\n"
] | [
-2,
-3
] | [
"python"
] | stackoverflow_0002101426_python.txt |
Q:
why 1 is ok,but 2 is error,use django and jquery
django view:
def json_view(request):
import json
tag=request.GET.get('tag')
if tag=='userName':
username=request.GET.get('userName')
result='successName'
if username:
try:
user=User.objects.get(username... | why 1 is ok,but 2 is error,use django and jquery | django view:
def json_view(request):
import json
tag=request.GET.get('tag')
if tag=='userName':
username=request.GET.get('userName')
result='successName'
if username:
try:
user=User.objects.get(username=username)
result='existName'
... | [
"Write a unit test that isolates the problem. Documentation: http://docs.djangoproject.com/en/dev/topics/testing/\nThe body of the test should be something like:\nfrom django.test.client import Client\nc = Client()\nresponse = c.get('/json_view/', {'tag': 'email', 'email': '...'})\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002099345_django_python.txt |
Q:
What is the name for [x for x in some_list] type of construct in python?
Couldn't really find it, but probably it's me not knowing how to search properly :(
Just wanted to find out what the name is for:
[x for x in some_list]
type of construct?
A:
It's a list comprehension
| What is the name for [x for x in some_list] type of construct in python? | Couldn't really find it, but probably it's me not knowing how to search properly :(
Just wanted to find out what the name is for:
[x for x in some_list]
type of construct?
| [
"It's a list comprehension\n"
] | [
14
] | [] | [] | [
"python"
] | stackoverflow_0002101826_python.txt |
Q:
How can I serialize Python objects to XML?
I need to serialize my Python objects into XML data. I tried to use Django, but it only works for QuerySet objects and not for any simple Python object.
How can I serialize a Python object into XML data?
A:
http://freshmeat.net/projects/gnosisxml/
A:
You could also ha... | How can I serialize Python objects to XML? | I need to serialize my Python objects into XML data. I tried to use Django, but it only works for QuerySet objects and not for any simple Python object.
How can I serialize a Python object into XML data?
| [
"http://freshmeat.net/projects/gnosisxml/\n",
"You could also have a look at the objectify module from lxml.\n"
] | [
3,
3
] | [] | [] | [
"python",
"serialization",
"xml_serialization"
] | stackoverflow_0002101902_python_serialization_xml_serialization.txt |
Q:
Is it possible to make user input invisible as a 'sudo' password input?
I'm using raw_input() to receive password from user in interactive mode, but I want to make input symbols invisible for security reasons, as it is when you're typing your password using sudo or connecting to a database. How I should do it?
A:... | Is it possible to make user input invisible as a 'sudo' password input? | I'm using raw_input() to receive password from user in interactive mode, but I want to make input symbols invisible for security reasons, as it is when you're typing your password using sudo or connecting to a database. How I should do it?
| [
"You need the getpass module.\nfrom getpass import getpass\npassword = getpass()\n\n"
] | [
18
] | [] | [] | [
"console",
"input",
"interaction",
"python"
] | stackoverflow_0002101975_console_input_interaction_python.txt |
Q:
What program to write pdf including other pdf on Linux from Python?
On an Ubuntu server, I want to create pdfs which include other static pdfs. I have tried using ReportLab with pyPdf. Ideally I would use ReportLab to do the whole thing, but in order to import the pdfs requires their PageCatcher which has a large ... | What program to write pdf including other pdf on Linux from Python? | On an Ubuntu server, I want to create pdfs which include other static pdfs. I have tried using ReportLab with pyPdf. Ideally I would use ReportLab to do the whole thing, but in order to import the pdfs requires their PageCatcher which has a large recurring fee.
So I use pyPdf to merge a page created with ReportLab and... | [
"I have had a lot of success with the Java library iText. They have a great library of samples for pretty much anything you could think of doing with PDF files. This example is for concatenating PDF files and sounds like it would do what you need: http://itextpdf.com/examples/index.php?page=example&id=123. There is... | [
1,
0
] | [] | [] | [
"pdf",
"pdf_generation",
"pypdf",
"python",
"reportlab"
] | stackoverflow_0002071727_pdf_pdf_generation_pypdf_python_reportlab.txt |
Q:
Subtract dict A from dict B (deep del)?
If I have a deeply nested dict is there a built-in way to subtract/remove list of "paths" (eg: keyA.keyB.key1, keyA.keyC.key2, etc) or a the keys of a second dict from the original dict? Or maybe there is a common module which has functionality like this?
A:
Here's a sugge... | Subtract dict A from dict B (deep del)? | If I have a deeply nested dict is there a built-in way to subtract/remove list of "paths" (eg: keyA.keyB.key1, keyA.keyC.key2, etc) or a the keys of a second dict from the original dict? Or maybe there is a common module which has functionality like this?
| [
"Here's a suggestion:\nD = { \"keyA\": { \n \"keyB\" : {\n \"keyC\" : 42,\n \"keyD\": 13\n },\n \"keyE\" : 55\n }\n }\n\ndef remove_path(dictionary, path):\n for node in path[:-1]:\n dictionary = dictionary[node]\n del dictionary[path[-1]]\n\nrem... | [
2,
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002100697_dictionary_python.txt |
Q:
Json communication between flash and javascript
note: using django/python/javascript/flash
So its been two days since I'm stuck at the error. I did the things you told me to and found a couple of ways around it but nothing worked. These are the results.
Javascript does not receive the normal string it has to be a ... | Json communication between flash and javascript | note: using django/python/javascript/flash
So its been two days since I'm stuck at the error. I did the things you told me to and found a couple of ways around it but nothing worked. These are the results.
Javascript does not receive the normal string it has to be a json object so. in views.py
somestring = json.dumps(... | [
"why do you communicate between flash and js via json? actionscript has a very powerfull build in ExternalInterface to communicate with javascript.\n"
] | [
1
] | [] | [] | [
"flash",
"json",
"python"
] | stackoverflow_0002102294_flash_json_python.txt |
Q:
Django primary key
When querying in django say People.objects.all(pk=code), what does pk=code mean?
A:
Calling People.objects.all(pk=code) (calling all) will result in the pk=code being ignored and a QuerySet for all People returned.
Calling People.objects.get(pk=code) (calling get) will result in the People obj... | Django primary key | When querying in django say People.objects.all(pk=code), what does pk=code mean?
| [
"Calling People.objects.all(pk=code) (calling all) will result in the pk=code being ignored and a QuerySet for all People returned.\nCalling People.objects.get(pk=code) (calling get) will result in the People object with pk=code returned, or an error if not found.\n",
"It's a query to get the People object that h... | [
7,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002101838_django_python.txt |
Q:
Python Send Keystrokes to Non-Active Application
I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like t... | Python Send Keystrokes to Non-Active Application | I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in the ... | [
"SendKeys is a Python module for Windows that can send one or more keystrokes or keystroke combinations to the active window.\n\nIf you need to do some automated work in the background, make another user/session and do it in that.\nHowever if you must do something of this like on windows, I always reach for autoit.... | [
3,
3,
2
] | [] | [] | [
"python",
"sendkeys"
] | stackoverflow_0002098480_python_sendkeys.txt |
Q:
Why python multiprocessing module cause CPU completely run out?
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
I am trying python 2.6 multiprocessing module with this simple code snippet.
from multiprocessing import Pool
p = Pool(5)
def f(x):
return x*x
print p.map(f, [1,2,3])... | Why python multiprocessing module cause CPU completely run out? |
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
I am trying python 2.6 multiprocessing module with this simple code snippet.
from multiprocessing import Pool
p = Pool(5)
def f(x):
return x*x
print p.map(f, [1,2,3])
But this code cause my OS stopped responding. It looks like the C... | [
"You aren't protecting the entry point at all, so each subprocess is trying to start the same map call and so on (into infinity!). Try the following:\nif __name__ == \"__main__\":\n print p.map(f, [1,2,3])\n\nSee this section of the module's documentation.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0002102354_python.txt |
Q:
wxPython - lines drawn with Device Context disappear when focus changes
I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window?
class SimpleDraw(wx... | wxPython - lines drawn with Device Context disappear when focus changes | I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window?
class SimpleDraw(wx.Frame):
def __init__(self, parent, id, title, size=(640, 480)):
self.p... | [
"Your issue is that you are only drawing when the user clicks. The resize/erase (when another window covers yours) problems are because your window doesn't maintain a \"buffer\" which it can redraw.\nHere, I've modified your sample, it seems to be working okay.\nimport wx\n\nclass SimpleDraw(wx.Frame):\n def __i... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002098482_python_wxpython.txt |
Q:
How can multiple calculations be launched in parallel, while stopping them all when the first one returns? [Python]
How can multiple calculations be launched in parallel, while stopping them all when the first one returns?
The application I have in mind is the following: there are multiple ways of calculating a ce... | How can multiple calculations be launched in parallel, while stopping them all when the first one returns? [Python] | How can multiple calculations be launched in parallel, while stopping them all when the first one returns?
The application I have in mind is the following: there are multiple ways of calculating a certain value; each method takes a different amount of time depending on the function parameters; by launching calculations... | [
"I would look at the multiprocessing module if you haven't already. It offers a way of offloading tasks to separate processes whilst providing you with a simple, threading like interface.\nIt provides the same kinds of primatives as you get in the threading module, for example, worker pools and queues for passing ... | [
1,
0,
0
] | [] | [] | [
"multiple_processes",
"parallel_processing",
"python"
] | stackoverflow_0002102216_multiple_processes_parallel_processing_python.txt |
Q:
why this dos command does not work inside python?
I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
... | why this dos command does not work inside python? | I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
i... | [
"\\ (backslash) is an escape character within string constants, so your string ends up changed. Use double \\s (like so \\\\) within string constants:\n\nsubprocess.Popen('rd /s /q .\\\\ProcessControlSimulator\\\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n",
"My advice is try not to us... | [
12,
9,
7,
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002102452_python_subprocess.txt |
Q:
problem in installing django
problem with installing django
i am geting folllowing error
E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1>setup.py install
Traceback (most recent call last):
File "E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1\setup.py", line
48, in ?
root_dir = os.path.dirnam... | problem in installing django | problem with installing django
i am geting folllowing error
E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1>setup.py install
Traceback (most recent call last):
File "E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1\setup.py", line
48, in ?
root_dir = os.path.dirname(__file__)
NameError: name '__fil... | [
"The Python version you are using, 2.2, is more than seven years old. Django is only compatible with versions 2.4 upwards.\n",
"You should usepython setup.py install\n"
] | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002101132_django_python.txt |
Q:
Prepare a string for Google Ajax Search?
I have strings such as
["Tabula Rasa", "façade", "DJ Tiësto"]
I'm accessing Google Ajax API in Python using the base url:
base = 'http://ajax.googleapis.com/ajax/services/search/web'
'?v=1.0&q=%s'
I'm having issues using these strings plain and noticed I have to transf... | Prepare a string for Google Ajax Search? | I have strings such as
["Tabula Rasa", "façade", "DJ Tiësto"]
I'm accessing Google Ajax API in Python using the base url:
base = 'http://ajax.googleapis.com/ajax/services/search/web'
'?v=1.0&q=%s'
I'm having issues using these strings plain and noticed I have to transform certain characters,
eg. "Tabula Rasa" -->... | [
"What you're looking for is urllib.quote():\n>>> urllib.quote(\"Tabula Rasa\")\n'Tabula%20Rasa'\n\nThe non-ASCII strings may need to be recoded into the encoding expected by the Google AJAX API, if you don't have them in the same encoding already.\n"
] | [
2
] | [] | [] | [
"google_ajax_api",
"google_api",
"python",
"url"
] | stackoverflow_0002103317_google_ajax_api_google_api_python_url.txt |
Q:
determine the type of a value which is represented as string in python
When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below.
import csv
a = "1,2,3,4,5"
r = csv.reader([a])
for row in r:
d = row
d
['1', '2', '3', '4', '5']
type(d[0])... | determine the type of a value which is represented as string in python | When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below.
import csv
a = "1,2,3,4,5"
r = csv.reader([a])
for row in r:
d = row
d
['1', '2', '3', '4', '5']
type(d[0])
<type 'str'>
I want to determine for each value if it is a string, float, ... | [
"You could do something like this:\nfrom datetime import datetime\n\ntests = [\n # (Type, Test)\n (int, int),\n (float, float),\n (datetime, lambda value: datetime.strptime(value, \"%Y/%m/%d\"))\n]\n\ndef getType(value):\n for typ, test in tests:\n try:\n test(value)\n ... | [
15,
7,
2,
1,
1,
0,
0
] | [] | [] | [
"casting",
"csv",
"python",
"types"
] | stackoverflow_0002103071_casting_csv_python_types.txt |
Q:
Python newbie class design question
I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User".
class User(object):
def __init__(self):
pass
class Users(... | Python newbie class design question | I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User".
class User(object):
def __init__(self):
pass
class Users(object):
def __init__(self):
se... | [
"I would say not really. Your Users class appears to just be a list of users, so I would just make it a list rather than a whole class. Here's what I would do:\nclass User(object):\n def __init__(self, user_id=None, email=None):\n self.user_id, self.email = user_id, email\n\nusers = []\nusers.append(User(... | [
17,
11,
6,
4,
1
] | [] | [] | [
"iterator",
"oop",
"python"
] | stackoverflow_0002103532_iterator_oop_python.txt |
Q:
Re-creating threading and concurrency knowledge in increasingly popular languages
I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurre... | Re-creating threading and concurrency knowledge in increasingly popular languages | I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.
As I start to learn more about Python, Ruby, and other language... | [
"The basic principles of concurrent programming existed before java and were summarized in those java books you're talking about. The java.util.concurrent library was similarly derived from previous code and research papers on concurrent programming.\nHowever, some implementation issues are specific to Java. It has... | [
11,
5,
3,
1,
1
] | [] | [] | [
"concurrency",
"java",
"multithreading",
"python",
"ruby"
] | stackoverflow_0000440036_concurrency_java_multithreading_python_ruby.txt |
Q:
Two forms in django templates without conflict
I'm creating a template with two different forms but I have the following problem: when I submit the first one the second is also validated and get validation errors. What can I do to avoid this conflict?
Thanks and sorry for my english.
A:
use the prefix argument o... | Two forms in django templates without conflict | I'm creating a template with two different forms but I have the following problem: when I submit the first one the second is also validated and get validation errors. What can I do to avoid this conflict?
Thanks and sorry for my english.
| [
"use the prefix argument on your forms\n"
] | [
5
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0002103805_django_django_forms_django_templates_python.txt |
Q:
Django: Check on type of relation a form has
I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.
Example:
#models.py
class BaseClass(models.Model):
# Some generic stuff.
class SomeClass(BaseClass):
# This clas... | Django: Check on type of relation a form has | I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models.
Example:
#models.py
class BaseClass(models.Model):
# Some generic stuff.
class SomeClass(BaseClass):
# This class doesnt have any many2many relations
class SomeO... | [
"if hasattr(form, 'save_m2m'):\n form.save_m2m()\n\nYou should bear in mind that save_m2m is only necessary (and only exists) when you call form.save with commit=False argument. If you save it with commit=True which is the default, there's no need in save_m2m.\n",
"I just figured out the probable solution for ... | [
0,
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0002100297_django_django_views_python.txt |
Q:
Efficiently search two-tuple
What's the best one-liner replacement for the code below? I'm sure there's a smarter way.
choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE'))
some_int = 2
for choice in choices:
if choice[0] == some_int:
label = choice[1]
break;
# label == 'TWO'
A:
labels = dict(choi... | Efficiently search two-tuple | What's the best one-liner replacement for the code below? I'm sure there's a smarter way.
choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE'))
some_int = 2
for choice in choices:
if choice[0] == some_int:
label = choice[1]
break;
# label == 'TWO'
| [
"labels = dict(choices)\nlabel = labels[some_int]\n\nyou could, of course, join this into an one-liner, if you don't need labels anywhere else.\n",
"You could use a dict.\n>>> choices = { 1: 'ONE', 2: 'TWO', 3: 'THREE' }\n>>> label = choices[2]\n>>> label\n'TWO'\n\n",
"For a one-off search, if you're committed ... | [
14,
6,
5,
3
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0002104095_python_tuples.txt |
Q:
Python tool to balance parentheses, quotes, and brackets
Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.)
I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement"... | Python tool to balance parentheses, quotes, and brackets | Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.)
I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement" and start swearing, because it means that somewhere in about ... | [
"I use Eclipse with PyDev. It's very good for this sort of thing, and lots more.\n",
"emacs will automatically highlight matching pairs of parentheses/brackets/quotes/etc. as you type them, and it will inform you immediately if you mismatch them (e.g. if you type a [ followed by a )). I'm sure vim also does thi... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002104227_python.txt |
Q:
Django/Python: How do you start a new process in Python?
After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that b... | Django/Python: How do you start a new process in Python? | After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that because I don't care if it's actually multithreaded or if it's ... | [
"If you want to call an external process, use the subprocess module. \nIf on the other hand you want to side-step the GIL and spin of some Python task, use the multiprocessing module. It provides an interface very much like the threading package's but utilizes subprocesses so you are not bound by the constraints ... | [
2
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0002104235_django_multithreading_python.txt |
Q:
wx.DatePickerCtrl in dialog ignores value entered after hitting return on wxGTK
I have a dialog with a date picker control. Hitting enter in the date picker closes the dialog (as expected). However, the date picker doesn't pick up the value entered by the user on wxGTK. Run the sample attached, click the button, e... | wx.DatePickerCtrl in dialog ignores value entered after hitting return on wxGTK | I have a dialog with a date picker control. Hitting enter in the date picker closes the dialog (as expected). However, the date picker doesn't pick up the value entered by the user on wxGTK. Run the sample attached, click the button, enter a new date in the date picker, using the keyboard, and hit enter. The print stat... | [
"I had a similar problem. I tried to just call datepicker.Navigate() every time before retrieving the date from the DatePickerCtrl with datepicker.GetValue(). It seemed to work.\n",
"This seems to work-around the issue:\nimport wx\n\nclass Dialog(wx.Dialog):\n def __init__(self, *args, **kwargs):\n supe... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001568491_python_wxpython.txt |
Q:
Can a process keep running after the user sees the "Thanks. You're done!" page
I'm trying to understand threading better. If I create a program that allows people to upload a photo and then I create a new process to resize the image in a hundred ways (taking 5 seconds or longer), and the main program returns a res... | Can a process keep running after the user sees the "Thanks. You're done!" page | I'm trying to understand threading better. If I create a program that allows people to upload a photo and then I create a new process to resize the image in a hundred ways (taking 5 seconds or longer), and the main program returns a response HTML page to the user saying "Thanks. You're done!", can the other process sti... | [
"Considering a Message or Job Queue is a good idea when you have background processing to do. This way you won't have to write your own code to handle job scheduling, priority etc. You can also add more servers to the queue when the first one starts running out of capacity.There's a package called Celery that is su... | [
9
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0002104313_django_multithreading_python.txt |
Q:
Load and Reuse Django Template Filters
Is it possible to load a django template tag/filter to use as a function in one of my template tags?
I'm trying to load up some of the django.contrib.humanize filters so I can apply them to the results of some of my custom template tags. I can't seem to import them at all, a... | Load and Reuse Django Template Filters | Is it possible to load a django template tag/filter to use as a function in one of my template tags?
I'm trying to load up some of the django.contrib.humanize filters so I can apply them to the results of some of my custom template tags. I can't seem to import them at all, and I don't want to have to rewrite any of th... | [
"Template tags are just Python functions; you can import their module and call them with impunity, the only requirement being that you pass them appropriate arguments. The django.contrib.humanize.templatetags.humanize module has separate functions to do the work, so it's even easier in that specific case.\n"
] | [
3
] | [] | [] | [
"django",
"python",
"templatetags"
] | stackoverflow_0002104767_django_python_templatetags.txt |
Q:
Python: Replacing item in a list of lists
Heres my code:
data = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
]
element = 4
x = 0
y = 0
data[x][y] = element
I want t... | Python: Replacing item in a list of lists | Heres my code:
data = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
]
element = 4
x = 0
y = 0
data[x][y] = element
I want to replace the element at coordinates 0,0 but wh... | [
"Works just fine for me...\n>>> data = [\n... [5,3,0,0,7,0,0,0,0],\n... [6,0,0,1,9,5,0,0,0],\n... [0,9,8,0,0,0,0,6,0],\n... [8,0,0,0,6,0,0,0,3],\n... [4,0,0,8,0,3,0,0,1],\n... [7,0,0,0,2,0,0,0,6],\n... [0,6,0,0,0,0,2,8,0],\n... [0,0,0,4,1,9,0,0,5],\n... [0,0,0,0,8,0,0,7,9]\n... ]\n>>> element = 4\n>>> x = 0\n>>> y ... | [
1,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002104796_python.txt |
Q:
QObject (QPlainTextEdit) & Multithreading issues
Im currently trying to learn Networking with Python asyncore and pyqt4.
I coded a small server, which basically listens on some port, and resends all messages it recieves to the sender.
Since both qts QApplication.exec_() and asyncore.loop() are functions which neve... | QObject (QPlainTextEdit) & Multithreading issues | Im currently trying to learn Networking with Python asyncore and pyqt4.
I coded a small server, which basically listens on some port, and resends all messages it recieves to the sender.
Since both qts QApplication.exec_() and asyncore.loop() are functions which never return i could not start them both in one thread, so... | [
"It appears you're trying to access QtGui classes from a thread other than the main thread. Like in some other GUI toolkits (e.g. Java Swing), that's not allowed. From the Threads and QObjects web page:\n\nAlthough QObject is reentrant, the GUI\n classes, notably QWidget and all its\n subclasses, are not reentran... | [
15
] | [] | [] | [
"asyncore",
"multithreading",
"pyqt4",
"python",
"qt4"
] | stackoverflow_0002104779_asyncore_multithreading_pyqt4_python_qt4.txt |
Q:
why no color output with Python?
I have a batch file which calls .Net solution to build the project. On the dos console window, the warning and error will be in different color, green and red, looks nice. When the batch file called from Python, no color at all, all in a single color. Is it possible to get the same... | why no color output with Python? | I have a batch file which calls .Net solution to build the project. On the dos console window, the warning and error will be in different color, green and red, looks nice. When the batch file called from Python, no color at all, all in a single color. Is it possible to get the same colorful result with python? my call ... | [
"Some programs test to see if they're actually connected to a console/terminal, and suppress attribute changes if they're not in order to make it easier to parse/process the output. I know that on *nix systems you can use unbuffer to fool the program, but I don't know if there's a Windows equivalent.\n",
"If this... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0002104785_python.txt |
Q:
Django queryset that returns all unassigned fks
I have 2 models with a 1-1 relation (essentially a resource pool). For the example code, I will simply use nuts and bolts. There will be many more nuts (available resources) than bolts (which will each require 1 nut). However, if a nut can only be assigned to one ... | Django queryset that returns all unassigned fks | I have 2 models with a 1-1 relation (essentially a resource pool). For the example code, I will simply use nuts and bolts. There will be many more nuts (available resources) than bolts (which will each require 1 nut). However, if a nut can only be assigned to one bolt.
The constraint is easy enough to set up with th... | [
"Try this:\nself.fields['nut'].queryset = Nut.objects.exclude(\n pk__in=Bolt.objects.values('nut').query)\n\nUpdate:\nOf three expressions generating the same sql query:\npk__in=Bolt.objects.values('nut')\npk__in=Bolt.objects.values_list('nut')\npk__in=Bolt.objects.values('nut').query\n\nI'd choose the last one ... | [
4,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002104921_django_django_models_python.txt |
Q:
Adding arrays with different number of dimensions
Let's say I have a 2D Numpy array:
>>> a = np.random.random((4,6))
and I want to add a 1D array to each row:
>>> c = np.random.random((6,))
>>> a + c
This works. Now if I try adding a 1D array to each column, I get an error:
>>> b = np.random.random((4,))
>>> a +... | Adding arrays with different number of dimensions | Let's say I have a 2D Numpy array:
>>> a = np.random.random((4,6))
and I want to add a 1D array to each row:
>>> c = np.random.random((6,))
>>> a + c
This works. Now if I try adding a 1D array to each column, I get an error:
>>> b = np.random.random((4,))
>>> a + b
Traceback (most recent call last):
File "<stdin>",... | [
"This is a distinctive feature of numpy called 'broadcasting':\nif you can multiply a vector by a scalar why not allow multiplying a matrix by a vector? Just like every element of a vector is multiplied by a scalar in the first case, every cell in the matrix row is multiplied by the corresponding vector element in ... | [
13,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002104643_numpy_python.txt |
Q:
Error Installing Gitosis on Fedora Core
I'm trying to follow these instructions on installing gitosis:
http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way
and these:
http://www.webtop.com.au/installing-git-and-gitosis-on-fedora-10
And at the point where I need to clone the gitosis-admin.... | Error Installing Gitosis on Fedora Core | I'm trying to follow these instructions on installing gitosis:
http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way
and these:
http://www.webtop.com.au/installing-git-and-gitosis-on-fedora-10
And at the point where I need to clone the gitosis-admin.git repository from the server I'm setting up... | [
"Make sure you're running that command as the git user, and make sure that the git user owns the /home/git directory. \nAre you running git clone git@yourserver:gitosis-admin.git ?\nIt sounds like one of those things is not the case.\n"
] | [
0
] | [] | [] | [
"fedora",
"git",
"gitosis",
"linux",
"python"
] | stackoverflow_0002105390_fedora_git_gitosis_linux_python.txt |
Q:
In Jinja2, how can I use macros in combination with block tags?
I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses mac... | In Jinja2, how can I use macros in combination with block tags? | I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses macros to support passing of arguments.
My base template contains this c... | [
"Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a set tag will be accessible from the template it is extending. For example, if you have a template named layout.html:\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n\"http://www.w3.org/... | [
22
] | [] | [] | [
"django",
"django_templates",
"jinja2",
"python",
"templates"
] | stackoverflow_0002104957_django_django_templates_jinja2_python_templates.txt |
Q:
SVN serve and PySVN Error message: Expected FS format between '1' and '3'; found format '4'
For research purposes, I copied a SVN repo to my Windows machine using svnsync so I can replay on my machine without loading the actual server.
I've been using PySVN in scripts to control the revision number I want the repo... | SVN serve and PySVN Error message: Expected FS format between '1' and '3'; found format '4' | For research purposes, I copied a SVN repo to my Windows machine using svnsync so I can replay on my machine without loading the actual server.
I've been using PySVN in scripts to control the revision number I want the repo to be in and have been using it fine so far. Now I got a repo from a different project and svnsy... | [
"Which version of ubuntu you have? 9.04? It does not have subversion 1.6 afair.\nWhat versions do\ndpkg -l subversion\ndpkg -l python-svn\n\nreport?\n"
] | [
1
] | [] | [] | [
"pysvn",
"python",
"svn",
"ubuntu"
] | stackoverflow_0002105456_pysvn_python_svn_ubuntu.txt |
Q:
os.walk() python: xml representation of a directory structure, recursion
So I am trying to use os.walk() to generate an XML representation of a directory structure. I seem to be getting a ton of duplicates. It properly places directories within each other and files in the right place for the first portion of the x... | os.walk() python: xml representation of a directory structure, recursion | So I am trying to use os.walk() to generate an XML representation of a directory structure. I seem to be getting a ton of duplicates. It properly places directories within each other and files in the right place for the first portion of the xml file; however, after it does it correctly it then continues traversing inco... | [
"I'd recommend against using os.walk(), since you have to do so much to massage its output. Instead, just use a recursive function that uses os.listdir(), os.path.join(), os.path.isdir(), etc.\nimport os\nfrom xml.sax.saxutils import escape as xml_escape\n\ndef DirAsXML(path):\n result = '<dir>\\n<name>%s</name... | [
9,
6,
0
] | [] | [] | [
"directory_structure",
"os.walk",
"python",
"recursion",
"xml"
] | stackoverflow_0002104997_directory_structure_os.walk_python_recursion_xml.txt |
Q:
OOP Design - In Python, is this a quality OO Design or an epic fail?
In a system that accepts orders which have payments which have gateway transactions should the objects be like this:
class Order(object):
... Inside init ...
self.total_in_dollars = <Dollar Amount>
self.is_paid = <Boolean ... | OOP Design - In Python, is this a quality OO Design or an epic fail? | In a system that accepts orders which have payments which have gateway transactions should the objects be like this:
class Order(object):
... Inside init ...
self.total_in_dollars = <Dollar Amount>
self.is_paid = <Boolean Value>
class Payment(object):
... Inside init ...
self.or... | [
"You appear to be assigning what should obviously be instance variables as class variables, which is clearly a very wrong tack to take. IOW, the variables should be self.total_in_dollars (for instance of Order) and so forth, assigned in __init__, not class-variables, assigned in the class statement!\nSimply creati... | [
6,
2,
2
] | [] | [] | [
"django",
"oop",
"python"
] | stackoverflow_0002105376_django_oop_python.txt |
Q:
Help creating model for Django app
I'm trying to make a childcare administration app with Django but I've some problems with the payments code.
Each kid has to pay monthly 10 times a year. These payments have some particularities:
Some kids could pay a different amount of money depending on the economical situati... | Help creating model for Django app | I'm trying to make a childcare administration app with Django but I've some problems with the payments code.
Each kid has to pay monthly 10 times a year. These payments have some particularities:
Some kids could pay a different amount of money depending on the economical situation of the parents.
The amount of the pay... | [
"No matter how your final models will look like, assuming that you will keep Payment model, you could add to it two fields:\n payment_date = model.DateField()\n already_paid = models.BooleanField()\n\nThen, to get overdue payments, you will be able to make a query:\n Payment.objects.filter(payment_date__lt... | [
0,
0
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0002104033_django_models_python.txt |
Q:
App Engine urlfetch is raising exceptions when i think it should not be
I've written my first Python application with the App Engine APIs, it is intended to monitor a list of servers and notify me when one of them goes down, by sending a message to my iPhone using Prowl, or sending me an email, or both.
Problem is... | App Engine urlfetch is raising exceptions when i think it should not be | I've written my first Python application with the App Engine APIs, it is intended to monitor a list of servers and notify me when one of them goes down, by sending a message to my iPhone using Prowl, or sending me an email, or both.
Problem is, a few times a week it notifies me a server is down even when it clearly isn... | [
"other folks have been reporting issues with the fetch service (e.g. http://code.google.com/p/googleappengine/issues/detail?id=1902&q=urlfetch&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component)\ncan you print the exception, it may have more detail, e.g.:\n\"DownloadError: Application... | [
2
] | [] | [] | [
"google_app_engine",
"monitoring",
"python"
] | stackoverflow_0002105971_google_app_engine_monitoring_python.txt |
Q:
Do OO design principles apply to Python?
It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).
Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?
A:
The biggest... | Do OO design principles apply to Python? | It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).
Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?
| [
"The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make in... | [
36,
13,
4,
4,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0000546479_oop_python.txt |
Q:
Identifying numeric and array types in numpy
Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric qu... | Identifying numeric and array types in numpy | Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard... | [
"As others have answered, there could be other numeric types besides the ones you mention.\nOne approach would be to check explicitly for the capabilities you want, with something like\n# Python 2\ndef is_numeric(obj):\n attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']\n return all(hasattr(obj,... | [
20,
7,
6,
1,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0000500328_numpy_python.txt |
Q:
Can you separate python projects logically into separate files/classes like in C#/Java?
I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done?
Also, do... | Can you separate python projects logically into separate files/classes like in C#/Java? | I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done?
Also, do things like "namespaces" and "projects" exist in this realm? As well as object oriented pri... | [
"Yes, you can, and you should! :)\nHere is a nice introduction to Python Modules (including packages).\n\nCorrection: you probably should not put each single class into a separate file (like Java mandates and many C++ places do). The language is pretty lax about it as you can see in the linked tutorial, keep an ope... | [
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002106271_python.txt |
Q:
Where (at which point in the code) does pyAMF client accept SSL certificate?
I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below)
The code below works fine, but I don't understand at which point th... | Where (at which point in the code) does pyAMF client accept SSL certificate? | I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below)
The code below works fine, but I don't understand at which point the client accepts the certificate
Server:
import os.path
import logging
import cher... | [
"PyAMF uses httplib under the hood to power the remoting requests. When connecting via https://, httplib.HTTPSConnection is used as the connection attribute to the RemotingService.\nIt states in the docs that (in reference to HTTPSConnection):\n\nNote: This does not do any certificate verification\n\nSo, in answer ... | [
2
] | [] | [] | [
"certificate",
"cherrypy",
"pyamf",
"python",
"ssl"
] | stackoverflow_0002084292_certificate_cherrypy_pyamf_python_ssl.txt |
Q:
Passing C function pointers between two python modules
I'm writing an application working with plugins. There are two types of plugins: Engine and Model. Engine objects have an update() method that call the Model.velocity() method.
For performance reasons these methods are allowed to be written in C. This means th... | Passing C function pointers between two python modules | I'm writing an application working with plugins. There are two types of plugins: Engine and Model. Engine objects have an update() method that call the Model.velocity() method.
For performance reasons these methods are allowed to be written in C. This means that sometimes they will be written in Python and sometimes wr... | [
"The CObject (PyCOBject) data type exists for this purpose. It holds a void*, but you can store any data you wish. You do have to be careful not to pass the wrong CObject to the wrong functions, as some other library's CObjects will look just like your own.\nIf you want more type security, you could easily roll you... | [
1
] | [] | [] | [
"c",
"function_pointers",
"python"
] | stackoverflow_0002106324_c_function_pointers_python.txt |
Q:
CherryPy changes my response code
In my python application using mod_wsgi and cherrypy ontop of Apache my response code get changed to a 500 from a 403. I am explicitly setting this to 403.
i.e.
cherrypy.response.status = 403
I do not understand where and why the response code that the client receives is 500. ... | CherryPy changes my response code | In my python application using mod_wsgi and cherrypy ontop of Apache my response code get changed to a 500 from a 403. I am explicitly setting this to 403.
i.e.
cherrypy.response.status = 403
I do not understand where and why the response code that the client receives is 500. Does anyone have any experience with th... | [
"The HTTP 500 error is used for internal server errors. Something in the server or your application is likely throwing an exception, so no matter what you set the response code to be before this, CherryPy will send a 500 back.\nYou can look into whatever tools CherryPy includes for debugging or logging (I'm not fa... | [
1
] | [] | [] | [
"apache",
"cherrypy",
"mod_wsgi",
"python"
] | stackoverflow_0002106377_apache_cherrypy_mod_wsgi_python.txt |
Q:
pydev issue with gobject
It seems that Pydev (1.5.4) on Eclipse (3.5.1) with Python 2.6 isn't able to correctly cross-reference the package gobject. Putting import gobject works OK but any more than that (e.g. class X(gobject.GObject) causes Pydev to report "unresolved reference" errors.
What could be the problem... | pydev issue with gobject | It seems that Pydev (1.5.4) on Eclipse (3.5.1) with Python 2.6 isn't able to correctly cross-reference the package gobject. Putting import gobject works OK but any more than that (e.g. class X(gobject.GObject) causes Pydev to report "unresolved reference" errors.
What could be the problem?
Note that every other packag... | [
"The issue is related to this limitation of PyDev:\n\nI have a library installed and Pydev\n does not find it\nWell, problems have been reported on\n Mac and Linux, and the main reason\n seems to be symlinks. Pydev will only\n find extensions that are 'really'\n below the python install directory.\n This happ... | [
1
] | [] | [] | [
"gobject",
"linux",
"pydev",
"python"
] | stackoverflow_0002106349_gobject_linux_pydev_python.txt |
Q:
What is the purpose of pinax's groups?
I viewed the DjangoCon 2009 talks about pinax by James Tauber and pydanny and heared about pinax's groups. But I don't get the actual usecases they describe, even after reading the documentation.
So what is the real purpose of groups and what advantages do I get in using them... | What is the purpose of pinax's groups? | I viewed the DjangoCon 2009 talks about pinax by James Tauber and pydanny and heared about pinax's groups. But I don't get the actual usecases they describe, even after reading the documentation.
So what is the real purpose of groups and what advantages do I get in using them?
It would be nice if you could provide a si... | [
"Say you have a wiki app or a todo app and you don't want your site just to have one wiki and one todo list. Say that you want your site to have teams where each team gets its own wiki and todo list.\nThe groups app in Pinax provides the base for you to built your teams app on. It helps you create a new model (Team... | [
6
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0002098190_django_pinax_python.txt |
Q:
using django and twisted together
1)I want to devlop a website that has forums and chat.The chat and forums are linked in some way.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum.
I was thinking of using django for forums and twisted for chat thing.Can ... | using django and twisted together | 1)I want to devlop a website that has forums and chat.The chat and forums are linked in some way.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum.
I was thinking of using django for forums and twisted for chat thing.Can i combine the two?
The chat application... | [
"I would not combine the two per se; calls into Django would happen synchronously which means that Twisted's event loop would be blocked. Better to treat the Twisted process as a standalone app using Django and to have a classic web server handle the Django app.\nYou are not likely to find a shared host that will a... | [
13,
10,
1
] | [] | [] | [
"chat",
"django",
"forums",
"python",
"twisted"
] | stackoverflow_0002099189_chat_django_forums_python_twisted.txt |
Q:
how can i active my account,i send email to me use django-registration
Thank you for registering an account at example.com.
To activate your registration, please visit the following page:
http://example.com/activate/d5544f645c80f8a6c9af934c03a2ee2d7902dc1f/
This page will expire in 7 days.
example.com?????
i cl... | how can i active my account,i send email to me use django-registration | Thank you for registering an account at example.com.
To activate your registration, please visit the following page:
http://example.com/activate/d5544f645c80f8a6c9af934c03a2ee2d7902dc1f/
This page will expire in 7 days.
example.com?????
i click the url,but not active my account.
why????
| [
"Googling produces this: http://codespatter.com/2009/01/05/django-settings-site-domain-examplecom/\n\nYou can change it through the Django admin interface, phpMyAdmin, or however you feel comfortable. It’s in the django_site table. When setting SITE_ID in settings.py it is the ID in this table.\n\nSo it looks like ... | [
2,
0
] | [] | [] | [
"django",
"python",
"registration"
] | stackoverflow_0002106559_django_python_registration.txt |
Q:
python, regex to find anchor link html
I need a regex in python to find a links html in a larger set of html.
so if I have:
<ul class="something">
<li id="li_id">
<a href="#" title="myurl">URL Text</a>
</li>
</ul>
I would get back:
<a href="#" title="myurl">URL Text</a>
I'd like to do it with a regex and not... | python, regex to find anchor link html | I need a regex in python to find a links html in a larger set of html.
so if I have:
<ul class="something">
<li id="li_id">
<a href="#" title="myurl">URL Text</a>
</li>
</ul>
I would get back:
<a href="#" title="myurl">URL Text</a>
I'd like to do it with a regex and not beautifulsoup or something similar to that.... | [
"Soup is good for you:\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('''<ul class=\"something\">\n... <li id=\"li_id\">\n... <a href=\"#\" title=\"myurl\">URL Text</a>\n... </li>\n... </ul>''')\n\nThere are many arguments you can pass to the findAll method; more here. The one line below wi... | [
4,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002106597_python_regex.txt |
Q:
Python win32 service
I am fairly new to python, and have no experience with writing services for windows. I have tried to hack together a windows service based on afew tutorials i have found out there.
I need this service to constantly monitor a directory for changes and when it sees a change it runs a script. Her... | Python win32 service | I am fairly new to python, and have no experience with writing services for windows. I have tried to hack together a windows service based on afew tutorials i have found out there.
I need this service to constantly monitor a directory for changes and when it sees a change it runs a script. Here is what i have so far:
i... | [
"One thing to keep in mind with Windows services is that by default, they run under the LOCAL_SYSTEM account. This means that permissions to local volumes apply (LOCAL_SYSTEM can certainly be denied access to any given folder), and that LOCAL_SYSTEM does not have any access to any network volumes.\n",
"I'm not fa... | [
2,
1
] | [] | [] | [
"python",
"pywin32",
"service",
"winapi"
] | stackoverflow_0002106366_python_pywin32_service_winapi.txt |
Q:
Is a reason I can't add a ManyToManyField?
So I'm building a Django application,
and these are a few models I have:
class MagicType(models.Model):
name = models.CharField(max_length=155)
parent = models.ForeignKey('self', null=True, blank=True)
class Spell(models.Model):
name = models.CharField(ma... | Is a reason I can't add a ManyToManyField? | So I'm building a Django application,
and these are a few models I have:
class MagicType(models.Model):
name = models.CharField(max_length=155)
parent = models.ForeignKey('self', null=True, blank=True)
class Spell(models.Model):
name = models.CharField(max_length=250, db_index=True)
magic_words = m... | [
"Is MagicType declared in the same models file (and before) Spell?\nDoes magic_types = models.ManyToManyField('MagicType') work (with 'MagicType' quoted)? \n",
"I suggest you use django-extensions , this will give you a commnad sqldiiff that works better than evolution, because there is a problem creating the in... | [
3,
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002098696_django_django_models_python.txt |
Q:
Restart a Python Program
I'm writing a Python program that, if the user changes settings while running it, needs to be restarted to apply the changed settings. Is there a way of doing this? I'm thinking something along the lines of:
import sys
command_line = ' '.join(sys.argv)
# Now do something with command_line
... | Restart a Python Program | I'm writing a Python program that, if the user changes settings while running it, needs to be restarted to apply the changed settings. Is there a way of doing this? I'm thinking something along the lines of:
import sys
command_line = ' '.join(sys.argv)
# Now do something with command_line
# Now call my custom exit proc... | [
"I would bypass all the angst you're likely to get from trying to re-run yourself and leave it in the hands of the environment.\nBy that, I mean:\n\nHave a controlling program which does nothing more than run your program (with the same parameters it was given) in a loop while your program exits with a specific \"r... | [
8,
6
] | [] | [] | [
"python",
"restart"
] | stackoverflow_0002107317_python_restart.txt |
Q:
indentation problem in my python program
I am using the following code and geting some indentation problem
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.qu... | indentation problem in my python program | I am using the following code and geting some indentation problem
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
I am geting following error
File "E:\S... | [
"Most likely you're using a mix of tabs and spaces in your indentation... Use all spaces / all tabs instead. (The most widely adopted style is to use 4 spaces per level of indent.)\nTo fix this particular instance of the problem, check make the def __unicode__(self): line start with the same indent as the pub_date ... | [
3,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002107327_django_python.txt |
Q:
Iterating over a large Django queryset while the data is changing elsewhere
Iterating over a queryset, like so:
class Book(models.Model):
# <snip some other stuff>
activity = models.PositiveIntegerField(default=0)
views = models.PositiveIntegerField(default=0)
def calculate_statistics():
s... | Iterating over a large Django queryset while the data is changing elsewhere | Iterating over a queryset, like so:
class Book(models.Model):
# <snip some other stuff>
activity = models.PositiveIntegerField(default=0)
views = models.PositiveIntegerField(default=0)
def calculate_statistics():
self.activity = book.views * 4
book.save()
def cron_job_calculate_all_boo... | [
"The following will do the job for you in Django 1.1, no loop necessary:\nfrom django.db.models import F\nBook.objects.all().update(activity=F('views')*4)\n\nYou can have a more complicated calculation too:\nfor book in Book.objects.all().iterator():\n Book.objects.filter(pk=book.pk).update(activity=book.calcula... | [
4,
3,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002104404_django_django_models_python.txt |
Q:
Error when adding a ManyToManyField in Django
Ok, so I posted a question recently regarding an error when adding a ManyToManyField
The Models are the ones below
class MagicType(models.Model):
name = models.CharField(max_length=155)
parent = models.ForeignKey('self', null=True, blank=True)
class Spell(m... | Error when adding a ManyToManyField in Django | Ok, so I posted a question recently regarding an error when adding a ManyToManyField
The Models are the ones below
class MagicType(models.Model):
name = models.CharField(max_length=155)
parent = models.ForeignKey('self', null=True, blank=True)
class Spell(models.Model):
name = models.CharField(max_leng... | [
"Same thing, i answer your another question Is a reason I can't add a ManyToManyField? basicly this error is because your code in models (ORM) change but your database isn't, and django-evolution doesn't fix many problems with changes in the database, i suggest you look for django-extensions (http://code.google.com... | [
3,
1
] | [] | [] | [
"django",
"django_evolution",
"django_models",
"django_orm",
"python"
] | stackoverflow_0002106491_django_django_evolution_django_models_django_orm_python.txt |
Q:
Re-open files in Python?
Say I have this simple python script:
file = open('C:\\some_text.txt')
print file.readlines()
print file.readlines()
When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a... | Re-open files in Python? | Say I have this simple python script:
file = open('C:\\some_text.txt')
print file.readlines()
print file.readlines()
When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file s... | [
"You can reset the file pointer by calling seek():\nfile.seek(0)\n\nwill do it. You need that line after your first readlines(). Note that file has to support random access for the above to work.\n",
"For small files, it's probably much faster to just keep the file's contents in memory\nfile = open('C:\\\\some_... | [
79,
3,
3
] | [] | [] | [
"file",
"python"
] | stackoverflow_0002106820_file_python.txt |
Q:
should not access parent frame untill closes the child?
I have two frames one parent and child.
the parent will invoke the child.
The program should not allow the user to access the parent until the user closes the child
How can i achive it?
Need a solution without hiding the parent
A:
See the wx.Window.MakeMod... | should not access parent frame untill closes the child? | I have two frames one parent and child.
the parent will invoke the child.
The program should not allow the user to access the parent until the user closes the child
How can i achive it?
Need a solution without hiding the parent
| [
"See the wx.Window.MakeModal() method (Frame inherits from Window).\n"
] | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002107489_python_wxpython.txt |
Q:
How do I rotate/flip an image without using photologue/ImageModel?
I need a functionality in Django to rotate an image posted by users using a form. I need a method I can maybe put in imageutils.py and then use it in my form.
How can it be achieved?
A:
Use the Python Imaging Library directly:
from PIL import Ima... | How do I rotate/flip an image without using photologue/ImageModel? | I need a functionality in Django to rotate an image posted by users using a form. I need a method I can maybe put in imageutils.py and then use it in my form.
How can it be achieved?
| [
"Use the Python Imaging Library directly:\nfrom PIL import Image\nim = Image.open(\"yourfilename.jpg\")\nim = im.rotate(90)\nim.save(\"yourrotatedfilename.jpg\", \"JPEG\")\n\nThis is tested, and works. You'll need to have the Python Imaging Library installed and on your Python path, obviously, and you'll need to fi... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002107888_django_python.txt |
Q:
How to update xml file using lxml and python?
<example>
<login>
<id>1</id>
<username>kites</username>
<password>kites</password>
</login>
</example>
How can i update password using lxml?
and now can i add one more record to the same file?
please provide me a sample code
A:
exampl... | How to update xml file using lxml and python? | <example>
<login>
<id>1</id>
<username>kites</username>
<password>kites</password>
</login>
</example>
How can i update password using lxml?
and now can i add one more record to the same file?
please provide me a sample code
| [
"example = etree.Element(\"example\")\nlogin = etree.SubElement(example, \"login\")\npassword = etree.SubElement(login,\"password\")\npassword.text = \"newPassword\"\n\nThis is a good tutorial\n"
] | [
4
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0002108334_lxml_python_xml.txt |
Q:
Save method manytomany
I've got a model called Card which has a ManyToMany relationship to
Tag. When I save a Card, I'd like to create a Product as well, which I
want to have the same ManyToMany relationship to tag.
How do I access the instance's tags? self.tags.all() gives an empty
list, while if I check afte... | Save method manytomany | I've got a model called Card which has a ManyToMany relationship to
Tag. When I save a Card, I'd like to create a Product as well, which I
want to have the same ManyToMany relationship to tag.
How do I access the instance's tags? self.tags.all() gives an empty
list, while if I check after saving, the card actually ... | [
"Are you using the django-admin to save the model and tags? The many-to-many fields don't get saved there until after the post-save signal of the model. What you can do in this case is overide the admin classes save_model method. E.g.:\nclass CardAdmin(admin.ModelAdmin):\n\n def save_model(self, request, obj, fo... | [
2,
0
] | [] | [] | [
"django",
"many_to_many",
"methods",
"python",
"save"
] | stackoverflow_0002108039_django_many_to_many_methods_python_save.txt |
Q:
How to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library
Can someone tell me how to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library (Python).
Thanks a lot in advance.. :)
A:
Looking at the documentation, it seem... | How to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library | Can someone tell me how to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library (Python).
Thanks a lot in advance.. :)
| [
"Looking at the documentation, it seems that it's up to you, the library user, to pad the data yourself. The documentation states that the block size for AES is always 16 bytes, so you need to pad the data to a multiple of 16 bytes.\nHow the padding is done depends on the type of the data. For strings the best appr... | [
5,
3
] | [] | [] | [
"encryption",
"pycrypto",
"python"
] | stackoverflow_0002108047_encryption_pycrypto_python.txt |
Q:
Django/Python mailing list implementation
My site requires sending periodic update emails to all our registered clients.
To keep our lists clear, I want to track all failed deliveries and purge the mailing lists accordingly. I am assuming I am not the first nor the last to do this.
Can anyone recommend an existing... | Django/Python mailing list implementation | My site requires sending periodic update emails to all our registered clients.
To keep our lists clear, I want to track all failed deliveries and purge the mailing lists accordingly. I am assuming I am not the first nor the last to do this.
Can anyone recommend an existing app/library that I can use to accomplish this ... | [
"I think you need a mailing list server like mailman, there is django-mailman (a django's admin interface for mailman), and follow this steps:\n\nInstall mailman\nInstall django-mailman\nComplete your user's registration algorithm for your users and register them in mailman.\nWhen you need send a mail, send it to y... | [
4,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002104133_django_python.txt |
Q:
Facebook Page details and the RESTful API?
Hi I have a list of Facebook Page urls
eg...
http://www.facebook.com/daftpunk
http://www.facebook.com/DavidGuetta
...
What's the best way to:
Check if these urls are actually for Facebook Pages and not Profiles
Collect details such as # of fans from these Pages
Help wo... | Facebook Page details and the RESTful API? | Hi I have a list of Facebook Page urls
eg...
http://www.facebook.com/daftpunk
http://www.facebook.com/DavidGuetta
...
What's the best way to:
Check if these urls are actually for Facebook Pages and not Profiles
Collect details such as # of fans from these Pages
Help would be very much appreciated.
| [
"Without scraping any content (which is against Facebook's terms of service anyway):\n\nExtract the username part of the URL\ni.e. the bit after the\nwww.facebook.com/\nDo an FQL query of the form select\nfan_count from\npage where\nusername='michaeljackson'\nIf a result is return, you know it's a\nPage and not a ... | [
3,
2,
1,
0
] | [] | [] | [
"facebook",
"pyfacebook",
"python"
] | stackoverflow_0002104996_facebook_pyfacebook_python.txt |
Q:
Google App Engine and OpenID
I am trying to implement OpenID in a GoogleAppEngine project. In this case, which OpenIDStore I have to use. Thanks
A:
I try with AEoid which seems alright. Here's live example and my code
| Google App Engine and OpenID | I am trying to implement OpenID in a GoogleAppEngine project. In this case, which OpenIDStore I have to use. Thanks
| [
"I try with AEoid which seems alright. Here's live example and my code\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"openid",
"python"
] | stackoverflow_0002101817_google_app_engine_openid_python.txt |
Q:
Creating a FeaturedContent feature in Django using contenttypes
I'm using the contenttypes framework to create a "featured content" feature on my site. I've basically done this by defining a model like so:
class FeaturedContent(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models... | Creating a FeaturedContent feature in Django using contenttypes | I'm using the contenttypes framework to create a "featured content" feature on my site. I've basically done this by defining a model like so:
class FeaturedContent(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKe... | [
"You will need to create a stackedinline admin, for each of your models that need this option in the admin.\nSomething like the following:\nclass ObjectInline(admin.StackedInline):\n model = YourFancyModelthatisFeatured\n extra = 0\n\nclass FancyModelAdmin(admin.ModelAdmin):\n inlines = [ObjectInline]\n\nB... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002109281_django_django_models_python.txt |
Q:
Getting information about static files in Python App Engine; workarounds
I'm working on an App Engine project that will have customizable themes. I'd like to be able to use jQuery UI themes. The problem is figuring out what the CSS file is going to be named. (Typically, "jquery-ui-1.7.2.custom.css". Version nu... | Getting information about static files in Python App Engine; workarounds | I'm working on an App Engine project that will have customizable themes. I'd like to be able to use jQuery UI themes. The problem is figuring out what the CSS file is going to be named. (Typically, "jquery-ui-1.7.2.custom.css". Version numbers will change, and people tend to rename things, but there should only be ... | [
"To accomplish what you are asking, I would use the datastore for serving the CSS files. Since this would allow easy listing, sorting and even modification and uploading.\nOther than that, your next best options would be to store the CSS data inside a script (a dictionary where the filename is the key name, and the... | [
1
] | [] | [] | [
"google_app_engine",
"jquery_ui",
"python",
"themes"
] | stackoverflow_0002099008_google_app_engine_jquery_ui_python_themes.txt |
Q:
Performance of python library keyczar in Windows
I am running this code to see the performance impact of the keyczar encryption library from google:
from keyczar import keyczar, keys
def main(iters):
key = keys.RsaPrivateKey.Generate()
msg = "ciao"
crypt = None
for i in range(iters):
print... | Performance of python library keyczar in Windows | I am running this code to see the performance impact of the keyczar encryption library from google:
from keyczar import keyczar, keys
def main(iters):
key = keys.RsaPrivateKey.Generate()
msg = "ciao"
crypt = None
for i in range(iters):
print i, "\r",
crypt = key.Encrypt(msg)
for i i... | [
"PyCrypto has a C module called _fastmath which uses GNU MP for the public key operations. If it is not available, it instead uses Python's native long integers, which are much much slower.\nThe two files are src/_fastmath.c and lib/Crypto/PublicKey/_slowmath.py\nIt's likely that Python on Windows does not include ... | [
1,
0
] | [] | [] | [
"keyczar",
"profiling",
"python"
] | stackoverflow_0002074195_keyczar_profiling_python.txt |
Q:
A good django search app? — How to perform fuzzy search with Haystack?
I'm using django-haystack at the moment
with apache-solr as the backend.
Problem is I cannot get the app to perform the search functionality I'm looking for
Searching for sub-parts in a word
eg. Searching for "buntu" does not give me "ubuntu... | A good django search app? — How to perform fuzzy search with Haystack? | I'm using django-haystack at the moment
with apache-solr as the backend.
Problem is I cannot get the app to perform the search functionality I'm looking for
Searching for sub-parts in a word
eg. Searching for "buntu" does not give me "ubuntu"
Searching for similar words
eg. Searching for "ubantu" would give "ubunt... | [
"This is really about how you pass the query back to Haystack (and therefore to Solr). You can do a 'fuzzy' search in Solr/Lucene by using a ~ after the word:\nubuntu~\n\nwould return both buntu and ubantu. See the Lucene documentation on this.\nHow you pass this through via Haystack depends on how you're using it ... | [
9
] | [] | [] | [
"django",
"django_haystack",
"fuzzy_search",
"python",
"solr"
] | stackoverflow_0002110411_django_django_haystack_fuzzy_search_python_solr.txt |
Q:
Python zipfile hangs when writing
I am trying to use the zipfile module in Python to create simple zip files:
import zipfile
files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip_file_name = 'zipfile_test.zip'
zfh = zipfile.ZipFile(zip_file_name, 'w')
for file in files:
print 'Archiving file %s' % file
zfh.wr... | Python zipfile hangs when writing | I am trying to use the zipfile module in Python to create simple zip files:
import zipfile
files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip_file_name = 'zipfile_test.zip'
zfh = zipfile.ZipFile(zip_file_name, 'w')
for file in files:
print 'Archiving file %s' % file
zfh.write(zip_file_name)
zfh.close()
The fil... | [
"You're putting the zip file into the zip file:\nzfh.write(zip_file_name)\n\nShould be:\nzfh.write(file)\n\n"
] | [
10
] | [] | [] | [
"python",
"python_zipfile"
] | stackoverflow_0002110739_python_python_zipfile.txt |
Q:
Django - How to model this correctly?
I want to model the following situation. I have a table of items, and a table of players, and a player can have many items and have multiple copies of the same item. I can easily model the player having multiple items:
class Item(models.Model):
name = models.CharField(max_... | Django - How to model this correctly? | I want to model the following situation. I have a table of items, and a table of players, and a player can have many items and have multiple copies of the same item. I can easily model the player having multiple items:
class Item(models.Model):
name = models.CharField(max_length = 200, blank = False)
class Player(... | [
"Use an explicit through table with a quantity field.\n",
"If the items are non-unique you can use a PlayerItem model and define it as a through model as Daniel Roseman suggested. To avoid saving the same item twice you can use unique_together:\nclass Item(models.Model):\n name = models.CharField(max_length = ... | [
5,
0
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0002109293_django_model_python.txt |
Q:
Cleaning up nested for loops in python
I have this code:
def GetSteamAccts(): #Get list of steam logins on this computer.
templist = []
Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories.
for SF_i in range(len(Ste... | Cleaning up nested for loops in python | I have this code:
def GetSteamAccts(): #Get list of steam logins on this computer.
templist = []
Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories.
for SF_i in range(len(Steamapp_Folders)):
if os.path.exists(S... | [
"for i in range(len(somelist)):\n something( somelist[i] )\n\nshould be written as\nfor x in somelist: \n something( x )\n\nAlso you can write everything much shorter:\ndef GetSteamAccts():\n Steamapp_Folders = [f for f in (\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\\", \n ... | [
9,
5,
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002110753_python.txt |
Q:
Looping over datasets in Python
I'm trying to write a Python script that will perform the same action on multiple databases. There are too many for me to input them by hand, so I'd like to write a script that will loop over them.
Right now, I've gotten as far as the following before getting stuck:
countylist = ['0... | Looping over datasets in Python | I'm trying to write a Python script that will perform the same action on multiple databases. There are too many for me to input them by hand, so I'd like to write a script that will loop over them.
Right now, I've gotten as far as the following before getting stuck:
countylist = ['01001','01002','01003','01004']
for it... | [
"countylist = ['01001','01002','01003','01004']\nfile_1 = \"F:\\\\file1.shp\"\nfor item in countylist:\n file_2 = \"F:\\\\file%s.shp\" % item\n output_2 = \"F:\\\\output%s.shp\" % item\n # Here, I do my commands that are dependent on\n # the name of the file changing.\n\n# Here, outside of the loop, fil... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002111072_python_string.txt |
Q:
create a grayscale image
I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a... | create a grayscale image | I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a integer from 0 to 255. To sav... | [
"When you create the new image, give it the mode L:\nim = Image.new('L', size)\nim.putdata([x1, x2, x3, ...])\n\nWhere data is a list of values not tuples.\n",
"There are several ways to do this, but if you already have the data in memory, look into using Image.frombuffer or Image.fromstring using the 'L' mode (f... | [
22,
3,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0002111150_python_python_imaging_library.txt |
Q:
Django template ifequal tag
I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about.
I have a list of int ... | Django template ifequal tag | I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about.
I have a list of int city ID's that should be checked ... | [
"{% for id in pflags %}{% ifequal id city.id %} ... {% endfor %}\n\nCould it be that id is a string and city.id is an integer?\n",
"The code you've posted would go into infinite loops if either pflags or mflags were non-empty.\nConsider e.g. this snippet from your code:\n i = 0\n while i < len(pflags):\n pfla... | [
5,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002099064_django_django_templates_python.txt |
Q:
lxml and loops to create xml rss in python
I have been using lxml to create the xml of rss feed. But I am having trouble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how t... | lxml and loops to create xml rss in python | I have been using lxml to create the xml of rss feed. But I am having trouble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how to loop for a dynamic number of items without rem... | [
"Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list: E.channel(*args), where args would be [E.title(...), E.link(...),...]. Similarly, keyword arguments can be passed using dict and two stars (**). See documentation.\n",
"This lxml tutorial says:... | [
6,
5,
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0002104751_lxml_python.txt |
Q:
Are there any declaration keywords in Python?
Are there any declaration keywords in Python, like local, global, private, public etc.? I know that variable types are not specified in Python; but how do you know if the code x = 5 creates a new variable, or sets an existing one?
A:
I really like the understanding t... | Are there any declaration keywords in Python? | Are there any declaration keywords in Python, like local, global, private, public etc.? I know that variable types are not specified in Python; but how do you know if the code x = 5 creates a new variable, or sets an existing one?
| [
"I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, \"how do you know if this statement: creates a new variable or sets an existing variable?\"\nIf you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid glob... | [
15,
14,
12,
7,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0000571514_python_variables.txt |
Q:
Hooking into django views
Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example:
Instead of writing
@foo
@bar
@baz
def view(request):
# do something
all the time, I'd like to have
def view(request):
markers = ['some', 'markers']
an... | Hooking into django views | Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example:
Instead of writing
@foo
@bar
@baz
def view(request):
# do something
all the time, I'd like to have
def view(request):
markers = ['some', 'markers']
and hook this into django:
for vi... | [
"Depending on what you want to do (or achieve), you can write a custom middelware and implement the method process_view (and/or any other method that you need):\n\nprocess_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will cont... | [
2,
1
] | [] | [] | [
"django",
"django_views",
"hook",
"python"
] | stackoverflow_0002110399_django_django_views_hook_python.txt |
Q:
python virtual environment on source control
I have created a python web virtual environment contains all django, pylons related packages. I use the host ubuntu desktop PC at home and I have ubuntu virtual machine running on windows PC laptop.
Both the operating systems are linux only. I will be using the same env... | python virtual environment on source control | I have created a python web virtual environment contains all django, pylons related packages. I use the host ubuntu desktop PC at home and I have ubuntu virtual machine running on windows PC laptop.
Both the operating systems are linux only. I will be using the same environment for production that will be ubuntu server... | [
"You might want to look into virtualenv. This will allow you to set up your working environment, 'freeze' the list of packages that are needed to replicate it, and store that list of requirements in version control so that others can check it out and rebuild the environment with a single step.\n",
"You can but yo... | [
2,
0,
0
] | [] | [] | [
"installation",
"linux",
"python",
"virtualenv"
] | stackoverflow_0002108105_installation_linux_python_virtualenv.txt |
Q:
Am I doing these unit tests right?
I'm new to unit tests for my own projects, so this is my first attempt to write a unit test from scratch. I'm using python, and the unittest module. The TodoList class being tested here is a wrapper for actual lists, with a few extra methods for stuff like saving to disc. It also... | Am I doing these unit tests right? | I'm new to unit tests for my own projects, so this is my first attempt to write a unit test from scratch. I'm using python, and the unittest module. The TodoList class being tested here is a wrapper for actual lists, with a few extra methods for stuff like saving to disc. It also defines a few methods for getting items... | [
"I think that you are going in the right way. But I will send some suggestions;\n\nMove the self.testdata.close() from setUp() to the tearDown() function.\nSurround the others open/close with try/finally blocks. So, if a file didn't open with success it will be closed.\n\n\n try:\n file.open()\n finall... | [
3,
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002112014_python_unit_testing.txt |
Q:
iterable long-object?
This is a problem from euler-project. No.13
import math
#no.13
sum = []
number = 0
a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230... | iterable long-object? | This is a problem from euler-project. No.13
import math
#no.13
sum = []
number = 0
a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104... | [
"I am not sure what the overall goal of your program is but the error you are getting is because in the line:\na = int(''.join(str(i) for i in a)) \n\nYou are trying to iterate over a long and in Python as the error message indicates a long is not an iterable you cannot process it one digit at a time directly. You ... | [
3,
2,
1,
0
] | [] | [] | [
"iterable",
"long_integer",
"python"
] | stackoverflow_0002105569_iterable_long_integer_python.txt |
Q:
Math functions as well as flags
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.In... | Math functions as well as flags | from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.IntegerField()
commited = models.Intege... | [
"I don't understand your last sentence, but for the rest of it, showing a calculated field in the admin list_display is easy - just create a method on the model or the admin. In your case, the easiest thing is to drop the existing 'available' field and use a model method marked as a property.\n@property\ndef availa... | [
0,
0
] | [] | [] | [
"django_admin",
"python"
] | stackoverflow_0002111945_django_admin_python.txt |
Q:
Import vs C's #include
In C:
#include "foo.h"
int main()
{
}
I believe that "foo.h" effectively gets copied and pasted in at the spot of the "#include".
Python imports are different though, I'm finding.
I just refactored a bit of GAE code that initially had ALL request handlers in one big index.py file.
NEW dire... | Import vs C's #include | In C:
#include "foo.h"
int main()
{
}
I believe that "foo.h" effectively gets copied and pasted in at the spot of the "#include".
Python imports are different though, I'm finding.
I just refactored a bit of GAE code that initially had ALL request handlers in one big index.py file.
NEW directory tree:
+
|
+- [handler... | [
"While in C it works more or less \"copy-pasting\" the code, in Python is quite different.\nRemember the Zen of Python?\nExplicit is better than implicit.\n...\nNamespaces are one honking great idea -- let's do more of those!\n\nEach time you import a module, you execute its code, but you keep all the scopes of the... | [
3,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002112707_import_python.txt |
Q:
In Python in Google App Engine, how do you capture output produced by the print statement?
I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for ... | In Python in Google App Engine, how do you capture output produced by the print statement? | I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for all of my problems except for those containing the print statement. Something seems to go wrong ... | [
"I think Hooked has the right answer, but I think you'd be better off storing the value of sys.stdout before you modify it and restoring that value afterwards rather than restoring sys.__stdout__ because (I think) the App Engine runtime tinkers with sys.stdout in its own way.\nThat leaves you with something like\ni... | [
5,
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002112396_google_app_engine_python.txt |
Q:
Pylons Uploading Distorted Images on Windows
I'm creating an web app in Pylons, and am working on an image upload action. This is currently running using egg:paste#http on my windows machine, in the basic development configuration described in the pylons documentation quickstart.
When I POST an image to my applic... | Pylons Uploading Distorted Images on Windows | I'm creating an web app in Pylons, and am working on an image upload action. This is currently running using egg:paste#http on my windows machine, in the basic development configuration described in the pylons documentation quickstart.
When I POST an image to my application, then move the image to the web root directo... | [
"You are probably just missing the 'b' (binary) flag for effectively writing the file as binary:\nsave_file = open(os_path, 'wb')\n\nBut I don't see why you need the shutil.copyfileobj call in there, why not do something like this:\nfile_save_path = os.path.join(config.images_dir, request.POST['image'].filename)\nf... | [
3
] | [] | [] | [
"file_upload",
"image",
"paster",
"pylons",
"python"
] | stackoverflow_0002113126_file_upload_image_paster_pylons_python.txt |
Q:
Does python have the equivalent of Perl's regex "local" variable?
While searching for a solution to a python regular expression problem I found this page which demonstrates that [some version of] perl allows variables within regular expressions.
e.g. a perl regex something like:
^(?{ local $d=0}\((?{ $d++ }.*?\)(... | Does python have the equivalent of Perl's regex "local" variable? | While searching for a solution to a python regular expression problem I found this page which demonstrates that [some version of] perl allows variables within regular expressions.
e.g. a perl regex something like:
^(?{ local $d=0}\((?{ $d++ }.*?\)(?d--)
Where variable $d is incremented and decremented depending on wh... | [
"No. You need a grammer - pyparsing is nice (and easy)\n"
] | [
2
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0002113843_perl_python_regex.txt |
Q:
Preserving argument default values while method chaining
If I have to wrap an existing method, let us say wrapee() from a new method, say wrapper(), and the wrapee() provides default values for some arguments, how do I preserve its semantics without introducing unnecessary dependencies and maintenance? Let us say,... | Preserving argument default values while method chaining | If I have to wrap an existing method, let us say wrapee() from a new method, say wrapper(), and the wrapee() provides default values for some arguments, how do I preserve its semantics without introducing unnecessary dependencies and maintenance? Let us say, the goal is to be able to use wrapper() in place of wrapee() ... | [
"Check out argument lists in the Python docs.\n>>> def wrapper(param1, *stuff, **kargs):\n... print(param1)\n... print(stuff)\n... print(args)\n...\n>>> wrapper(3, 4, 5, foo=2)\n3\n(4, 5)\n{'foo': 2}\n\nThen to pass the args along:\nwrapee(param1, *stuff, **kargs)\n\nThe *stuff is a variable number of non-named ... | [
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002114510_python.txt |
Q:
libnet creates UDP packets with invalid checksums
I'm using pylibnet to construct and send UDP packets. The UDP packets I construct in this way all seem to have invalid checksums. Example:
# python
Python 2.4.3 (#1, Sep 3 2009, 15:37:12)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright"... | libnet creates UDP packets with invalid checksums | I'm using pylibnet to construct and send UDP packets. The UDP packets I construct in this way all seem to have invalid checksums. Example:
# python
Python 2.4.3 (#1, Sep 3 2009, 15:37:12)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>... | [
"It's nothing to do with tcpdump bugs or checksum offloading. Libnet calculates the checksum in user mode as well (FYI). The problem has to do with the fact that you did not specify a length for the UDP header. This is not automagically calculated in pylibnet or libnet so you have to specify it for the time being. ... | [
3,
1,
1
] | [] | [] | [
"libnet",
"python",
"udp"
] | stackoverflow_0001903500_libnet_python_udp.txt |
Q:
which style is preferred?
Option 1:
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
Option 2:
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
So that I can then call:
for c in ("Ch... | which style is preferred? | Option 1:
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
Option 2:
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
So that I can then call:
for c in ("China", "Japan"):
for f in (f1,... | [
"Neither, I would go for\ndef f2(c):\n d = {\n \"USA\": \"N.Y.\",\n \"China\": \"Shanghai\"\n }\n\n return d.get(c, \"N/A\")\n\nThis way is shorter and \"get\" is designed for the job.\nAlso an except without an explicit exception is bad pratice, so use except KeyError: not just except. \nExceptions do not... | [
22,
11,
9,
7,
4,
1,
0
] | [] | [] | [
"coding_style",
"exception",
"python"
] | stackoverflow_0002114540_coding_style_exception_python.txt |
Q:
explorer right click context menu with python?
I'm wondering how to go about adding a menu item to explorers right click context menu. For instance, when I right click on a file I get things like winrars "Add to archive" I want something like that and I'm wondering how to do it with python.
A:
To Add more items ... | explorer right click context menu with python? | I'm wondering how to go about adding a menu item to explorers right click context menu. For instance, when I right click on a file I get things like winrars "Add to archive" I want something like that and I'm wondering how to do it with python.
| [
"To Add more items to explorer right click menu, you just need to add some registry keys.\nFor example, take a look at this site, there is some examples and some tools.\nhttp://windowsxp.mvps.org/context_folders.htm\n",
"Adding Entries to the Standard Context Menu\n_winreg - Windows registry access\n"
] | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0002114853_python.txt |
Q:
What is the deal with the pony in Python community?
Pony references are in several places:
http://www.mail-archive.com/python-dev@python.org/msg44751.html
http://pypi.python.org/pypi/django-pony/
http://djangopony.com/
Is there a cultural reference that I am missing? What is the deal with ponies?
A:
When you s... | What is the deal with the pony in Python community? | Pony references are in several places:
http://www.mail-archive.com/python-dev@python.org/msg44751.html
http://pypi.python.org/pypi/django-pony/
http://djangopony.com/
Is there a cultural reference that I am missing? What is the deal with ponies?
| [
"When you start listing what you want, \"I want a fast HTTP parser\", \"I want ORM that just works\", \"I want higher order functions\", the idea is that while you're wishing for things, you might as well wish for a pony too. This is probably a reference to a Calvin and Hobbes strip from \"Someone under the bed is... | [
69,
15,
3
] | [] | [] | [
"django",
"pony",
"python"
] | stackoverflow_0002115360_django_pony_python.txt |
Q:
What should I name my global module in Python?
I'm writing an application in Python, and I've got a number of universal variables (such as the reference to the main window, the user settings, and the list of active items in the UI) which have to be accessible from all parts of the program1. I only just realized I... | What should I name my global module in Python? | I'm writing an application in Python, and I've got a number of universal variables (such as the reference to the main window, the user settings, and the list of active items in the UI) which have to be accessible from all parts of the program1. I only just realized I've named the module globals.py and I'm importing th... | [
"I would try to avoid such a global container module altogether, and instead put these variables into their own modules, which can then be imported from all parts of the system.\nFor example, the main window would probably go into a variable in main.py. User settings could go into usersettings.py which would provi... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"global_variables",
"naming_conventions",
"python"
] | stackoverflow_0002107682_global_variables_naming_conventions_python.txt |
Q:
"Featuring" content in a Django website
I'm working on a new Django project, and the client wants to "feature" content on the homepage and a few other sections of the website. Content in this case could be a blog post, an event, a news story, etc. Each item would have a "start featuring" datetime and an "stop feat... | "Featuring" content in a Django website | I'm working on a new Django project, and the client wants to "feature" content on the homepage and a few other sections of the website. Content in this case could be a blog post, an event, a news story, etc. Each item would have a "start featuring" datetime and an "stop featuring" datetime.
I've done this a few differ... | [
"Have you looked at the contenttypes framework? You could set up a FeaturedItem model, with start and end datetimes, and a generic foreign key. This allows the relationship to be with any model.\nIf you heavily feature objects from particular models, look at the section on reverse generic relations.\n",
"I'm tryi... | [
7,
0
] | [] | [] | [
"content_management_system",
"django",
"python"
] | stackoverflow_0001631592_content_management_system_django_python.txt |
Q:
Python Program converted into Java
Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could s... | Python Program converted into Java | Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done a... | [
"You need to fix your if statements the \"==\" operator checks for equality, and you must put the variable you are checking against in each section of the statement.\npublic int winCraps{\n roll = rollDice();\n if (roll == 7 || roll == 11) {\n return true;\n }\n else if(roll == 2 || roll == 3 || ... | [
2,
2,
1,
1,
0,
0,
0
] | [
"One major error in your first program that you have in the Java conversion is the conditionals.\nSomething like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.\nYou want something like:\nelse if(roll==2 || roll==3 || roll==12)\nAs for random... | [
-1
] | [
"java",
"python"
] | stackoverflow_0002112952_java_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.