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:
Math in python - converting data files to matrices
Today, as I tried to put together a script in Octave, I thought, this may be easier in python. Indeed the math operators of lists are a breeze, but loading in the file in the format is not as easy. Then I thought, it probably is, I am just not familiar with the module to do it!
So, I have a typical data file with four columns of numbers. I would like to load each column into separate lists. Is there a module I should use to make this easier?
A:
For fast calculations with matrices you should try Numpy, it has some functions to load data from files.
A:
I don't know whether this is applicable to your problem, but you might try it with numpy, especially its loadtxt and savetxt functions. You should then use only numpy arrays and avoid Python lists as they are not apt for numerical computations.
A:
If you're dealing with 2-dimensional data or enormously long lists, Numpy is the way to go, but if you're not looking to do terribly advanced math, you can get by with regular Python.
>>> table = []
>>> a = "32 42 63 1123"
>>> table.append(a.split(" ")) # this would be some loop where you file.readline()...
>>> table.append(a.split(" "))
>>> table.append(a.split(" "))
>>> table.append(a.split(" "))
>>> table
[['32', '42', '63', '1123'], ['32', '42', '63', '1123'],
['32', '42', '63', '1123'], ['32', '42', '63', '1123']]
>>> zip(*table) # this "transposes" the list of lists
[('32', '32', '32', '32'), ('42', '42', '42', '42'),
('63', '63', '63', '63'), ('1123', '1123', '1123', '1123')]
>>>
A:
The easiest way to get Numpy working is to download Enthought Python Distribution. This is especially true for Mac since installing numpy, scipy, ... from scratch will take you a lot of effort.
For loading and saving some files like:
# This is some comment
1 2 3
4 5 6
7 8 9
You do
import numpy as np
data = np.loadtxt(input_filename, comment='#')
| Math in python - converting data files to matrices | Today, as I tried to put together a script in Octave, I thought, this may be easier in python. Indeed the math operators of lists are a breeze, but loading in the file in the format is not as easy. Then I thought, it probably is, I am just not familiar with the module to do it!
So, I have a typical data file with four columns of numbers. I would like to load each column into separate lists. Is there a module I should use to make this easier?
| [
"For fast calculations with matrices you should try Numpy, it has some functions to load data from files. \n",
"I don't know whether this is applicable to your problem, but you might try it with numpy, especially its loadtxt and savetxt functions. You should then use only numpy arrays and avoid Python lists as they are not apt for numerical computations.\n",
"If you're dealing with 2-dimensional data or enormously long lists, Numpy is the way to go, but if you're not looking to do terribly advanced math, you can get by with regular Python.\n>>> table = []\n>>> a = \"32 42 63 1123\"\n>>> table.append(a.split(\" \")) # this would be some loop where you file.readline()...\n>>> table.append(a.split(\" \"))\n>>> table.append(a.split(\" \"))\n>>> table.append(a.split(\" \"))\n>>> table\n[['32', '42', '63', '1123'], ['32', '42', '63', '1123'],\n['32', '42', '63', '1123'], ['32', '42', '63', '1123']]\n>>> zip(*table) # this \"transposes\" the list of lists\n[('32', '32', '32', '32'), ('42', '42', '42', '42'), \n('63', '63', '63', '63'), ('1123', '1123', '1123', '1123')]\n>>>\n\n",
"The easiest way to get Numpy working is to download Enthought Python Distribution. This is especially true for Mac since installing numpy, scipy, ... from scratch will take you a lot of effort.\nFor loading and saving some files like:\n# This is some comment\n1 2 3 \n4 5 6\n7 8 9\n\nYou do\nimport numpy as np\ndata = np.loadtxt(input_filename, comment='#')\n\n"
] | [
2,
1,
1,
0
] | [] | [] | [
"io",
"list",
"python"
] | stackoverflow_0003121370_io_list_python.txt |
Q:
Can a formfield be selected w/mechanize based on the type of the field (eg. TextControl, TextareaControl)?
I'm trying to parse an html form using mechanize. The form itself has an arbitrary number of hidden fields and the field names and id's are randomly generated so I have no obvious way to directly select them. Clearly using a name or id is out, and due to the random number of hidden fields I cannot select them based on the sequence number since this always changes too.
However there are always two TextControl fields right after each other, and then below that is a TextareaControl. These are the 3 fields I need access too, basically I need to parse their names and all is well. I've been looking through the mechanize documentation for the past couple hours and haven't come up with anything that seems to be able to do this, however simple it should seem to be (to me anyway).
I have come up with an alternate solution that involves making a list of the form controls, iterating through it to find the controls that contain the string 'Text' returning a new list of those, and then finally stripping out the name using a regular expression. While this works it seems unnecessary and I'm wondering if there's a more elegant solution. Thanks guys.
edit: Here's what I'm currently doing to extract that info if anyone's curious. I think I'm probably just going to stick with this. It seems unnecessary but it gets the job done and it's nothing intensive so I'm not worried about efficiency or anything.
def formtextFieldParse(browser):
'''Expects a mechanize.Browser object with a form already selected. Parses
through the fields returning a tuple of the name of those fields. There
SHOULD only be 3 fields. 2 text followed by 1 textarea corresponding to
Posting Title, Specific Location, and Posting Description'''
import re
pattern = '\(.*\)'
fields = str(browser).split('\n')
textfields = []
for field in fields:
if 'Text' in field: textfields.append(field)
titleFieldName = re.findall(pattern, textfields[0])[0][1:-2]
locationFieldName = re.findall(pattern, textfields[1])[0][1:-2]
descriptionFieldName = re.findall(pattern, textfields[2])[0][1:-2]
A:
I don't think mechanize has the exact functionality you require; could you use mechanize to get the HTML page, then parse the latter for example with BeautifulSoup?
| Can a formfield be selected w/mechanize based on the type of the field (eg. TextControl, TextareaControl)? | I'm trying to parse an html form using mechanize. The form itself has an arbitrary number of hidden fields and the field names and id's are randomly generated so I have no obvious way to directly select them. Clearly using a name or id is out, and due to the random number of hidden fields I cannot select them based on the sequence number since this always changes too.
However there are always two TextControl fields right after each other, and then below that is a TextareaControl. These are the 3 fields I need access too, basically I need to parse their names and all is well. I've been looking through the mechanize documentation for the past couple hours and haven't come up with anything that seems to be able to do this, however simple it should seem to be (to me anyway).
I have come up with an alternate solution that involves making a list of the form controls, iterating through it to find the controls that contain the string 'Text' returning a new list of those, and then finally stripping out the name using a regular expression. While this works it seems unnecessary and I'm wondering if there's a more elegant solution. Thanks guys.
edit: Here's what I'm currently doing to extract that info if anyone's curious. I think I'm probably just going to stick with this. It seems unnecessary but it gets the job done and it's nothing intensive so I'm not worried about efficiency or anything.
def formtextFieldParse(browser):
'''Expects a mechanize.Browser object with a form already selected. Parses
through the fields returning a tuple of the name of those fields. There
SHOULD only be 3 fields. 2 text followed by 1 textarea corresponding to
Posting Title, Specific Location, and Posting Description'''
import re
pattern = '\(.*\)'
fields = str(browser).split('\n')
textfields = []
for field in fields:
if 'Text' in field: textfields.append(field)
titleFieldName = re.findall(pattern, textfields[0])[0][1:-2]
locationFieldName = re.findall(pattern, textfields[1])[0][1:-2]
descriptionFieldName = re.findall(pattern, textfields[2])[0][1:-2]
| [
"I don't think mechanize has the exact functionality you require; could you use mechanize to get the HTML page, then parse the latter for example with BeautifulSoup?\n"
] | [
1
] | [] | [] | [
"html",
"mechanize",
"python",
"regex"
] | stackoverflow_0003122687_html_mechanize_python_regex.txt |
Q:
How to install Python SSL module on OSX?
When I deploy my google app engine project, I get the following warning:
WARNING appengine_rpc.py:399 ssl module not found.
Without the ssl module, the identity of the remote host cannot be verified, and
connections may NOT be secure. To fix this, please install the ssl module from
http://pypi.python.org/pypi/ssl.
I downloaded the package, but when I try
python setup.py build
I get the following error output:
looking for /usr/include/openssl/ssl.h
looking for /usr/local/ssl/include/openssl/ssl.h
looking for /usr/contrib/ssl/include/openssl/ssl.h
Traceback (most recent call last):
File "setup.py", line 167, in <module>
ssl_incs, ssl_libs, libs = find_ssl()
File "setup.py", line 142, in find_ssl
raise Exception("No SSL support found")
Exception: No SSL support found
What do I need to do to install it, is it a path issue or something?
A:
Fixed by installing pycrypto first, following the instructions from here and using the insight from an answer to this question.
The full command line I used for the eventual build was:
CC='/usr/bin/gcc-4.0' python2.5 setup.py build
A:
The stock Apple python on both 10.5 and 10.6 includes the ssl module (unclear about earlier versions):
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> ssl.__file__
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ssl.pyc'
(from 10.5.8)
You could actually get that error message from appengine_rpc.py even if you have ssl - you need to make sure that your GAE download has:
/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/cacerts/cacerts.txt
If you have both of those things, try doing:
import google.appengine.tools.https_wrapper
Which should work with the stock Apple python, but if it doesn't the error messages might be more informative. If you have multiple pythons installed such that one is screwing up GAE, make sure to use the Python Path preference in GAE to point to the Apple Python.
A:
You may need to manually install openssl, although the headers should be placed in /usr/include by the default Xcode installation. (If you haven't installed Xcode, it's unlikely you have gcc on your machine, and the build would fail later in the process anyway.)
| How to install Python SSL module on OSX? | When I deploy my google app engine project, I get the following warning:
WARNING appengine_rpc.py:399 ssl module not found.
Without the ssl module, the identity of the remote host cannot be verified, and
connections may NOT be secure. To fix this, please install the ssl module from
http://pypi.python.org/pypi/ssl.
I downloaded the package, but when I try
python setup.py build
I get the following error output:
looking for /usr/include/openssl/ssl.h
looking for /usr/local/ssl/include/openssl/ssl.h
looking for /usr/contrib/ssl/include/openssl/ssl.h
Traceback (most recent call last):
File "setup.py", line 167, in <module>
ssl_incs, ssl_libs, libs = find_ssl()
File "setup.py", line 142, in find_ssl
raise Exception("No SSL support found")
Exception: No SSL support found
What do I need to do to install it, is it a path issue or something?
| [
"Fixed by installing pycrypto first, following the instructions from here and using the insight from an answer to this question.\nThe full command line I used for the eventual build was:\nCC='/usr/bin/gcc-4.0' python2.5 setup.py build\n\n",
"The stock Apple python on both 10.5 and 10.6 includes the ssl module (unclear about earlier versions):\nPython 2.6.5 (r265:79359, Mar 24 2010, 01:32:55) \n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import ssl\n>>> ssl.__file__\n'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ssl.pyc'\n\n(from 10.5.8)\nYou could actually get that error message from appengine_rpc.py even if you have ssl - you need to make sure that your GAE download has:\n/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/cacerts/cacerts.txt\n\nIf you have both of those things, try doing:\nimport google.appengine.tools.https_wrapper\n\nWhich should work with the stock Apple python, but if it doesn't the error messages might be more informative. If you have multiple pythons installed such that one is screwing up GAE, make sure to use the Python Path preference in GAE to point to the Apple Python.\n",
"You may need to manually install openssl, although the headers should be placed in /usr/include by the default Xcode installation. (If you haven't installed Xcode, it's unlikely you have gcc on your machine, and the build would fail later in the process anyway.)\n"
] | [
5,
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"ssl"
] | stackoverflow_0003078403_google_app_engine_python_ssl.txt |
Q:
Stop an operation without stopping the module in python
Well, I have made a module that allows you to copy a file to a directory easier. Now, I also have some "try's" and "except's" in there to make sure it doesn't fail in the big messy way and doesn't close the terminal, but I also want it to display different error messages when a wrong string or variable is put in, and end the module, but not the...if I may say, Terminal running it, so I did this:
def copy():
import shutil
import os
try:
cpy = input("CMD>>> Name of file(with extension): ")
open(cpy, "r")
except:
print("ERROR>>> 02x00 No such file")
try:
dri = input("CMD>>> Name of Directory: ")
os.chdir(dri)
os.chdir("..")
except:
print("ERROR>>> 03x00 No such directory")
try:
shutil.copy(cpy, dri)
except:
print("ERROR>>> 04x00 Command Failure")
Problem is that it doesn't end the module if there is no file or directory, only at the finish.
A:
You may be thinking that when an exception is raised, Python just stops what it's doing, but that's not quite true. The except: block actually catches the exception raised, and is supposed to handle it. After an except: block finishes, Python will continue on executing the rest of the code in the file.
In your case, I'd put a return after each print(...). That way, after Python prints out an error message, it will also return from the copy() function rather than continuing to ask for more input.
A:
If you did want to make the module exit on error...
Here's how you'd do it.
def copy():
import shutil
import os
import sys
try:
cpy = input("CMD>>> Name of file(with extension): ")
open(cpy, "r")
except:
sys.exit("ERROR>>> 02x00 No such file")
try:
dri = input("CMD>>> Name of Directory: ")
os.chdir(dri)
os.chdir("..")
except:
sys.exit("ERROR>>> 03x00 No such directory")
try:
shutil.copy(cpy, dri)
except:
sys.exit("ERROR>>> 04x00 Command Failure")
sys.exit(0) (for success) and sys.exit(1) (for failure) are usually used but, since you want to output the error, the above example will output the error string to stderr.
Here's a link for more info on sys.exit().
| Stop an operation without stopping the module in python | Well, I have made a module that allows you to copy a file to a directory easier. Now, I also have some "try's" and "except's" in there to make sure it doesn't fail in the big messy way and doesn't close the terminal, but I also want it to display different error messages when a wrong string or variable is put in, and end the module, but not the...if I may say, Terminal running it, so I did this:
def copy():
import shutil
import os
try:
cpy = input("CMD>>> Name of file(with extension): ")
open(cpy, "r")
except:
print("ERROR>>> 02x00 No such file")
try:
dri = input("CMD>>> Name of Directory: ")
os.chdir(dri)
os.chdir("..")
except:
print("ERROR>>> 03x00 No such directory")
try:
shutil.copy(cpy, dri)
except:
print("ERROR>>> 04x00 Command Failure")
Problem is that it doesn't end the module if there is no file or directory, only at the finish.
| [
"You may be thinking that when an exception is raised, Python just stops what it's doing, but that's not quite true. The except: block actually catches the exception raised, and is supposed to handle it. After an except: block finishes, Python will continue on executing the rest of the code in the file.\nIn your case, I'd put a return after each print(...). That way, after Python prints out an error message, it will also return from the copy() function rather than continuing to ask for more input.\n",
"If you did want to make the module exit on error...\nHere's how you'd do it.\ndef copy():\n import shutil\n import os\n import sys\n try:\n cpy = input(\"CMD>>> Name of file(with extension): \")\n open(cpy, \"r\")\n except:\n sys.exit(\"ERROR>>> 02x00 No such file\")\n try:\n dri = input(\"CMD>>> Name of Directory: \")\n os.chdir(dri)\n os.chdir(\"..\")\n except:\n sys.exit(\"ERROR>>> 03x00 No such directory\")\n try:\n shutil.copy(cpy, dri)\n except:\n sys.exit(\"ERROR>>> 04x00 Command Failure\")\n\nsys.exit(0) (for success) and sys.exit(1) (for failure) are usually used but, since you want to output the error, the above example will output the error string to stderr.\nHere's a link for more info on sys.exit(). \n"
] | [
2,
0
] | [] | [] | [
"exception",
"exception_handling",
"module",
"python"
] | stackoverflow_0003122365_exception_exception_handling_module_python.txt |
Q:
Defining a part of a column as a unique field in sqlalchemy
In sqlalchemy 0.5 i have a table defined like this one:
orders = Table('orders', metadata,
Column('id', Integer, primary_key=True),
Column('responsable', String(255)),
Column('customer', String(255)),
Column('progressive', Integer),
Column('date', Date),
Column('exported', Boolean()),
)
Is it possible to define only the customer and year of the date as unique ?
The year isn't a column only a part of a date but it could be nice to have the year of the date and the customer to be a single key of the table.
Is it possible in sqlalchemy 0.5 ?
Thanks
A:
Without splitting the date field into a month field, a date field, and a year field, there really isn't a way to do what you're asking. It would (probably) be easier and simpler for you to include the whole date (month/day/year) in the composite primary; if (id, year) uniquely defines a record, then so will (id, date).
A:
Quoth the documentation:
Multiple columns may be assigned the
primary_key=True flag which denotes a
multi-column primary key, known as a
composite primary key.
A:
You can use a function in a constraint but it's not database independent. See here for details: Compound UniqueConstraint with a function
However I would argue that the best thing to do would be to create a column for year. It will certainly be easier.
| Defining a part of a column as a unique field in sqlalchemy | In sqlalchemy 0.5 i have a table defined like this one:
orders = Table('orders', metadata,
Column('id', Integer, primary_key=True),
Column('responsable', String(255)),
Column('customer', String(255)),
Column('progressive', Integer),
Column('date', Date),
Column('exported', Boolean()),
)
Is it possible to define only the customer and year of the date as unique ?
The year isn't a column only a part of a date but it could be nice to have the year of the date and the customer to be a single key of the table.
Is it possible in sqlalchemy 0.5 ?
Thanks
| [
"Without splitting the date field into a month field, a date field, and a year field, there really isn't a way to do what you're asking. It would (probably) be easier and simpler for you to include the whole date (month/day/year) in the composite primary; if (id, year) uniquely defines a record, then so will (id, date).\n",
"Quoth the documentation:\n\nMultiple columns may be assigned the\n primary_key=True flag which denotes a\n multi-column primary key, known as a\n composite primary key.\n\n",
"You can use a function in a constraint but it's not database independent. See here for details: Compound UniqueConstraint with a function\nHowever I would argue that the best thing to do would be to create a column for year. It will certainly be easier. \n"
] | [
1,
0,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003080823_python_sqlalchemy.txt |
Q:
how to make dynamically generated forms with one to many relationships in django
i am trying to write a quiz system to learn django where users can add quizes to the system.
my models look like
from google.appengine.ext import db
class Quiz(db.Model):
title=db.StringProperty(required=True)
created_by=db.UserProperty()
date_created=db.DateTimeProperty(auto_now_add=True)
class Question(db.Model):
question=db.StringProperty(required=True)
answer_1=db.StringProperty(required=True)
answer_2=db.StringProperty(required=True)
answer_3=db.StringProperty(required=True)
correct_answer=db.StringProperty(choices=['1','2','3','4'])
quiz=db.ReferenceProperty(Quiz)
my question is how do create Form+views+templates to present user with a page to create quizes
so far i have come up with this.
Views:
from google.appengine.ext.db.djangoforms import ModelForm
from django.shortcuts import render_to_response
from models import Question,Quiz
from django.newforms import Form
def create_quiz(request):
return render_to_response('index.html',{'xquestion':QuestionForm(),'xquiz':QuizForm()})
class QuestionForm(ModelForm):
class Meta:
model=Question
exclude=['quiz']
class QuizForm(ModelForm):
class Meta:
model=Quiz
exclude=['created_by']
template(index.html)
Please Enter the Questions
<form action="" method='post'>
{{xquiz.as_table}}
{{xquestion.as_table}}
<input type='submit'>
</form>
How can i have multiple Questions in the quiz form?
| how to make dynamically generated forms with one to many relationships in django | i am trying to write a quiz system to learn django where users can add quizes to the system.
my models look like
from google.appengine.ext import db
class Quiz(db.Model):
title=db.StringProperty(required=True)
created_by=db.UserProperty()
date_created=db.DateTimeProperty(auto_now_add=True)
class Question(db.Model):
question=db.StringProperty(required=True)
answer_1=db.StringProperty(required=True)
answer_2=db.StringProperty(required=True)
answer_3=db.StringProperty(required=True)
correct_answer=db.StringProperty(choices=['1','2','3','4'])
quiz=db.ReferenceProperty(Quiz)
my question is how do create Form+views+templates to present user with a page to create quizes
so far i have come up with this.
Views:
from google.appengine.ext.db.djangoforms import ModelForm
from django.shortcuts import render_to_response
from models import Question,Quiz
from django.newforms import Form
def create_quiz(request):
return render_to_response('index.html',{'xquestion':QuestionForm(),'xquiz':QuizForm()})
class QuestionForm(ModelForm):
class Meta:
model=Question
exclude=['quiz']
class QuizForm(ModelForm):
class Meta:
model=Quiz
exclude=['created_by']
template(index.html)
Please Enter the Questions
<form action="" method='post'>
{{xquiz.as_table}}
{{xquestion.as_table}}
<input type='submit'>
</form>
How can i have multiple Questions in the quiz form?
| [] | [] | [
"so far so good, as of now you should be having a working view with the forms rendered, if there are no errors.\nnow you just need to handle the post data in create_quiz view\nif request.method == 'POST':\n xquiz = QuizForm(request.POST)\n quiz_instance = xquiz.save(commit=False)\n quiz_instance.created_by = request.user\n quiz_instance.save()\n xquestion = QuestionForm(request.POST)\n question_instance = xquestion.save(commit=False)\n question_instance.quiz = quiz_instance\n question_instance.save()\n\nupdate: if you are looking for multiple question forms then you need to look at formsets, http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1\n"
] | [
-1
] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003122962_django_google_app_engine_python.txt |
Q:
Parsing Java Class From Perl or Python
I want to get a .java file, recognize the first class in the file, and get information about annotations, methods and attributes from this class.
Is there any module in both languages that already does that?
I could build up a simple regexp to do it also, but I don't known how to recognize in the regexp the braces indicating the end of the class/method.
A:
If you load the java classes inside Jython you probably could use introspection to find the information you need.
A:
Why are you trying this in perl/python rather than just using a javadoc-aware program that can pull out the info?
A:
I would suggest Inline::Java for accessing Java class from Perl,Once you have that interface running, you can easily access methods and attributes from the class.
| Parsing Java Class From Perl or Python | I want to get a .java file, recognize the first class in the file, and get information about annotations, methods and attributes from this class.
Is there any module in both languages that already does that?
I could build up a simple regexp to do it also, but I don't known how to recognize in the regexp the braces indicating the end of the class/method.
| [
"If you load the java classes inside Jython you probably could use introspection to find the information you need.\n",
"Why are you trying this in perl/python rather than just using a javadoc-aware program that can pull out the info?\n",
"I would suggest Inline::Java for accessing Java class from Perl,Once you have that interface running, you can easily access methods and attributes from the class.\n"
] | [
2,
0,
0
] | [] | [] | [
"java",
"parsing",
"perl",
"python"
] | stackoverflow_0003120073_java_parsing_perl_python.txt |
Q:
Django: vibrant community and future?
I'm in that horrible questioning state. I'm trying to decide between Django and Rails.
From what I've read, Django probably fits my needs better, both from a "cultural" and goal point of view. The baked-in admin interface pretty much sells me alone. However, I have one critical concern: it looks like the Rails community is much larger. This could be a plus OR a minus; read on.
I have experience hanging my hat on a technology that does not have as vibrant a commmunity as its "competitor." I run a Mac consulting firm in the Bay Area. Up until very, very recently (like the last year!), finding resources for very difficult issues (especially server- and network-related) was so difficult that it was often not even worth trying. This is now changing rapidly due to the Halo Effect, but if it wasn't for Steve Jobs' return to Apple and the iPhone, the future would look just as bleak as the past.
So, while Django looks awesome, I am concerned about pigeonholing myself in yet another niche. I'm less concerned with my theoretical job prospects as a Django developer (I like my job) than I am with simply having resources available to create and maintain cutting-edge projects that can evolve with the Web, and not lag too far behind.
From the above point of view, it looks like Rails has the advantage. However, here's a problem I've noticed that seems to come from the vibrancy of the Rails community: Want to accomplish a particular Rails programming task you've never done before? Google it; you'll find three to six+ different plugins, each with as many advocates as detractors. How do you decide which to use without spending hours and hours learning and prototyping? How do you know that the one you choose won't be end-of-lifed in 12 months, and you'll have to redo that part of your app in order to stay current with the latest Rails distribution?
My latter point brings me right back to where I started: Django seems like a time-saver. Except now I have two reasons to think so, not just one.
I should mention that I've already spent a significant amount of time learning Ruby and Rails, dabbled a bit in Python, and quite prefer Ruby.
Would love your thoughts.
A:
If the size and the vibrancy of the community is the main problem, than maybe you should look at other framework stacks not just Django and Rails (those two make allot of noise and hype, but there are other much more bigger that don't get that loud - e.g. Java/JVM based framework stacks have users in a few order of magnitude higher than those two you mention).
If the game however is just between these two, when I would decide, I would take in consideration especially the available tools (how good the IDE support is) - at least for me they're very very important, since they're what make a productivity difference.
Even if on the Mac the hype is of course TextMate, with all the respect, that is just an advanced editor - not an IDE with "smart" features like error highlighting in code, smart and correct completion, etc.
The smartest existing IDE for Rails is RubyMine, so considering that for Python (Django) there's nothing not even close that advanced, I would choose Ruby on Rails even for this just only reason. Of course, another plus point for RoR is the bigger number of books available (so when in doubt, I have better chances to find a solution in one of them).
A:
What about Pylons?
A:
From what I have seen neither one looks like it will become a niche any time soon, both have active communities and dedicated developers. Ruby and python are both great languages, and both are being actively developed as well. At some point Django will have to migrate from python 2.x to 3.y, which may be a little bit painful, but the same sort of thing can be expected from rails at some point in the future.
I think you have narrowed it down to the right two for being main stream yet not stagnant. They both have advantages and disadvantages, and if there isn't a clear reason to chose one or the other for your project, I would say go with the language you prefer. Python is my language of choice, so baring some killer reason to chose RoR, Django is the natural way to go to continue developing the way I like to. If you prefer ruby, I would recommend going with RoR unless Django seems to fit your application in a way RoR does not.
| Django: vibrant community and future? | I'm in that horrible questioning state. I'm trying to decide between Django and Rails.
From what I've read, Django probably fits my needs better, both from a "cultural" and goal point of view. The baked-in admin interface pretty much sells me alone. However, I have one critical concern: it looks like the Rails community is much larger. This could be a plus OR a minus; read on.
I have experience hanging my hat on a technology that does not have as vibrant a commmunity as its "competitor." I run a Mac consulting firm in the Bay Area. Up until very, very recently (like the last year!), finding resources for very difficult issues (especially server- and network-related) was so difficult that it was often not even worth trying. This is now changing rapidly due to the Halo Effect, but if it wasn't for Steve Jobs' return to Apple and the iPhone, the future would look just as bleak as the past.
So, while Django looks awesome, I am concerned about pigeonholing myself in yet another niche. I'm less concerned with my theoretical job prospects as a Django developer (I like my job) than I am with simply having resources available to create and maintain cutting-edge projects that can evolve with the Web, and not lag too far behind.
From the above point of view, it looks like Rails has the advantage. However, here's a problem I've noticed that seems to come from the vibrancy of the Rails community: Want to accomplish a particular Rails programming task you've never done before? Google it; you'll find three to six+ different plugins, each with as many advocates as detractors. How do you decide which to use without spending hours and hours learning and prototyping? How do you know that the one you choose won't be end-of-lifed in 12 months, and you'll have to redo that part of your app in order to stay current with the latest Rails distribution?
My latter point brings me right back to where I started: Django seems like a time-saver. Except now I have two reasons to think so, not just one.
I should mention that I've already spent a significant amount of time learning Ruby and Rails, dabbled a bit in Python, and quite prefer Ruby.
Would love your thoughts.
| [
"If the size and the vibrancy of the community is the main problem, than maybe you should look at other framework stacks not just Django and Rails (those two make allot of noise and hype, but there are other much more bigger that don't get that loud - e.g. Java/JVM based framework stacks have users in a few order of magnitude higher than those two you mention).\nIf the game however is just between these two, when I would decide, I would take in consideration especially the available tools (how good the IDE support is) - at least for me they're very very important, since they're what make a productivity difference.\nEven if on the Mac the hype is of course TextMate, with all the respect, that is just an advanced editor - not an IDE with \"smart\" features like error highlighting in code, smart and correct completion, etc.\nThe smartest existing IDE for Rails is RubyMine, so considering that for Python (Django) there's nothing not even close that advanced, I would choose Ruby on Rails even for this just only reason. Of course, another plus point for RoR is the bigger number of books available (so when in doubt, I have better chances to find a solution in one of them).\n",
"What about Pylons?\n",
"From what I have seen neither one looks like it will become a niche any time soon, both have active communities and dedicated developers. Ruby and python are both great languages, and both are being actively developed as well. At some point Django will have to migrate from python 2.x to 3.y, which may be a little bit painful, but the same sort of thing can be expected from rails at some point in the future.\nI think you have narrowed it down to the right two for being main stream yet not stagnant. They both have advantages and disadvantages, and if there isn't a clear reason to chose one or the other for your project, I would say go with the language you prefer. Python is my language of choice, so baring some killer reason to chose RoR, Django is the natural way to go to continue developing the way I like to. If you prefer ruby, I would recommend going with RoR unless Django seems to fit your application in a way RoR does not.\n"
] | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003122923_django_python_ruby_ruby_on_rails.txt |
Q:
How to encrypt a string using the key
I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.
It's ok if somebody could lead me to some library.
A:
My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library. M2Crypto is a Python wrapper around OpenSSL. The API is pretty much a straight translation of OpenSSL's into Python, so the somewhat sketchy documentation shouldn't be too much of a problem. If the public key encryption algorithm you need to use is supported by M2Crypto, then you could very well use it to do your public key cryptography.
I found the M2Crypto test suite to be a useful example of using its API. In particular, the RSA (in test_rsa.py), PGP (in test_pgp.py), and EVP (in test_evp.py) tests will help you figure out how to set up and use the library. Do be aware that they are unit-tests, so it can be a little tricky to figure out exactly what code is necessary and what is an artefact of being a test.
PS: As I'm new, my posts can only contain one link so I had to delete most of them. Sorry.
Example
from M2Crypto import RSA
rsa = RSA.load_pub_key('rsa.pub.pem')
encrypted = rsa.public_encrypt('your message', RSA.pkcs1_oaep_padding)
print encrypted.encode('base64')
Output
X3iTasRwRdW0qPRQBXiKN5zvPa3LBiCDnA3HLH172wXTEr4LNq2Kl32PCcXpIMxh7j9CmysLyWu5
GLQ18rUNqi9ydG4ihwz3v3xeNMG9O3/Oc1XsHqqIRI8MrCWTTEbAWaXFX1YVulVLaVy0elODECKV
4e9gCN+5dx/aG9LtPOE=
A:
Here's the script that demonstrates how to encrypt a message using M2Crypto ($ easy_install m2crypto) given that public key is in varkey variable:
#!/usr/bin/env python
import urllib2
from M2Crypto import BIO, RSA
def readkey(filename):
try:
key = open(filename).read()
except IOError:
key = urllib2.urlopen(
'http://svn.osafoundation.org/m2crypto/trunk/tests/' + filename
).read()
open(filename, 'w').write(key)
return key
def test():
message = 'disregard the -man- (I mean file) behind curtain'
varkey = readkey('rsa.pub.pem')
# demonstrate how to load key from a string
bio = BIO.MemoryBuffer(varkey)
rsa = RSA.load_pub_key_bio(bio)
# encrypt
encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
print encrypted.encode('base64')
del rsa, bio
# decrypt
read_password = lambda *args: 'qwerty'
rsa = RSA.load_key_string(readkey('rsa.priv2.pem'), read_password)
decrypted = rsa.private_decrypt(encrypted, RSA.pkcs1_oaep_padding)
print decrypted
assert message == decrypted
if __name__ == "__main__":
test()
Output
gyLD3B6jXspHu+o7M/TGLAqALihw7183E2effp9ALYfu8azYEPwMpjbw9nVSwJ4VvX3TBa4V0HAU
n6x3xslvOnegv8dv3MestEcTH9b3r2U1rsKJc1buouuc+MR77Powj9JOdizQPT22HQ2VpEAKFMK+
8zHbkJkgh4K5XUejmIk=
disregard the -man- (I mean file) behind curtain
A:
From my recent python experience, python doesn't do encryption natively. You need to use an external (3rd party) package. Each of these, obviously, offers a different experience. Which are you using? This will probably determine how your syntax will vary.
A:
You might want to have a look at:
http://www.example-code.com/python/encryption.asp
or this
http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/
A:
Have you ever heard about "RSAError: data too large for key size"?
Try your sample with more long message:
encrypted = rsa.public_encrypt('My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library', RSA.pkcs1_oaep_padding)
| How to encrypt a string using the key | I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.
It's ok if somebody could lead me to some library.
| [
"My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library. M2Crypto is a Python wrapper around OpenSSL. The API is pretty much a straight translation of OpenSSL's into Python, so the somewhat sketchy documentation shouldn't be too much of a problem. If the public key encryption algorithm you need to use is supported by M2Crypto, then you could very well use it to do your public key cryptography.\nI found the M2Crypto test suite to be a useful example of using its API. In particular, the RSA (in test_rsa.py), PGP (in test_pgp.py), and EVP (in test_evp.py) tests will help you figure out how to set up and use the library. Do be aware that they are unit-tests, so it can be a little tricky to figure out exactly what code is necessary and what is an artefact of being a test.\nPS: As I'm new, my posts can only contain one link so I had to delete most of them. Sorry.\nExample\nfrom M2Crypto import RSA\n\nrsa = RSA.load_pub_key('rsa.pub.pem')\nencrypted = rsa.public_encrypt('your message', RSA.pkcs1_oaep_padding)\nprint encrypted.encode('base64')\n\nOutput\n\nX3iTasRwRdW0qPRQBXiKN5zvPa3LBiCDnA3HLH172wXTEr4LNq2Kl32PCcXpIMxh7j9CmysLyWu5\nGLQ18rUNqi9ydG4ihwz3v3xeNMG9O3/Oc1XsHqqIRI8MrCWTTEbAWaXFX1YVulVLaVy0elODECKV\n4e9gCN+5dx/aG9LtPOE=\n\n",
"Here's the script that demonstrates how to encrypt a message using M2Crypto ($ easy_install m2crypto) given that public key is in varkey variable:\n#!/usr/bin/env python\nimport urllib2\nfrom M2Crypto import BIO, RSA\n\ndef readkey(filename):\n try:\n key = open(filename).read()\n except IOError:\n key = urllib2.urlopen(\n 'http://svn.osafoundation.org/m2crypto/trunk/tests/' + filename\n ).read()\n open(filename, 'w').write(key)\n return key\n\ndef test():\n message = 'disregard the -man- (I mean file) behind curtain'\n varkey = readkey('rsa.pub.pem')\n # demonstrate how to load key from a string\n bio = BIO.MemoryBuffer(varkey)\n rsa = RSA.load_pub_key_bio(bio)\n # encrypt\n encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)\n print encrypted.encode('base64')\n del rsa, bio \n # decrypt\n read_password = lambda *args: 'qwerty'\n rsa = RSA.load_key_string(readkey('rsa.priv2.pem'), read_password)\n decrypted = rsa.private_decrypt(encrypted, RSA.pkcs1_oaep_padding)\n print decrypted\n assert message == decrypted\n\nif __name__ == \"__main__\":\n test()\n\nOutput\n\ngyLD3B6jXspHu+o7M/TGLAqALihw7183E2effp9ALYfu8azYEPwMpjbw9nVSwJ4VvX3TBa4V0HAU\nn6x3xslvOnegv8dv3MestEcTH9b3r2U1rsKJc1buouuc+MR77Powj9JOdizQPT22HQ2VpEAKFMK+\n8zHbkJkgh4K5XUejmIk=\n\ndisregard the -man- (I mean file) behind curtain\n\n",
"From my recent python experience, python doesn't do encryption natively. You need to use an external (3rd party) package. Each of these, obviously, offers a different experience. Which are you using? This will probably determine how your syntax will vary.\n",
"You might want to have a look at:\nhttp://www.example-code.com/python/encryption.asp\nor this\nhttp://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/\n",
"Have you ever heard about \"RSAError: data too large for key size\"?\nTry your sample with more long message:\nencrypted = rsa.public_encrypt('My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library', RSA.pkcs1_oaep_padding)\n\n"
] | [
7,
3,
1,
0,
0
] | [
"You could use MD5 or SHA1 hashing along with your key...\n"
] | [
-2
] | [
"encryption",
"python"
] | stackoverflow_0001320671_encryption_python.txt |
Q:
Make django admin logEntry read only?
I found this post and it was very useful, but what I need is to make the logEntry model read-only in the admin interface. Is there a way to achieve that?
Thanks!
A:
Here is the example from the post you mentioned, with the needed change to make the fields read-only:
from django.contrib.admin.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin):
readonly_fields = ('content_type', 'user', 'action_time')
admin.site.register(LogEntry, LogEntryAdmin)
This works only in Django 1.2 so it is possible you will have to upgrade your Django package.
| Make django admin logEntry read only? | I found this post and it was very useful, but what I need is to make the logEntry model read-only in the admin interface. Is there a way to achieve that?
Thanks!
| [
"Here is the example from the post you mentioned, with the needed change to make the fields read-only:\nfrom django.contrib.admin.models import LogEntry\n\nclass LogEntryAdmin(admin.ModelAdmin):\n readonly_fields = ('content_type', 'user', 'action_time')\n\nadmin.site.register(LogEntry, LogEntryAdmin)\n\nThis works only in Django 1.2 so it is possible you will have to upgrade your Django package.\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"logging",
"python"
] | stackoverflow_0003121830_django_django_models_logging_python.txt |
Q:
appcfg.py upload_data require auth in Mac OSX
I have Google App SDK on Mac OSX 1.4.11, all python environment are OK. I try to upload data from manually generated .csv using appcfg.py. When upload directly to Google appspot.com all succeed.
Just to perform upload data locally it fail for authentication reason as generated below:
Application: myapplication; version: 1.
Uploading data records.
[INFO ] Logging to bulkloader-log-20100626.105711
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100626.105711.sql3
[INFO ] Connecting to /http//localhost:8080/remote_api
[ERROR ] Exception during authentication
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 3169, in Run
self.request_manager.Authenticate()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 1178, in Authenticate
remote_api_stub.MaybeInvokeAuthentication()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/remote_api/remote_api_stub.py", line 542, in MaybeInvokeAuthentication
datastore_stub._server.Send(datastore_stub._path, payload=None)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/appengine_rpc.py", line 346, in Send
f = self.opener.open(req)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 387, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 425, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error
[INFO ] Authentication Failed
Any advise of this issue?
A:
You're getting an internal server error on the development server. Check the development server logs for a traceback.
| appcfg.py upload_data require auth in Mac OSX | I have Google App SDK on Mac OSX 1.4.11, all python environment are OK. I try to upload data from manually generated .csv using appcfg.py. When upload directly to Google appspot.com all succeed.
Just to perform upload data locally it fail for authentication reason as generated below:
Application: myapplication; version: 1.
Uploading data records.
[INFO ] Logging to bulkloader-log-20100626.105711
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100626.105711.sql3
[INFO ] Connecting to /http//localhost:8080/remote_api
[ERROR ] Exception during authentication
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 3169, in Run
self.request_manager.Authenticate()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 1178, in Authenticate
remote_api_stub.MaybeInvokeAuthentication()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/remote_api/remote_api_stub.py", line 542, in MaybeInvokeAuthentication
datastore_stub._server.Send(datastore_stub._path, payload=None)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/appengine_rpc.py", line 346, in Send
f = self.opener.open(req)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 387, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 425, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error
[INFO ] Authentication Failed
Any advise of this issue?
| [
"You're getting an internal server error on the development server. Check the development server logs for a traceback.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003122832_google_app_engine_google_cloud_datastore_python.txt |
Q:
howoto fix working directory is always home? (python)
This is my first question.
My python script opens and reads from a present text file using the following simple funct:
open("config.ini", "r")
As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir.
In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because
os.path.exists("config.ini")
returns false even if the file is there!
Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another.
Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home!
How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one.
Should I maybe suggest this user to fix his machine in some way?
Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain.
Thank you very much in advance! =)
A:
Could it be that the user is executing your script from his home directory?
I.e. suppose the script is in:
/home/user/test/foo/foo.py
But the user calls it thus:
/home/user> python test/foo/foo.py
In this case, the "current directory" the script sees is /home/user.
What you can do is find out the directory the script itself resides in by calling this function:
import os
def script_dir():
return os.path.dirname(os.path.realpath(__file__))
It will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.
A:
Along the same lines as Eli Bendersky's suggestion, you might want to try:
os.path.exists(os.path.join(sys.path[0],"config.ini"))
since sys.path[0] should always be the directory in which the script resides.
| howoto fix working directory is always home? (python) | This is my first question.
My python script opens and reads from a present text file using the following simple funct:
open("config.ini", "r")
As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir.
In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because
os.path.exists("config.ini")
returns false even if the file is there!
Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another.
Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home!
How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one.
Should I maybe suggest this user to fix his machine in some way?
Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain.
Thank you very much in advance! =)
| [
"Could it be that the user is executing your script from his home directory?\nI.e. suppose the script is in:\n/home/user/test/foo/foo.py\n\nBut the user calls it thus:\n/home/user> python test/foo/foo.py\n\nIn this case, the \"current directory\" the script sees is /home/user.\nWhat you can do is find out the directory the script itself resides in by calling this function:\nimport os\n\ndef script_dir():\n return os.path.dirname(os.path.realpath(__file__))\n\nIt will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.\n",
"Along the same lines as Eli Bendersky's suggestion, you might want to try:\nos.path.exists(os.path.join(sys.path[0],\"config.ini\"))\n\nsince sys.path[0] should always be the directory in which the script resides.\n"
] | [
5,
0
] | [] | [] | [
"home_directory",
"python",
"working_directory"
] | stackoverflow_0003123390_home_directory_python_working_directory.txt |
Q:
How do I "print" something to the console in pylons?
paster serve --reload development.ini
..for debug = true
THis is what I do to load a development server for Pylons.
However, when I do:
print "hello world"
THis message doesn't print out in the console. In Django, it does.
A:
In Pylons logging package is the method to perform logging:
import logging
log = logging.getLogger(__name__)
log.debug('hello world')
This will work as long as you have logging setup configured correctly in your development.ini. I think the code above should be sufficient without any modifications to default configuration. In case it isn't you can call log.info, log.warn, log.error or log.critical instead of log.debug for your message to pass through.
I highly recommend reading this chapter of Pylons Book.
| How do I "print" something to the console in pylons? | paster serve --reload development.ini
..for debug = true
THis is what I do to load a development server for Pylons.
However, when I do:
print "hello world"
THis message doesn't print out in the console. In Django, it does.
| [
"In Pylons logging package is the method to perform logging:\nimport logging\nlog = logging.getLogger(__name__)\nlog.debug('hello world')\n\nThis will work as long as you have logging setup configured correctly in your development.ini. I think the code above should be sufficient without any modifications to default configuration. In case it isn't you can call log.info, log.warn, log.error or log.critical instead of log.debug for your message to pass through. \nI highly recommend reading this chapter of Pylons Book.\n"
] | [
4
] | [] | [] | [
"console",
"django",
"pylons",
"python"
] | stackoverflow_0003120202_console_django_pylons_python.txt |
Q:
python request param
I m working on django view.I m posting a form which has a param name 'service'.Service is checkbox so it will have mulitple values.When i am getting the values of service in my code it is giving me only one value not the array.Here is my sample code
{% for ser in allService %}
<td >
<input type="checkbox" name="service" value="{{ ser.id }}" >{{ ser.description }}
</td>
{% endfor %}
def update(request):
service=request.POST.get('service')
print service
how can i get a array.In java we getParameterValues('service')
A:
The POST attribute is a QueryDict, so you can do this:
service = request.POST.getlist('service')
| python request param | I m working on django view.I m posting a form which has a param name 'service'.Service is checkbox so it will have mulitple values.When i am getting the values of service in my code it is giving me only one value not the array.Here is my sample code
{% for ser in allService %}
<td >
<input type="checkbox" name="service" value="{{ ser.id }}" >{{ ser.description }}
</td>
{% endfor %}
def update(request):
service=request.POST.get('service')
print service
how can i get a array.In java we getParameterValues('service')
| [
"The POST attribute is a QueryDict, so you can do this:\nservice = request.POST.getlist('service')\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003123954_django_python.txt |
Q:
Django for a simple web application
I'm developing an app (an API) in python and I would like to offer some of its functionality through a web interface (like web services do).
I've been looking at django, but I don't know if really fits well in my idea. I only want to create a web page that invokes to my API methods in order to acomplish the functionality that offers that web page. But, after followed the tutorial, I feel a little confused about the point of django. It seems to me to be more related with an ORM than a classic web application.
Is django a solution so heavy for such a simple development (as I mentioned, make calls to my API through the web)? Do I always have to use a database?
Thanks.
A:
I love django but there is an lot of it to get your head around! If you don't want the database bit, focus on urls.py and views.py that will process your urls and return the info you want as an http response.
eg. urls.py
urlpatterns += patterns('myapp.views',
url(r'^getstuff/$', 'getstuff' ),
)
in views.py
def getstuff(request):
do whatever in python
return HttpResponse(stuff to return)
A:
You don't need to use database in Django projects.
Basically django comes with some standardized architecture that follows MVC pattern (or MVT as sometimes described). This includes models, views, url dispatching, templates, etc.
Probably you need to do following things to accomplish your task:
create url definition in urls.py
to some django view
write
django view that call somehow your
api and displays result as a web
page
you don't need models and database at all but you need to get familliar with views, urls, templates. It might look like a big machinery for your simple case but if you have some time I encourage you to these django basics.
If you are looking for somethin much simpler I heard about webpy project. This might be better option if you need something really simple.
A:
An important question is: Do you want the web services to be provided by a full-featured server like Apache, or are you just looking at the "web server" to be a thread (or equivalent) in your program?
If you want to run Apache, then I'd recommend something like Werkzeug, which will handle most of the WSGI stuff for you. For templating, I've heard good things about Jinja2.
If that is too much, and all you want is a lightweight, simple server (something that, say, just spits out some HTML or XML when asked, and doesn't need any fancy URL handling), you can use the SimpleHTTPServer or CGIHTTPServer modules that ship with Python.
Django is a full-featured, integrated package that provides almost everything you need to write database-backed web applications. While its various components can be used in isolation, if you're only using one thing (the template and view engines, in your case), it is probably overkill.
A:
No need for a framework at all. Raw wsgi isn't hard but a little verbose. So I like to use WebOb
Here's Raw wsgi
def application(environ, start_response):
start_response("200 OK", [])
return ["<html><body><h1>Hello World</h1></body></html>"]
Here's the webob version
from webob.dec import wsgify
from webob import Request
@wsgify
def application(request):
return Response("<html><body><h1>Hello World</h1></body></html>")
That's enough to run under apache mod_wsgi, and there are plenty of libraries that you can use that expect/produce webob Request and Responses. Anything that Turbogears 2 or repoze.bfg uses is fair game at that point.
A:
You definitely don't have to use a database with Django. Whether it fits your needs, only you can tell. There are other Python web frameworks that you can use.
| Django for a simple web application | I'm developing an app (an API) in python and I would like to offer some of its functionality through a web interface (like web services do).
I've been looking at django, but I don't know if really fits well in my idea. I only want to create a web page that invokes to my API methods in order to acomplish the functionality that offers that web page. But, after followed the tutorial, I feel a little confused about the point of django. It seems to me to be more related with an ORM than a classic web application.
Is django a solution so heavy for such a simple development (as I mentioned, make calls to my API through the web)? Do I always have to use a database?
Thanks.
| [
"I love django but there is an lot of it to get your head around! If you don't want the database bit, focus on urls.py and views.py that will process your urls and return the info you want as an http response.\neg. urls.py\nurlpatterns += patterns('myapp.views',\n\n url(r'^getstuff/$', 'getstuff' ),\n)\n\nin views.py\ndef getstuff(request):\n\n do whatever in python\n\n return HttpResponse(stuff to return)\n\n",
"You don't need to use database in Django projects.\nBasically django comes with some standardized architecture that follows MVC pattern (or MVT as sometimes described). This includes models, views, url dispatching, templates, etc.\nProbably you need to do following things to accomplish your task:\n\ncreate url definition in urls.py\nto some django view \nwrite\ndjango view that call somehow your\napi and displays result as a web\npage\n\nyou don't need models and database at all but you need to get familliar with views, urls, templates. It might look like a big machinery for your simple case but if you have some time I encourage you to these django basics.\nIf you are looking for somethin much simpler I heard about webpy project. This might be better option if you need something really simple.\n",
"An important question is: Do you want the web services to be provided by a full-featured server like Apache, or are you just looking at the \"web server\" to be a thread (or equivalent) in your program?\nIf you want to run Apache, then I'd recommend something like Werkzeug, which will handle most of the WSGI stuff for you. For templating, I've heard good things about Jinja2.\nIf that is too much, and all you want is a lightweight, simple server (something that, say, just spits out some HTML or XML when asked, and doesn't need any fancy URL handling), you can use the SimpleHTTPServer or CGIHTTPServer modules that ship with Python.\nDjango is a full-featured, integrated package that provides almost everything you need to write database-backed web applications. While its various components can be used in isolation, if you're only using one thing (the template and view engines, in your case), it is probably overkill.\n",
"No need for a framework at all. Raw wsgi isn't hard but a little verbose. So I like to use WebOb\nHere's Raw wsgi\ndef application(environ, start_response):\n start_response(\"200 OK\", [])\n return [\"<html><body><h1>Hello World</h1></body></html>\"]\n\nHere's the webob version\nfrom webob.dec import wsgify\nfrom webob import Request\n\n@wsgify\ndef application(request):\n return Response(\"<html><body><h1>Hello World</h1></body></html>\")\n\nThat's enough to run under apache mod_wsgi, and there are plenty of libraries that you can use that expect/produce webob Request and Responses. Anything that Turbogears 2 or repoze.bfg uses is fair game at that point. \n",
"You definitely don't have to use a database with Django. Whether it fits your needs, only you can tell. There are other Python web frameworks that you can use.\n"
] | [
5,
4,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003123683_django_python.txt |
Q:
Diffing a JSON document
Well, my question is a little complicated, but here goes:
I have a Python server that stores client (written in JavaScript) sessions, and has complete knowledge of what the client currently has stored in its state.
The server will constantly fetch data from the database and check for any changes against the client state. The data is JSON; consisting mostly of lists and dicts. I need a way to send a response to the client telling it to alter its data to match what the server has.
I have considered:
Sending a JSON-serialised recursively
diffed dict of changed elements and
not ever using lists - not bad, but I
can't use lists
Send the entire server version of the client state to the client -
costly and inefficient
Find some convoluted way to diff lists - painful and messy
Text-based diff of the two after dumping as JSON - plain silly
I'm pretty stumped on this, and I'd appreciate any help with this.
UPDATE
I'm considering sending nulls to the client to remove data it no longer requires and that the server has removed from its version of the client state.
A:
Related question
How to push diffs of data (possibly JSON) to a server?
See
http://ajaxian.com/archives/json-diff-released
http://michael.hinnerup.net/blog/2008/01/15/diffing_json_objects/
There are a couple of possible approaches:
Do an actual tree-parsing recursive diff;
Encapsulate your JSON updates such that they generate the diff at the same time;
Generate change-only JSON directly from your data.
What are your expected mean and max sizes for client-state JSON?
What are your expected mean and max sizes for diff updates?
How often will updates be requested?
How quickly does the base data change?
Why can't you use lists?
You could store just a last-known client state timestamp and query the database for items which have changed since then - effectively, let the database do the diff for you. This would require a last-changed timestamp and item-deleted flag on each table item; instead of directly deleting items, set the item-deleted flag, and have a cleanup query that deletes all records with item-deleted flag set more than two full update cycles ago.
It might be helpful to see some sample data - two sets of JSON client-state data and the diff between them.
| Diffing a JSON document | Well, my question is a little complicated, but here goes:
I have a Python server that stores client (written in JavaScript) sessions, and has complete knowledge of what the client currently has stored in its state.
The server will constantly fetch data from the database and check for any changes against the client state. The data is JSON; consisting mostly of lists and dicts. I need a way to send a response to the client telling it to alter its data to match what the server has.
I have considered:
Sending a JSON-serialised recursively
diffed dict of changed elements and
not ever using lists - not bad, but I
can't use lists
Send the entire server version of the client state to the client -
costly and inefficient
Find some convoluted way to diff lists - painful and messy
Text-based diff of the two after dumping as JSON - plain silly
I'm pretty stumped on this, and I'd appreciate any help with this.
UPDATE
I'm considering sending nulls to the client to remove data it no longer requires and that the server has removed from its version of the client state.
| [
"Related question\n\nHow to push diffs of data (possibly JSON) to a server?\n\nSee\n\nhttp://ajaxian.com/archives/json-diff-released\nhttp://michael.hinnerup.net/blog/2008/01/15/diffing_json_objects/\n\nThere are a couple of possible approaches:\n\nDo an actual tree-parsing recursive diff;\nEncapsulate your JSON updates such that they generate the diff at the same time;\nGenerate change-only JSON directly from your data.\n\nWhat are your expected mean and max sizes for client-state JSON?\nWhat are your expected mean and max sizes for diff updates?\nHow often will updates be requested?\nHow quickly does the base data change?\nWhy can't you use lists?\nYou could store just a last-known client state timestamp and query the database for items which have changed since then - effectively, let the database do the diff for you. This would require a last-changed timestamp and item-deleted flag on each table item; instead of directly deleting items, set the item-deleted flag, and have a cleanup query that deletes all records with item-deleted flag set more than two full update cycles ago.\nIt might be helpful to see some sample data - two sets of JSON client-state data and the diff between them.\n"
] | [
3
] | [] | [] | [
"diff",
"json",
"python"
] | stackoverflow_0003123645_diff_json_python.txt |
Q:
how to model a follower stream in appengine?
I am trying to design tables to buildout a follower relationship.
Say I have a stream of 140char records that have user, hashtag and other text.
Users follow other users, and can also follow hashtags.
I am outlining the way I've designed this below, but there are two limitaions in my design. I was wondering if others had smarter ways to accomplish the same goal.
The issues with this are
The list of followers is copied in for each record
If a new follower is added or one removed, 'all' the
records have to be updated.
The code
class HashtagFollowers(db.Model):
"""
This table contains the followers for each hashtag
"""
hashtag = db.StringProperty()
followers = db.StringListProperty()
class UserFollowers(db.Model):
"""
This table contains the followers for each user
"""
username = db.StringProperty()
followers = db.StringListProperty()
class stream(db.Model):
"""
This table contains the data stream
"""
username = db.StringProperty()
hashtag = db.StringProperty()
text = db.TextProperty()
def save(self):
"""
On each save all the followers for each hashtag and user
are added into a another table with this record as the parent
"""
super(stream, self).save()
hfs = HashtagFollowers.all().filter("hashtag =", self.hashtag).fetch(10)
for hf in hfs:
sh = streamHashtags(parent=self, followers=hf.followers)
sh.save()
ufs = UserFollowers.all().filter("username =", self.username).fetch(10)
for uf in ufs:
uh = streamUsers(parent=self, followers=uf.followers)
uh.save()
class streamHashtags(db.Model):
"""
The stream record is the parent of this record
"""
followers = db.StringListProperty()
class streamUsers(db.Model):
"""
The stream record is the parent of this record
"""
followers = db.StringListProperty()
Now, to get the stream of followed hastags
indexes = db.GqlQuery("""SELECT __key__ from streamHashtags where followers = 'myusername'""")
keys = [k,parent() for k in indexes[offset:numresults]]
return db.get(keys)
Is there a smarter way to do this?
A:
The problem you want to solve is called the fan-out problem.
Brett Slatkin from the Google App Engine team gave a talk with a efficient/scalable solution to fan-out problem on the App Engine. You can find a video of the talk here:
http://code.google.com/events/io/2009/sessions/BuildingScalableComplexApps.html
A:
Yes this is the fan-out problem as others have noted and Brett Slatkin's talk should be looked at by those interested.
However, I raised 2 specific limitations i.e.
The list of followers is copied in for each record
This as they say is not a bug but a feature. In fact it is in this way that fan-out on appengine scales.
If a new follower is added or one removed, 'all' the records have to be updated.
Either that OR do nothing so future records are not followed. In other words one does not just follow people's streams one follows people's stream at a given time. So if on day 2 you unfollow, your follower stream will still show records from the user that came in on day one, but not day two and onwards. [Note: This is different from how twitter does it]
A:
You could use a reference property and then have a common table with the followers in it, which you reference to
| how to model a follower stream in appengine? | I am trying to design tables to buildout a follower relationship.
Say I have a stream of 140char records that have user, hashtag and other text.
Users follow other users, and can also follow hashtags.
I am outlining the way I've designed this below, but there are two limitaions in my design. I was wondering if others had smarter ways to accomplish the same goal.
The issues with this are
The list of followers is copied in for each record
If a new follower is added or one removed, 'all' the
records have to be updated.
The code
class HashtagFollowers(db.Model):
"""
This table contains the followers for each hashtag
"""
hashtag = db.StringProperty()
followers = db.StringListProperty()
class UserFollowers(db.Model):
"""
This table contains the followers for each user
"""
username = db.StringProperty()
followers = db.StringListProperty()
class stream(db.Model):
"""
This table contains the data stream
"""
username = db.StringProperty()
hashtag = db.StringProperty()
text = db.TextProperty()
def save(self):
"""
On each save all the followers for each hashtag and user
are added into a another table with this record as the parent
"""
super(stream, self).save()
hfs = HashtagFollowers.all().filter("hashtag =", self.hashtag).fetch(10)
for hf in hfs:
sh = streamHashtags(parent=self, followers=hf.followers)
sh.save()
ufs = UserFollowers.all().filter("username =", self.username).fetch(10)
for uf in ufs:
uh = streamUsers(parent=self, followers=uf.followers)
uh.save()
class streamHashtags(db.Model):
"""
The stream record is the parent of this record
"""
followers = db.StringListProperty()
class streamUsers(db.Model):
"""
The stream record is the parent of this record
"""
followers = db.StringListProperty()
Now, to get the stream of followed hastags
indexes = db.GqlQuery("""SELECT __key__ from streamHashtags where followers = 'myusername'""")
keys = [k,parent() for k in indexes[offset:numresults]]
return db.get(keys)
Is there a smarter way to do this?
| [
"The problem you want to solve is called the fan-out problem.\nBrett Slatkin from the Google App Engine team gave a talk with a efficient/scalable solution to fan-out problem on the App Engine. You can find a video of the talk here:\nhttp://code.google.com/events/io/2009/sessions/BuildingScalableComplexApps.html\n",
"Yes this is the fan-out problem as others have noted and Brett Slatkin's talk should be looked at by those interested.\nHowever, I raised 2 specific limitations i.e.\n\nThe list of followers is copied in for each record\n\nThis as they say is not a bug but a feature. In fact it is in this way that fan-out on appengine scales.\n\nIf a new follower is added or one removed, 'all' the records have to be updated.\n\nEither that OR do nothing so future records are not followed. In other words one does not just follow people's streams one follows people's stream at a given time. So if on day 2 you unfollow, your follower stream will still show records from the user that came in on day one, but not day two and onwards. [Note: This is different from how twitter does it]\n",
"You could use a reference property and then have a common table with the followers in it, which you reference to\n"
] | [
5,
1,
0
] | [
"I'm not sure how to do this in Google App-Engine, but one database schema I would consider would be:\n\nTables:\n User -- a table of users with their attributes\n HashTag -- a table of HashTags with their attributes\n Follows -- a table that defines who follows whom\n\nColumns in the Follows table:\n followed int, -- the id of the followed entity (could be \n User or Hashtag)\n followed_is_user bit, -- whether the followed item is a User\n followed_is_tag bit, -- whether the followed item is a HashTag\n follower int -- the id of the follower (this can only be \n a User so you may want to make this a foreign \n key on the User table)\n\nYou could probably condense the two bit columns into one, but this would allow you to add other things that Users could follow in the future.\n"
] | [
-1
] | [
"bigtable",
"database_design",
"google_app_engine",
"python"
] | stackoverflow_0002898298_bigtable_database_design_google_app_engine_python.txt |
Q:
simplifying threading in python
I am looking for a way to ease my threaded code.
There are a lot of places in my code where I do something like:
for arg in array:
t=Thread(lambda:myFunction(arg))
t.start()
i.e running the same function, each time for different parameters, in threads.
This is of course a simplified version of the real code, and usually the code inside the for loop is ~10-20 lines long, that cannot be made simple by using one auxiliary function like myFunction in the example above (had that been the case, I could've just used a thread pool).
Also, this scenario is very, very common in my code, so there are tons of lines which I consider redundant. It would help me a lot if I didn't need to handle all this boilerplate code, but instead be able to do something like:
for arg in array:
with threaded():
myFunction(arg)
i.e somehow threaded() takes every line of code inside it and runs it in a separate thread.
I know that context managers aren't supposed to be used in such situations, that it's probably a bad idea and will require an ugly hack, but nonetheless - can it be done, and how?
A:
How about this:
for arg in array:
def _thread():
# code here
print arg
t = Thread(_thread)
t.start()
additionally, with decorators, you can sugar it up a little:
def spawn_thread(func):
t = Thread(func)
t.start()
return t
for arg in array:
@spawn_thread
def _thread():
# code here
print arg
A:
Would a thread pool help you here? Many implementations for Python exist, for example this one.
P.S: still interested to know what your exact use-case is
A:
What you want is a kind of "contextual thread pool".
Take a look at the ThreadPool class in this module, designed to be used similar to the manner you've given. Use would be something like this:
with ThreadPool() as pool:
for arg in array:
pool.add_thread(target=myFunction, args=[arg])
Failures in any task given to a ThreadPool will flag an error, and perform the standard error backtrace handling.
A:
I think you're over-complicating it. This is the "pattern" I use:
# util.py
def start_thread(func, *args):
thread = threading.Thread(target=func, args=args)
thread.setDaemon(True)
thread.start()
return thread
# in another module
import util
...
for arg in array:
util.start_thread(myFunction, arg)
I don't see the big deal about having to create myFunction. You could even define the function inline with the function that starts it.
def do_stuff():
def thread_main(arg):
print "I'm a new thread with arg=%s" % arg
for arg in array:
util.start_thread(thread_main, arg)
If you're creating a large number of threads, a thread pool definitely makes more sense. You can easily make your own with the Queue and threading modules. Basically create a jobs queue, create N worker threads, give each thread a "pointer" to the queue and have them pull jobs from the queue and process them.
| simplifying threading in python | I am looking for a way to ease my threaded code.
There are a lot of places in my code where I do something like:
for arg in array:
t=Thread(lambda:myFunction(arg))
t.start()
i.e running the same function, each time for different parameters, in threads.
This is of course a simplified version of the real code, and usually the code inside the for loop is ~10-20 lines long, that cannot be made simple by using one auxiliary function like myFunction in the example above (had that been the case, I could've just used a thread pool).
Also, this scenario is very, very common in my code, so there are tons of lines which I consider redundant. It would help me a lot if I didn't need to handle all this boilerplate code, but instead be able to do something like:
for arg in array:
with threaded():
myFunction(arg)
i.e somehow threaded() takes every line of code inside it and runs it in a separate thread.
I know that context managers aren't supposed to be used in such situations, that it's probably a bad idea and will require an ugly hack, but nonetheless - can it be done, and how?
| [
"How about this:\nfor arg in array:\n def _thread():\n # code here\n print arg\n\n t = Thread(_thread)\n t.start()\n\nadditionally, with decorators, you can sugar it up a little:\ndef spawn_thread(func):\n t = Thread(func)\n t.start()\n return t\n\nfor arg in array:\n @spawn_thread\n def _thread():\n # code here\n print arg\n\n",
"Would a thread pool help you here? Many implementations for Python exist, for example this one.\n\nP.S: still interested to know what your exact use-case is\n",
"What you want is a kind of \"contextual thread pool\".\nTake a look at the ThreadPool class in this module, designed to be used similar to the manner you've given. Use would be something like this:\nwith ThreadPool() as pool:\n for arg in array:\n pool.add_thread(target=myFunction, args=[arg])\n\nFailures in any task given to a ThreadPool will flag an error, and perform the standard error backtrace handling.\n",
"I think you're over-complicating it. This is the \"pattern\" I use:\n# util.py\ndef start_thread(func, *args):\n thread = threading.Thread(target=func, args=args)\n thread.setDaemon(True)\n thread.start()\n return thread\n\n# in another module\nimport util\n...\nfor arg in array:\n util.start_thread(myFunction, arg)\n\nI don't see the big deal about having to create myFunction. You could even define the function inline with the function that starts it.\ndef do_stuff():\n def thread_main(arg):\n print \"I'm a new thread with arg=%s\" % arg\n for arg in array:\n util.start_thread(thread_main, arg)\n\nIf you're creating a large number of threads, a thread pool definitely makes more sense. You can easily make your own with the Queue and threading modules. Basically create a jobs queue, create N worker threads, give each thread a \"pointer\" to the queue and have them pull jobs from the queue and process them.\n"
] | [
1,
0,
0,
0
] | [] | [] | [
"contextmanager",
"multithreading",
"python"
] | stackoverflow_0003123876_contextmanager_multithreading_python.txt |
Q:
Separating HTML into groups using BeautifulSoup when groups are all in the same element
Here's an example:
<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>
If each animal was in a separate element I could just iterate over the elements. That would be great. But the website I'm trying to parse has all the information in one element.
What would be the best way of either separating the soup into different animals, or to some other way extract the attributes and which animal they belong to?
(feel free to recommend a better title)
A:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("""
<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>
""")
animals = []
attributes = {}
for p in soup.findAll('p'):
if (p['class'] == 'animal'):
animals.append(p.string)
elif (p['class'] == 'attribute'):
if animals[-1] not in attributes.keys():
attributes[animals[-1]] = [p.string]
else:
attributes[animals[-1]].append(p.string)
print animals
print attributes
That should work.
A:
If you don't need to keep the animal names in order you can simplify Jamie's answer like this
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("""
<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>
""")
attributes = {}
for p in soup.findAll('p'):
if (p['class'] == 'animal'):
animal = p.string
attributes[animal] = []
elif (p['class'] == 'attribute'):
attributes[animal].append(p.string)
print attributes.keys()
print attributes
| Separating HTML into groups using BeautifulSoup when groups are all in the same element | Here's an example:
<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>
If each animal was in a separate element I could just iterate over the elements. That would be great. But the website I'm trying to parse has all the information in one element.
What would be the best way of either separating the soup into different animals, or to some other way extract the attributes and which animal they belong to?
(feel free to recommend a better title)
| [
"from BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(\"\"\"\n<p class='animal'>cats</p>\n<p class='attribute'>they meow</p>\n<p class='attribute'>they have fur</p>\n<p class='animal'>turtles</p>\n<p class='attribute'>they don't make noises</p>\n<p class='attribute'>they have shells</p>\n\"\"\")\n\nanimals = []\nattributes = {}\n\nfor p in soup.findAll('p'):\n if (p['class'] == 'animal'):\n animals.append(p.string)\n elif (p['class'] == 'attribute'):\n if animals[-1] not in attributes.keys():\n attributes[animals[-1]] = [p.string]\n else:\n attributes[animals[-1]].append(p.string)\n\nprint animals\nprint attributes\n\nThat should work.\n",
"If you don't need to keep the animal names in order you can simplify Jamie's answer like this\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(\"\"\"\n<p class='animal'>cats</p>\n<p class='attribute'>they meow</p>\n<p class='attribute'>they have fur</p>\n<p class='animal'>turtles</p>\n<p class='attribute'>they don't make noises</p>\n<p class='attribute'>they have shells</p>\n\"\"\")\n\nattributes = {}\n\nfor p in soup.findAll('p'):\n if (p['class'] == 'animal'):\n animal = p.string\n attributes[animal] = []\n elif (p['class'] == 'attribute'):\n attributes[animal].append(p.string)\n\nprint attributes.keys()\nprint attributes\n\n"
] | [
2,
2
] | [] | [] | [
"beautifulsoup",
"html",
"parsing",
"python"
] | stackoverflow_0003124612_beautifulsoup_html_parsing_python.txt |
Q:
In Python, how do you use decimal module in a script rather than the interpreter?
I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works:
>>> from decimal import *
>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")
But, when I put the following code:
from decimal import *
print Decimal('1.2')+Decimal('2.3')
in a separate file (called decimal.py) and run it as a module, the interpreter complains:
NameError: name 'Decimal' is not defined
I also tried putting this code in a separate file:
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
When I run it as a module, the interpreter says:
AttributeError: 'module' object has no attribute 'Decimal'
What's going on?
A:
You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.
To solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.
A:
This works fine as is for me on Python 2.5.2
from decimal import *
print Decimal('1.2')+Decimal('2.3')
I would encourage you to specify what you want to use from decimal
from decimal import Decimal
print Decimal('1.2')+Decimal('2.3')
In your other example you should use
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
| In Python, how do you use decimal module in a script rather than the interpreter? | I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works:
>>> from decimal import *
>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")
But, when I put the following code:
from decimal import *
print Decimal('1.2')+Decimal('2.3')
in a separate file (called decimal.py) and run it as a module, the interpreter complains:
NameError: name 'Decimal' is not defined
I also tried putting this code in a separate file:
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
When I run it as a module, the interpreter says:
AttributeError: 'module' object has no attribute 'Decimal'
What's going on?
| [
"You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.\nTo solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.\n",
"This works fine as is for me on Python 2.5.2\nfrom decimal import *\nprint Decimal('1.2')+Decimal('2.3')\n\nI would encourage you to specify what you want to use from decimal\nfrom decimal import Decimal\nprint Decimal('1.2')+Decimal('2.3')\n\nIn your other example you should use\nimport decimal\nprint decimal.Decimal('1.2')+decimal.Decimal('2.3') \n\n"
] | [
21,
12
] | [] | [] | [
"decimal",
"python"
] | stackoverflow_0003124905_decimal_python.txt |
Q:
How to order by aggregate with conditions on fields of a relation
My code:
class School(models.Model): pass
class Student(models.Model):
school = models.ForeignKey(School)
TYPE_CHOICES = (
('ug', 'Undergraduate'),
('gr', 'Graduate'),
('al', 'Alumnus'),
)
type = models.CharField(max_length=2)
How do I obtain a QuerySet of Schools ordered by the number of Undergraduate Students?
A:
from django.db.models import Count
School.objects.filter(student__type='ug').annotate(
num_students=Count('student')
).order_by('num_students')
See the documentation on the relationship between aggregate and filter clauses.
| How to order by aggregate with conditions on fields of a relation | My code:
class School(models.Model): pass
class Student(models.Model):
school = models.ForeignKey(School)
TYPE_CHOICES = (
('ug', 'Undergraduate'),
('gr', 'Graduate'),
('al', 'Alumnus'),
)
type = models.CharField(max_length=2)
How do I obtain a QuerySet of Schools ordered by the number of Undergraduate Students?
| [
"from django.db.models import Count\nSchool.objects.filter(student__type='ug').annotate(\n num_students=Count('student')\n ).order_by('num_students')\n\nSee the documentation on the relationship between aggregate and filter clauses.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003124922_django_django_models_python.txt |
Q:
Remote execution of commands using the Django ORM
Can I somehow work with remote databases (if they can do it) with the Django ORM?
It is understood that the sitting has spelled out the local database. And periodically to make connection to various external databases and perform any sort of commands such as load dump.
A:
If you can connect to the database remotely, then you can simply specify its host/port in settings.py exactly as you would a local one.
| Remote execution of commands using the Django ORM | Can I somehow work with remote databases (if they can do it) with the Django ORM?
It is understood that the sitting has spelled out the local database. And periodically to make connection to various external databases and perform any sort of commands such as load dump.
| [
"If you can connect to the database remotely, then you can simply specify its host/port in settings.py exactly as you would a local one.\n"
] | [
1
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0003123801_django_orm_python.txt |
Q:
Forcing to make floating point calculations
In IronPython is there any way to force the expression containing integer values to be calculated as floating point. For instance, I'd like the expression
1/3
to be evaluated as
1./3.
with the result 0.333...
I need this to make a simple run-time expression calculator within a C# project by means of IronPython. I cannot force users to input expression with trailing decimal points.
A:
from __future__ import division
print 1 / 3
print 1 // 3
A:
You may force a floating point division like any of these, no matter if anything is imported from __future__:
print val1 / (val2 + 0.0)
print (val1 + 0.0) / val2
print float(val1) / val2
print val1 / float(val2)
A:
If your users are entering values anyway, then presumably you are converting the values to ints. So simply convert them to float instead.
val1 = float(raw_input())
val2 = float(raw_input())
print val1/val2
| Forcing to make floating point calculations | In IronPython is there any way to force the expression containing integer values to be calculated as floating point. For instance, I'd like the expression
1/3
to be evaluated as
1./3.
with the result 0.333...
I need this to make a simple run-time expression calculator within a C# project by means of IronPython. I cannot force users to input expression with trailing decimal points.
| [
"from __future__ import division\n\nprint 1 / 3\nprint 1 // 3\n\n",
"You may force a floating point division like any of these, no matter if anything is imported from __future__:\nprint val1 / (val2 + 0.0)\nprint (val1 + 0.0) / val2\nprint float(val1) / val2\nprint val1 / float(val2)\n\n",
"If your users are entering values anyway, then presumably you are converting the values to ints. So simply convert them to float instead.\nval1 = float(raw_input())\nval2 = float(raw_input())\nprint val1/val2\n\n"
] | [
11,
11,
2
] | [] | [] | [
"expression",
"ironpython",
"python"
] | stackoverflow_0003125192_expression_ironpython_python.txt |
Q:
Not able to add custom fields to django-registration
I extended RegistrationFormUniqueEmail
class CustomRegistrationFormUniqueEmail(RegistrationFormUniqueEmail):
first_name = forms.CharField(label=_('First name'), max_length=30,required=True)
last_name = forms.CharField(label=_('Last name'), max_length=30, required=True)
def save(self, profile_callback=None):
new_user = super(CustomRegistrationFormUniqueEmail, self).save(profile_callback=profile_callback)
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
return new_user
then changed view
# form = form_class(data=request.POST, files=request.FILES)
form = CustomRegistrationFormUniqueEmail(data=request.POST, files=request.FILES)
But, still I see default form which contains four fields only.
A:
We recently implemented such a form. Here's what we've done:
Create a new backend (just copy it from the default backend to start with)
registration/
backends/
default/
custom/ # <- your new backend
...
In the new urls.py adjust the backend arguments
...
{ 'backend': 'registration.backends.custom.DefaultBackend' },
...
Create a forms.py under custom. Adjust this form to your liking (fields and validations)
In the registration/urls.py point to the proper backend:
# from registration.backends.default.urls import *
from registration.backends.custom.urls import *
That should work. Particularly this works because:
Your custom/__init__.py will have a DefaultBackend class with a get_form_class method:
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
And you import your own RegistrationForm in that file, too:
from registration.backends.custom.forms import RegistrationForm
A:
I'm not sure, off hand, why it isn't working but I am pretty sure you do not need to edit django-registration's views.py ... you can pass your new CustomRegistrationFormUniqueEmail as an argument in urls.py.
A:
You can try to look here Extending django-registration using signals and here http://dmitko.ru/?p=546
| Not able to add custom fields to django-registration | I extended RegistrationFormUniqueEmail
class CustomRegistrationFormUniqueEmail(RegistrationFormUniqueEmail):
first_name = forms.CharField(label=_('First name'), max_length=30,required=True)
last_name = forms.CharField(label=_('Last name'), max_length=30, required=True)
def save(self, profile_callback=None):
new_user = super(CustomRegistrationFormUniqueEmail, self).save(profile_callback=profile_callback)
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
return new_user
then changed view
# form = form_class(data=request.POST, files=request.FILES)
form = CustomRegistrationFormUniqueEmail(data=request.POST, files=request.FILES)
But, still I see default form which contains four fields only.
| [
"We recently implemented such a form. Here's what we've done:\n\nCreate a new backend (just copy it from the default backend to start with)\nregistration/\n backends/\n default/\n custom/ # <- your new backend\n\n...\nIn the new urls.py adjust the backend arguments\n...\n{ 'backend': 'registration.backends.custom.DefaultBackend' },\n...\n\nCreate a forms.py under custom. Adjust this form to your liking (fields and validations)\nIn the registration/urls.py point to the proper backend:\n # from registration.backends.default.urls import *\n from registration.backends.custom.urls import *\n\n\nThat should work. Particularly this works because:\n\nYour custom/__init__.py will have a DefaultBackend class with a get_form_class method:\ndef get_form_class(self, request):\n \"\"\"\n Return the default form class used for user registration.\n \"\"\"\n return RegistrationForm\n\nAnd you import your own RegistrationForm in that file, too:\nfrom registration.backends.custom.forms import RegistrationForm\n\n\n",
"I'm not sure, off hand, why it isn't working but I am pretty sure you do not need to edit django-registration's views.py ... you can pass your new CustomRegistrationFormUniqueEmail as an argument in urls.py.\n",
"You can try to look here Extending django-registration using signals and here http://dmitko.ru/?p=546\n"
] | [
3,
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_registration",
"python"
] | stackoverflow_0002934867_django_django_forms_django_registration_python.txt |
Q:
Disable all `pylint` 'Convention' messages
Background
I find pylint useful, but I also find it is horrifically undocumented, has painfully verbose output, and lacks an intuitive interface.
I'd like to use pylint, but it keeps pumping out an absurd number of pointless 'convention' messages, e.g. C: 2: Line too long (137/80) etc.
Question
If I could disable these, pylint would be much more usable for me. How does one disable these 'convention' messages?
My own efforts
I've tried putting disable-msg=C301 in ~/.pylintrc (which is being loaded because when I put an error in there pylint complains) which I understand to be the "Line too Long" message based on running this command in the pylint package directory (documentation that can be found would be nice):
$ grep "Line too long" **/*.py
checkers/format.py: 'C0301': ('Line too long (%s/%s)',
Yet this disable-msg does nothing. I'd disable the entire convention category with the disable-msg-cat= command, but there's no indication anywhere I can find of what an identifier of the convention category would be for this command — the intuitive disable-message-cat=convention has no effect.
I'd be much obliged for some direction on this issue.
Thank you.
Brian
A:
If I'm not mistaken, you should be able to use --disable-msg-cat=C (can't remember whether it's uppercase or lowercase or both) to accomplish this.
UPDATE: In later versions of pylint, you should use --disable=C
| Disable all `pylint` 'Convention' messages | Background
I find pylint useful, but I also find it is horrifically undocumented, has painfully verbose output, and lacks an intuitive interface.
I'd like to use pylint, but it keeps pumping out an absurd number of pointless 'convention' messages, e.g. C: 2: Line too long (137/80) etc.
Question
If I could disable these, pylint would be much more usable for me. How does one disable these 'convention' messages?
My own efforts
I've tried putting disable-msg=C301 in ~/.pylintrc (which is being loaded because when I put an error in there pylint complains) which I understand to be the "Line too Long" message based on running this command in the pylint package directory (documentation that can be found would be nice):
$ grep "Line too long" **/*.py
checkers/format.py: 'C0301': ('Line too long (%s/%s)',
Yet this disable-msg does nothing. I'd disable the entire convention category with the disable-msg-cat= command, but there's no indication anywhere I can find of what an identifier of the convention category would be for this command — the intuitive disable-message-cat=convention has no effect.
I'd be much obliged for some direction on this issue.
Thank you.
Brian
| [
"If I'm not mistaken, you should be able to use --disable-msg-cat=C (can't remember whether it's uppercase or lowercase or both) to accomplish this.\nUPDATE: In later versions of pylint, you should use --disable=C\n"
] | [
28
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0003125333_pylint_python.txt |
Q:
django on windows server 2008
Does Django work on Windows server 2008?
A:
Yes it does. Django can run on apache which runs just fine on windows 2008. You can read more about it here.
A:
Yes, there are several ways to run it on Windows. You can do it with Apache, but even better it can be run from IIS using any of the following WSGI compliant extensions:
PyISAPIe
ISAPI-WSGI
| django on windows server 2008 | Does Django work on Windows server 2008?
| [
"Yes it does. Django can run on apache which runs just fine on windows 2008. You can read more about it here.\n",
"Yes, there are several ways to run it on Windows. You can do it with Apache, but even better it can be run from IIS using any of the following WSGI compliant extensions:\n\nPyISAPIe\nISAPI-WSGI\n\n"
] | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003124662_django_python.txt |
Q:
python subprocess hide stdout and wait it to complete
I have this code:
def method_a(self):
command_line = 'somtoolbox GrowingSOM ' + som_prop_path
subprocess.Popen(shlex.split(command_line))
......
def method_b(self): .....
....
and like you all see, method_a has a subprocess that is calling the somtoolbox program. But this program have a long stdout, and I want to hide it. I tried:
subprocess.Popen(shlex.split(command_line), stdout=subprocess.PIPE)
But it returned this sentence:
cat: record error: Broked Pipe
(this is a translation of the portuguese sentence: "cat: erro de gravação: Pipe quebrado")
(I'm from brazil)
Also, I have other methods (like method_b there), that are called after the method_a, and tis methods are running before the subprocess complete the process.
How I can hide the stdout at all (and don't want it anywhere), and make the other code wait for the subprocess to finish the execution ?
Obs: The somtoolbox is a java program, that gives the long output to the terminal.
Tried:
outputTuple = subprocess.Popen(shlex.split(command_line), stdout = subprocess.PIPE).communicate()
but continuous returning output to the shell.
Help!
A:
The best way to do that is to redirect the output into /dev/null. You can do that like this:
devnull = open('/dev/null', 'w')
subprocess.Popen(shlex.split(command_line), stdout=devnull)
Then to wait until it's done, you can use .wait() on the Popen object, getting you to this:
devnull = open('/dev/null', 'w')
process = subprocess.Popen(shlex.split(command_line), stdout=devnull)
retcode = process.wait()
retcode will then contain the return code of the process.
ADDITIONAL: As mentioned in comments, this won't hide stderr. To hide stderr as well you'd do it like so:
devnull = open('/dev/null', 'w')
process = subprocess.Popen(shlex.split(command_line), stdout=devnull, stderr=devnull)
retcode = process.wait()
A:
Popen.communicate is used to wait for the process to terminate. For example:
from subprocess import PIPE, Popen
outputTuple = Popen(["gcc", "--version"], stdout = PIPE).communicate()
will return a tuple of strings, one for stdout and another one for stderr output.
| python subprocess hide stdout and wait it to complete | I have this code:
def method_a(self):
command_line = 'somtoolbox GrowingSOM ' + som_prop_path
subprocess.Popen(shlex.split(command_line))
......
def method_b(self): .....
....
and like you all see, method_a has a subprocess that is calling the somtoolbox program. But this program have a long stdout, and I want to hide it. I tried:
subprocess.Popen(shlex.split(command_line), stdout=subprocess.PIPE)
But it returned this sentence:
cat: record error: Broked Pipe
(this is a translation of the portuguese sentence: "cat: erro de gravação: Pipe quebrado")
(I'm from brazil)
Also, I have other methods (like method_b there), that are called after the method_a, and tis methods are running before the subprocess complete the process.
How I can hide the stdout at all (and don't want it anywhere), and make the other code wait for the subprocess to finish the execution ?
Obs: The somtoolbox is a java program, that gives the long output to the terminal.
Tried:
outputTuple = subprocess.Popen(shlex.split(command_line), stdout = subprocess.PIPE).communicate()
but continuous returning output to the shell.
Help!
| [
"The best way to do that is to redirect the output into /dev/null. You can do that like this:\ndevnull = open('/dev/null', 'w')\nsubprocess.Popen(shlex.split(command_line), stdout=devnull)\n\nThen to wait until it's done, you can use .wait() on the Popen object, getting you to this:\ndevnull = open('/dev/null', 'w')\nprocess = subprocess.Popen(shlex.split(command_line), stdout=devnull)\nretcode = process.wait()\n\nretcode will then contain the return code of the process.\nADDITIONAL: As mentioned in comments, this won't hide stderr. To hide stderr as well you'd do it like so:\ndevnull = open('/dev/null', 'w')\nprocess = subprocess.Popen(shlex.split(command_line), stdout=devnull, stderr=devnull)\nretcode = process.wait()\n\n",
"Popen.communicate is used to wait for the process to terminate. For example:\nfrom subprocess import PIPE, Popen\noutputTuple = Popen([\"gcc\", \"--version\"], stdout = PIPE).communicate()\n\nwill return a tuple of strings, one for stdout and another one for stderr output.\n"
] | [
18,
5
] | [] | [] | [
"python",
"stdout",
"subprocess",
"synchronization"
] | stackoverflow_0003125525_python_stdout_subprocess_synchronization.txt |
Q:
What does a dynamic language like python give you? Coming from a c#/java background. show me the light!
Possible Duplicate:
What’s with the love of dynamic Languages
I'm coming from a c#/java background i.e. strongly typed, OOP language.
I'm very much interested in Python, but I need to learn a little more about the advantages of a dynamic language.
What power does it really give me? (in web applications).
Can someone outline some of the advantages and cool tricks I can do?
A:
I don't think of dynamically typed languages as "allowing cool tricks" (they do, but mostly it's not really sound to use "cool" tricks in production software -- they come in handy for testing, debugging, etc, but when it comes to getting good, fast stuff deployed for production, simplicity rules).
Rather, I think of such languages as "not getting in my way" -- in particular, not slowing me down by forcing me to redundantly specify things over and over. Not every statically typed languages does "get in your way" -- good ones with solid, logically correct type systems like Haskell let the compiler deduce types (though you may redundantly specify them if you like redundancy... or, more to the point, if you want stricter constraints than what the compiler can actually deduce from the code). But in Java (and to a lesser extent in C# except when you use the reasonably recent var keyword) redundancy is the rule, and that impacts productivity.
A compromise can be offered by third-party checking systems for Python, like typecheck -- I don't use it, myself, but I can see how somebody who really thinks static type checking adds a lot of value might be happy with it. There's even a syntax (which the Python compiler accepts but does nothing with) in recent Python versions to let you annotate your function arguments and return values -- its purpose is to let such packages as typecheck be extended to merge more naturally with the language proper (though I don't think typecheck does yet).
Edit:
As I wrote here, and I quote:
I love the explanations of Van Roy and
Haridi, p. 104-106 of their book,
though I may or may not agree with
their conclusions (which are basically
that the intrinsic difference is tiny
-- they point to Oz and Alice as interoperable languages without and
with static typing, respectively), all
the points they make are good. Most
importantly, I believe, the way
dynamic typing allows real modularity
(harder with static typing, since type
discipline must be enforced across
module boundaries), and "exploratory
computing in a computation model that
integrates several programming
paradigms".
"Dynamic typing is recommended", they
conclude, "when programs must be as
flexible as possible". I recommend
reading the Agile Manifesto to
understand why maximal flexibility is
crucial in most real-world application
programming -- and therefore why, in
said real world rather than in the
more academic circles Dr. Van Roy and
Dr. Hadidi move in, dynamic typing is
generally preferable, and not such a
tiny issue as they make the difference
to be. Still, they at least show more
awareness of the issues, in devoting 3
excellent pages of discussion about
it, pros and cons, than almost any
other book I've seen -- most books
have clearly delineated and preformed
precedence one way or the other, so
the discussion is rarely as balanced
as that;).
A:
I enjoyed reading this comparison between Python and Java.
In relation with web, I would recommend doing a simple example with Django to see how it works.
A:
Python (like all dynamic languages) defers attribute lookups until runtime. This allows you to break past the ideas of polymorphism and interfaces, and leverage the power of duck-typing, whereby you can use a type that merely looks like it should work, instead of having to worry about its ancestry or what it claims to implement.
A:
Can't speak for python per se, but I was playing around with the PSObject class in Powershell last week which allows you to dynamically add members, methods, etc. Coming from a C++\C# background, this seemed like magic - no need to re-comile to get these constructs in-built making it a much nicer workflow for what I was doing.
A:
Python is strongly typed and object oriented the difference is that Python is also dynamic.
In Python classes are objects like everything else and as every other object you can create and modify them at runtime. This basically means that you can create and change modules, metaclasses, classes, attributes/methods and functions at runtime. You can add base classes to already existing classes and several other things.
| What does a dynamic language like python give you? Coming from a c#/java background. show me the light! |
Possible Duplicate:
What’s with the love of dynamic Languages
I'm coming from a c#/java background i.e. strongly typed, OOP language.
I'm very much interested in Python, but I need to learn a little more about the advantages of a dynamic language.
What power does it really give me? (in web applications).
Can someone outline some of the advantages and cool tricks I can do?
| [
"I don't think of dynamically typed languages as \"allowing cool tricks\" (they do, but mostly it's not really sound to use \"cool\" tricks in production software -- they come in handy for testing, debugging, etc, but when it comes to getting good, fast stuff deployed for production, simplicity rules).\nRather, I think of such languages as \"not getting in my way\" -- in particular, not slowing me down by forcing me to redundantly specify things over and over. Not every statically typed languages does \"get in your way\" -- good ones with solid, logically correct type systems like Haskell let the compiler deduce types (though you may redundantly specify them if you like redundancy... or, more to the point, if you want stricter constraints than what the compiler can actually deduce from the code). But in Java (and to a lesser extent in C# except when you use the reasonably recent var keyword) redundancy is the rule, and that impacts productivity.\nA compromise can be offered by third-party checking systems for Python, like typecheck -- I don't use it, myself, but I can see how somebody who really thinks static type checking adds a lot of value might be happy with it. There's even a syntax (which the Python compiler accepts but does nothing with) in recent Python versions to let you annotate your function arguments and return values -- its purpose is to let such packages as typecheck be extended to merge more naturally with the language proper (though I don't think typecheck does yet).\nEdit:\nAs I wrote here, and I quote:\n\nI love the explanations of Van Roy and\n Haridi, p. 104-106 of their book,\n though I may or may not agree with\n their conclusions (which are basically\n that the intrinsic difference is tiny\n -- they point to Oz and Alice as interoperable languages without and\n with static typing, respectively), all\n the points they make are good. Most\n importantly, I believe, the way\n dynamic typing allows real modularity\n (harder with static typing, since type\n discipline must be enforced across\n module boundaries), and \"exploratory\n computing in a computation model that\n integrates several programming\n paradigms\".\n\"Dynamic typing is recommended\", they\n conclude, \"when programs must be as\n flexible as possible\". I recommend\n reading the Agile Manifesto to\n understand why maximal flexibility is\n crucial in most real-world application\n programming -- and therefore why, in\n said real world rather than in the\n more academic circles Dr. Van Roy and\n Dr. Hadidi move in, dynamic typing is\n generally preferable, and not such a\n tiny issue as they make the difference\n to be. Still, they at least show more\n awareness of the issues, in devoting 3\n excellent pages of discussion about\n it, pros and cons, than almost any\n other book I've seen -- most books\n have clearly delineated and preformed\n precedence one way or the other, so\n the discussion is rarely as balanced\n as that;).\n\n",
"I enjoyed reading this comparison between Python and Java.\nIn relation with web, I would recommend doing a simple example with Django to see how it works.\n",
"Python (like all dynamic languages) defers attribute lookups until runtime. This allows you to break past the ideas of polymorphism and interfaces, and leverage the power of duck-typing, whereby you can use a type that merely looks like it should work, instead of having to worry about its ancestry or what it claims to implement.\n",
"Can't speak for python per se, but I was playing around with the PSObject class in Powershell last week which allows you to dynamically add members, methods, etc. Coming from a C++\\C# background, this seemed like magic - no need to re-comile to get these constructs in-built making it a much nicer workflow for what I was doing.\n",
"Python is strongly typed and object oriented the difference is that Python is also dynamic.\nIn Python classes are objects like everything else and as every other object you can create and modify them at runtime. This basically means that you can create and change modules, metaclasses, classes, attributes/methods and functions at runtime. You can add base classes to already existing classes and several other things.\n"
] | [
5,
2,
1,
0,
0
] | [] | [] | [
"dynamic_languages",
"oop",
"python"
] | stackoverflow_0003125448_dynamic_languages_oop_python.txt |
Q:
Network - testing connectivity [Python or C]
Let's say I want to see if my ftp server is online, how could I do this in a program.
Also, what do you think would be the easiest least intrusive way.
A:
Personally, I would try nmap first to do this, http://nmap.org.
nmap $HOSTNAME -p 21
To test port 21 (ftp) on a list of servers in python might look like this:
#!/usr/bin/env python
from socket import *
host_list=['localhost', 'stackoverflow.com']
port=21 # (FTP port)
def test_port(ip_address, port, timeout=3):
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(timeout)
result = s.connect_ex((ip_address, port))
s.close()
if(result == 0):
return True
else:
return False
for host in host_list:
if test_port(gethostbyname(host), port):
print 'Successfully connected to',
else:
print 'Failed to connect to',
print '%s on port %d' % (host, port)
A:
Connect to the port of your FTP server to see if it is accepting connections.
If you want to go one step further you could send an ls command and check that you get a sensible response.
If you want to do it in Python you can use ftplib.
| Network - testing connectivity [Python or C] | Let's say I want to see if my ftp server is online, how could I do this in a program.
Also, what do you think would be the easiest least intrusive way.
| [
"Personally, I would try nmap first to do this, http://nmap.org. \nnmap $HOSTNAME -p 21\n\nTo test port 21 (ftp) on a list of servers in python might look like this:\n#!/usr/bin/env python \nfrom socket import * \n\nhost_list=['localhost', 'stackoverflow.com']\n\nport=21 # (FTP port)\n\ndef test_port(ip_address, port, timeout=3):\n s = socket(AF_INET, SOCK_STREAM)\n s.settimeout(timeout)\n result = s.connect_ex((ip_address, port))\n s.close()\n if(result == 0):\n return True\n else:\n return False\n\nfor host in host_list:\n if test_port(gethostbyname(host), port):\n print 'Successfully connected to',\n else:\n print 'Failed to connect to',\n print '%s on port %d' % (host, port)\n\n",
"Connect to the port of your FTP server to see if it is accepting connections.\nIf you want to go one step further you could send an ls command and check that you get a sensible response.\nIf you want to do it in Python you can use ftplib.\n"
] | [
2,
1
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0003125724_networking_python.txt |
Q:
Selecting Widgets
In Tkinter I'm trying to make it so when a command is run a widget is automatically selected, so that a one may bind events to the newly selected widget.
Basically I want it so when I press a button a text widget appears. When it appears normally one would have to click the text widget to facilitate the running of events bound to the text widget. I want that behavior to automatically happen when the user clicks the button. So that one does not have to click the button and then the text widget, but simply the button.
I'd also like it so if one started typing after the button was pressed it would automatically start filling the text widget. Again to cut out having to click on the text widget.
What bit of code does the above?
A:
The terminology which describes what you want is "focus" -- you want to set the keyboard focus to your text widget. To do that you need to use the focus_set() and/or focus_force() methods on the text widget.
| Selecting Widgets | In Tkinter I'm trying to make it so when a command is run a widget is automatically selected, so that a one may bind events to the newly selected widget.
Basically I want it so when I press a button a text widget appears. When it appears normally one would have to click the text widget to facilitate the running of events bound to the text widget. I want that behavior to automatically happen when the user clicks the button. So that one does not have to click the button and then the text widget, but simply the button.
I'd also like it so if one started typing after the button was pressed it would automatically start filling the text widget. Again to cut out having to click on the text widget.
What bit of code does the above?
| [
"The terminology which describes what you want is \"focus\" -- you want to set the keyboard focus to your text widget. To do that you need to use the focus_set() and/or focus_force() methods on the text widget. \n"
] | [
0
] | [] | [] | [
"binding",
"python",
"tkinter"
] | stackoverflow_0003125707_binding_python_tkinter.txt |
Q:
Refreshing label in Python
I creating applet in gnome panel. All code is good. But info in panel is static. But need refresh this info in time. 1 secon or 5 second...
Here is part of python code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import gobject
import gtk
import pygtk
import gnomeapplet
import time
import urllib2
pygtk.require('2.0')
def applet_factory(applet, iid):
label = gtk.Label("Simple text")
applet.add(label)
applet.show_all()
print('Factory started')
if __name__ == '__main__': # testing for execution
print('Starting factory')
gnomeapplet.bonobo_factory('OAFIID:SampleApplet_Factory',
gnomeapplet.Applet.__gtype__,
'Sample Applet', '0.1',
applet_factory)
I need refresh "simple text" label in time interval. How did that?
A:
What about...:
def applet_factory(applet, iid):
label = gtk.Label("Simple text")
applet.add(label)
applet.show_all()
return label
thelabel = applet_factory(applet, iid)
def redrawlabel(*args):
thelabel.queue_draw()
# process all events
while gtk.events_pending():
gtk.main_iteration(False)
return True
# call redrawlabel every 5 minutes
gtk.timeout_add(5*60*1000, redrawlabel)
If you also need to set the text to something different, thelabel.set_text('something else') will do that.
| Refreshing label in Python | I creating applet in gnome panel. All code is good. But info in panel is static. But need refresh this info in time. 1 secon or 5 second...
Here is part of python code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import gobject
import gtk
import pygtk
import gnomeapplet
import time
import urllib2
pygtk.require('2.0')
def applet_factory(applet, iid):
label = gtk.Label("Simple text")
applet.add(label)
applet.show_all()
print('Factory started')
if __name__ == '__main__': # testing for execution
print('Starting factory')
gnomeapplet.bonobo_factory('OAFIID:SampleApplet_Factory',
gnomeapplet.Applet.__gtype__,
'Sample Applet', '0.1',
applet_factory)
I need refresh "simple text" label in time interval. How did that?
| [
"What about...:\ndef applet_factory(applet, iid): \n label = gtk.Label(\"Simple text\")\n applet.add(label)\n applet.show_all()\n return label\n\nthelabel = applet_factory(applet, iid)\n\ndef redrawlabel(*args):\n thelabel.queue_draw()\n # process all events\n while gtk.events_pending():\n gtk.main_iteration(False)\n return True\n\n# call redrawlabel every 5 minutes\ngtk.timeout_add(5*60*1000, redrawlabel)\n\nIf you also need to set the text to something different, thelabel.set_text('something else') will do that.\n"
] | [
0
] | [] | [] | [
"applet",
"python"
] | stackoverflow_0003126058_applet_python.txt |
Q:
How to run Python top level/interpreter with file input?
Say I had a Python file, and I wanted to run it in the top level, but after it finishes, I want to pick up where it leaves off. I want to be able to use the objects it creates, etc.
A simple example, let's say I have a Python script that does i = 5. When the script ends, I want to be returned to the top level and be able to continue with i = 5.
A:
Assuming I'm understanding your question correctly, the -i switch is what you're looking for:
~$ echo "i = 5" > start.py
~$ python -i start.py
>>> i
5
A:
Looks like you're looking for execfile - for example:
$ cat >seti.py
i = 5
^C
$ cat >useit.py
execfile('seti.py')
print i
$ python useit.py
5
$
A:
python -i or the code module.
A:
As mentioned, 'python -i ' is the closest answer to your question. You can also use 'import' to run scripts in the interpreter. For example, if you're editing "testscript.py" you could do:
$ ls -l
-rw-r--r-- 1 Xxxx None 771 2009-02-07 18:26 testscript.py
$ python
>>> import testscript
>>> print testlist
['result1', 'result2']
>>>
testscript.py has to be in sys.path for this to work (sys.path includes the current working directory automatically).
This is useful if you want to run a few different scripts and have the environment from all of them at the same time.
A:
you can also set PYTHONINSPECT in your environment
| How to run Python top level/interpreter with file input? | Say I had a Python file, and I wanted to run it in the top level, but after it finishes, I want to pick up where it leaves off. I want to be able to use the objects it creates, etc.
A simple example, let's say I have a Python script that does i = 5. When the script ends, I want to be returned to the top level and be able to continue with i = 5.
| [
"Assuming I'm understanding your question correctly, the -i switch is what you're looking for:\n~$ echo \"i = 5\" > start.py\n~$ python -i start.py \n>>> i\n5\n\n",
"Looks like you're looking for execfile - for example:\n$ cat >seti.py\ni = 5\n^C\n$ cat >useit.py\nexecfile('seti.py')\nprint i\n$ python useit.py \n5\n$ \n\n",
"python -i or the code module.\n",
"As mentioned, 'python -i ' is the closest answer to your question. You can also use 'import' to run scripts in the interpreter. For example, if you're editing \"testscript.py\" you could do:\n$ ls -l\n-rw-r--r-- 1 Xxxx None 771 2009-02-07 18:26 testscript.py\n$ python\n>>> import testscript\n>>> print testlist\n['result1', 'result2']\n>>>\n\ntestscript.py has to be in sys.path for this to work (sys.path includes the current working directory automatically).\nThis is useful if you want to run a few different scripts and have the environment from all of them at the same time. \n",
"you can also set PYTHONINSPECT in your environment \n"
] | [
4,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003125678_python.txt |
Q:
Following a Dynamic Score
I have little to no formal discrete math training, and have run into a wee bit of an issue. I am trying to write an agent which reads in a human player's (arbitrary) score and scores a point every so often. The agent needs to "lag behind" and "catch up" every so often, so that the human player believes there is some competition going on. Then, the agent must either win or lose (depending on the condition) against the human.
I have tried a few different techniques, including a wonky probabilistic loop (which failed horribly). I was thinking that this problem calls for something like an emission Hidden Markov Model (HMM), but I'm not sure how to implement it (or even whether this is the best approach).
I have a gist up, but again, it sucks.
I hope the __main__ function provides some insight as to the goal of this agent. It is going to be called in pygame.
A:
I think you may be over-thinking this. You can use simple probability to estimate how often and by how much the computer's score should "catch-up". Additionally, you can calculate the difference between the computer's score and human's score, and then feed this to a sigmoid-like function to give you the degree at which the computer's score increases.
Illustrative Python:
#!/usr/bin/python
import random, math
human_score = 0
computer_score = 0
trials = 100
computer_ahead_factor = 5 # maximum amount of points the computer can be ahead by
computer_catchup_prob = 0.33 # probability of computer catching up
computer_ahead_prob = 0.5 # probability of computer being ahead of human
computer_advantage_count = 0
for i in xrange(trials):
# Simulate player score increase.
human_score += random.randint(0,5) # add an arbitrary random amount
# Simulate computer lagging behind human, by calculating the probability of
# computer jumping ahead based on proximity to the human's score.
score_diff = human_score - computer_score
p = (math.atan(score_diff)/(math.pi/2.) + 1)/2.
if random.random() < computer_ahead_prob:
computer_score = human_score + random.randint(0,computer_ahead_factor)
elif random.random() < computer_catchup_prob:
computer_score += int(abs(score_diff)*p)
# Display scores.
print 'Human score:',human_score
print 'Computer score:',computer_score
computer_advantage_count += computer_score > human_score
print 'Effective computer advantage ratio: %.6f' % (computer_advantage_count/float(trials),)
A:
I am making the assumption that the human cannot see the computer agent playing the game. If this is the case, here is one idea you might try.
Create a list of all the possible point combinations that can be scored for any given move. For each move, find a score range which you would like the agent to end up within after the current turn. Reduce the set of possible move values to only the values which would end the agent in that particular range and randomly select one. As conditions change for how far behind or ahead you would like the agent to get, simply slide your range appropriately.
If you are looking for something with some kind of built in and researched psychological effects for the human, I cant help you with that. You will need to define more rules for us if you want something more specific to your situation than this.
| Following a Dynamic Score | I have little to no formal discrete math training, and have run into a wee bit of an issue. I am trying to write an agent which reads in a human player's (arbitrary) score and scores a point every so often. The agent needs to "lag behind" and "catch up" every so often, so that the human player believes there is some competition going on. Then, the agent must either win or lose (depending on the condition) against the human.
I have tried a few different techniques, including a wonky probabilistic loop (which failed horribly). I was thinking that this problem calls for something like an emission Hidden Markov Model (HMM), but I'm not sure how to implement it (or even whether this is the best approach).
I have a gist up, but again, it sucks.
I hope the __main__ function provides some insight as to the goal of this agent. It is going to be called in pygame.
| [
"I think you may be over-thinking this. You can use simple probability to estimate how often and by how much the computer's score should \"catch-up\". Additionally, you can calculate the difference between the computer's score and human's score, and then feed this to a sigmoid-like function to give you the degree at which the computer's score increases.\nIllustrative Python:\n#!/usr/bin/python\nimport random, math\nhuman_score = 0\ncomputer_score = 0\ntrials = 100\ncomputer_ahead_factor = 5 # maximum amount of points the computer can be ahead by\ncomputer_catchup_prob = 0.33 # probability of computer catching up\ncomputer_ahead_prob = 0.5 # probability of computer being ahead of human\ncomputer_advantage_count = 0\nfor i in xrange(trials):\n # Simulate player score increase.\n human_score += random.randint(0,5) # add an arbitrary random amount\n # Simulate computer lagging behind human, by calculating the probability of\n # computer jumping ahead based on proximity to the human's score.\n score_diff = human_score - computer_score\n p = (math.atan(score_diff)/(math.pi/2.) + 1)/2.\n if random.random() < computer_ahead_prob:\n computer_score = human_score + random.randint(0,computer_ahead_factor)\n elif random.random() < computer_catchup_prob:\n computer_score += int(abs(score_diff)*p)\n # Display scores.\n print 'Human score:',human_score\n print 'Computer score:',computer_score\n computer_advantage_count += computer_score > human_score\nprint 'Effective computer advantage ratio: %.6f' % (computer_advantage_count/float(trials),)\n\n",
"I am making the assumption that the human cannot see the computer agent playing the game. If this is the case, here is one idea you might try.\nCreate a list of all the possible point combinations that can be scored for any given move. For each move, find a score range which you would like the agent to end up within after the current turn. Reduce the set of possible move values to only the values which would end the agent in that particular range and randomly select one. As conditions change for how far behind or ahead you would like the agent to get, simply slide your range appropriately.\nIf you are looking for something with some kind of built in and researched psychological effects for the human, I cant help you with that. You will need to define more rules for us if you want something more specific to your situation than this.\n"
] | [
2,
0
] | [] | [] | [
"agent",
"artificial_intelligence",
"python",
"statistics"
] | stackoverflow_0003115744_agent_artificial_intelligence_python_statistics.txt |
Q:
Should a modifying class method save itself or be explicity called after the method is called?
Suppose a class has a method that modifies it's internals.
Should that method call save on itself before returning or should the save be left to the caller to explicitly save after the modifying method has been called?
Example:
Explicitly calling save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
bar = Bar()
bar.set_foo("foobar")
bar.save()
or allowing method to call save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
self.save()
bar = Bar()
bar.set_foo("foobar")
I'm working with django, but I was wondering if there was a best practice in django or in general for this situation.
A:
The user of your API might want to make several changes, saving the object after every change is anything but good so no, don't call save in your method.
A:
The user of your API might forget to call .save() and then get screwed. So I think its better to call save for him. For cases like those Daslch mentions, if it makes sense, you can define:
def set_foo(self, foo, skip_save=False):
self.foo = foo
if not skip_save:
self.save()
so the user can, if she wishes to (and explicitly states that), avoid the save.
A:
Actually, I agree with both Ofri and Daslch ... depending on what day of the week it is. If this is just one of many modification routines you might do to a particular object, then it will get quite expensive having each of them do their own save. On the other hand, if this is a rare, self-contained event then you want to do the save because it may not be obvious to the caller (ie, someone other than you that it needs to be done.
For example, tagging events (which use ManyToMany anyway) should require no additional save() on the programmers part.
A:
To deal with all the issues expressed in various existing answers, I suggest the following approach: make a method, call it say saving or modifying, that is a context manager. The entry to that method sets a private flag which says the modification is in progress; the exit resets the flags and performs the saving; all modifying methods check the flag and raise an exception if not set. For example, using a base class and a save method that real subclasses must override:
import contextlib
class CarefullyDesigned(object):
def __init__(self):
self.__saving = False
def _save(self):
raise NotImplementedError('Must override `_save`!')
def _checksaving(self):
"Call at start of subclass `save` and modifying-methods"
if not self.__saving: raise ValueError('No saving in progress!')
@contextlib.contextmanager
def saving(self):
if self.__saving: raise ValueError('Saving already in progress!')
self.__saving = True
yield
self._save()
self.__saving = False
Example use...:
class Bar(models.Model, CarefullyDesigned):
def __init__(self, *a, **k):
models.Model.__init__(self, *a, **k)
CarefullyDesigned.__init__(self)
def _save(self):
self._checksaving()
self.save()
def set_foo(self, foo):
self._checksaving()
self.foo = foo
def set_fie(self, fie):
self._checksaving()
self.fie = fie
bar = Bar()
with bar.saving():
bar.set_foo("foobar")
bar.set_fie("fo fum")
This guarantees the user won't forget to call saving nor accidentally call it in a nested way (that's the purpose of all of those exceptions), and call save only once when the group of modifying-methods is done, in a handy and, I'd say, pretty natural way.
| Should a modifying class method save itself or be explicity called after the method is called? | Suppose a class has a method that modifies it's internals.
Should that method call save on itself before returning or should the save be left to the caller to explicitly save after the modifying method has been called?
Example:
Explicitly calling save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
bar = Bar()
bar.set_foo("foobar")
bar.save()
or allowing method to call save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
self.save()
bar = Bar()
bar.set_foo("foobar")
I'm working with django, but I was wondering if there was a best practice in django or in general for this situation.
| [
"The user of your API might want to make several changes, saving the object after every change is anything but good so no, don't call save in your method.\n",
"The user of your API might forget to call .save() and then get screwed. So I think its better to call save for him. For cases like those Daslch mentions, if it makes sense, you can define:\ndef set_foo(self, foo, skip_save=False):\n self.foo = foo\n if not skip_save:\n self.save()\n\nso the user can, if she wishes to (and explicitly states that), avoid the save.\n",
"Actually, I agree with both Ofri and Daslch ... depending on what day of the week it is. If this is just one of many modification routines you might do to a particular object, then it will get quite expensive having each of them do their own save. On the other hand, if this is a rare, self-contained event then you want to do the save because it may not be obvious to the caller (ie, someone other than you that it needs to be done.\nFor example, tagging events (which use ManyToMany anyway) should require no additional save() on the programmers part.\n",
"To deal with all the issues expressed in various existing answers, I suggest the following approach: make a method, call it say saving or modifying, that is a context manager. The entry to that method sets a private flag which says the modification is in progress; the exit resets the flags and performs the saving; all modifying methods check the flag and raise an exception if not set. For example, using a base class and a save method that real subclasses must override:\nimport contextlib\n\nclass CarefullyDesigned(object):\n\n def __init__(self):\n self.__saving = False\n\n def _save(self):\n raise NotImplementedError('Must override `_save`!')\n\n def _checksaving(self):\n \"Call at start of subclass `save` and modifying-methods\"\n if not self.__saving: raise ValueError('No saving in progress!')\n\n @contextlib.contextmanager\n def saving(self):\n if self.__saving: raise ValueError('Saving already in progress!')\n self.__saving = True\n yield\n self._save()\n self.__saving = False\n\nExample use...:\nclass Bar(models.Model, CarefullyDesigned):\n\n def __init__(self, *a, **k):\n models.Model.__init__(self, *a, **k)\n CarefullyDesigned.__init__(self)\n\n def _save(self):\n self._checksaving()\n self.save()\n\n def set_foo(self, foo):\n self._checksaving()\n self.foo = foo\n\n def set_fie(self, fie):\n self._checksaving()\n self.fie = fie\n\nbar = Bar()\nwith bar.saving():\n bar.set_foo(\"foobar\")\n bar.set_fie(\"fo fum\")\n\nThis guarantees the user won't forget to call saving nor accidentally call it in a nested way (that's the purpose of all of those exceptions), and call save only once when the group of modifying-methods is done, in a handy and, I'd say, pretty natural way.\n"
] | [
3,
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003125198_django_python.txt |
Q:
TypeError: unsupported operand type(s)
This is a program I'm writing that's supposed to display some text in a window...
import pyglet
from pyglet import window
from pyglet.text.layout import TextLayout
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__(width = 800, height = 600,
caption = "Prototype")
self.disclaimer = pyglet.text.Label("Hello World",
font_name = 'Times New Roman',
font_size=36,
color = (255, 255, 255, 255),
x = TextLayout.width / 2,
y = TextLayout.height / 2,
anchor_x='center', anchor_y='center')
def on_draw(self):
self.clear()
self.disclaimer.draw()
if __name__ == '__main__':
window = Window()
pyglet.app.run()
...however every time I try to run it I get this error
line 16
x = TextLayout.width / 2,
TypeError: unsupported operand type(s) for /: 'property' and 'int'
I'm pretty sure this means that I tried to divide a string but in the Pyglet Documentation it says that width and height are ints. I have no idea what I'm doing wrong.
A:
TextLayout is a class -- so TextLayout.width is a raw property, pretty useless to you; you want to get width from an instance of the TextLayout class, not from the class itself! Moreover, the class is specifically used to lay out text documents, so I don't really see why you would want to get it at all (since you have no document object around).
I suspect that what actually you want is:
x = self.width / 2,
y = self.height / 2,
and remove the import of, and all mentions of, TextLayout.
A:
If you're using Python version 3.x the division operator / results in a float type number. Use // to get truncated (traditional style) integer division.
| TypeError: unsupported operand type(s) | This is a program I'm writing that's supposed to display some text in a window...
import pyglet
from pyglet import window
from pyglet.text.layout import TextLayout
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__(width = 800, height = 600,
caption = "Prototype")
self.disclaimer = pyglet.text.Label("Hello World",
font_name = 'Times New Roman',
font_size=36,
color = (255, 255, 255, 255),
x = TextLayout.width / 2,
y = TextLayout.height / 2,
anchor_x='center', anchor_y='center')
def on_draw(self):
self.clear()
self.disclaimer.draw()
if __name__ == '__main__':
window = Window()
pyglet.app.run()
...however every time I try to run it I get this error
line 16
x = TextLayout.width / 2,
TypeError: unsupported operand type(s) for /: 'property' and 'int'
I'm pretty sure this means that I tried to divide a string but in the Pyglet Documentation it says that width and height are ints. I have no idea what I'm doing wrong.
| [
"TextLayout is a class -- so TextLayout.width is a raw property, pretty useless to you; you want to get width from an instance of the TextLayout class, not from the class itself! Moreover, the class is specifically used to lay out text documents, so I don't really see why you would want to get it at all (since you have no document object around).\nI suspect that what actually you want is:\n x = self.width / 2,\n y = self.height / 2,\n\nand remove the import of, and all mentions of, TextLayout.\n",
"If you're using Python version 3.x the division operator / results in a float type number. Use // to get truncated (traditional style) integer division.\n"
] | [
3,
0
] | [] | [] | [
"pyglet",
"python",
"typeerror"
] | stackoverflow_0003126436_pyglet_python_typeerror.txt |
Q:
Does NLTK have a tool for dependency parsing?
I'm building a NLP application and have been using the Stanford Parser for most of my parsing work, but I would like to start using Python.
So far, NLTK seems like the best bet, but I cannot figure out how to parse grammatical dependencies. I.e. this is an example from the Stanford Parser. I want to be able to produce this in NTLK using Python from the original sentence "I am switching to Python.":
nsubj(switching-3, I-1)
aux(switching-3, am-2)
prep_to(switching-3, Python-5)
Can anyone give me a shove in the right direction to parse grammatical dependencies?
A:
NLTK includes support for using the MaltParser, see nltk.parse.malt.MaltParser.
The pretrained English model for the MaltParser that's available here parses to the Stanford basic dependency representation. However, you would still need to call Stanford's JavaNLP code to convert the basic dependencies to the CCprocessed representation given above in your example parse.
| Does NLTK have a tool for dependency parsing? | I'm building a NLP application and have been using the Stanford Parser for most of my parsing work, but I would like to start using Python.
So far, NLTK seems like the best bet, but I cannot figure out how to parse grammatical dependencies. I.e. this is an example from the Stanford Parser. I want to be able to produce this in NTLK using Python from the original sentence "I am switching to Python.":
nsubj(switching-3, I-1)
aux(switching-3, am-2)
prep_to(switching-3, Python-5)
Can anyone give me a shove in the right direction to parse grammatical dependencies?
| [
"NLTK includes support for using the MaltParser, see nltk.parse.malt.MaltParser.\nThe pretrained English model for the MaltParser that's available here parses to the Stanford basic dependency representation. However, you would still need to call Stanford's JavaNLP code to convert the basic dependencies to the CCprocessed representation given above in your example parse. \n"
] | [
14
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0003125926_nlp_nltk_python.txt |
Q:
Python "denormalize" unicode combining characters
I'm looking to standardize some unicode text in python. I'm wondering if there's an easy way to get the "denormalized" form of a combining unicode character in python? e.g. if I have the sequence u'o\xaf' (i.e. latin small letter o followed by combining macron), to get ō (latin small letter o with macron). It's easy to go the other way:
o = unicodedata.lookup("LATIN SMALL LETTER O WITH MACRON")
o = unicodedata.normalize('NFD', o)
A:
As I have commented, U+00AF is not a combining macron. But you can convert it into U+0020 U+0304 with an NFKD transform.
>>> unicodedata.normalize('NFKD', u'o\u00af')
u'o \u0304'
Then you could remove the space and get ō with NFC.
(Note that NFKD is quite aggressive on decomposition in a way that some semantics can be lost — anything that is "compatible" will be separated out. e.g.
'½' (U+008D) ↦ '1' '⁄' (U+2044) '2';
'²' (U+00B2) ↦ '2'
'①' (U+2460) ↦ '1'
etc.)
A:
o = unicodedata.normalize('NFC', o)
| Python "denormalize" unicode combining characters | I'm looking to standardize some unicode text in python. I'm wondering if there's an easy way to get the "denormalized" form of a combining unicode character in python? e.g. if I have the sequence u'o\xaf' (i.e. latin small letter o followed by combining macron), to get ō (latin small letter o with macron). It's easy to go the other way:
o = unicodedata.lookup("LATIN SMALL LETTER O WITH MACRON")
o = unicodedata.normalize('NFD', o)
| [
"As I have commented, U+00AF is not a combining macron. But you can convert it into U+0020 U+0304 with an NFKD transform.\n>>> unicodedata.normalize('NFKD', u'o\\u00af')\nu'o \\u0304'\n\nThen you could remove the space and get ō with NFC.\n\n(Note that NFKD is quite aggressive on decomposition in a way that some semantics can be lost — anything that is \"compatible\" will be separated out. e.g.\n\n'½' (U+008D) ↦ '1' '⁄' (U+2044) '2';\n'²' (U+00B2) ↦ '2'\n'①' (U+2460) ↦ '1'\n\netc.)\n",
"o = unicodedata.normalize('NFC', o)\n\n"
] | [
5,
4
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0003126929_python_unicode.txt |
Q:
Instantiating named GTK widgets in Python
I have a simple GUI build with Glade 3 and I have a gtk.Entry widget with name "input_entry1". I would like to instantiate new gtk.Entry widget called "input_entry2" but I would like to do it simply in Python code, not with Glade, but I can't figure out how to set a name to instance of widget (or create a named widget).
Thanks a lot, Tomas
A:
In C you could name your widgets using gtk_widget_set_name function. I think in Python you can use set_name method:
http://www.pygtk.org/pygtk2tutorial/sec-WidgetNameMethods.html
| Instantiating named GTK widgets in Python | I have a simple GUI build with Glade 3 and I have a gtk.Entry widget with name "input_entry1". I would like to instantiate new gtk.Entry widget called "input_entry2" but I would like to do it simply in Python code, not with Glade, but I can't figure out how to set a name to instance of widget (or create a named widget).
Thanks a lot, Tomas
| [
"In C you could name your widgets using gtk_widget_set_name function. I think in Python you can use set_name method:\nhttp://www.pygtk.org/pygtk2tutorial/sec-WidgetNameMethods.html\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003127031_gtk_pygtk_python.txt |
Q:
Eclipse and WX compatibility issue
I decided to give PyDev and Eclipse a try.
I have compatible version of Python (2.6.5) and wx, but when I try to run a program with PyDev/Eclipse I get the following error:
import wx File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/init.py",
line 45, in File
"/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core.py",
line 4, in ImportError:
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/core.so:
no appropriate 64-bit architecture
(see "man python" for running in
32-bit mode)
I just don't understand why I would get an error while try to run a program under Eclipse, that I know would run if I ran it through say the terminal.
A:
You may find this post helpful.
| Eclipse and WX compatibility issue | I decided to give PyDev and Eclipse a try.
I have compatible version of Python (2.6.5) and wx, but when I try to run a program with PyDev/Eclipse I get the following error:
import wx File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/init.py",
line 45, in File
"/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core.py",
line 4, in ImportError:
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/core.so:
no appropriate 64-bit architecture
(see "man python" for running in
32-bit mode)
I just don't understand why I would get an error while try to run a program under Eclipse, that I know would run if I ran it through say the terminal.
| [
"You may find this post helpful.\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003110491_python_wxpython.txt |
Q:
GWT Request Builder problem (same site policy issue?)
I am trying out GWT in this 'configuration':
1) I have written a server backend in python which will produce json output (running at localhot:8094)
2) I have written a very simple GWT app that will use RequestBuilder to set GET to the python server (in development mode of the GWT eclipse plugin, it is accessible via http://127.0.0.1:8888/test.html)
The code is simply
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Test implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_URL = "http://localhost:8094";
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, SERVER_URL);
try {
requestBuilder.sendRequest(null, new Jazz10RequestCallback());
} catch (RequestException e) {
Window.alert("Failed to send the message: "
+ e.getMessage());
}
}
class Jazz10RequestCallback implements RequestCallback{
public void onError(Request request, Throwable exception) {
// never reach here
Window.alert("Failed to send the message: "
+ exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
// render output
Window.alert(response.getText());
}
}
}
However the alert always comes from onResponseReceived and display nothing (empty string I suppose)
I can reach my python server alright and download the json via the browser. But I cannot see any request hitting the server from GWT.
I have ensured that "inherits name='com.google.gwt.http.HTTP" is in the gwt.xml file
Questions are:
1) Is it same site policy restriction at work here? I would expect Exception (and hence the fail message), but it did not happen
2) If it is indeed the same site policy issue, what is the easiest way to deploy the GWT scripts from the python backend? The eclipse gwt plugin produces some artifact in the war subdirectory. Is it sufficient to copy these files to some static directory of my python backend?
A:
1) Yes it is, while the host is the same, you are trying to access a different port - SOP doesn't allow that. You're probably getting JavaScript exceptions - check Firebug's console or something similar.
2) Follow the guide in the official docs. You don't need a Java server - just one that can serve HTTP content (so, for example, Apache is fine). I have no experience with Python as the backend, but I'm sure there's a solution for serving Python and HTTP.
When using the -noserver flag, your
external server is used by the GWT
Hosted Mode browser to serve up both
your dynamic content, and all static
content (such as the GWT application's
host page, other HTML files, images,
CSS, and so on.)
The dynamic content in this case would be your Python scripts.
A:
yep this will fail due to SOP. What HTTP response code do you get? Normally in this case in comes back as 0 instead of 200 (OK). A solutions may be to use a JSONP approach I wrote a bit on JSONP with GWT as part of this article: http://www.bristol-gtug.org/?p=76
A:
This might be too late. If you are not accessing local resources using a relative path and such, you are right, it's subjected to SOP (same origin policy). The -no-server flag won't be of much help to resolve this issue. To by-pass this issue, read http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/FAQ_JSONFeedsFromOtherDomain . An even better solution would be to use com.google.gwt.jsonp.client.JsonpRequestBuilder, (remember to inherit inherits name = 'com.google.gwt.jsonp.Jsonp' \) which is utilize by the gdata api ("better" in the sense that you don't have to write it yourself). Hope this helps. Cheers~
| GWT Request Builder problem (same site policy issue?) | I am trying out GWT in this 'configuration':
1) I have written a server backend in python which will produce json output (running at localhot:8094)
2) I have written a very simple GWT app that will use RequestBuilder to set GET to the python server (in development mode of the GWT eclipse plugin, it is accessible via http://127.0.0.1:8888/test.html)
The code is simply
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Test implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_URL = "http://localhost:8094";
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, SERVER_URL);
try {
requestBuilder.sendRequest(null, new Jazz10RequestCallback());
} catch (RequestException e) {
Window.alert("Failed to send the message: "
+ e.getMessage());
}
}
class Jazz10RequestCallback implements RequestCallback{
public void onError(Request request, Throwable exception) {
// never reach here
Window.alert("Failed to send the message: "
+ exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
// render output
Window.alert(response.getText());
}
}
}
However the alert always comes from onResponseReceived and display nothing (empty string I suppose)
I can reach my python server alright and download the json via the browser. But I cannot see any request hitting the server from GWT.
I have ensured that "inherits name='com.google.gwt.http.HTTP" is in the gwt.xml file
Questions are:
1) Is it same site policy restriction at work here? I would expect Exception (and hence the fail message), but it did not happen
2) If it is indeed the same site policy issue, what is the easiest way to deploy the GWT scripts from the python backend? The eclipse gwt plugin produces some artifact in the war subdirectory. Is it sufficient to copy these files to some static directory of my python backend?
| [
"1) Yes it is, while the host is the same, you are trying to access a different port - SOP doesn't allow that. You're probably getting JavaScript exceptions - check Firebug's console or something similar.\n2) Follow the guide in the official docs. You don't need a Java server - just one that can serve HTTP content (so, for example, Apache is fine). I have no experience with Python as the backend, but I'm sure there's a solution for serving Python and HTTP.\n\nWhen using the -noserver flag, your\n external server is used by the GWT\n Hosted Mode browser to serve up both\n your dynamic content, and all static\n content (such as the GWT application's\n host page, other HTML files, images,\n CSS, and so on.)\n\nThe dynamic content in this case would be your Python scripts.\n",
"yep this will fail due to SOP. What HTTP response code do you get? Normally in this case in comes back as 0 instead of 200 (OK). A solutions may be to use a JSONP approach I wrote a bit on JSONP with GWT as part of this article: http://www.bristol-gtug.org/?p=76\n",
"This might be too late. If you are not accessing local resources using a relative path and such, you are right, it's subjected to SOP (same origin policy). The -no-server flag won't be of much help to resolve this issue. To by-pass this issue, read http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/FAQ_JSONFeedsFromOtherDomain . An even better solution would be to use com.google.gwt.jsonp.client.JsonpRequestBuilder, (remember to inherit inherits name = 'com.google.gwt.jsonp.Jsonp' \\) which is utilize by the gdata api (\"better\" in the sense that you don't have to write it yourself). Hope this helps. Cheers~\n"
] | [
2,
1,
1
] | [] | [] | [
"gwt",
"json",
"python",
"same_origin_policy"
] | stackoverflow_0002389999_gwt_json_python_same_origin_policy.txt |
Q:
URLs and side effects (Django)
I'm wondering if it's considered okay (particularly, in Django) to have a URL that's only intended for actions with side effects, that's only intended to be accessed by POST, and that is basically invisible to the user. Let's say, for the sake of making this concrete, I have a little messaging system on my site, and from their inbox, a user should be able to do a bunch of things like:
Delete a message
Mark a message as read
Report a message as spam
With all of those things causing a page refresh, but leading back to the same page. I'm wondering how to design my URLs and views around this. I see (at least) two options, and I have no idea which is more idiomatic.
Option 1)
Have a separate URL and view for each action. So, /inbox/delete-message/ maps to views.delete_message, and so on. At the end of each of those views, it redirects back to /inbox/.
I like the way things are clearly separated with this option. If a user somehow finds themselves sending a GET request to /inbox/delete-message/, that presents a sort of weird situation though (do I throw up an error page? silently redirect them?).
Option 2)
Use the same URL and view for each action, and have a POST parameter that identifies the action. So I would have one rather long inbox view, which would have a bunch of if statements testing whether request.POST['action'] == 'delete', or request.POST['delete'] == 'true' or whatever.
This option feels less clean to me, but I also feel like it's more common.
Which would be preferred by Djangonauts? Or is there another option that's better than either of the above?
A:
A modified option #1 is the best approach. Consider this: suppose we weren't talking about a web app, but instead were just designing an inbox class. Which do you like better, a number of methods (delete_message(), mark_as_spam(), etc), or one big method (do_stuff(action))? Of course you would use the separate methods.
A separate URL for each action, each with a separate view, is far preferable. If you don't like the redirect at the end, then don't use it. Instead, have a render_inbox(request) method that returns an HttpResponse, and call the method at the end of each of your views. Of course, redirecting after a POST is a good way to prevent double-actions, and always leaves the user with a consistent URL.
Even better might be to use Ajax to hide the actions, but that is more involved.
A:
I don't think there's anything wrong with either option, but #2 is potentially better from a performance standpoint. After the action is posted you can render the inbox without a redirect, so it cuts down on the HTTP traffic.
A:
If you're writing a web 2.0 messaging app, you would be using AJAX calls and wouldn't be loading a new page at all. The process would proceed like so:
User clicks [delete] for a message. This button has a javascript action bound to it. This action does the following:
i. Change the UI to indicate that something is happening (grey the message or put up an hourglass).
ii. Send a request to /messages/inbox/1234/delete. (where 1234 is some identifier that indicates which message)
iii. When the response from the server comes back, it should indicate success or failure. Reflect this status in the current UI. For example, on success, refresh the inbox view (or just remove the deleted item).
On the server side, now you can create a URL handler for each desired action (i.e. /delete, /flag, etc.).
If want to use an even more RESTful approach, you would use the HTTP action itself to indicate the action to perform. So instead of including delete in your URL, it would be in the action. So instead of GET or POST, use DELETE /messages/inbox/1234. To set a flag for having been read, use SET /messages/inbox/1234?read=true.
I don't know how straightforward it is in Django to implement this latter recommendation, but in general, it's a good idea utilize the protocol (in this case HTTP), rather than work around it by encoding your actions into a URL or parameter.
A:
I agree that #2 is a better approach.
But take care with overloading the submit <input /> with different methods -- if a user is using it with keyboard input and hits enter, it won't necessarily submit the <input /> you're expecting. Either disable auto-submit-on-enter, or code things up so that if there is more than one thing that submit can do, there's another field that sets what the action should be (eg a 'delete' checkbox, which is tested during a request.POST)
If you went with #1 I'd say that a GET to a POST-only view should be met with a 405 (method not supported) - or, failing that, a 404.
| URLs and side effects (Django) | I'm wondering if it's considered okay (particularly, in Django) to have a URL that's only intended for actions with side effects, that's only intended to be accessed by POST, and that is basically invisible to the user. Let's say, for the sake of making this concrete, I have a little messaging system on my site, and from their inbox, a user should be able to do a bunch of things like:
Delete a message
Mark a message as read
Report a message as spam
With all of those things causing a page refresh, but leading back to the same page. I'm wondering how to design my URLs and views around this. I see (at least) two options, and I have no idea which is more idiomatic.
Option 1)
Have a separate URL and view for each action. So, /inbox/delete-message/ maps to views.delete_message, and so on. At the end of each of those views, it redirects back to /inbox/.
I like the way things are clearly separated with this option. If a user somehow finds themselves sending a GET request to /inbox/delete-message/, that presents a sort of weird situation though (do I throw up an error page? silently redirect them?).
Option 2)
Use the same URL and view for each action, and have a POST parameter that identifies the action. So I would have one rather long inbox view, which would have a bunch of if statements testing whether request.POST['action'] == 'delete', or request.POST['delete'] == 'true' or whatever.
This option feels less clean to me, but I also feel like it's more common.
Which would be preferred by Djangonauts? Or is there another option that's better than either of the above?
| [
"A modified option #1 is the best approach. Consider this: suppose we weren't talking about a web app, but instead were just designing an inbox class. Which do you like better, a number of methods (delete_message(), mark_as_spam(), etc), or one big method (do_stuff(action))? Of course you would use the separate methods.\nA separate URL for each action, each with a separate view, is far preferable. If you don't like the redirect at the end, then don't use it. Instead, have a render_inbox(request) method that returns an HttpResponse, and call the method at the end of each of your views. Of course, redirecting after a POST is a good way to prevent double-actions, and always leaves the user with a consistent URL.\nEven better might be to use Ajax to hide the actions, but that is more involved.\n",
"I don't think there's anything wrong with either option, but #2 is potentially better from a performance standpoint. After the action is posted you can render the inbox without a redirect, so it cuts down on the HTTP traffic.\n",
"If you're writing a web 2.0 messaging app, you would be using AJAX calls and wouldn't be loading a new page at all. The process would proceed like so:\n\nUser clicks [delete] for a message. This button has a javascript action bound to it. This action does the following:\ni. Change the UI to indicate that something is happening (grey the message or put up an hourglass).\nii. Send a request to /messages/inbox/1234/delete. (where 1234 is some identifier that indicates which message)\niii. When the response from the server comes back, it should indicate success or failure. Reflect this status in the current UI. For example, on success, refresh the inbox view (or just remove the deleted item).\n\nOn the server side, now you can create a URL handler for each desired action (i.e. /delete, /flag, etc.).\nIf want to use an even more RESTful approach, you would use the HTTP action itself to indicate the action to perform. So instead of including delete in your URL, it would be in the action. So instead of GET or POST, use DELETE /messages/inbox/1234. To set a flag for having been read, use SET /messages/inbox/1234?read=true.\nI don't know how straightforward it is in Django to implement this latter recommendation, but in general, it's a good idea utilize the protocol (in this case HTTP), rather than work around it by encoding your actions into a URL or parameter.\n",
"I agree that #2 is a better approach. \nBut take care with overloading the submit <input /> with different methods -- if a user is using it with keyboard input and hits enter, it won't necessarily submit the <input /> you're expecting. Either disable auto-submit-on-enter, or code things up so that if there is more than one thing that submit can do, there's another field that sets what the action should be (eg a 'delete' checkbox, which is tested during a request.POST) \nIf you went with #1 I'd say that a GET to a POST-only view should be met with a 405 (method not supported) - or, failing that, a 404.\n"
] | [
2,
1,
1,
0
] | [] | [] | [
"django",
"django_views",
"post",
"python",
"url"
] | stackoverflow_0003126969_django_django_views_post_python_url.txt |
Q:
py2exe com dll problem
i'm trying making a com dll in python. but i try register to compiled dll have a error message "run time error r6034" and "could not load python dll" what is the solution this problem ?
mycode :
setup.py:
# This is the distutils script for creating a Python-based com dll
# server using ctypes.com. This script should be run like this:
#
# % python setup.py py2exe
#
# After you run this (from this directory) you will find two directories here:
# "build" and "dist". The .dll file in dist is what you are looking for.
##############################################################################
from distutils.core import setup
import py2exe
import sys
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the version info resources (Properties -- Version)
self.version = "0.0.1"
self.company_name = "my company"
self.copyright = "2006, my company"
self.name = "my com server name"
my_com_server_target = Target(
description = "my com server",
# use module name for ctypes.com dll server
modules = ["view.view"],
# the following line embeds the typelib within the dll
#other_resources = [("TYPELIB", 1, open(r"view\view.tlb", "rb").read())],
# we only want the inproc (dll) server
create_exe = False
)
setup(
name="my_com_server",
# the following two parameters embed support files within dll file
options={"py2exe": {"bundle_files": 1, }},
zipfile=None,
version="0.0.1",
description="my com server",
# author, maintainer, contact go here:
author="First Last",
author_email="some_name@some_company.com",
packages=["view"],
ctypes_com_server=[my_com_server_target]
)
and view.py:
# -*- coding: utf-8 -*-
# A sample context menu handler.
# Adds a 'Hello from Python' menu entry to .py files. When clicked, a
# simple message box is displayed.
#
# To demostrate:
# * Execute this script to register the context menu.
# * Open Windows Explorer, and browse to a directory with a .py file.
# * Right-Click on a .py file - locate and click on 'Hello from Python' on
# the context menu.
import ConfigParser
import os.path
import urllib
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]
IShellExtInit_Methods = ["Initialize"]
#HKCR Key Affected object types
#* All files
#AllFileSystemObjects All regular files and file folders
#Folder All folders, virtual and filesystem
#Directory File folders
#Drive Root folders of all system drives
#Network Entire network
#NetShare All network shares
TYPES = [
'*',
'Directory',
]
SUBKEY = 'MindRetrieve'
def alertError(hwnd, exc):
win32gui.MessageBox(hwnd, str(exc), str(exc.__class__), win32con.MB_OK)
class ShellExtension:
_reg_progid_ = "MindRetrieve.ShellExtension.ContextMenu"
_reg_desc_ = "MindRetrieve Shell Extension (context menu)"
_reg_clsid_ = "{ABB05546-EB55-4433-B068-A57667706828}"
_com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
_public_methods_ = IContextMenu_Methods + IShellExtInit_Methods
def Initialize(self, folder, dataobj, hkey):
print "Init", folder, dataobj, hkey
self.dataobj = dataobj
def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags
try:
# Query the items clicked on
# files = self.getFiles()
# msg = len(files) > 1 and '&Tag %s files' % len(files) or '&Tag with MindRetrieve'
# # TODO: we do not support tagging multiple files now
# if not(files):
# return
msg = '&Tag with MindRetrieve'
idCmd = idCmdFirst
items = []
if (uFlags & 0x000F) == shellcon.CMF_NORMAL: # Check == here, since CMF_NORMAL=0
print "CMF_NORMAL..."
items.append(msg)
elif uFlags & shellcon.CMF_VERBSONLY:
print "CMF_VERBSONLY..."
items.append(msg)# + " - shortcut")
elif uFlags & shellcon.CMF_EXPLORE:
print "CMF_EXPLORE..."
items.append(msg)# + " - normal file, right-click in Explorer")
elif uFlags & shellcon.CMF_DEFAULTONLY:
print "CMF_DEFAULTONLY...\r\n"
else:
print "** unknown flags", uFlags
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
for item in items:
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_STRING|win32con.MF_BYPOSITION,
idCmd, item)
indexMenu += 1
idCmd += 1
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
return idCmd-idCmdFirst # Must return number of menu items we added.
except Exception, e:
alertError(hwnd, e)
raise
def InvokeCommand(self, ci):
mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
try:
files = self.getFiles()
if not files:
return
fname = files[0]
# win32gui.MessageBox(hwnd, fname, str(fname.__class__), win32con.MB_OK)
fname = fname.encode('utf-8')
file_url = urllib.pathname2url(fname)
# 2005-12-20 Test urllib.pathname2url()
#
#>>> urllib.pathname2url(r'c:\tung\wäi')
#'///C|/tung/w%84i'
#>>> urllib.pathname2url(r'\tung\wäi')
#'/tung/w%84i'
#>>> urllib.pathname2url(r'tung\wäi')
#'tung/w%84i'
# prefer ':' as the drive separator rather than '|'
if file_url.startswith('///') and file_url[4:5] == '|':
file_url = file_url.replace('|',':',1)
if file_url.startswith('//'):
file_url = 'file:' + file_url
elif file_url.startswith('/'):
file_url = 'file://' + file_url
else:
# fname is a relative filename? Should not happen!
file_url = 'file:///' + file_url
url = getBaseURL() + '?url=' + urllib.quote(file_url)
shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpFile=url,
nShow=win32con.SW_NORMAL,
)
except Exception, e:
alertError(hwnd, e)
raise
def GetCommandString(self, cmd, typ):
return "&Tag with MindRetrieve"
def getFiles(self):
format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
sm = self.dataobj.GetData(format_etc)
num_files = shell.DragQueryFile(sm.data_handle, -1)
files = [shell.DragQueryFile(sm.data_handle, i) for i in range(num_files)]
return files
def getConfigPath():
""" get the DLL path from registry """
import _winreg
# _winreg.QueryValue() may throw WindowsError
# COM server registration in deployed environment
# e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\InprocServer32
# =c:\Program Files\MindRetrieve\context_menu.dll
subkey = 'CLSID\\%s\\InprocServer32' % ShellExtension._reg_clsid_
path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
head, tail = os.path.split(path)
# quick check if this is in deployed environment
if os.path.isabs(head):
return head
# Otherwise assume in development environment
# e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\PythonCOMPath
# =g:\bin\py_repos\mindretrieve\trunk\minds\weblib\win32
subkey = 'CLSID\\%s\\PythonCOMPath' % ShellExtension._reg_clsid_
path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
idx = path.lower().rfind('minds') # truncate trailing 'minds\weblib\win32'
if idx > 0:
path = path[:idx-1]
return path
def getHTTPAdminPort():
""" get HTTP.admin_port from config.ini """
pathname = os.path.join(getConfigPath(), 'config.ini')
cp = ConfigParser.ConfigParser()
cp.read(pathname)
admin_port = cp.getint('http','admin_port')
return admin_port
def getBaseURL():
""" get the base URL """
port = getHTTPAdminPort()
return 'http://localhost:%s/weblib/_' % port
def DllRegisterServer():
import _winreg
for typ in TYPES:
# e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex" % typ)
subkey = _winreg.CreateKey(key, "ContextMenuHandlers")
subkey2 = _winreg.CreateKey(subkey, SUBKEY)
_winreg.SetValueEx(subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
print ShellExtension._reg_desc_, "registration complete."
def DllUnregisterServer():
import _winreg
for typ in TYPES:
try:
# e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex\\ContextMenuHandlers\\%s" % (typ, SUBKEY))
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
print ShellExtension._reg_desc_, "unregistration complete."
def main(argv):
# assume argv == sys.argv
from win32com.server import register
register.UseCommandLine(ShellExtension,
finalize_register = DllRegisterServer,
finalize_unregister = DllUnregisterServer)
def test(argv):
""" adhoc tests """
print 'URL:', getBaseURL()
if __name__=='__main__':
import sys
if '-t' not in sys.argv:
main(sys.argv)
else:
test(sys.argv)
A:
Per the docs about error R6034, it means you're loading the C runtime libraries wrong because you're missing a "manifest". Per this thread, it seems the needed approach is just:
i found that if i make a manifest file
and copy the content of
python.exe.manifest everything is
working correctly
(can't verify that this is true as I still have no working Windows -- I now do own a cheap refurb Windows machine, got it just to try and help more with such problems, but can't find the antivirus disk and without one of course I can't safely go online).
py2exe's tutorial covers the issues of bundling the runtime libraries and making a manifest for that, and goes in more details than the above-quoted short explanation.
A:
One potential problem I see. You're specifying view as both a package name and a module name. This is confusing as well as not recommended. At least for the purposes of getting help, rename the package to view_p (or something more descriptive) so we can reference one or another.
So now:
modules = ['view_p.view']
and
packages = ['view_p']
And view.py goes in a directory called view_p and in that directory, there should also be a __init__.py.
A:
Another potential problem I see is you're using pywin32 to construct your COM server but you're using the "ctypes_com_server" parameter to py2exe. Maybe this is supported, but it's possible that there are some incompatibility across these implementations that prevents your intended usage.
| py2exe com dll problem | i'm trying making a com dll in python. but i try register to compiled dll have a error message "run time error r6034" and "could not load python dll" what is the solution this problem ?
mycode :
setup.py:
# This is the distutils script for creating a Python-based com dll
# server using ctypes.com. This script should be run like this:
#
# % python setup.py py2exe
#
# After you run this (from this directory) you will find two directories here:
# "build" and "dist". The .dll file in dist is what you are looking for.
##############################################################################
from distutils.core import setup
import py2exe
import sys
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the version info resources (Properties -- Version)
self.version = "0.0.1"
self.company_name = "my company"
self.copyright = "2006, my company"
self.name = "my com server name"
my_com_server_target = Target(
description = "my com server",
# use module name for ctypes.com dll server
modules = ["view.view"],
# the following line embeds the typelib within the dll
#other_resources = [("TYPELIB", 1, open(r"view\view.tlb", "rb").read())],
# we only want the inproc (dll) server
create_exe = False
)
setup(
name="my_com_server",
# the following two parameters embed support files within dll file
options={"py2exe": {"bundle_files": 1, }},
zipfile=None,
version="0.0.1",
description="my com server",
# author, maintainer, contact go here:
author="First Last",
author_email="some_name@some_company.com",
packages=["view"],
ctypes_com_server=[my_com_server_target]
)
and view.py:
# -*- coding: utf-8 -*-
# A sample context menu handler.
# Adds a 'Hello from Python' menu entry to .py files. When clicked, a
# simple message box is displayed.
#
# To demostrate:
# * Execute this script to register the context menu.
# * Open Windows Explorer, and browse to a directory with a .py file.
# * Right-Click on a .py file - locate and click on 'Hello from Python' on
# the context menu.
import ConfigParser
import os.path
import urllib
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]
IShellExtInit_Methods = ["Initialize"]
#HKCR Key Affected object types
#* All files
#AllFileSystemObjects All regular files and file folders
#Folder All folders, virtual and filesystem
#Directory File folders
#Drive Root folders of all system drives
#Network Entire network
#NetShare All network shares
TYPES = [
'*',
'Directory',
]
SUBKEY = 'MindRetrieve'
def alertError(hwnd, exc):
win32gui.MessageBox(hwnd, str(exc), str(exc.__class__), win32con.MB_OK)
class ShellExtension:
_reg_progid_ = "MindRetrieve.ShellExtension.ContextMenu"
_reg_desc_ = "MindRetrieve Shell Extension (context menu)"
_reg_clsid_ = "{ABB05546-EB55-4433-B068-A57667706828}"
_com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
_public_methods_ = IContextMenu_Methods + IShellExtInit_Methods
def Initialize(self, folder, dataobj, hkey):
print "Init", folder, dataobj, hkey
self.dataobj = dataobj
def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags
try:
# Query the items clicked on
# files = self.getFiles()
# msg = len(files) > 1 and '&Tag %s files' % len(files) or '&Tag with MindRetrieve'
# # TODO: we do not support tagging multiple files now
# if not(files):
# return
msg = '&Tag with MindRetrieve'
idCmd = idCmdFirst
items = []
if (uFlags & 0x000F) == shellcon.CMF_NORMAL: # Check == here, since CMF_NORMAL=0
print "CMF_NORMAL..."
items.append(msg)
elif uFlags & shellcon.CMF_VERBSONLY:
print "CMF_VERBSONLY..."
items.append(msg)# + " - shortcut")
elif uFlags & shellcon.CMF_EXPLORE:
print "CMF_EXPLORE..."
items.append(msg)# + " - normal file, right-click in Explorer")
elif uFlags & shellcon.CMF_DEFAULTONLY:
print "CMF_DEFAULTONLY...\r\n"
else:
print "** unknown flags", uFlags
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
for item in items:
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_STRING|win32con.MF_BYPOSITION,
idCmd, item)
indexMenu += 1
idCmd += 1
win32gui.InsertMenu(hMenu, indexMenu,
win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
0, None)
indexMenu += 1
return idCmd-idCmdFirst # Must return number of menu items we added.
except Exception, e:
alertError(hwnd, e)
raise
def InvokeCommand(self, ci):
mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
try:
files = self.getFiles()
if not files:
return
fname = files[0]
# win32gui.MessageBox(hwnd, fname, str(fname.__class__), win32con.MB_OK)
fname = fname.encode('utf-8')
file_url = urllib.pathname2url(fname)
# 2005-12-20 Test urllib.pathname2url()
#
#>>> urllib.pathname2url(r'c:\tung\wäi')
#'///C|/tung/w%84i'
#>>> urllib.pathname2url(r'\tung\wäi')
#'/tung/w%84i'
#>>> urllib.pathname2url(r'tung\wäi')
#'tung/w%84i'
# prefer ':' as the drive separator rather than '|'
if file_url.startswith('///') and file_url[4:5] == '|':
file_url = file_url.replace('|',':',1)
if file_url.startswith('//'):
file_url = 'file:' + file_url
elif file_url.startswith('/'):
file_url = 'file://' + file_url
else:
# fname is a relative filename? Should not happen!
file_url = 'file:///' + file_url
url = getBaseURL() + '?url=' + urllib.quote(file_url)
shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpFile=url,
nShow=win32con.SW_NORMAL,
)
except Exception, e:
alertError(hwnd, e)
raise
def GetCommandString(self, cmd, typ):
return "&Tag with MindRetrieve"
def getFiles(self):
format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
sm = self.dataobj.GetData(format_etc)
num_files = shell.DragQueryFile(sm.data_handle, -1)
files = [shell.DragQueryFile(sm.data_handle, i) for i in range(num_files)]
return files
def getConfigPath():
""" get the DLL path from registry """
import _winreg
# _winreg.QueryValue() may throw WindowsError
# COM server registration in deployed environment
# e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\InprocServer32
# =c:\Program Files\MindRetrieve\context_menu.dll
subkey = 'CLSID\\%s\\InprocServer32' % ShellExtension._reg_clsid_
path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
head, tail = os.path.split(path)
# quick check if this is in deployed environment
if os.path.isabs(head):
return head
# Otherwise assume in development environment
# e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\PythonCOMPath
# =g:\bin\py_repos\mindretrieve\trunk\minds\weblib\win32
subkey = 'CLSID\\%s\\PythonCOMPath' % ShellExtension._reg_clsid_
path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
idx = path.lower().rfind('minds') # truncate trailing 'minds\weblib\win32'
if idx > 0:
path = path[:idx-1]
return path
def getHTTPAdminPort():
""" get HTTP.admin_port from config.ini """
pathname = os.path.join(getConfigPath(), 'config.ini')
cp = ConfigParser.ConfigParser()
cp.read(pathname)
admin_port = cp.getint('http','admin_port')
return admin_port
def getBaseURL():
""" get the base URL """
port = getHTTPAdminPort()
return 'http://localhost:%s/weblib/_' % port
def DllRegisterServer():
import _winreg
for typ in TYPES:
# e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex" % typ)
subkey = _winreg.CreateKey(key, "ContextMenuHandlers")
subkey2 = _winreg.CreateKey(subkey, SUBKEY)
_winreg.SetValueEx(subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
print ShellExtension._reg_desc_, "registration complete."
def DllUnregisterServer():
import _winreg
for typ in TYPES:
try:
# e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex\\ContextMenuHandlers\\%s" % (typ, SUBKEY))
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
print ShellExtension._reg_desc_, "unregistration complete."
def main(argv):
# assume argv == sys.argv
from win32com.server import register
register.UseCommandLine(ShellExtension,
finalize_register = DllRegisterServer,
finalize_unregister = DllUnregisterServer)
def test(argv):
""" adhoc tests """
print 'URL:', getBaseURL()
if __name__=='__main__':
import sys
if '-t' not in sys.argv:
main(sys.argv)
else:
test(sys.argv)
| [
"Per the docs about error R6034, it means you're loading the C runtime libraries wrong because you're missing a \"manifest\". Per this thread, it seems the needed approach is just:\n\ni found that if i make a manifest file\n and copy the content of\n python.exe.manifest everything is\n working correctly\n\n(can't verify that this is true as I still have no working Windows -- I now do own a cheap refurb Windows machine, got it just to try and help more with such problems, but can't find the antivirus disk and without one of course I can't safely go online).\npy2exe's tutorial covers the issues of bundling the runtime libraries and making a manifest for that, and goes in more details than the above-quoted short explanation.\n",
"One potential problem I see. You're specifying view as both a package name and a module name. This is confusing as well as not recommended. At least for the purposes of getting help, rename the package to view_p (or something more descriptive) so we can reference one or another.\nSo now:\nmodules = ['view_p.view']\n\nand \npackages = ['view_p']\n\nAnd view.py goes in a directory called view_p and in that directory, there should also be a __init__.py.\n",
"Another potential problem I see is you're using pywin32 to construct your COM server but you're using the \"ctypes_com_server\" parameter to py2exe. Maybe this is supported, but it's possible that there are some incompatibility across these implementations that prevents your intended usage.\n"
] | [
2,
0,
0
] | [] | [] | [
"py2exe",
"python",
"pywin32"
] | stackoverflow_0003126379_py2exe_python_pywin32.txt |
Q:
Sending binary data over IPC from C to Python
I have a C program and a Python program on the same machine. The C program generates some data in nested structures. What form of IPC is the best way to get this data across to the python program?
Serializing in C (especially nested structures) is a real bear, from what I hear, due to lack of serialization libraries. I am not very familiar with shared memory, but I assume the formatting of the C structures may not be very palatable to the python program when it comes to memory alignment and following pointers. The ctype and struct library seems to be for non-nested structures only. So far, what I am thinking is:
Wrap all the data in the C program into some xml or json format, write it via socket to python program and then let python program interpret the xml/json formatted data. Looks very cumbersome with lots of overheads.
Any better ideas ?
A:
I think you answered your own question. JSON is certainly a good choice. It's also not terribly difficult to do your own serialization in C.
| Sending binary data over IPC from C to Python | I have a C program and a Python program on the same machine. The C program generates some data in nested structures. What form of IPC is the best way to get this data across to the python program?
Serializing in C (especially nested structures) is a real bear, from what I hear, due to lack of serialization libraries. I am not very familiar with shared memory, but I assume the formatting of the C structures may not be very palatable to the python program when it comes to memory alignment and following pointers. The ctype and struct library seems to be for non-nested structures only. So far, what I am thinking is:
Wrap all the data in the C program into some xml or json format, write it via socket to python program and then let python program interpret the xml/json formatted data. Looks very cumbersome with lots of overheads.
Any better ideas ?
| [
"I think you answered your own question. JSON is certainly a good choice. It's also not terribly difficult to do your own serialization in C.\n"
] | [
2
] | [] | [] | [
"c",
"python",
"serialization",
"sockets"
] | stackoverflow_0003127467_c_python_serialization_sockets.txt |
Q:
Items ordering in Python dictionary
I am in simple doubt... I created the following dictionary:
>>> alpha={'a': 10, 'b': 5, 'c': 11}
But, when I want to see the dictionary keys and values I got:
>>> alpha
{'a': 10, 'c': 11, 'b': 5}
See that the "b" and "c" has swapped their position. How can I make the position be the same of the moment that the dictionary was created?
A:
Dictionaries are unordered containers - if you want to preserve order, you can use collections.OrderedDict (Python 2.7 or later), or use another container type which is naturally order-preserving.
Generally if you have an access pattern that cares about ordered retrieval then a dictionary is solving a problem you don't have (fast access to random elements), while giving you a new one.
A:
Dictonaries are not guaranting sorting of keys. You can find this information in python docs: http://docs.python.org/tutorial/datastructures.html#dictionaries
You can always sort dictionary keys or use other, more specialized collection.
| Items ordering in Python dictionary | I am in simple doubt... I created the following dictionary:
>>> alpha={'a': 10, 'b': 5, 'c': 11}
But, when I want to see the dictionary keys and values I got:
>>> alpha
{'a': 10, 'c': 11, 'b': 5}
See that the "b" and "c" has swapped their position. How can I make the position be the same of the moment that the dictionary was created?
| [
"Dictionaries are unordered containers - if you want to preserve order, you can use collections.OrderedDict (Python 2.7 or later), or use another container type which is naturally order-preserving.\nGenerally if you have an access pattern that cares about ordered retrieval then a dictionary is solving a problem you don't have (fast access to random elements), while giving you a new one.\n",
"Dictonaries are not guaranting sorting of keys. You can find this information in python docs: http://docs.python.org/tutorial/datastructures.html#dictionaries\nYou can always sort dictionary keys or use other, more specialized collection.\n"
] | [
21,
4
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003127945_dictionary_python.txt |
Q:
When matching html or xml tags, should one worry about casing?
If you are parsing html or xml (with python), and looking for certain tags, it can hurt performance to lower or uppercase an entire document so that your comparisons are accurate. What percentage (estimated) of xml and html docs use any upper case characters in their tags?
A:
XML (and XHTML) tags are case-sensitive ... so <this> and <tHis> would be different elements.
However a lot (rough estimate) of HTML (not XHTML) tags are random-case.
A:
Only if you're using XHTML as this is case sensitive, whereas HTML is not so you can ignore case differences. Test for the doctype before worrying about checking for case.
A:
I think you're overly concerned about performance. If you're talking about arbitrary web pages, 90% of them will be HTML, not XHTML, so you should do case-insensitive comparisons. Lowercasing a string is extremely fast, and should be less than 1% of the total time of your parser. If you're not sure, carefully time your parser on a document that's already all lowercase, with and without the lowercase conversions.
Even a pure-Python implementation of lower() would be negligible compared to the rest of the parsing, but it's better than that - CPython implements lower() in C code, so it really is as fast as possible.
Remember, premature optimization is the root of all evil. Make your program correct first, then make it fast.
| When matching html or xml tags, should one worry about casing? | If you are parsing html or xml (with python), and looking for certain tags, it can hurt performance to lower or uppercase an entire document so that your comparisons are accurate. What percentage (estimated) of xml and html docs use any upper case characters in their tags?
| [
"XML (and XHTML) tags are case-sensitive ... so <this> and <tHis> would be different elements.\nHowever a lot (rough estimate) of HTML (not XHTML) tags are random-case.\n",
"Only if you're using XHTML as this is case sensitive, whereas HTML is not so you can ignore case differences. Test for the doctype before worrying about checking for case.\n",
"I think you're overly concerned about performance. If you're talking about arbitrary web pages, 90% of them will be HTML, not XHTML, so you should do case-insensitive comparisons. Lowercasing a string is extremely fast, and should be less than 1% of the total time of your parser. If you're not sure, carefully time your parser on a document that's already all lowercase, with and without the lowercase conversions.\nEven a pure-Python implementation of lower() would be negligible compared to the rest of the parsing, but it's better than that - CPython implements lower() in C code, so it really is as fast as possible.\nRemember, premature optimization is the root of all evil. Make your program correct first, then make it fast.\n"
] | [
5,
2,
1
] | [] | [] | [
"html",
"python",
"xml"
] | stackoverflow_0003127984_html_python_xml.txt |
Q:
Problem with date in Python
I'm developing a web application and would like to display user's current date basing on his timezone. Here is my code:
userTimezone = -5 #EAST is positive, WEST negative
utcTimestamp = time.mktime(time.gmtime())
userDate = time.gmtime(utcTimestamp+userTimezone*60*60)
I think the problem is with gmtime() since it does some conversions automatically. If I could, I would replace gmtime with function which doesn't convert anything, but haven't found any.
A:
you are probably looking for time.localtime(seconds). gmtime always returns utc time.
A:
Set time.timezone to the user's timezone, then display it using localtime().
| Problem with date in Python | I'm developing a web application and would like to display user's current date basing on his timezone. Here is my code:
userTimezone = -5 #EAST is positive, WEST negative
utcTimestamp = time.mktime(time.gmtime())
userDate = time.gmtime(utcTimestamp+userTimezone*60*60)
I think the problem is with gmtime() since it does some conversions automatically. If I could, I would replace gmtime with function which doesn't convert anything, but haven't found any.
| [
"you are probably looking for time.localtime(seconds). gmtime always returns utc time.\n",
"Set time.timezone to the user's timezone, then display it using localtime().\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003128068_python.txt |
Q:
Why can't I in python call HDIO_GETGEO?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########## THIS NOW WORKS! ##########
UNSUITABLE_ENVIRONMENT_ERROR = \
"This program requires at least Python 2.6 and Linux"
import sys
import struct
import os
from array import array
# +++ Check environment
try:
import platform # Introduced in Python 2.3
except ImportError:
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.system() != "Linux":
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.python_version_tuple()[:2] < (2, 6):
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
# --- Check environment
HDIO_GETGEO = 0x301 # Linux
import fcntl
def get_disk_geometry(fd):
geometry = array('c',"XXXXXXXX")
fcntl.ioctl(fd, HDIO_GETGEO, geometry, True)
heads, sectors, cylinders, start = \
struct.unpack("BBHL",geometry.tostring())
return { 'heads' : heads, 'cylinders': cylinders, 'sectors': sectors, "start": start }
from pprint import pprint
fd=os.open("/dev/sdb", os.O_RDWR)
pprint(get_disk_geometry(fd))
A:
Nobody seems to be able to tell me why you can't do this, but you can do it with ctypes so it doesn't really matter.
#!/usr/bin/env python
from ctypes import *
import os
from pprint import pprint
libc = CDLL("libc.so.6")
HDIO_GETGEO = 0x301 # Linux
class HDGeometry(Structure):
_fields_ = (("heads", c_ubyte),
("sectors", c_ubyte),
("cylinders", c_ushort),
("start", c_ulong))
def __repr__(self):
return """Heads: %s, Sectors %s, Cylinders %s, Start %s""" % (
self.heads, self.sectors, self.cylinders, self.start)
def get_disk_geometry(fd):
""" Returns the heads, sectors, cylinders and start of disk as rerpoted by
BIOS. These us usually bogus, but we still need them"""
buffer = create_string_buffer(sizeof(HDGeometry))
g = cast(buffer, POINTER(HDGeometry))
result = libc.ioctl(fd, HDIO_GETGEO, byref(buffer))
assert result == 0
return g.contents
if __name__ == "__main__":
fd = os.open("/dev/sdb", os.O_RDWR)
print repr(get_disk_geometry(fd))
| Why can't I in python call HDIO_GETGEO? | #!/usr/bin/env python
# -*- coding: utf-8 -*-
########## THIS NOW WORKS! ##########
UNSUITABLE_ENVIRONMENT_ERROR = \
"This program requires at least Python 2.6 and Linux"
import sys
import struct
import os
from array import array
# +++ Check environment
try:
import platform # Introduced in Python 2.3
except ImportError:
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.system() != "Linux":
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.python_version_tuple()[:2] < (2, 6):
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
# --- Check environment
HDIO_GETGEO = 0x301 # Linux
import fcntl
def get_disk_geometry(fd):
geometry = array('c',"XXXXXXXX")
fcntl.ioctl(fd, HDIO_GETGEO, geometry, True)
heads, sectors, cylinders, start = \
struct.unpack("BBHL",geometry.tostring())
return { 'heads' : heads, 'cylinders': cylinders, 'sectors': sectors, "start": start }
from pprint import pprint
fd=os.open("/dev/sdb", os.O_RDWR)
pprint(get_disk_geometry(fd))
| [
"Nobody seems to be able to tell me why you can't do this, but you can do it with ctypes so it doesn't really matter.\n#!/usr/bin/env python\nfrom ctypes import *\nimport os\nfrom pprint import pprint\n\nlibc = CDLL(\"libc.so.6\")\nHDIO_GETGEO = 0x301 # Linux\n\nclass HDGeometry(Structure):\n _fields_ = ((\"heads\", c_ubyte),\n (\"sectors\", c_ubyte),\n (\"cylinders\", c_ushort),\n (\"start\", c_ulong))\n\n def __repr__(self):\n return \"\"\"Heads: %s, Sectors %s, Cylinders %s, Start %s\"\"\" % (\n self.heads, self.sectors, self.cylinders, self.start)\n\ndef get_disk_geometry(fd):\n \"\"\" Returns the heads, sectors, cylinders and start of disk as rerpoted by\n BIOS. These us usually bogus, but we still need them\"\"\"\n\n buffer = create_string_buffer(sizeof(HDGeometry))\n g = cast(buffer, POINTER(HDGeometry))\n result = libc.ioctl(fd, HDIO_GETGEO, byref(buffer))\n assert result == 0\n return g.contents\n\nif __name__ == \"__main__\":\n fd = os.open(\"/dev/sdb\", os.O_RDWR)\n print repr(get_disk_geometry(fd))\n\n"
] | [
0
] | [] | [] | [
"ioctl",
"python"
] | stackoverflow_0003126700_ioctl_python.txt |
Q:
Google App Engine/WSGIApplication: How to check debug?
In the WSGIApplication's constructor, it takes a debug argument. Is there a way to access the value set for this from the the handler classes that inherit from webapp.RequestHandler?
def main():
application = webapp.WSGIApplication([('/', fooHandler)
],
debug=True)
util.run_wsgi_app(application)
A:
A WSGIApplication instance records the value of the debug parameter as self.__debug: the double underscore is a strong indication that no code outside the class itself is supposed to look at this attribute, as it's considered an internal application detail and could change "at any time" (even in a minor revision of the API). If you want to ignore this extremely strong indication, you could, technically, use webapp.WSGIApplication.active_instance._WSGIApplication__debug to look at it, but it's a truly bad idea.
A much better idea is to subclass WSGIApplication in your own code to make the attribute publically visible:
class MyWSGIapp(webapp.WSGIApplication):
def __init__(self, url_mapping, debug=False):
self.debugmode = debug
webapp.WSGIApplication.__init__(self, url_mapping, debug)
Now, when you use MyWSGIapp instead of webapp.WSGIApplication to start things off, webapp.WSGIApplication.active_instance.debugmode becomes a clean, solid way to access the attribute of interest from wherever else in your application.
| Google App Engine/WSGIApplication: How to check debug? | In the WSGIApplication's constructor, it takes a debug argument. Is there a way to access the value set for this from the the handler classes that inherit from webapp.RequestHandler?
def main():
application = webapp.WSGIApplication([('/', fooHandler)
],
debug=True)
util.run_wsgi_app(application)
| [
"A WSGIApplication instance records the value of the debug parameter as self.__debug: the double underscore is a strong indication that no code outside the class itself is supposed to look at this attribute, as it's considered an internal application detail and could change \"at any time\" (even in a minor revision of the API). If you want to ignore this extremely strong indication, you could, technically, use webapp.WSGIApplication.active_instance._WSGIApplication__debug to look at it, but it's a truly bad idea.\nA much better idea is to subclass WSGIApplication in your own code to make the attribute publically visible:\nclass MyWSGIapp(webapp.WSGIApplication):\n def __init__(self, url_mapping, debug=False):\n self.debugmode = debug\n webapp.WSGIApplication.__init__(self, url_mapping, debug)\n\nNow, when you use MyWSGIapp instead of webapp.WSGIApplication to start things off, webapp.WSGIApplication.active_instance.debugmode becomes a clean, solid way to access the attribute of interest from wherever else in your application.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003128230_google_app_engine_python.txt |
Q:
Global variable for debug options and logging in GAE Python
I'd like a global variable to determine if I'm in debug mode or not. Is that what __debug__ is for? How do I set/read it on Google App Engine?
If I use logging.debug(), will that automatically be turned off if I don't run the app with debug=True?
application = webapp.WSGIApplication(# ...
debug=True)
A:
__debug__ is built-in constant defined by Python. The docs say this: "This constant is true if Python was not started with an -O option. Assignments to debug are illegal and raise a SyntaxError. See also the assert statement."
The debug=True you pass to webapp.WSGIApplication is completely separate.
Neither of these will affect logging.debug() either. You can use logging.setLevel() to control how logging.debug() is handled.
| Global variable for debug options and logging in GAE Python | I'd like a global variable to determine if I'm in debug mode or not. Is that what __debug__ is for? How do I set/read it on Google App Engine?
If I use logging.debug(), will that automatically be turned off if I don't run the app with debug=True?
application = webapp.WSGIApplication(# ...
debug=True)
| [
"__debug__ is built-in constant defined by Python. The docs say this: \"This constant is true if Python was not started with an -O option. Assignments to debug are illegal and raise a SyntaxError. See also the assert statement.\"\nThe debug=True you pass to webapp.WSGIApplication is completely separate.\nNeither of these will affect logging.debug() either. You can use logging.setLevel() to control how logging.debug() is handled.\n"
] | [
5
] | [] | [] | [
"debugging",
"google_app_engine",
"python"
] | stackoverflow_0003128359_debugging_google_app_engine_python.txt |
Q:
Python VM arguments
OS:WinXP
Python 2.6
A Python project in Eclipse, if you go to 'run configuration' arguments tab. There's a section for 'Python VM arguments (Python.exe)'. Does anyone know where to find a reference for what arguments does Python VM have? I tried keyword 'Python (VM or Virtual Machine) arguments' but couldn't find it. Thanks.
A:
These would be the command line arguments to the python interpreter So the docs would be standard python
ie the optional part after the python executable and before args in
python [-BdEiOQsStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]
| Python VM arguments | OS:WinXP
Python 2.6
A Python project in Eclipse, if you go to 'run configuration' arguments tab. There's a section for 'Python VM arguments (Python.exe)'. Does anyone know where to find a reference for what arguments does Python VM have? I tried keyword 'Python (VM or Virtual Machine) arguments' but couldn't find it. Thanks.
| [
"These would be the command line arguments to the python interpreter So the docs would be standard python\nie the optional part after the python executable and before args in \n\npython [-BdEiOQsStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]\n\n"
] | [
2
] | [] | [] | [
"arguments",
"eclipse",
"python",
"windows_xp"
] | stackoverflow_0003128602_arguments_eclipse_python_windows_xp.txt |
Q:
How do I write data to disk in UTF-8 encoding in Python?
The following Python code ...
html_data = urllib2.urlopen(some_url).read()
f = codecs.open(filename, 'w', encoding='utf-8')
f.write(html_data)
f.close()
... sometimes fails with UnicodeDecodeError ...
File "/.../lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/.../lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 5605: ordinal not in range(128)
My questions:
How do I make sure my urllib2.urlopen(some_url).read() call always returns UTF-8?
Is there anything wrong with my codecs.open(...) call that prevents it from storing my data to disk in UTF-8 encoding?
A:
The problem is not with codecs.open -- it's with passing to .write a byte string that (given the \xd0 code in it) is clearly encoded in some ISO-8859-* or related codec.
urllib2.urlopen returns a response object which, besides file-like behavior, as the extra method:
info() — return the meta-information
of the page, such as headers, in the
form of an httplib.HTTPMessage
instance (see Quick Reference to HTTP
Headers)
In particular the Content-Type header, for text-like contents, should have a charset parameter specifying the encoding it uses, e.g. Content-Type: text/html; charset=ISO-8859-4. You need to parse and isolate the charset and use it to decode the contents into Unicode (so your codecs.opened file-like object always gets unicode arguments to write and properly writes them out in utf-8).
If charset is missing, or using it to decode the text results in errors (suggesting charset is wrong), as the last hope of salvation you can try the Universal Encoding Detector which uses heuristics for the purpose (after all, many pages on the web have horrible metadata errors, as well as broken HTML and so forth).
A:
AFAIK, You cannot do that. However, You can detect encoding from headers / html and re-encode.
I don't know. I have always used binary mode for writing and it always worked
Example:
data = urlopen(uri).read().decode(encoding)
f = open(file_name, 'wb')
f.write(data.encode('utf-8'))
f.close()
| How do I write data to disk in UTF-8 encoding in Python? | The following Python code ...
html_data = urllib2.urlopen(some_url).read()
f = codecs.open(filename, 'w', encoding='utf-8')
f.write(html_data)
f.close()
... sometimes fails with UnicodeDecodeError ...
File "/.../lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/.../lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 5605: ordinal not in range(128)
My questions:
How do I make sure my urllib2.urlopen(some_url).read() call always returns UTF-8?
Is there anything wrong with my codecs.open(...) call that prevents it from storing my data to disk in UTF-8 encoding?
| [
"The problem is not with codecs.open -- it's with passing to .write a byte string that (given the \\xd0 code in it) is clearly encoded in some ISO-8859-* or related codec.\nurllib2.urlopen returns a response object which, besides file-like behavior, as the extra method:\n\ninfo() — return the meta-information\n of the page, such as headers, in the\n form of an httplib.HTTPMessage\n instance (see Quick Reference to HTTP\n Headers)\n\nIn particular the Content-Type header, for text-like contents, should have a charset parameter specifying the encoding it uses, e.g. Content-Type: text/html; charset=ISO-8859-4. You need to parse and isolate the charset and use it to decode the contents into Unicode (so your codecs.opened file-like object always gets unicode arguments to write and properly writes them out in utf-8).\nIf charset is missing, or using it to decode the text results in errors (suggesting charset is wrong), as the last hope of salvation you can try the Universal Encoding Detector which uses heuristics for the purpose (after all, many pages on the web have horrible metadata errors, as well as broken HTML and so forth).\n",
"\nAFAIK, You cannot do that. However, You can detect encoding from headers / html and re-encode. \nI don't know. I have always used binary mode for writing and it always worked\n\nExample:\ndata = urlopen(uri).read().decode(encoding)\nf = open(file_name, 'wb')\nf.write(data.encode('utf-8'))\nf.close()\n\n"
] | [
2,
1
] | [] | [] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0003128648_python_unicode_utf_8.txt |
Q:
How to run context-aware commands in Python?
I want to write some python package installing script in Python into virtualenv. I write a function for installing virtualenv
def prepareRadioenv():
if not os.path.exists('radioenv'):
print 'Create radioenv'
system('easy_install virtualenv')
system('virtualenv --no-site-package radioenv')
print 'Activate radioenv'
system('source radioenv/bin/activate')
I try to use "source radioenv/bin/activate" to activate the virtual environment, unfortunately, os.system create a subprocess for doing the command. The environment change made by activate disappear with the subprocess, it doesn't affect the Python process. Here comes the problem, how can I execute some context-aware command sequence in Python?
Another example:
system("cd foo")
system("./bar")
Here the cd doens't affect following system(".bar"). How to make those environment context lives in different commands?
Is there something like context-aware shell? So that I can write some Python code like this:
shell = ShellContext()
shell.system("cd bar")
shell.system("./configure")
shell.system("make install")
if os.path.exists('bar'):
shell.system("remove")
Thanks.
A:
To activate the virtualenv from within Python, use the activate_this.py script (which is created with the virtualenv) with execfile.
activate_this = os.path.join("path/to/radioenv", "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))
A:
You are trying to use Python as a shell?
In parallel with the answer by Daniel Roseman, which seems to be the biggest part of what you need, note that:
shell.system("cd bar")
is spelt in Python as:
os.chdir("bar")
Check the os module for other functions you seem to need, like rmdir, remove and mkdir.
| How to run context-aware commands in Python? | I want to write some python package installing script in Python into virtualenv. I write a function for installing virtualenv
def prepareRadioenv():
if not os.path.exists('radioenv'):
print 'Create radioenv'
system('easy_install virtualenv')
system('virtualenv --no-site-package radioenv')
print 'Activate radioenv'
system('source radioenv/bin/activate')
I try to use "source radioenv/bin/activate" to activate the virtual environment, unfortunately, os.system create a subprocess for doing the command. The environment change made by activate disappear with the subprocess, it doesn't affect the Python process. Here comes the problem, how can I execute some context-aware command sequence in Python?
Another example:
system("cd foo")
system("./bar")
Here the cd doens't affect following system(".bar"). How to make those environment context lives in different commands?
Is there something like context-aware shell? So that I can write some Python code like this:
shell = ShellContext()
shell.system("cd bar")
shell.system("./configure")
shell.system("make install")
if os.path.exists('bar'):
shell.system("remove")
Thanks.
| [
"To activate the virtualenv from within Python, use the activate_this.py script (which is created with the virtualenv) with execfile.\nactivate_this = os.path.join(\"path/to/radioenv\", \"bin/activate_this.py\")\nexecfile(activate_this, dict(__file__=activate_this))\n\n",
"You are trying to use Python as a shell?\nIn parallel with the answer by Daniel Roseman, which seems to be the biggest part of what you need, note that:\nshell.system(\"cd bar\")\n\nis spelt in Python as:\nos.chdir(\"bar\")\n\nCheck the os module for other functions you seem to need, like rmdir, remove and mkdir.\n"
] | [
3,
1
] | [] | [] | [
"command_line",
"python",
"shell",
"unix"
] | stackoverflow_0003128452_command_line_python_shell_unix.txt |
Q:
Google App Engine: Preferred/idiomatic way to "refresh" a model from the datastore?
I have observed the following: (Odp is a model)
o = Odp.get(odpKey)
o.foo = 0
foo()
assert o.foo == 1 # fails
def foo():
o = Odp.get(odpKey)
o.foo += 1
o.put()
It looks like the first copy of o isn't refreshed when it's underlying datastore representation is updated. So, what is the preferred way to refresh it?
I was thinking something like:
o = Odp.get(odpKey)
o.foo = 0
foo()
o = Odp.get(o.key())
assert o.foo == 1 # win
Or is there a better way?
A:
t looks like the first copy of o isn't
refreshed when it's underlying
datastore representation is updated.
Correct: there are two completely independent objects in memory during the execution of function foo -- both happen to be bound to barenames equal to o, in different scopes, but that's an irrelevant detail (just further confusing things;-).
o = Odp.get(odpKey)
o.foo = 0
foo()
o = Odp.get(o.key())
assert o.foo == 1 # win
"win" only the first time -- because the o.foo = 0 only affects a copy that's never put to the DB, and then o is rebound to a third copy just gotten from the DB, then o.foo will be 1 the first time (if the foo attribute defaults to 0) but not on subsequent attempts as it keeps increasing by one every time. You need an o.put() before the call to foo() to make the o.foo = 0 assignment have any meaning or sense whatsoever.
A better idea is to have the foo function accept an optional argument (the object in question) and have it get a fresh copy only if it didn't receive that argument; and then in any case return the object it's working on. IOW, you'd have:
o = Odp.get(odpKey)
o.foo = 0
o = foo(o)
assert o.foo == 1 # always OK
def foo(o=None):
if o is None:
o = Odp.get(odpKey)
o.foo += 1
return o
You might add an o.put() somewhere, but normally it's better to save only when a set of related changes have all been applied to the in-memory copy. Doing essentially all the work on a single in-memory copy saves a lot of roundtrips to the DB and thereby speeds your app up by a lot.
| Google App Engine: Preferred/idiomatic way to "refresh" a model from the datastore? | I have observed the following: (Odp is a model)
o = Odp.get(odpKey)
o.foo = 0
foo()
assert o.foo == 1 # fails
def foo():
o = Odp.get(odpKey)
o.foo += 1
o.put()
It looks like the first copy of o isn't refreshed when it's underlying datastore representation is updated. So, what is the preferred way to refresh it?
I was thinking something like:
o = Odp.get(odpKey)
o.foo = 0
foo()
o = Odp.get(o.key())
assert o.foo == 1 # win
Or is there a better way?
| [
"\nt looks like the first copy of o isn't\n refreshed when it's underlying\n datastore representation is updated.\n\nCorrect: there are two completely independent objects in memory during the execution of function foo -- both happen to be bound to barenames equal to o, in different scopes, but that's an irrelevant detail (just further confusing things;-).\no = Odp.get(odpKey)\no.foo = 0\nfoo()\no = Odp.get(o.key())\nassert o.foo == 1 # win\n\n\"win\" only the first time -- because the o.foo = 0 only affects a copy that's never put to the DB, and then o is rebound to a third copy just gotten from the DB, then o.foo will be 1 the first time (if the foo attribute defaults to 0) but not on subsequent attempts as it keeps increasing by one every time. You need an o.put() before the call to foo() to make the o.foo = 0 assignment have any meaning or sense whatsoever.\nA better idea is to have the foo function accept an optional argument (the object in question) and have it get a fresh copy only if it didn't receive that argument; and then in any case return the object it's working on. IOW, you'd have:\no = Odp.get(odpKey)\no.foo = 0\no = foo(o)\nassert o.foo == 1 # always OK\n\ndef foo(o=None):\n if o is None:\n o = Odp.get(odpKey)\n o.foo += 1\n return o\n\nYou might add an o.put() somewhere, but normally it's better to save only when a set of related changes have all been applied to the in-memory copy. Doing essentially all the work on a single in-memory copy saves a lot of roundtrips to the DB and thereby speeds your app up by a lot.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003128778_google_app_engine_python.txt |
Q:
Getting size of Gtk.Table in python
I am having a problem with widget Gtk.Table - I would like to know, if there is a way how to get a current size of the table (number of rows and columns).
Thank you, very much for help, Tomas
A:
You should just be able to access the properties n-columns and n-rows.
You can do this using:
cols = mytable.get_property('n-columns')
rows = mytable.get_property('n-rows')
A:
You have to read GTK properties:
t = gtk.Table(myNumberOfRows, myNumberofCols)
t.get_property("n-rows") # number of rows in the table
t.get_property("n-columns") # number of cols in the table
A:
In most recent versions of PyGTK you can get/set those values via table.props.n_columns and table.props.n_rows, which is synonymous with the get_property() (mentioned in the other answers) and set_property() methods.
| Getting size of Gtk.Table in python | I am having a problem with widget Gtk.Table - I would like to know, if there is a way how to get a current size of the table (number of rows and columns).
Thank you, very much for help, Tomas
| [
"You should just be able to access the properties n-columns and n-rows.\nYou can do this using:\ncols = mytable.get_property('n-columns')\nrows = mytable.get_property('n-rows')\n\n",
"You have to read GTK properties:\nt = gtk.Table(myNumberOfRows, myNumberofCols)\nt.get_property(\"n-rows\") # number of rows in the table\nt.get_property(\"n-columns\") # number of cols in the table\n\n",
"In most recent versions of PyGTK you can get/set those values via table.props.n_columns and table.props.n_rows, which is synonymous with the get_property() (mentioned in the other answers) and set_property() methods.\n"
] | [
0,
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003126802_gtk_pygtk_python.txt |
Q:
Python curse getmouse function?
I'm trying to find a way to get mouse click event in curse module in Python.
I read the document on http://docs.python.org/library/curses.html and it suggested to do
c == curses.getch()
if(c == curses.KEY_MOUSE):
curses.getmouse()
...
However, this "if statement" seems to never get triggered... and if I tried to move the getmouse() function outside of "if statement" to force it to return the mouse information, it return
(devid,x,y,z,bstate) = curses.getmouse()
_curses.error: getmouse() returned ERR
Any other thought?
A:
Have you enabled mouse-event reporting with the mousemask function, and checked its return value to make sure it confirms that it can actually report some mouse-events? Depending on the terminal (or emulator program for one, these days;-), mouse event reporting may or may not be possible, in whole or in part; and in any case, it's disabled by default in curses (not just on Python, that's a curses general idea;-) unless and until you explicitly enable it with the mousemask call.
| Python curse getmouse function? | I'm trying to find a way to get mouse click event in curse module in Python.
I read the document on http://docs.python.org/library/curses.html and it suggested to do
c == curses.getch()
if(c == curses.KEY_MOUSE):
curses.getmouse()
...
However, this "if statement" seems to never get triggered... and if I tried to move the getmouse() function outside of "if statement" to force it to return the mouse information, it return
(devid,x,y,z,bstate) = curses.getmouse()
_curses.error: getmouse() returned ERR
Any other thought?
| [
"Have you enabled mouse-event reporting with the mousemask function, and checked its return value to make sure it confirms that it can actually report some mouse-events? Depending on the terminal (or emulator program for one, these days;-), mouse event reporting may or may not be possible, in whole or in part; and in any case, it's disabled by default in curses (not just on Python, that's a curses general idea;-) unless and until you explicitly enable it with the mousemask call.\n"
] | [
5
] | [] | [] | [
"curses",
"mouseevent",
"python"
] | stackoverflow_0003129364_curses_mouseevent_python.txt |
Q:
scipy smart optimize
I need to fit some points from different datasets with straight lines. From every dataset I want to fit a line. So I got the parameters ai and bi that describe the i-line: ai + bi*x. The problem is that I want to impose that every ai are equal because I want the same intercepta. I found a tutorial here: http://www.scipy.org/Cookbook/FittingData#head-a44b49d57cf0165300f765e8f1b011876776502f. The difference is that I don't know a priopri how many dataset I have. My code is this:
from numpy import *
from scipy import optimize
# here I have 3 dataset, but in general I don't know how many dataset are they
ypoints = [array([0, 2.1, 2.4]), # first dataset, 3 points
array([0.1, 2.1, 2.9]), # second dataset
array([-0.1, 1.4])] # only 2 points
xpoints = [array([0, 2, 2.5]), # first dataset
array([0, 2, 3]), # second, also x coordinates are different
array([0, 1.5])] # the first coordinate is always 0
fitfunc = lambda a, b, x: a + b * x
errfunc = lambda p, xs, ys: array([ yi - fitfunc(p[0], p[i+1], xi)
for i, (xi,yi) in enumerate(zip(xs, ys)) ])
p_arrays = [r_[0.]] * len(xpoints)
pinit = r_[[ypoints[0][0]] + p_arrays]
fit_parameters, success = optimize.leastsq(errfunc, pinit, args = (xpoints, ypoints))
I got
Traceback (most recent call last):
File "prova.py", line 19, in <module>
fit_parameters, success = optimize.leastsq(errfunc, pinit, args = (xpoints, ypoints))
File "/usr/lib64/python2.6/site-packages/scipy/optimize/minpack.py", line 266, in leastsq
m = check_func(func,x0,args,n)[0]
File "/usr/lib64/python2.6/site-packages/scipy/optimize/minpack.py", line 12, in check_func
res = atleast_1d(thefunc(*((x0[:numinputs],)+args)))
File "prova.py", line 14, in <lambda>
for i, (xi,yi) in enumerate(zip(xs, ys)) ])
ValueError: setting an array element with a sequence.
A:
(Side note: use def, not lambda assigned to a name -- that's utterly silly and has nothing but downsides, lambda's only use is making anonymous functions!).
Your errfunc should return a sequence (array or otherwise) of floating point numbers, but it's not, because you're trying to put as the items of your arrays the arrays which are the differences each y point (remember, ypoints aka ys is a list of arrays!) and the fit functions' results. So you need to "collapse" the expression yi - fitfunc(p[0], p[i+1], xi) to a single floating point number, e.g. norm(yi - fitfunc(p[0], p[i+1], xi)).
A:
if you just need a linear fit, then it is better to estimate it with linear regression instead of a non-linear optimizer.
More fit statistics could be obtained be using scikits.statsmodels instead.
import numpy as np
from numpy import array
ypoints = np.r_[array([0, 2.1, 2.4]), # first dataset, 3 points
array([0.1, 2.1, 2.9]), # second dataset
array([-0.1, 1.4])] # only 2 points
xpoints = [array([0, 2, 2.5]), # first dataset
array([0, 2, 3]), # second, also x coordinates are different
array([0, 1.5])] # the first coordinate is always 0
xp = np.hstack(xpoints)
indicator = []
for i,a in enumerate(xpoints):
indicator.extend([i]*len(a))
indicator = np.array(indicator)
x = xp[:,None]*(indicator[:,None]==np.arange(3)).astype(int)
x = np.hstack((np.ones((xp.shape[0],1)),x))
print np.dot(np.linalg.pinv(x), ypoints)
# [ 0.01947973 0.98656987 0.98481549 0.92034684]
The matrix of regressors has a common intercept, but different columns for each dataset:
>>> x
array([[ 1. , 0. , 0. , 0. ],
[ 1. , 2. , 0. , 0. ],
[ 1. , 2.5, 0. , 0. ],
[ 1. , 0. , 0. , 0. ],
[ 1. , 0. , 2. , 0. ],
[ 1. , 0. , 3. , 0. ],
[ 1. , 0. , 0. , 0. ],
[ 1. , 0. , 0. , 1.5]])
| scipy smart optimize | I need to fit some points from different datasets with straight lines. From every dataset I want to fit a line. So I got the parameters ai and bi that describe the i-line: ai + bi*x. The problem is that I want to impose that every ai are equal because I want the same intercepta. I found a tutorial here: http://www.scipy.org/Cookbook/FittingData#head-a44b49d57cf0165300f765e8f1b011876776502f. The difference is that I don't know a priopri how many dataset I have. My code is this:
from numpy import *
from scipy import optimize
# here I have 3 dataset, but in general I don't know how many dataset are they
ypoints = [array([0, 2.1, 2.4]), # first dataset, 3 points
array([0.1, 2.1, 2.9]), # second dataset
array([-0.1, 1.4])] # only 2 points
xpoints = [array([0, 2, 2.5]), # first dataset
array([0, 2, 3]), # second, also x coordinates are different
array([0, 1.5])] # the first coordinate is always 0
fitfunc = lambda a, b, x: a + b * x
errfunc = lambda p, xs, ys: array([ yi - fitfunc(p[0], p[i+1], xi)
for i, (xi,yi) in enumerate(zip(xs, ys)) ])
p_arrays = [r_[0.]] * len(xpoints)
pinit = r_[[ypoints[0][0]] + p_arrays]
fit_parameters, success = optimize.leastsq(errfunc, pinit, args = (xpoints, ypoints))
I got
Traceback (most recent call last):
File "prova.py", line 19, in <module>
fit_parameters, success = optimize.leastsq(errfunc, pinit, args = (xpoints, ypoints))
File "/usr/lib64/python2.6/site-packages/scipy/optimize/minpack.py", line 266, in leastsq
m = check_func(func,x0,args,n)[0]
File "/usr/lib64/python2.6/site-packages/scipy/optimize/minpack.py", line 12, in check_func
res = atleast_1d(thefunc(*((x0[:numinputs],)+args)))
File "prova.py", line 14, in <lambda>
for i, (xi,yi) in enumerate(zip(xs, ys)) ])
ValueError: setting an array element with a sequence.
| [
"(Side note: use def, not lambda assigned to a name -- that's utterly silly and has nothing but downsides, lambda's only use is making anonymous functions!).\nYour errfunc should return a sequence (array or otherwise) of floating point numbers, but it's not, because you're trying to put as the items of your arrays the arrays which are the differences each y point (remember, ypoints aka ys is a list of arrays!) and the fit functions' results. So you need to \"collapse\" the expression yi - fitfunc(p[0], p[i+1], xi) to a single floating point number, e.g. norm(yi - fitfunc(p[0], p[i+1], xi)).\n",
"if you just need a linear fit, then it is better to estimate it with linear regression instead of a non-linear optimizer.\nMore fit statistics could be obtained be using scikits.statsmodels instead.\nimport numpy as np\nfrom numpy import array\n\nypoints = np.r_[array([0, 2.1, 2.4]), # first dataset, 3 points\n array([0.1, 2.1, 2.9]), # second dataset\n array([-0.1, 1.4])] # only 2 points\n\nxpoints = [array([0, 2, 2.5]), # first dataset\n array([0, 2, 3]), # second, also x coordinates are different\n array([0, 1.5])] # the first coordinate is always 0\n\nxp = np.hstack(xpoints)\nindicator = []\nfor i,a in enumerate(xpoints):\n indicator.extend([i]*len(a))\n\nindicator = np.array(indicator)\n\n\nx = xp[:,None]*(indicator[:,None]==np.arange(3)).astype(int)\nx = np.hstack((np.ones((xp.shape[0],1)),x))\n\nprint np.dot(np.linalg.pinv(x), ypoints)\n# [ 0.01947973 0.98656987 0.98481549 0.92034684]\n\nThe matrix of regressors has a common intercept, but different columns for each dataset:\n>>> x\narray([[ 1. , 0. , 0. , 0. ],\n [ 1. , 2. , 0. , 0. ],\n [ 1. , 2.5, 0. , 0. ],\n [ 1. , 0. , 0. , 0. ],\n [ 1. , 0. , 2. , 0. ],\n [ 1. , 0. , 3. , 0. ],\n [ 1. , 0. , 0. , 0. ],\n [ 1. , 0. , 0. , 1.5]])\n\n"
] | [
1,
1
] | [] | [] | [
"optimization",
"python",
"scipy"
] | stackoverflow_0003094624_optimization_python_scipy.txt |
Q:
Google App Engine: Devserver is hideously slow
My devserver has become hideously slow for some reason. (Python, Windows 7, GAE 1.3.3) I'm not sure if I'm doing something wrong, or if it's just not meant to handle the load I'm putting on it. I have 1000 models of a certain type in the datastore. I am trying to delete them with this method:
def _deleteType(type):
results = type.all().fetch(1000)
while results:
db.delete(results)
results = type.all().fetch(1000)
It's taken 20+ minutes. I restarted the devserver, and the SDK console still said I have 1000 of these models in the DB. What's going on?
Is there a better way to cleanse my app of all data?
A:
Getting (and passing to db.delete) just the keys rather than the whole objects should be a bit faster. However, by far the fastest way to clear the datastore at start-up on the SDK is to start your app with:
dev_appserver.py --clear_datastore myapp
| Google App Engine: Devserver is hideously slow | My devserver has become hideously slow for some reason. (Python, Windows 7, GAE 1.3.3) I'm not sure if I'm doing something wrong, or if it's just not meant to handle the load I'm putting on it. I have 1000 models of a certain type in the datastore. I am trying to delete them with this method:
def _deleteType(type):
results = type.all().fetch(1000)
while results:
db.delete(results)
results = type.all().fetch(1000)
It's taken 20+ minutes. I restarted the devserver, and the SDK console still said I have 1000 of these models in the DB. What's going on?
Is there a better way to cleanse my app of all data?
| [
"Getting (and passing to db.delete) just the keys rather than the whole objects should be a bit faster. However, by far the fastest way to clear the datastore at start-up on the SDK is to start your app with:\n dev_appserver.py --clear_datastore myapp\n\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003129391_google_app_engine_python.txt |
Q:
Google App Engine: upload_data fails because "target machine actively refused it" on devserver
I'm trying to upload data from a CSV to my app using the devserver:
appcfg.py upload_data --config_file="DataLoader.py" --filename="data.csv" --kind=Foo --url=http://localhost:8083/remote_api "path/to/app"
The result:
Application: appname; version: 1.
Uploading data records.
[INFO ] Logging to bulkloader-log-20100626.181045
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100626.181045.sql3
Please enter login credentials for localhost
Email: email@domain.com
Password for email@domain.com:
[INFO ] Connecting to localhost:8083/remote_api
[INFO ] Starting import; maximum 10 entities per post
Google\google_appengine\google\appengine\api\datastore_types.py:673: DeprecationWarning: object.__init__() takes no parameters
super(Link, self).__init__(self, link)
............[INFO ] Unexpected thread death: WorkerThread-7
[INFO ] An error occurred. Shutting down...
........[ERROR ] Error in WorkerThread-1: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
[ERROR ] Error in WorkerThread-7: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
[INFO ] 1230 entites total, 0 previously transferred
[INFO ] 200 entities (218274 bytes) transferred in 25.8 seconds
[INFO ] Some entities not successfully transferred
The count of entities transferred ranges between 200-850 as I try subsequent times.
What is going on here? Normally this works fine. Navigating to http://localhost:8083/ works, and the app runs just fine. (Except the lack of data.)
A:
Decrease the number of threads to 4 by adding the command line option --num_threads=4
If it still doesn't work decrease further the number of threads.
| Google App Engine: upload_data fails because "target machine actively refused it" on devserver | I'm trying to upload data from a CSV to my app using the devserver:
appcfg.py upload_data --config_file="DataLoader.py" --filename="data.csv" --kind=Foo --url=http://localhost:8083/remote_api "path/to/app"
The result:
Application: appname; version: 1.
Uploading data records.
[INFO ] Logging to bulkloader-log-20100626.181045
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100626.181045.sql3
Please enter login credentials for localhost
Email: email@domain.com
Password for email@domain.com:
[INFO ] Connecting to localhost:8083/remote_api
[INFO ] Starting import; maximum 10 entities per post
Google\google_appengine\google\appengine\api\datastore_types.py:673: DeprecationWarning: object.__init__() takes no parameters
super(Link, self).__init__(self, link)
............[INFO ] Unexpected thread death: WorkerThread-7
[INFO ] An error occurred. Shutting down...
........[ERROR ] Error in WorkerThread-1: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
[ERROR ] Error in WorkerThread-7: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
[INFO ] 1230 entites total, 0 previously transferred
[INFO ] 200 entities (218274 bytes) transferred in 25.8 seconds
[INFO ] Some entities not successfully transferred
The count of entities transferred ranges between 200-850 as I try subsequent times.
What is going on here? Normally this works fine. Navigating to http://localhost:8083/ works, and the app runs just fine. (Except the lack of data.)
| [
"Decrease the number of threads to 4 by adding the command line option --num_threads=4\nIf it still doesn't work decrease further the number of threads.\n"
] | [
10
] | [] | [] | [
"google_app_engine",
"python",
"urlopen"
] | stackoverflow_0003126036_google_app_engine_python_urlopen.txt |
Q:
Py-Postgresql and Raritan PowerIQ - Can't seem to find table?
I'm trying to write some Python3 to interface with the backend PostgreSQL server on a Raritan Power IQ (http://www.raritan.com/products/power-management/power-iq/) system.
I've used pgAdminIII to connect to the server, and it connects fine with my credentials. I can see the databases, as well as the schemas in each database.
I'm now using py-postgresql to attempt to script it, and I'm hitting some issues.
I use the following to connect:
postgresql.open("pq://odbcuser:password@XX.XX.XX.XX:5432/raritan")
to connect to the raritan database, using user "odbcuser" and password "password" (no, that's not the real one...lol).
It appears to connect successfully. I'm able to to run some queries, e.g.
ps = db.prepare("SELECT * from pg_tables;")
ps()
manages to list all the tables/views in the "raritan" database.
However, I then try to access a specific view and it breaks. The "raritan" database has two schemas, "odbc" and "public".
I can access views from the public schema. E.g.:
ps = db.prepare("SELECT * from public.qrypwrall;")
ps()
works to an extent - I get a permission denied error, same as I under pgAdminIII, as my account doesn't have access to that view, but syntactally, it seems fine and it does find the table.
However, when I try to access a view under "odbc", it just breaks. E.g.:
>>> ps = db.prepare("SELECT * from odbc.Aisles;")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 2291, in prepare
ps._fini()
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 1393, in _
fini
self.database._pq_complete()
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 2538, in _
pq_complete
self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', None
))
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 471, in ra
ise_error
self.raise_server_error(error_message, **kw)
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 462, in ra
ise_server_error
raise server_error
postgresql.exceptions.UndefinedTableError: relation "odbc.aisles" does not exist
CODE: 42P01
LOCATION: File 'namespace.c', line 268, in RangeVarGetRelid from SERVER
STATEMENT: [parsing]
statement_id: py:0x10ca1b0
string: SELECT * from odbc.Aisles;
CONNECTION: [idle]
client_address: 10.180.9.213/32
client_port: 2612
version:
PostgreSQL 8.3.7 on i686-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 2
0071124 (Red Hat 4.1.2-42)
CONNECTOR: [IP4] pq://odbcuser:***@10.180.138.121:5432/raritan
category: None
DRIVER: postgresql.driver.pq3.Driver
However, I can access the same table (Aisles) fine under pgAdminIII, using the same credentials (and unlike public, I actually have permissions to all these tables.
Is there any reason that py-postgresql might not see these views? Or anything you can pick out from the error messages?
I have a suspicion that it's to do with PowerIQ using mixed-case for the table names (e.g. "Aisle"). However, I'm not exactly sure how to deal with these in psycopg. How exactly would I modify say, my cursor.execute like to quote the table?
cursor.execute('SELECT * from "public.Aisles"')
also doesn't work.
Cheers,
Victor
A:
Have you tried it this way: 'SELECT * from public."Aisles"?
Quoting the whole thing makes it a non-qualified (no schema) table name which has a dot in it.
| Py-Postgresql and Raritan PowerIQ - Can't seem to find table? | I'm trying to write some Python3 to interface with the backend PostgreSQL server on a Raritan Power IQ (http://www.raritan.com/products/power-management/power-iq/) system.
I've used pgAdminIII to connect to the server, and it connects fine with my credentials. I can see the databases, as well as the schemas in each database.
I'm now using py-postgresql to attempt to script it, and I'm hitting some issues.
I use the following to connect:
postgresql.open("pq://odbcuser:password@XX.XX.XX.XX:5432/raritan")
to connect to the raritan database, using user "odbcuser" and password "password" (no, that's not the real one...lol).
It appears to connect successfully. I'm able to to run some queries, e.g.
ps = db.prepare("SELECT * from pg_tables;")
ps()
manages to list all the tables/views in the "raritan" database.
However, I then try to access a specific view and it breaks. The "raritan" database has two schemas, "odbc" and "public".
I can access views from the public schema. E.g.:
ps = db.prepare("SELECT * from public.qrypwrall;")
ps()
works to an extent - I get a permission denied error, same as I under pgAdminIII, as my account doesn't have access to that view, but syntactally, it seems fine and it does find the table.
However, when I try to access a view under "odbc", it just breaks. E.g.:
>>> ps = db.prepare("SELECT * from odbc.Aisles;")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 2291, in prepare
ps._fini()
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 1393, in _
fini
self.database._pq_complete()
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 2538, in _
pq_complete
self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', None
))
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 471, in ra
ise_error
self.raise_server_error(error_message, **kw)
File "C:\Python31\lib\site-packages\postgresql\driver\pq3.py", line 462, in ra
ise_server_error
raise server_error
postgresql.exceptions.UndefinedTableError: relation "odbc.aisles" does not exist
CODE: 42P01
LOCATION: File 'namespace.c', line 268, in RangeVarGetRelid from SERVER
STATEMENT: [parsing]
statement_id: py:0x10ca1b0
string: SELECT * from odbc.Aisles;
CONNECTION: [idle]
client_address: 10.180.9.213/32
client_port: 2612
version:
PostgreSQL 8.3.7 on i686-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 2
0071124 (Red Hat 4.1.2-42)
CONNECTOR: [IP4] pq://odbcuser:***@10.180.138.121:5432/raritan
category: None
DRIVER: postgresql.driver.pq3.Driver
However, I can access the same table (Aisles) fine under pgAdminIII, using the same credentials (and unlike public, I actually have permissions to all these tables.
Is there any reason that py-postgresql might not see these views? Or anything you can pick out from the error messages?
I have a suspicion that it's to do with PowerIQ using mixed-case for the table names (e.g. "Aisle"). However, I'm not exactly sure how to deal with these in psycopg. How exactly would I modify say, my cursor.execute like to quote the table?
cursor.execute('SELECT * from "public.Aisles"')
also doesn't work.
Cheers,
Victor
| [
"Have you tried it this way: 'SELECT * from public.\"Aisles\"?\nQuoting the whole thing makes it a non-qualified (no schema) table name which has a dot in it.\n"
] | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0003115374_postgresql_python.txt |
Q:
Django: NameError: name 'Category' is not defined
I'm practicing on Django and using some online tutorial to build a web blog. It went smoothly with the first project, yet when I tried the 2nd one, through developing the first view, there was this statement:
categories = models.ManyToManyField(Category, related_name ="packages")
In the tutorial, validating the model gives 0 errors, yet when I ran validating command it gave me :NameError: name 'Category' is not defined
I triple checked the syntax of all the file and there was no single syntax error, there is no additional imports mentioned in the tutorial.
What's wrong ?
A:
It sounds like you may be new to Python, since you say "I triple checked the syntax of all the file and there was no single syntax error, there is no additional imports mentioned in the tutorial."
Be aware that in Python, many name-related errors that would be caught at compile time in languages like C++ are caught at runtime instead. This tripped me up a little when I started using Python. Runtime errors could simply be indicating a mere typo, etc. (If this sounds nasty, don't worry-- there's free tools out there to check your program as a compiler for stuff like that some other languages would)
Is Category defined in the same file that that line appears in?
If not, you must specifically import the name Category. Suppose Category is defined in another file, argh.py.
import argh
is no good.
You would need to do
from argh import Category
(or alternatively change your code to reference argh.Category)
Anyway, your question can't really be answered better than that unless you give more information. That line isn't the problem. The problem is probably with the Category definition. Where is the definition of Category? Category is another model class. There should be code like
class Category:
#....
And it should either be in the same file, or if it's in a file called "prison.py" then the file you are working on should contain
from prison import Category
A:
It would be useful to link on "some".
However, problem is that You have not imported Category or You define Category under the model with the key mentioned.
| Django: NameError: name 'Category' is not defined | I'm practicing on Django and using some online tutorial to build a web blog. It went smoothly with the first project, yet when I tried the 2nd one, through developing the first view, there was this statement:
categories = models.ManyToManyField(Category, related_name ="packages")
In the tutorial, validating the model gives 0 errors, yet when I ran validating command it gave me :NameError: name 'Category' is not defined
I triple checked the syntax of all the file and there was no single syntax error, there is no additional imports mentioned in the tutorial.
What's wrong ?
| [
"It sounds like you may be new to Python, since you say \"I triple checked the syntax of all the file and there was no single syntax error, there is no additional imports mentioned in the tutorial.\"\nBe aware that in Python, many name-related errors that would be caught at compile time in languages like C++ are caught at runtime instead. This tripped me up a little when I started using Python. Runtime errors could simply be indicating a mere typo, etc. (If this sounds nasty, don't worry-- there's free tools out there to check your program as a compiler for stuff like that some other languages would)\nIs Category defined in the same file that that line appears in? \nIf not, you must specifically import the name Category. Suppose Category is defined in another file, argh.py.\nimport argh\n\nis no good.\nYou would need to do\nfrom argh import Category\n\n(or alternatively change your code to reference argh.Category)\nAnyway, your question can't really be answered better than that unless you give more information. That line isn't the problem. The problem is probably with the Category definition. Where is the definition of Category? Category is another model class. There should be code like\nclass Category:\n #....\n\nAnd it should either be in the same file, or if it's in a file called \"prison.py\" then the file you are working on should contain\nfrom prison import Category\n\n",
"It would be useful to link on \"some\".\nHowever, problem is that You have not imported Category or You define Category under the model with the key mentioned. \n"
] | [
4,
0
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0003128821_django_models_python.txt |
Q:
Mac version of Python doesn't support UTF-8 in curses module?
I'm trying to display a lot of unicode text in my curses application. My development machine is MacOSx 10.6 and I use the default python shipped with Apple.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
When I added unicode text to the screen, the screen all messed up. I tried to Google for solution and other people has suggested to link the _curses module with libncursesw library instead of libncurse library.
I checked my path and I found (see below) in /opt/local/lib
libncurses++.a
libncurses++w.a
libncurses.5.dylib
libncurses.a
libncurses.dylib
libncursesw.5.dylib
libncursesw.a
libncursesw.dylib
How do I check which library my curses module linked to, and how can I link against other library? Is it possible to do it without recompile my Python?
This is kind of embarrassed, but I figure the solution to print unicode properly in my environment. I think at some point time I did install curses libraries from Macports and forgot I have it already.
The problem that the text did not display the first time is because I need to set the locale within my python program. I thought the locale setting would inherit from the shell I'm running, but simply added two lines of code fixed my problem:
import locale
locale.setlocale(locale.LC_ALL,"")
Though, it's good to know where the python external library lives and how to check them.
A:
To check which other .sos a .so uses, use otool -L -- for example:
$ otool -L /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_curses.so
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_curses.so:
/Library/Frameworks/Python.framework/Versions/2.6/lib/libncurses.5.dylib (compatibility version 5.0.0, current version 5.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.10)
This is what I have on my Python 2.6.4 install on OSX 10.5 -- since you're using Apple's own Python on 10.6, the exact location of your _curses.so will be different, just do
$ python
>>> import _curses
>>> _curses.__file__
to see exactly where the _curses.so of interest in, then call otool -L on it.
Replacing a .so on the system-installed Python seems fraught with danger to me -- you could break something and end up having to reinstall the OS, etc. Why not install a Python download from python.org instead?
Get both the .dmg and the sources for the most recent release of 2.6 (unless you're so adventurous you want to try a release candidate 2.7;-), then you can install the .dmg (it will go to /usr/local, not overwriting the system Python; set your PATH appropriately in your .bashrc or wherever to have /usr/local/bin in your PATH ahead of /usr/bin), then, if your problem persists, you can rebuild from sources with whatever options you want, and replace the specific _curses.so in the local install, without disturbing the system directory at all (seems most prudent to me...).
A:
The Apple-supplied Python 2.6 shipped with OS X 10.6 resides here:
$ cd /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload
$ otool -L _curses*
_curses.so:
/usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1)
_curses_panel.so:
/usr/lib/libpanel.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)
/usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1)
It would be a very bad idea to try to modify anything in /System/Library as that could break OS X and/or be wiped out by a system update. If you need to relink, build your own Python from scratch or start with Homebrew, MacPorts, or Fink.
EDIT:
It appears that the current MacPorts Python 2.6 install uses libncursesw so installing it may be the simplest solution:
$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/
$ otool -L _curses*
_curses.so:
/opt/local/lib/libncursesw.5.dylib (compatibility version 5.0.0, current version 5.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
_curses_panel.so:
/opt/local/lib/libpanelw.5.dylib (compatibility version 5.0.0, current version 5.0.0)
/opt/local/lib/libncursesw.5.dylib (compatibility version 5.0.0, current version 5.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
| Mac version of Python doesn't support UTF-8 in curses module? | I'm trying to display a lot of unicode text in my curses application. My development machine is MacOSx 10.6 and I use the default python shipped with Apple.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
When I added unicode text to the screen, the screen all messed up. I tried to Google for solution and other people has suggested to link the _curses module with libncursesw library instead of libncurse library.
I checked my path and I found (see below) in /opt/local/lib
libncurses++.a
libncurses++w.a
libncurses.5.dylib
libncurses.a
libncurses.dylib
libncursesw.5.dylib
libncursesw.a
libncursesw.dylib
How do I check which library my curses module linked to, and how can I link against other library? Is it possible to do it without recompile my Python?
This is kind of embarrassed, but I figure the solution to print unicode properly in my environment. I think at some point time I did install curses libraries from Macports and forgot I have it already.
The problem that the text did not display the first time is because I need to set the locale within my python program. I thought the locale setting would inherit from the shell I'm running, but simply added two lines of code fixed my problem:
import locale
locale.setlocale(locale.LC_ALL,"")
Though, it's good to know where the python external library lives and how to check them.
| [
"To check which other .sos a .so uses, use otool -L -- for example:\n$ otool -L /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_curses.so\n/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_curses.so:\n /Library/Frameworks/Python.framework/Versions/2.6/lib/libncurses.5.dylib (compatibility version 5.0.0, current version 5.0.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.10)\n\nThis is what I have on my Python 2.6.4 install on OSX 10.5 -- since you're using Apple's own Python on 10.6, the exact location of your _curses.so will be different, just do\n$ python\n>>> import _curses\n>>> _curses.__file__\n\nto see exactly where the _curses.so of interest in, then call otool -L on it.\nReplacing a .so on the system-installed Python seems fraught with danger to me -- you could break something and end up having to reinstall the OS, etc. Why not install a Python download from python.org instead?\nGet both the .dmg and the sources for the most recent release of 2.6 (unless you're so adventurous you want to try a release candidate 2.7;-), then you can install the .dmg (it will go to /usr/local, not overwriting the system Python; set your PATH appropriately in your .bashrc or wherever to have /usr/local/bin in your PATH ahead of /usr/bin), then, if your problem persists, you can rebuild from sources with whatever options you want, and replace the specific _curses.so in the local install, without disturbing the system directory at all (seems most prudent to me...).\n",
"The Apple-supplied Python 2.6 shipped with OS X 10.6 resides here:\n$ cd /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload\n$ otool -L _curses*\n_curses.so:\n /usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1)\n_curses_panel.so:\n /usr/lib/libpanel.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)\n /usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1)\n\nIt would be a very bad idea to try to modify anything in /System/Library as that could break OS X and/or be wiped out by a system update. If you need to relink, build your own Python from scratch or start with Homebrew, MacPorts, or Fink.\nEDIT:\nIt appears that the current MacPorts Python 2.6 install uses libncursesw so installing it may be the simplest solution:\n$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/\n$ otool -L _curses*\n_curses.so:\n /opt/local/lib/libncursesw.5.dylib (compatibility version 5.0.0, current version 5.0.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)\n_curses_panel.so:\n /opt/local/lib/libpanelw.5.dylib (compatibility version 5.0.0, current version 5.0.0)\n /opt/local/lib/libncursesw.5.dylib (compatibility version 5.0.0, current version 5.0.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)\n\n"
] | [
2,
1
] | [] | [] | [
"curses",
"python",
"utf_8"
] | stackoverflow_0003129582_curses_python_utf_8.txt |
Q:
What is the Python equivalent of Perl's DBI?
What is Python's equivalent of Perl's DBI and how do I use it? More specifically, what is the Python equivalent of the following Perl code?
use DBI;
# connect to a MySQL database
my $dbh = DBI->connect("dbi:mysql:database=$database; host=localhost; port=3306", $user, $pass);
# select and read a few rows
my $sth = $dbh->prepare("SELECT id, name FROM table WHERE id <= ?;");
$sth->execute(321);
while (my @row = $sth->fetchrow_array) {
my $id = $row[0];
my $name = $row[1];
print "$id. $name\n";
}
# write to the database
$sth = $dbh->prepare("INSERT INTO table (id, name) VALUES (?, ?);");
$sth->execute(123, "foo");
A:
Shylent's post meets the OP's request for equivalent code. However it does not adequately address the issue of what is Python's equivalent to the Perl DBI.
For those not familiar with Perl's DBI, it provides a common interface for all database systems. To add support for new storage backend, a database driver or DBD needs to be written. Drivers exist for many different database systems, and even non-database targets like CSV files and spreadsheets.
It looks like the Python DB-API is the closest thing to the Perl DBI. However it is a specification, and not an implementation. To what extent any database driver conforms to the specification up to the author.
Of course, database systems vary in what SQL commands and syntax they support. Databases vary quite a bit in what features they provide. Any system that attempts to standardize database interaction will have portability issues to address as all these differing systems provide distinct feature sets.
My experience with Perl DBI has been very positive. It is fairly easy to write portable code that works with many DBD drivers. I have successfully used 4 different database drivers (Postgres, MySQL, a CSV file driver, and SQLite) in a single application by simply changing the database connection string. For more complex apps which need to access more "incompatible" features of the database, there are a number of abstraction libraries that extend the DBI interface and further simplify portability.
I don't have enough Python experience to be able to say how PEP249 plays out in the real world. My hope is that database driver developers hew close to the spec, and portability is easy to obtain. Perhaps someone with a deeper knowledge of Python will be able to expand on this topic. There is some information on Python database access at the Python wiki.
A:
import MySQLdb.cursors
db = MySQLdb.connect(db=database, host=localhost,
port=3306, user=user, passwd=pass,
cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
#this is not string interpolation, everything is quoted for you automatically
cur.execute("select id, name from table where id = %s", (321,))
for row in cur.fetchall():
print "%s. %s" % (row['id'], row['name'])
cur.execute("insert into table (id, name) values (%s, %s)", (123, 'foo'))
db.commit() # required, because autocommit is off by default
Python database API use a common convention, that is pretty much the same across different databases (but not quite!). You can read the MySQLdb documentation here.
There is also a more feature-rich interface to mysql, called oursql. It has real parametrization (not just glorified string interpolation), server-side cursors, data streaming and so on.
| What is the Python equivalent of Perl's DBI? | What is Python's equivalent of Perl's DBI and how do I use it? More specifically, what is the Python equivalent of the following Perl code?
use DBI;
# connect to a MySQL database
my $dbh = DBI->connect("dbi:mysql:database=$database; host=localhost; port=3306", $user, $pass);
# select and read a few rows
my $sth = $dbh->prepare("SELECT id, name FROM table WHERE id <= ?;");
$sth->execute(321);
while (my @row = $sth->fetchrow_array) {
my $id = $row[0];
my $name = $row[1];
print "$id. $name\n";
}
# write to the database
$sth = $dbh->prepare("INSERT INTO table (id, name) VALUES (?, ?);");
$sth->execute(123, "foo");
| [
"Shylent's post meets the OP's request for equivalent code. However it does not adequately address the issue of what is Python's equivalent to the Perl DBI.\nFor those not familiar with Perl's DBI, it provides a common interface for all database systems. To add support for new storage backend, a database driver or DBD needs to be written. Drivers exist for many different database systems, and even non-database targets like CSV files and spreadsheets. \nIt looks like the Python DB-API is the closest thing to the Perl DBI. However it is a specification, and not an implementation. To what extent any database driver conforms to the specification up to the author.\nOf course, database systems vary in what SQL commands and syntax they support. Databases vary quite a bit in what features they provide. Any system that attempts to standardize database interaction will have portability issues to address as all these differing systems provide distinct feature sets.\nMy experience with Perl DBI has been very positive. It is fairly easy to write portable code that works with many DBD drivers. I have successfully used 4 different database drivers (Postgres, MySQL, a CSV file driver, and SQLite) in a single application by simply changing the database connection string. For more complex apps which need to access more \"incompatible\" features of the database, there are a number of abstraction libraries that extend the DBI interface and further simplify portability. \nI don't have enough Python experience to be able to say how PEP249 plays out in the real world. My hope is that database driver developers hew close to the spec, and portability is easy to obtain. Perhaps someone with a deeper knowledge of Python will be able to expand on this topic. There is some information on Python database access at the Python wiki.\n",
"import MySQLdb.cursors\n\ndb = MySQLdb.connect(db=database, host=localhost,\n port=3306, user=user, passwd=pass,\n cursorclass=MySQLdb.cursors.DictCursor)\ncur = db.cursor()\n\n#this is not string interpolation, everything is quoted for you automatically\ncur.execute(\"select id, name from table where id = %s\", (321,))\n\nfor row in cur.fetchall():\n print \"%s. %s\" % (row['id'], row['name'])\n\ncur.execute(\"insert into table (id, name) values (%s, %s)\", (123, 'foo'))\ndb.commit() # required, because autocommit is off by default\n\nPython database API use a common convention, that is pretty much the same across different databases (but not quite!). You can read the MySQLdb documentation here.\nThere is also a more feature-rich interface to mysql, called oursql. It has real parametrization (not just glorified string interpolation), server-side cursors, data streaming and so on.\n"
] | [
20,
9
] | [] | [] | [
"python"
] | stackoverflow_0003128961_python.txt |
Q:
FTP request error. Django, FTP, Python
I'm trying to use this expression. And It tell me that: storbinary() takes at most 4 arguments (5 given)
ftp.storbinary("STOR " + os.path.basename(name), StringIO(content_str), "rb", 8*1024)
I can see here only 4 argument. where is hidden 5th argument. I'm confuse.
A:
You are calling a method, so the first argument is implicitly the object you're calling the method on. In other words, you don't see it, but it's there.
Looking at the ftplib documentation, it seems that your third argument, "rb", is incorrect. Your problem should be fixed if you simply remove that argument, as the third argument should be the blocksize.
| FTP request error. Django, FTP, Python | I'm trying to use this expression. And It tell me that: storbinary() takes at most 4 arguments (5 given)
ftp.storbinary("STOR " + os.path.basename(name), StringIO(content_str), "rb", 8*1024)
I can see here only 4 argument. where is hidden 5th argument. I'm confuse.
| [
"You are calling a method, so the first argument is implicitly the object you're calling the method on. In other words, you don't see it, but it's there.\nLooking at the ftplib documentation, it seems that your third argument, \"rb\", is incorrect. Your problem should be fixed if you simply remove that argument, as the third argument should be the blocksize.\n"
] | [
3
] | [] | [] | [
"django",
"ftp",
"python"
] | stackoverflow_0003130014_django_ftp_python.txt |
Q:
Pysqlite setup error
When intalling pysqlite on my Mac I get permission denied when it tries to create pysqlite2-doc dir. Any ideas why?
A:
What exact versions of Mac OSX and Python are you using? All modern ones come with sqlite already there and available for Python. Anyway, if you need to install something in a protected, you need sudo -- check it out!
| Pysqlite setup error | When intalling pysqlite on my Mac I get permission denied when it tries to create pysqlite2-doc dir. Any ideas why?
| [
"What exact versions of Mac OSX and Python are you using? All modern ones come with sqlite already there and available for Python. Anyway, if you need to install something in a protected, you need sudo -- check it out!\n"
] | [
1
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0003130009_pysqlite_python_sqlite.txt |
Q:
Python Conditional Regular Expression
This is a question involving a conditional regular expression in python:
I'd like to match the string "abc" with
match(1)="a"
match(2)="b"
match(3)="c"
but also match the string " a" with
match(1)="a"
match(2)=""
match(3)=""
The following code ALMOST does this, the problem is that in the first case match(1)="a"
but in the second case, match(4)="a" (not match(1) as desired).
In fact, if you iterate through all the groups with for g in re.search(myre,teststring2).groups():, you get 6 groups (not 3 as was expected).
import re
import sys
teststring1 = "abc"
teststring2 = " a"
myre = '^(?=(\w)(\w)(\w))|(?=\s{2}(\w)()())'
if re.search(myre,teststring1):
print re.search(myre,teststring1).group(1)
if re.search(myre,teststring2):
print re.search(myre,teststring2).group(1)
Any thoughts? (note this is for Python 2.5)
A:
Maybe...:
import re
import sys
teststring1 = "abc"
teststring2 = " a"
myre = '^\s{0,2}(\w)(\w?)(\w?)$'
if re.search(myre,teststring1):
print re.search(myre,teststring1).group(1)
if re.search(myre,teststring2):
print re.search(myre,teststring2).group(1)
This does give a in both cases as you wish, but maybe it would not match the way you want in other cases you're not showing (e.g. with no spaces in front, or spaces and more than one letter afterwards, so that the total length of the matched string is != 3... but I'm just guessing that you don't want matches in such cases...?)
A:
Each capturing group in the expression gets it's own index. Try this:
r = re.compile("^\s*(\w)(\w)?(\w)?$")
abc -> ('a', 'b', 'c')
a -> ('a', None, None)
To break it down:
^ // anchored at the beginning
\s* // Any number of spaces to start with
(\w) // capture the first letter, which is required
(\w)? // capture the second letter, which is optional
(\w)? // capture the third letter, which is optional
$ // anchored at the end
A:
myre = '^(?=\s{0,2}(\w)(?:(\w)(\w))?)'
This will handle the two cases you describe in the fashion you want, but is not necessarily a general solution. It feels like you've come up with a toy problem that represents a real one.
A general solution is very hard to come by because the processing of later elements depends on the processing of previous ones and/or the reverse. For example, the initial spaces shouldn't be there if you have the full abc. And if the initial spaces are there, you should only find a.
In my opinion, the best way to handle this is with the | construct you had originally. You can have some code after the match that pulls the groups out into an array and arranges them more to your liking.
The rule for groups is that all open parenthesis that are not immediately followed by ?: become a group. That group may be empty as it didn't actually match anything, but it will be there.
| Python Conditional Regular Expression | This is a question involving a conditional regular expression in python:
I'd like to match the string "abc" with
match(1)="a"
match(2)="b"
match(3)="c"
but also match the string " a" with
match(1)="a"
match(2)=""
match(3)=""
The following code ALMOST does this, the problem is that in the first case match(1)="a"
but in the second case, match(4)="a" (not match(1) as desired).
In fact, if you iterate through all the groups with for g in re.search(myre,teststring2).groups():, you get 6 groups (not 3 as was expected).
import re
import sys
teststring1 = "abc"
teststring2 = " a"
myre = '^(?=(\w)(\w)(\w))|(?=\s{2}(\w)()())'
if re.search(myre,teststring1):
print re.search(myre,teststring1).group(1)
if re.search(myre,teststring2):
print re.search(myre,teststring2).group(1)
Any thoughts? (note this is for Python 2.5)
| [
"Maybe...:\nimport re\nimport sys\n\nteststring1 = \"abc\"\nteststring2 = \" a\"\n\nmyre = '^\\s{0,2}(\\w)(\\w?)(\\w?)$'\n\nif re.search(myre,teststring1):\n print re.search(myre,teststring1).group(1)\n\nif re.search(myre,teststring2):\n print re.search(myre,teststring2).group(1)\n\nThis does give a in both cases as you wish, but maybe it would not match the way you want in other cases you're not showing (e.g. with no spaces in front, or spaces and more than one letter afterwards, so that the total length of the matched string is != 3... but I'm just guessing that you don't want matches in such cases...?)\n",
"Each capturing group in the expression gets it's own index. Try this:\nr = re.compile(\"^\\s*(\\w)(\\w)?(\\w)?$\")\n\nabc -> ('a', 'b', 'c')\na -> ('a', None, None)\n\nTo break it down:\n^ // anchored at the beginning\n\\s* // Any number of spaces to start with\n(\\w) // capture the first letter, which is required\n(\\w)? // capture the second letter, which is optional\n(\\w)? // capture the third letter, which is optional\n$ // anchored at the end\n\n",
"myre = '^(?=\\s{0,2}(\\w)(?:(\\w)(\\w))?)'\n\nThis will handle the two cases you describe in the fashion you want, but is not necessarily a general solution. It feels like you've come up with a toy problem that represents a real one.\nA general solution is very hard to come by because the processing of later elements depends on the processing of previous ones and/or the reverse. For example, the initial spaces shouldn't be there if you have the full abc. And if the initial spaces are there, you should only find a.\nIn my opinion, the best way to handle this is with the | construct you had originally. You can have some code after the match that pulls the groups out into an array and arranges them more to your liking.\nThe rule for groups is that all open parenthesis that are not immediately followed by ?: become a group. That group may be empty as it didn't actually match anything, but it will be there.\n"
] | [
9,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003130209_python_regex.txt |
Q:
If you add the same string to two different lists or collections in Python, are you using twice the memory?
For instance if you add the same string to a dict and a list?
A:
A copy of the string is not put into both, they just both point to the one string.
A:
Strings are immutable and are never copied. Indeed, even if you manually request a copy, you'll still get the same object:
>>> import copy
>>> s = "abc"
>>> t = copy.copy(s)
>>> u = copy.deepcopy(s)
>>> id(s), id(t), id(u)
(139730866789424, 139730866789424, 139730866789424)
>>> s is t, s is u
(True, True)
A:
If it's the same string, only one copy of it exists (and two references to that single object). Two strings that are equal on the other hand can very well end up as two copies, depending on what optimizations the compiler is able to do to avoid the duplication.
Consider, for example (Python 2.6 or earlier -- not sure what further optimizations may be added in the future):
>>> def f1(s, d, l):
... d['z'] = s
... l.append(s)
...
>>> d={}
>>> l=[]
>>> f1('ciao', d, l)
>>> d['z'] is l[0]
True
>>> def f1(s, d, l):
... d['z'] = s + 'zap'
... l.append(s + 'zap')
...
>>> f1('ciao', d, l)
>>> d['z'] is l[1]
False
>>> d['z'] == l[1]
True
>>>
The first one's a no-brainer -- clearly the same object. The second one involves two equal strings -- if the compiler was smarter it could have detected the equality and optimized things to avoid the duplication, but, in general, Python's compiler is tuned to compile very fast, not to spend much time optimizing things.
A:
No. If you have a single string object:
s = "Some string."
And you add it to, say, a dict and a list:
d = {"akey": s}
l = [s]
Then d["akey"] and l[0] will point to the same string object as s, not two different objects with the content "Some string.".
| If you add the same string to two different lists or collections in Python, are you using twice the memory? | For instance if you add the same string to a dict and a list?
| [
"A copy of the string is not put into both, they just both point to the one string.\n",
"Strings are immutable and are never copied. Indeed, even if you manually request a copy, you'll still get the same object:\n>>> import copy\n>>> s = \"abc\"\n>>> t = copy.copy(s)\n>>> u = copy.deepcopy(s)\n>>> id(s), id(t), id(u)\n(139730866789424, 139730866789424, 139730866789424)\n>>> s is t, s is u\n(True, True)\n\n",
"If it's the same string, only one copy of it exists (and two references to that single object). Two strings that are equal on the other hand can very well end up as two copies, depending on what optimizations the compiler is able to do to avoid the duplication.\nConsider, for example (Python 2.6 or earlier -- not sure what further optimizations may be added in the future):\n>>> def f1(s, d, l):\n... d['z'] = s\n... l.append(s)\n... \n>>> d={}\n>>> l=[]\n>>> f1('ciao', d, l)\n>>> d['z'] is l[0]\nTrue\n>>> def f1(s, d, l):\n... d['z'] = s + 'zap'\n... l.append(s + 'zap')\n... \n>>> f1('ciao', d, l)\n>>> d['z'] is l[1]\nFalse\n>>> d['z'] == l[1]\nTrue\n>>> \n\nThe first one's a no-brainer -- clearly the same object. The second one involves two equal strings -- if the compiler was smarter it could have detected the equality and optimized things to avoid the duplication, but, in general, Python's compiler is tuned to compile very fast, not to spend much time optimizing things.\n",
"No. If you have a single string object:\ns = \"Some string.\"\n\nAnd you add it to, say, a dict and a list:\nd = {\"akey\": s}\nl = [s]\n\nThen d[\"akey\"] and l[0] will point to the same string object as s, not two different objects with the content \"Some string.\".\n"
] | [
4,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003130275_python.txt |
Q:
Use markup in files using django
I am currently working on a website using, django, my problem is that the site has to be ported from using php scripts to using django.
Though the site content has been well maintained by the previous maintainer, I have to use markdown for files that already having a HUGE amount of content in them, like the main page is divided into three files inside a directory, like a.html, b.html, c.html though they all contain simple text content, do I have to render them all seperately, should i use the view.py file for parsing the structure or use a template for the same, the real question is how to parse the contents of a file INSIDE the template
I wrote a template:
{% extends "catalog.html" %}
{% block content %}
<div class="yui-g" id="masthead">
<div id="main_feature">
<div id="main_feature_content">
{% include "features/main.html" %}
</div>
</div>
</div>
<div class="yui-g" id="main_information">
<div class="yui-g" style="float: left; width: 49%">
{% include "features/about.html" %}
</div>
<div class="yui-g" style="float: right; width: 49%">
<h2>Recent Headlines</h2>
<a href="/news">More</a>
</div>
</div>
<div class="yui-g" id="features_container">
<div id="features">
<div class="feature feature_developer">
<div class="feature_content">
{% include "features/1.html" %}
</div>
</div>
<div class="feature feature_middle feature_community">
<div class="feature_content">
{% include "features/2.html" %}
</div>
</div>
<div class="feature feature_community">
<div class="feature_content">
{% include "features/3.html" %}
</div>
</div>
</div>
</div>
{% endblock %}
this is the included file i needed to parse :- {% include "features/about.html" %}
but anyone will understand that this will only display the file contents not the parsed html. Thanks for the help in advance
A:
The {% include %} tag only processes Django template files, and does not support any custom processing such as handling markdown in and of itself. You have a few options:
You can wrap all of the markdown content in the included templates with {% load markup %}{% filter markdown %} and {% endfilter %}. The filter tag applies the specified filter(s) to its contents. You will need the {% load markup %} line in the beginning of each template, as each template needs to load the additional tag libraries that it uses.
Your view can do the loading of the content and provide it as a context variable, so that you can do something like {{ aboutcontent|markdown }} in your template (where aboutcontent is the context variable your view provided).
Your view could also do the markdown conversion for you, so you'd simply have to do {{ aboutcontent }}.
You could write a custom templatetag that does the loading and markdown conversion for you, but that's far more complicated and you'd probably be better off with one of the other options, or simply rethinking and updating your templates to not require this processing.
| Use markup in files using django | I am currently working on a website using, django, my problem is that the site has to be ported from using php scripts to using django.
Though the site content has been well maintained by the previous maintainer, I have to use markdown for files that already having a HUGE amount of content in them, like the main page is divided into three files inside a directory, like a.html, b.html, c.html though they all contain simple text content, do I have to render them all seperately, should i use the view.py file for parsing the structure or use a template for the same, the real question is how to parse the contents of a file INSIDE the template
I wrote a template:
{% extends "catalog.html" %}
{% block content %}
<div class="yui-g" id="masthead">
<div id="main_feature">
<div id="main_feature_content">
{% include "features/main.html" %}
</div>
</div>
</div>
<div class="yui-g" id="main_information">
<div class="yui-g" style="float: left; width: 49%">
{% include "features/about.html" %}
</div>
<div class="yui-g" style="float: right; width: 49%">
<h2>Recent Headlines</h2>
<a href="/news">More</a>
</div>
</div>
<div class="yui-g" id="features_container">
<div id="features">
<div class="feature feature_developer">
<div class="feature_content">
{% include "features/1.html" %}
</div>
</div>
<div class="feature feature_middle feature_community">
<div class="feature_content">
{% include "features/2.html" %}
</div>
</div>
<div class="feature feature_community">
<div class="feature_content">
{% include "features/3.html" %}
</div>
</div>
</div>
</div>
{% endblock %}
this is the included file i needed to parse :- {% include "features/about.html" %}
but anyone will understand that this will only display the file contents not the parsed html. Thanks for the help in advance
| [
"The {% include %} tag only processes Django template files, and does not support any custom processing such as handling markdown in and of itself. You have a few options:\n\nYou can wrap all of the markdown content in the included templates with {% load markup %}{% filter markdown %} and {% endfilter %}. The filter tag applies the specified filter(s) to its contents. You will need the {% load markup %} line in the beginning of each template, as each template needs to load the additional tag libraries that it uses.\nYour view can do the loading of the content and provide it as a context variable, so that you can do something like {{ aboutcontent|markdown }} in your template (where aboutcontent is the context variable your view provided).\n\n\nYour view could also do the markdown conversion for you, so you'd simply have to do {{ aboutcontent }}.\n\nYou could write a custom templatetag that does the loading and markdown conversion for you, but that's far more complicated and you'd probably be better off with one of the other options, or simply rethinking and updating your templates to not require this processing.\n\n"
] | [
0
] | [] | [] | [
"django",
"markup",
"python"
] | stackoverflow_0003130373_django_markup_python.txt |
Q:
Thrift client-server multiple roles
this is my first question, so sorry if the form is wrong!
I'm trying to make thrift server (python) and client (c++).
However I need to exchange messages in both direction. Client should register (call server's function and wait), and server should listen on same port for N (N-> 100k) incoming connections (clients). After some conditions are satisfied, server needs to call functions on each client and collect results and interpret them.
I'm little confused, and first questions is "can this be done in Thrift"?
Second question is related to mechanism that will allow me bidirectional communication. I guess that I will need two services. One with client's functions other with server's.
But I'm confused with calling code. I understand one way communication (calling functions from server), but with calling functions from client side I have a problem.
Any suggestions???
Thanks!
A:
Consider using boost::asio for your client side, though depending on your level of C++, the code may seem too dense.
If you're looking for a simple example, take a look at:
http://www.linuxhowtos.org/C_C++/socket.htm
It contains both server-side and client-side code. Both sides create a socket and two-way communication is achieved by each side posting data to the socket. The server side is generally multi-threaded (with one thread per connection). The client side can be implemented as a single-threaded loop that alternates between querying the socket for any incoming information, performing computations, and posting results back to the socket.
A:
Since, you say you are having problem with calling functions from client side, here is a sample Thrift code with Java server and C++ client, where the client calls a function in server. http://fundoonick.blogspot.com/2010/06/sample-thrift-program-for-server-in.html
Hope this helps :)
| Thrift client-server multiple roles | this is my first question, so sorry if the form is wrong!
I'm trying to make thrift server (python) and client (c++).
However I need to exchange messages in both direction. Client should register (call server's function and wait), and server should listen on same port for N (N-> 100k) incoming connections (clients). After some conditions are satisfied, server needs to call functions on each client and collect results and interpret them.
I'm little confused, and first questions is "can this be done in Thrift"?
Second question is related to mechanism that will allow me bidirectional communication. I guess that I will need two services. One with client's functions other with server's.
But I'm confused with calling code. I understand one way communication (calling functions from server), but with calling functions from client side I have a problem.
Any suggestions???
Thanks!
| [
"Consider using boost::asio for your client side, though depending on your level of C++, the code may seem too dense.\nIf you're looking for a simple example, take a look at:\nhttp://www.linuxhowtos.org/C_C++/socket.htm\nIt contains both server-side and client-side code. Both sides create a socket and two-way communication is achieved by each side posting data to the socket. The server side is generally multi-threaded (with one thread per connection). The client side can be implemented as a single-threaded loop that alternates between querying the socket for any incoming information, performing computations, and posting results back to the socket.\n",
"Since, you say you are having problem with calling functions from client side, here is a sample Thrift code with Java server and C++ client, where the client calls a function in server. http://fundoonick.blogspot.com/2010/06/sample-thrift-program-for-server-in.html\nHope this helps :)\n"
] | [
1,
1
] | [] | [] | [
"c++",
"client_server",
"python",
"thrift"
] | stackoverflow_0002518537_c++_client_server_python_thrift.txt |
Q:
Is it possible to run two versions of Python side-by-side?
I've been learning Python for a couple of weeks, and although I've been successfully develop apps for Google App Engine with Python 2.6.5, it specifically requires Python 2.5.
Being mindful of compatibility issues when uploading apps (it's a situation I'd rather avoid while learning Python), I wonder if it's possible to have 2.5 and 2.6.5 installed on the same machine. Ideally I'd like to use 2.6.5 as the default, and configure GAE to somehow use 2.5.
A:
Absolutely.
If you're on *nix, you'd usually just use make altinstall instead of make install, that way the "python" binary won't get installed/overwritten, but instead you'd have e.g. python2.5 or python2.6 installed. Using a separate --prefix with the configure script is also an option, of course.
Some Linux distributions will have multiple versions available via their package managers. They'll similarly be installed as python2.5 etc. (With the distribution's blessed/native version also installed as the regular python binary.)
Windows users generally just install to different directories.
A:
Yes, it is possible to install multiple versions of Python "side-by-side".
On Ubuntu, you simply install with
sudo apt-get install python2.5
(On the current version of Ubuntu, 10.04, python2.6 comes installed by default.)
To use python 2.6, just call python or /usr/bin/python.
To use python 2.5, you call /usr/bin/python2.5.
If you tell us your operating system, we may be able to provide more relevant details.
Another possibility is to use virtualenv.
A:
OK, I figured out the answer to my own question, partly with the help of Nicholas Knight who pointed out that you just install different Python version to different Python directories. I was left scratching my head on how to get Google App Engine to use Python 2.5 (the required version) instead of Python 2.6. This is the answer:
1) Install Python 2.5.
2) Install Python 2.6 (or a more recent version), afterwards. This will be the system default.
3) Install the Google App Engine SDK.
4) Launch, "Google App Engine Launcher" from the Start Menu
5) Click Edit > Preferences, and enter the path to the pythonw.exe executable. Usually c:\Python25\pythonw.exe
| Is it possible to run two versions of Python side-by-side? | I've been learning Python for a couple of weeks, and although I've been successfully develop apps for Google App Engine with Python 2.6.5, it specifically requires Python 2.5.
Being mindful of compatibility issues when uploading apps (it's a situation I'd rather avoid while learning Python), I wonder if it's possible to have 2.5 and 2.6.5 installed on the same machine. Ideally I'd like to use 2.6.5 as the default, and configure GAE to somehow use 2.5.
| [
"Absolutely.\nIf you're on *nix, you'd usually just use make altinstall instead of make install, that way the \"python\" binary won't get installed/overwritten, but instead you'd have e.g. python2.5 or python2.6 installed. Using a separate --prefix with the configure script is also an option, of course.\nSome Linux distributions will have multiple versions available via their package managers. They'll similarly be installed as python2.5 etc. (With the distribution's blessed/native version also installed as the regular python binary.)\nWindows users generally just install to different directories.\n",
"Yes, it is possible to install multiple versions of Python \"side-by-side\". \nOn Ubuntu, you simply install with\nsudo apt-get install python2.5\n\n(On the current version of Ubuntu, 10.04, python2.6 comes installed by default.)\nTo use python 2.6, just call python or /usr/bin/python.\nTo use python 2.5, you call /usr/bin/python2.5. \nIf you tell us your operating system, we may be able to provide more relevant details.\nAnother possibility is to use virtualenv.\n",
"OK, I figured out the answer to my own question, partly with the help of Nicholas Knight who pointed out that you just install different Python version to different Python directories. I was left scratching my head on how to get Google App Engine to use Python 2.5 (the required version) instead of Python 2.6. This is the answer:\n1) Install Python 2.5.\n2) Install Python 2.6 (or a more recent version), afterwards. This will be the system default.\n3) Install the Google App Engine SDK.\n4) Launch, \"Google App Engine Launcher\" from the Start Menu\n5) Click Edit > Preferences, and enter the path to the pythonw.exe executable. Usually c:\\Python25\\pythonw.exe\n"
] | [
5,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003127915_google_app_engine_python.txt |
Q:
Filter ForeignKey by Boolean value in django
I have these models:
class Client(models.Model):
is_provider = models.BooleanField()
class Billing(models.Model):
client = models.ForeignKey(Client)
I want to limit the choices of ForeignKey to show only the clients with is_provider=True. Is there something like:
limit_choices_to = {'is_provider': True}
Or anything I can use to filter the ForeignKey?
A:
Do you have tried the following:
limit_choices_to = {'client__is_provider': True}
A:
Yes, you have the exact syntax already.
client = models.ForeignKey(Client, limit_choices_to = {'is_provider': True})
| Filter ForeignKey by Boolean value in django | I have these models:
class Client(models.Model):
is_provider = models.BooleanField()
class Billing(models.Model):
client = models.ForeignKey(Client)
I want to limit the choices of ForeignKey to show only the clients with is_provider=True. Is there something like:
limit_choices_to = {'is_provider': True}
Or anything I can use to filter the ForeignKey?
| [
"Do you have tried the following:\nlimit_choices_to = {'client__is_provider': True}\n\n",
"Yes, you have the exact syntax already.\nclient = models.ForeignKey(Client, limit_choices_to = {'is_provider': True})\n\n"
] | [
1,
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"foreign_keys",
"python"
] | stackoverflow_0003130832_django_django_admin_django_models_foreign_keys_python.txt |
Q:
Starting Python and PyQt - Tutorials, Books, general approaches
After doing web development (php/js) for the last few years i thought it is about time to also have a look at something different. I thought it may be always good to have look of different areas in programming to understand some different approaches better, so i now want to have look at GUI development.
As programming language i did choose Python where i now slowly get the basics and i also found this question:
How to learn python
which already contains good links and book proposals. So i am now mainly looking for some infos about PyQt:
Tutorials
Books
General tips for GUI development
I already looked at some tutorials, but didn't find any really good ones. Most were pretty short and didn't really explain anything.
Thanks in advance for advises.
A:
The first thing to realize is that you'll get more mileage out of understanding Qt than understanding PyQt. Most of the good documentation discusses Qt, not PyQt, so getting conversant with them (and how to convert that code to PyQt code) is a lifesaver. Note, I don't actually recommend programming Qt in C++; Python is a fantastic language for Qt programming, since it takes care of a lot of gruntwork, leaving you to actually code application logic.
The best book I've found for working with PyQt is Rapid GUI Programming with Python and Qt. It's got a nice small Python tutorial in the front, then takes you through the basics of building a Qt application. By the end of the book you should have a good idea of how to build an application, and some basic idea of where to start for more advanced topics.
The other critical reference is the bindings documentation for PyQt. Pay particular attention to the "New-style Signal and Slot Support"; it's a huge improvement over the old style. Once you really understand that document (and it's pretty short) you'll be able to navigate the Qt docs pretty easily.
A:
I had this bookmark saved:
http://www.harshj.com/2009/04/26/the-pyqt-intro/
A:
There is a step-by-step guide at popdevelop.com on how to set up Eclipse with PyQT.
A:
My advice would be: have some particular goal in mind, some app that you, or even better someone else, would use in a real world scenario.
I started with the same book Chris B mentioned, i.e. Rapid GUI Programming with Python and Qt and I found it useful and it touched many of the topics you would need in most GUI applications. Additionally, after some time and some confidence gained, you want to have PyQT Classes handy.
Do not avoid C++ examples to explain some problem you'd like to solve, rewriting it in Python is not that hard (depending on the problem, and scope of course).
| Starting Python and PyQt - Tutorials, Books, general approaches | After doing web development (php/js) for the last few years i thought it is about time to also have a look at something different. I thought it may be always good to have look of different areas in programming to understand some different approaches better, so i now want to have look at GUI development.
As programming language i did choose Python where i now slowly get the basics and i also found this question:
How to learn python
which already contains good links and book proposals. So i am now mainly looking for some infos about PyQt:
Tutorials
Books
General tips for GUI development
I already looked at some tutorials, but didn't find any really good ones. Most were pretty short and didn't really explain anything.
Thanks in advance for advises.
| [
"The first thing to realize is that you'll get more mileage out of understanding Qt than understanding PyQt. Most of the good documentation discusses Qt, not PyQt, so getting conversant with them (and how to convert that code to PyQt code) is a lifesaver. Note, I don't actually recommend programming Qt in C++; Python is a fantastic language for Qt programming, since it takes care of a lot of gruntwork, leaving you to actually code application logic.\nThe best book I've found for working with PyQt is Rapid GUI Programming with Python and Qt. It's got a nice small Python tutorial in the front, then takes you through the basics of building a Qt application. By the end of the book you should have a good idea of how to build an application, and some basic idea of where to start for more advanced topics.\nThe other critical reference is the bindings documentation for PyQt. Pay particular attention to the \"New-style Signal and Slot Support\"; it's a huge improvement over the old style. Once you really understand that document (and it's pretty short) you'll be able to navigate the Qt docs pretty easily.\n",
"I had this bookmark saved:\nhttp://www.harshj.com/2009/04/26/the-pyqt-intro/\n",
"There is a step-by-step guide at popdevelop.com on how to set up Eclipse with PyQT.\n",
"My advice would be: have some particular goal in mind, some app that you, or even better someone else, would use in a real world scenario.\nI started with the same book Chris B mentioned, i.e. Rapid GUI Programming with Python and Qt and I found it useful and it touched many of the topics you would need in most GUI applications. Additionally, after some time and some confidence gained, you want to have PyQT Classes handy.\nDo not avoid C++ examples to explain some problem you'd like to solve, rewriting it in Python is not that hard (depending on the problem, and scope of course).\n"
] | [
15,
4,
4,
1
] | [] | [] | [
"pyqt",
"python",
"user_interface"
] | stackoverflow_0003113002_pyqt_python_user_interface.txt |
Q:
Make urllib retry multiple times
My Python application makes a lot of HTTP requests using the urllib2 module. This application might be used over very unreliable networks where latencies could be low and dropped packets and network timeouts might be very common. Is is possible to override a part of the urllib2 module so that each request is retried an X number of times before raising any exceptions? Has anyone seen something like this?
Can i achieve this without modifying my whole application and just creating a wrapper over the urllib2 module. Thus any code making requests using this module automatically gets to use the retry functionality.
Thanks.
A:
Modifying parts of a library is never a good idea.
You can write wrappers around the methods you use to fetch data that would provide the desired behavior. Which would be trivial.
You can for example define methods with the same names as in urllib2 in your own module called myurllib2. Then just change the imports everywhere you use urllib2
| Make urllib retry multiple times | My Python application makes a lot of HTTP requests using the urllib2 module. This application might be used over very unreliable networks where latencies could be low and dropped packets and network timeouts might be very common. Is is possible to override a part of the urllib2 module so that each request is retried an X number of times before raising any exceptions? Has anyone seen something like this?
Can i achieve this without modifying my whole application and just creating a wrapper over the urllib2 module. Thus any code making requests using this module automatically gets to use the retry functionality.
Thanks.
| [
"Modifying parts of a library is never a good idea.\nYou can write wrappers around the methods you use to fetch data that would provide the desired behavior. Which would be trivial.\nYou can for example define methods with the same names as in urllib2 in your own module called myurllib2. Then just change the imports everywhere you use urllib2\n"
] | [
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0003130923_python_urllib_urllib2.txt |
Q:
Generate a nested list from flatten data in Python
To generate a Table of Content, I have these data available in a Python list:
data = [
{title: 'Section 1', level: 1, page_number: 1},
{title: 'Section 1.1', level: 2, page_number: 2},
{title: 'Section 1.2', level: 2, page_number: 3},
{title: 'Section 2', level: 1, page_number: 4},
{title: 'Section 2.1', level: 2, page_number: 5},
{title: 'Section 3', level: 1, page_number: 6},
]
From this, I'd like to obtain this kind of nested structure, much more compatible with the use of a template engine:
toc = [
{title: 'Section 1', page_number: 1, sub: [
{title: 'Section 1.1', page_number: 2, sub: []},
{title: 'Section 1.2', page_number: 3, sub: []},
]},
{title: 'Section 2', page_number: 4, sub: [
{title: 'Section 2.1', page_number: 5, sub: []},
]},
{title: 'Section 3', page_number: 6, sub: []},
]
Hints on how to achieve this? I tried with a recursive function but it's getting much tricky for my limited brain.
Any help much appreciated.
EDIT: Added fact that a section entry can have eventually no child. Sorry for the miss.
A:
Assuming chapters come in order, meaning child chapter is always after the parent, and there are no missing parent (skipped levels):
import pprint
data = [
{'title': 'Section 1', 'level': 1, 'page_number': 1},
{'title': 'Section 1.1', 'level': 2, 'page_number': 2},
{'title': 'Section 1.2', 'level': 2, 'page_number': 3},
{'title': 'Section 2', 'level': 1, 'page_number': 4},
{'title': 'Section 2.1', 'level': 2, 'page_number': 42},
{'title': 'Section 2.1.1', 'level': 3, 'page_number': 42},
{'title': 'Section 3', 'level': 1, 'page_number': 42},
]
toc = []
stack = [toc]
for d in data:
d['sub'] = []
while d['level'] < len(stack):
stack.pop()
while d['level'] > len(stack):
stack.append(stack[-1][-1]['sub'])
stack[-1].append(d)
pprint.pprint(toc)
Result:
[{'level': 1,
'page_number': 1,
'sub': [{'level': 2, 'page_number': 2, 'sub': [], 'title': 'Section 1.1'},
{'level': 2, 'page_number': 3, 'sub': [], 'title': 'Section 1.2'}],
'title': 'Section 1'},
{'level': 1,
'page_number': 4,
'sub': [{'level': 2,
'page_number': 42,
'sub': [{'level': 3,
'page_number': 42,
'sub': [],
'title': 'Section 2.1.1'}],
'title': 'Section 2.1'}],
'title': 'Section 2'},
{'level': 1, 'page_number': 42, 'sub': [], 'title': 'Section 3'}]
EDIT: changed it to have empty 'sub' items where there are no children. See the other variant in edit history.
A:
Does this do what you want?
TITLE, LEVEL, PAGE_NUMBER, SUB = 'title', 'level', 'page_number', 'sub'
data = [
{TITLE: 'Section 1', LEVEL: 1, PAGE_NUMBER: 1},
{TITLE: 'Section 1.1', LEVEL: 2, PAGE_NUMBER: 2},
{TITLE: 'Section 1.1.1', LEVEL: 3, PAGE_NUMBER: 2},
{TITLE: 'Section 1.2', LEVEL: 2, PAGE_NUMBER: 3},
{TITLE: 'Section 2', LEVEL: 1, PAGE_NUMBER: 4},
{TITLE: 'Section 2.1', LEVEL: 2, PAGE_NUMBER: 5},
]
levels = [ { SUB: [] } ]
for section in data:
section = dict(section)
current = section[LEVEL]
section[SUB] = []
levels[current-1][SUB].append(section)
del levels[current:]
levels.append(section)
toc = levels[0][SUB]
from pprint import pprint
pprint(toc)
A:
You could walk through each entry in your list and build a new list from there. Whenever there is a "Section x.y", you'll add it under sub.
newData = []
curParent = None
for d in data:
# child
if d['title'].find('.') > 0:
assert curParent # Make sure we have a valid parent dictionary
curParent['sub'].append({'title': d['title'], 'page_number': d['page_number'])
# parent
else:
curParent = {'title': d['title'], 'page_number': d['page_number'], 'sub': []}
newData.append(curParent)
That should work for 2 or 3 levels, if you need many more than a different approach might be better. Also, the find('.') might not work with other titles, but either use the level field (which seems redundant in your example) or regular expressions.
| Generate a nested list from flatten data in Python | To generate a Table of Content, I have these data available in a Python list:
data = [
{title: 'Section 1', level: 1, page_number: 1},
{title: 'Section 1.1', level: 2, page_number: 2},
{title: 'Section 1.2', level: 2, page_number: 3},
{title: 'Section 2', level: 1, page_number: 4},
{title: 'Section 2.1', level: 2, page_number: 5},
{title: 'Section 3', level: 1, page_number: 6},
]
From this, I'd like to obtain this kind of nested structure, much more compatible with the use of a template engine:
toc = [
{title: 'Section 1', page_number: 1, sub: [
{title: 'Section 1.1', page_number: 2, sub: []},
{title: 'Section 1.2', page_number: 3, sub: []},
]},
{title: 'Section 2', page_number: 4, sub: [
{title: 'Section 2.1', page_number: 5, sub: []},
]},
{title: 'Section 3', page_number: 6, sub: []},
]
Hints on how to achieve this? I tried with a recursive function but it's getting much tricky for my limited brain.
Any help much appreciated.
EDIT: Added fact that a section entry can have eventually no child. Sorry for the miss.
| [
"Assuming chapters come in order, meaning child chapter is always after the parent, and there are no missing parent (skipped levels):\nimport pprint\n\ndata = [\n {'title': 'Section 1', 'level': 1, 'page_number': 1},\n {'title': 'Section 1.1', 'level': 2, 'page_number': 2},\n {'title': 'Section 1.2', 'level': 2, 'page_number': 3},\n {'title': 'Section 2', 'level': 1, 'page_number': 4},\n {'title': 'Section 2.1', 'level': 2, 'page_number': 42},\n {'title': 'Section 2.1.1', 'level': 3, 'page_number': 42},\n {'title': 'Section 3', 'level': 1, 'page_number': 42},\n]\n\ntoc = []\nstack = [toc]\nfor d in data:\n d['sub'] = [] \n while d['level'] < len(stack):\n stack.pop()\n while d['level'] > len(stack):\n stack.append(stack[-1][-1]['sub'])\n stack[-1].append(d)\n\n\npprint.pprint(toc)\n\nResult:\n[{'level': 1,\n 'page_number': 1,\n 'sub': [{'level': 2, 'page_number': 2, 'sub': [], 'title': 'Section 1.1'},\n {'level': 2, 'page_number': 3, 'sub': [], 'title': 'Section 1.2'}],\n 'title': 'Section 1'},\n {'level': 1,\n 'page_number': 4,\n 'sub': [{'level': 2,\n 'page_number': 42,\n 'sub': [{'level': 3,\n 'page_number': 42,\n 'sub': [],\n 'title': 'Section 2.1.1'}],\n 'title': 'Section 2.1'}],\n 'title': 'Section 2'},\n {'level': 1, 'page_number': 42, 'sub': [], 'title': 'Section 3'}]\n\nEDIT: changed it to have empty 'sub' items where there are no children. See the other variant in edit history.\n",
"Does this do what you want?\nTITLE, LEVEL, PAGE_NUMBER, SUB = 'title', 'level', 'page_number', 'sub'\ndata = [\n {TITLE: 'Section 1', LEVEL: 1, PAGE_NUMBER: 1},\n {TITLE: 'Section 1.1', LEVEL: 2, PAGE_NUMBER: 2},\n {TITLE: 'Section 1.1.1', LEVEL: 3, PAGE_NUMBER: 2},\n {TITLE: 'Section 1.2', LEVEL: 2, PAGE_NUMBER: 3},\n {TITLE: 'Section 2', LEVEL: 1, PAGE_NUMBER: 4},\n {TITLE: 'Section 2.1', LEVEL: 2, PAGE_NUMBER: 5},\n]\n\nlevels = [ { SUB: [] } ]\nfor section in data:\n section = dict(section)\n current = section[LEVEL]\n section[SUB] = []\n levels[current-1][SUB].append(section)\n del levels[current:]\n levels.append(section)\n\ntoc = levels[0][SUB]\nfrom pprint import pprint\npprint(toc)\n\n",
"You could walk through each entry in your list and build a new list from there. Whenever there is a \"Section x.y\", you'll add it under sub.\nnewData = []\ncurParent = None\nfor d in data:\n # child\n if d['title'].find('.') > 0:\n assert curParent # Make sure we have a valid parent dictionary\n curParent['sub'].append({'title': d['title'], 'page_number': d['page_number'])\n # parent\n else:\n curParent = {'title': d['title'], 'page_number': d['page_number'], 'sub': []}\n newData.append(curParent)\n\nThat should work for 2 or 3 levels, if you need many more than a different approach might be better. Also, the find('.') might not work with other titles, but either use the level field (which seems redundant in your example) or regular expressions.\n"
] | [
4,
2,
0
] | [] | [] | [
"list",
"python",
"recursion",
"tree"
] | stackoverflow_0003130931_list_python_recursion_tree.txt |
Q:
How do I install WordPress in a Django subdirectory?
I have Django set up on my server at http://stevencampbell.org/
I want to be able to run WordPress at stevencampbell.org/blog/
I'm running all my Python and Django files through Fast_CGI (only Django option on my server). My .htaccess file looks like this:
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteRule ^(/media.*)$ /$1 [QSA,PT]
RewriteRule ^(/adminmedia.*)$ /$1 [QSA, PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]
Assumedly, I need to add another RewriteRule in for the blog directory, but none of my attempts so far have worked. I can access /blog/index.php, but /blog/ gives me a Django error, meaning that the directory is still be processed by the dispatch.fcgi file.
Also, I'm not really sure what I'm doing with these rewrite rules. Let me know if I'm doing anything else wrong.
A:
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteRule ^(/media.*)$ /$1 [QSA,PT]
RewriteRule ^(/adminmedia.*)$ /$1 [QSA, PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/blog(/.*)?$
RewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]
See that extra RewriteCond? Basically says "if the request is not /blog or /blog/whatever, then rewrite requests to dispatch.fcgi
In your WordPress .htaccess inside /blog, you should add the line RewriteBase /blog/ right after the RewriteEngine On statement.
A:
This sounds a little awkward. I don't know enough about mod_rewrite to get check your settings but why don't you simply use a Django based blogging engine instead of wordpress. Something like http://github.com/nathanborror/django-basic-apps perhaps?
| How do I install WordPress in a Django subdirectory? | I have Django set up on my server at http://stevencampbell.org/
I want to be able to run WordPress at stevencampbell.org/blog/
I'm running all my Python and Django files through Fast_CGI (only Django option on my server). My .htaccess file looks like this:
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteRule ^(/media.*)$ /$1 [QSA,PT]
RewriteRule ^(/adminmedia.*)$ /$1 [QSA, PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]
Assumedly, I need to add another RewriteRule in for the blog directory, but none of my attempts so far have worked. I can access /blog/index.php, but /blog/ gives me a Django error, meaning that the directory is still be processed by the dispatch.fcgi file.
Also, I'm not really sure what I'm doing with these rewrite rules. Let me know if I'm doing anything else wrong.
| [
"AddHandler fastcgi-script .fcgi\nRewriteEngine On\nRewriteRule ^(/media.*)$ /$1 [QSA,PT]\nRewriteRule ^(/adminmedia.*)$ /$1 [QSA, PT]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_URI} !^/blog(/.*)?$\nRewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]\n\nSee that extra RewriteCond? Basically says \"if the request is not /blog or /blog/whatever, then rewrite requests to dispatch.fcgi\nIn your WordPress .htaccess inside /blog, you should add the line RewriteBase /blog/ right after the RewriteEngine On statement.\n",
"This sounds a little awkward. I don't know enough about mod_rewrite to get check your settings but why don't you simply use a Django based blogging engine instead of wordpress. Something like http://github.com/nathanborror/django-basic-apps perhaps? \n"
] | [
1,
0
] | [] | [] | [
"django",
"fastcgi",
"mod_rewrite",
"python",
"wordpress"
] | stackoverflow_0003128256_django_fastcgi_mod_rewrite_python_wordpress.txt |
Q:
Python subprocess module - unexpected behavior
I need to interface a C console program (as subprocess) with Python using stdin/stdout.
the C program is more o less it:
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
Using python subprocess module I need to read data from this program, the write something, then read again and so on. I used the following code:
>>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> o,i=communicate('123\n')
the output of o is:
input>>
input was: 123.000000
input>>
input was: 0.000000
input>>
input was: 0.000000
I would expect the subprocess to wait on input until another o,i=communicate() call. Why it is proceding to the end of the program without any input? how to fix it?
A:
There can be at most one call to communicate() for each process, because communicate() waits for the child process to terminate. To repeatedly read and write from/to a process's standard streams, use the stdout and stdin attributes of the Popen class.
| Python subprocess module - unexpected behavior | I need to interface a C console program (as subprocess) with Python using stdin/stdout.
the C program is more o less it:
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
Using python subprocess module I need to read data from this program, the write something, then read again and so on. I used the following code:
>>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> o,i=communicate('123\n')
the output of o is:
input>>
input was: 123.000000
input>>
input was: 0.000000
input>>
input was: 0.000000
I would expect the subprocess to wait on input until another o,i=communicate() call. Why it is proceding to the end of the program without any input? how to fix it?
| [
"There can be at most one call to communicate() for each process, because communicate() waits for the child process to terminate. To repeatedly read and write from/to a process's standard streams, use the stdout and stdin attributes of the Popen class.\n"
] | [
3
] | [] | [] | [
"c",
"python",
"subprocess"
] | stackoverflow_0003131169_c_python_subprocess.txt |
Q:
Is there an sql admin panel made with Django? - Django
I'm using SQL Server 2005 with Django, I'm wondering if anyone has ever attempted to create an admin panel for SQL using Django.
Would be quite useful to have!
A:
You can ./manage.py inspectdb from the console and it automatically generates model files. You may then add the admin files to present the data how you want it.
| Is there an sql admin panel made with Django? - Django | I'm using SQL Server 2005 with Django, I'm wondering if anyone has ever attempted to create an admin panel for SQL using Django.
Would be quite useful to have!
| [
"You can ./manage.py inspectdb from the console and it automatically generates model files. You may then add the admin files to present the data how you want it.\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"python",
"sql",
"sql_server"
] | stackoverflow_0003131175_django_django_admin_python_sql_sql_server.txt |
Q:
Finding images with pure colours
I've read a number of questions on finding the colour palette of an image, but my problem is slightly different. I'm looking for images made up of pure colours: pictures of the open sky, colourful photo backgrounds, red brick walls etc.
So far I've used the App Engine Image.histogram() function to produce a histogram, filter out values below a certain occurrence threshold, and average the remaining ones down. That still seems to leave in a lot of extraneous photographs where there are blobs of pure colour in a mixed bag of other photos.
Any ideas much appreciated!
A:
How about doing this?
Blur the image using some fast blurring algorithm. (Search for stack blur or box blur)
Compute standard deviation of the pixels in RGB domain, once for each color.
Discard the image if the standard deviation is beyond a certain threshold.
A:
In my opinion a histogram will not be the ideal tool for the this task since it typically looks at separately at each color channel and you will loose information like this. So for example if you get peaks at 255 red, green and blue this can either mean that there is lots of red (0xFF0000), green (0x00FF00) and blue ( 0x0000FF) in the image or that the whole image is simply entirely white ( 0xFFFFFF).
I recommend you to use a color quantization algorithm on your image: http://en.wikipedia.org/wiki/Color_quantization and have it return you the 16 most dominant colors. Then maybe convert them to HSL and check for values with a high saturation.
| Finding images with pure colours | I've read a number of questions on finding the colour palette of an image, but my problem is slightly different. I'm looking for images made up of pure colours: pictures of the open sky, colourful photo backgrounds, red brick walls etc.
So far I've used the App Engine Image.histogram() function to produce a histogram, filter out values below a certain occurrence threshold, and average the remaining ones down. That still seems to leave in a lot of extraneous photographs where there are blobs of pure colour in a mixed bag of other photos.
Any ideas much appreciated!
| [
"How about doing this?\n\nBlur the image using some fast blurring algorithm. (Search for stack blur or box blur)\nCompute standard deviation of the pixels in RGB domain, once for each color.\nDiscard the image if the standard deviation is beyond a certain threshold.\n\n",
"In my opinion a histogram will not be the ideal tool for the this task since it typically looks at separately at each color channel and you will loose information like this. So for example if you get peaks at 255 red, green and blue this can either mean that there is lots of red (0xFF0000), green (0x00FF00) and blue ( 0x0000FF) in the image or that the whole image is simply entirely white ( 0xFFFFFF).\nI recommend you to use a color quantization algorithm on your image: http://en.wikipedia.org/wiki/Color_quantization and have it return you the 16 most dominant colors. Then maybe convert them to HSL and check for values with a high saturation.\n"
] | [
1,
0
] | [] | [] | [
"colors",
"image",
"image_processing",
"python"
] | stackoverflow_0003106788_colors_image_image_processing_python.txt |
Q:
In which language Boxee.tv IPTV software developed in?
I want to know the programming language used by Boxee.tv guys to build their IPTV software. My company is building a IPTV software which will fetch channels and stream channels from the internet.
Boxee's desktop client does the same. Since we want to create a Similar UI, I would like to know what have they used to create such a UI.
Is it flash or AIR , I see some python DLLs when I inspected their folder inside program files.
A:
Boxee is a fork of the famous free and open source media player XBMC.
C++ is the main language (Python language is used mainly for plugins)
| In which language Boxee.tv IPTV software developed in? | I want to know the programming language used by Boxee.tv guys to build their IPTV software. My company is building a IPTV software which will fetch channels and stream channels from the internet.
Boxee's desktop client does the same. Since we want to create a Similar UI, I would like to know what have they used to create such a UI.
Is it flash or AIR , I see some python DLLs when I inspected their folder inside program files.
| [
"Boxee is a fork of the famous free and open source media player XBMC.\nC++ is the main language (Python language is used mainly for plugins)\n"
] | [
3
] | [] | [] | [
"air",
"boxee",
"flash",
"python"
] | stackoverflow_0003131253_air_boxee_flash_python.txt |
Q:
Changing default date printing format in python
Can I change the default __str__() function of the datetime.datetime object?
By default, it returns something like '2010-06-28 12:43:56.985790', and i need it to print something like '2010-06-28T12:44:21.241228'(which is the isoformat() function).
I need this for JSON serializing of a django model.
My model is:
class Transport(models.Model):
user = models.ForeignKey(User)
source = models.ForeignKey(Marker, related_name="source_marker")
destination = models.ForeignKey(Marker, related_name="destination_marker")
object = models.CharField(choices=possesion_choices, max_length=2**6)
quantity = models.IntegerField()
time_sent = models.DateTimeField()
time_arrived = models.DateTimeField()
And when i serialize it (using the wadofstuff module), it prints something like
print serializers.serialize('json', Transport.objects.all(), relations=('source', 'destination',) indent=4)
[
{
"pk": 1,
"model": "main.transport",
"fields": {
[.. bla bla ..]
"time_sent": "2010-06-28 12:18:05",
"time_arrived": "2010-06-28 12:38:36",
[.. bla bla ..]
}
}
]
A:
Django uses a field's value_to_string method to provide the string representation within a serializer. So you could define a custom field subclass that overrides this method:
class MyDateTimeField(DateTimeField)
def value_to_string(self, obj):
val = self._get_val_from_obj(obj)
if val is None:
data = ''
else:
data = val.isoformat()
return data
Edited
Aargh, looks like I was looking in completely the wrong place. The serializers.python.Serializer.handle_field method actually checks for date-time fields and passes them through unchanged to the JSON encoder. So it's that encoder that we actually need to override.
class MyJSONEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.isoformat()
else:
return super(MyJSONEncoder, self).default(o)
Unfortunately, wadofstuff hardcodes the original DjangoJSONEncoder, so we'll need to override the serializer too.
from wadofstuff.django.serializers.json import Serializer
class BetterSerializer(Serializer):
"""
Convert a queryset to JSON.
"""
def end_serialization(self):
"""Output a JSON encoded queryset."""
self.options.pop('stream', None)
self.options.pop('fields', None)
self.options.pop('excludes', None)
self.options.pop('relations', None)
self.options.pop('extras', None)
simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,
**self.options)
| Changing default date printing format in python | Can I change the default __str__() function of the datetime.datetime object?
By default, it returns something like '2010-06-28 12:43:56.985790', and i need it to print something like '2010-06-28T12:44:21.241228'(which is the isoformat() function).
I need this for JSON serializing of a django model.
My model is:
class Transport(models.Model):
user = models.ForeignKey(User)
source = models.ForeignKey(Marker, related_name="source_marker")
destination = models.ForeignKey(Marker, related_name="destination_marker")
object = models.CharField(choices=possesion_choices, max_length=2**6)
quantity = models.IntegerField()
time_sent = models.DateTimeField()
time_arrived = models.DateTimeField()
And when i serialize it (using the wadofstuff module), it prints something like
print serializers.serialize('json', Transport.objects.all(), relations=('source', 'destination',) indent=4)
[
{
"pk": 1,
"model": "main.transport",
"fields": {
[.. bla bla ..]
"time_sent": "2010-06-28 12:18:05",
"time_arrived": "2010-06-28 12:38:36",
[.. bla bla ..]
}
}
]
| [
"Django uses a field's value_to_string method to provide the string representation within a serializer. So you could define a custom field subclass that overrides this method:\nclass MyDateTimeField(DateTimeField)\n def value_to_string(self, obj):\n val = self._get_val_from_obj(obj)\n if val is None:\n data = ''\n else:\n data = val.isoformat()\n return data\n\nEdited\nAargh, looks like I was looking in completely the wrong place. The serializers.python.Serializer.handle_field method actually checks for date-time fields and passes them through unchanged to the JSON encoder. So it's that encoder that we actually need to override.\nclass MyJSONEncoder(DjangoJSONEncoder):\n def default(self, o):\n if isinstance(o, datetime.datetime):\n return o.isoformat()\n else:\n return super(MyJSONEncoder, self).default(o)\n\nUnfortunately, wadofstuff hardcodes the original DjangoJSONEncoder, so we'll need to override the serializer too.\nfrom wadofstuff.django.serializers.json import Serializer\nclass BetterSerializer(Serializer):\n \"\"\"\n Convert a queryset to JSON.\n \"\"\"\n def end_serialization(self):\n \"\"\"Output a JSON encoded queryset.\"\"\"\n self.options.pop('stream', None)\n self.options.pop('fields', None)\n self.options.pop('excludes', None)\n self.options.pop('relations', None)\n self.options.pop('extras', None)\n simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,\n **self.options)\n\n"
] | [
3
] | [] | [] | [
"django",
"javascript",
"json",
"python"
] | stackoverflow_0003131404_django_javascript_json_python.txt |
Q:
Custom views in Django admin panel
I am working on a Django project where I need to change almost half the features and the way Django admin manages the models. For e.g. I have to create an application and then create an administrator and assign that application such that this admin can manage only that particular application. The administrators would be created by the global administrator of the project using the admin panel.
Please suggest.
Thanks in advance.
A:
You can control who has access read/write/delete to what applications' data via the admin using permissions.
| Custom views in Django admin panel | I am working on a Django project where I need to change almost half the features and the way Django admin manages the models. For e.g. I have to create an application and then create an administrator and assign that application such that this admin can manage only that particular application. The administrators would be created by the global administrator of the project using the admin panel.
Please suggest.
Thanks in advance.
| [
"You can control who has access read/write/delete to what applications' data via the admin using permissions.\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003131083_django_django_admin_python.txt |
Q:
How to get REALLY fast Python over a simple loop
I'm working on a SPOJ problem, INTEST. The goal is to specify the number of test cases (n) and a divisor (k), then feed your program n numbers. The program will accept each number on a newline of stdin and after receiving the nth number, will tell you how many were divisible by k.
The only challenge in this problem is getting your code to be FAST because k can be anything up to 10^7 and n can be as high as 10^9.
I'm trying to write it in Python and have trouble speeding it up. Any ideas?
Edit 2: I finally got it to pass at 10.54 seconds. I used nearly all of your answers to get there, and thus it was hard to choose one as 'correct', but I believe the one I chose sums it up the best. Thanks to you all. Final passing code is below.
Edit: I included some of the suggested updates in the included code.
Extensions and third-party modules are not allowed. The code is also run by the SPOJ judge machine, so I do not have the option of changing interpreters.
import sys
import psyco
psyco.full()
def main():
from sys import stdin, stdout
first_in = stdin.readline()
thing = first_in.split()
n = int(thing[0])
k = int(thing[1])
total = 0
list = stdin.readlines()
for item in list:
if int(item) % k == 0:
total += 1
stdout.write(str(total) + "\n")
if __name__ == "__main__":
main()
A:
[Edited to reflect new findings and passing code on spoj]
Generally, when using Python for spoj:
Don't use "raw_input", use sys.stdin.readlines(). That can make a difference for large input. Also, if possible (and it is, for this problem), read everything at once (sys.stdin. readlines()), instead of reading line by line ("for line in sys.stdin...").
Similarly, don't use "print", use sys.stdout.write() - and don't forget "\n". Of course, this is only relevant when printing multiple times.
As S.Mark suggested, use psyco. It's available for both python2.5 and python2.6, at spoj (test it, it's there, and easy to spot: solutions using psyco usually have a ~35Mb memory usage offset). It's really simple: just add, after "import sys": import psyco; psyco.full()
As Justin suggested, put your code (except psyco incantation) inside a function, and simply call it at the end of your code
Sometimes creating a list and checking its length can be faster than creating a list and adding its components.
Favour list comprehensions (and generator expressions, when possible) over "for" and "while" as well. For some constructs, map/reduce/filter may also speed up your code.
Using (some of) these guidelines, I've managed to pass INTEST. Still testing alternatives, though.
A:
Hey, I got it to be within the time limit. I used the following:
Psyco with Python 2.5.
a simple loop with a variable to keep count in
my code was all in a main() function (except the psyco import) which I called.
The last one is what made the difference. I believe that it has to do with variable visibility, but I'm not completely sure. My time was 10.81 seconds. You might get it to be faster with a list comprehension.
Edit:
Using a list comprehension brought my time down to 8.23 seconds. Bringing the line from sys import stdin, stdout inside of the function shaved off a little too to bring my time down to 8.12 seconds.
A:
Use psyco, it will JIT your code, very effective when there is big loop and calculations.
Edit: Looks like third party modules are not allowed,
So, you may try converting your loop to list comprehensions, it supposed to be run at C level, so it should be faster a little bit.
sum(1 if int(line) % k == 0 else 0 for line in sys.stdin)
A:
Just recently Alex Martinelli said that invoking code inside a function, outperforms code run in the module ( I can't find the post though )
So, why don't you try:
import sys
import psyco
psyco.full1()
def main():
first_in = raw_input()
thing = first_in.split()
n = int(thing[0])
k = int(thing[1])
total = 0
i = 0
total = sum(1 if int(line) % k == 0 else 0 for line in sys.stdin)
print total
if __name__ == "__main__":
main()
IIRC the reason was code inside a function can be optimized.
A:
Using list comprehensions with psyco is counter productive.
This code:
count = 0
for l in sys.stdin:
count += not int(l)%k
runs twice as fast as
count = sum(not int(l)%k for l in sys.stdin)
when using psyco.
A:
For other readers, here is the INTEST problem statement. It's intended to be an I/O throughput test.
On my system, I was able to shave 15% off the execution time by replacing the loop with the following:
print sum(1 for line in sys.stdin if int(line) % k == 0)
| How to get REALLY fast Python over a simple loop | I'm working on a SPOJ problem, INTEST. The goal is to specify the number of test cases (n) and a divisor (k), then feed your program n numbers. The program will accept each number on a newline of stdin and after receiving the nth number, will tell you how many were divisible by k.
The only challenge in this problem is getting your code to be FAST because k can be anything up to 10^7 and n can be as high as 10^9.
I'm trying to write it in Python and have trouble speeding it up. Any ideas?
Edit 2: I finally got it to pass at 10.54 seconds. I used nearly all of your answers to get there, and thus it was hard to choose one as 'correct', but I believe the one I chose sums it up the best. Thanks to you all. Final passing code is below.
Edit: I included some of the suggested updates in the included code.
Extensions and third-party modules are not allowed. The code is also run by the SPOJ judge machine, so I do not have the option of changing interpreters.
import sys
import psyco
psyco.full()
def main():
from sys import stdin, stdout
first_in = stdin.readline()
thing = first_in.split()
n = int(thing[0])
k = int(thing[1])
total = 0
list = stdin.readlines()
for item in list:
if int(item) % k == 0:
total += 1
stdout.write(str(total) + "\n")
if __name__ == "__main__":
main()
| [
"[Edited to reflect new findings and passing code on spoj]\nGenerally, when using Python for spoj:\n\nDon't use \"raw_input\", use sys.stdin.readlines(). That can make a difference for large input. Also, if possible (and it is, for this problem), read everything at once (sys.stdin. readlines()), instead of reading line by line (\"for line in sys.stdin...\").\nSimilarly, don't use \"print\", use sys.stdout.write() - and don't forget \"\\n\". Of course, this is only relevant when printing multiple times.\nAs S.Mark suggested, use psyco. It's available for both python2.5 and python2.6, at spoj (test it, it's there, and easy to spot: solutions using psyco usually have a ~35Mb memory usage offset). It's really simple: just add, after \"import sys\": import psyco; psyco.full()\nAs Justin suggested, put your code (except psyco incantation) inside a function, and simply call it at the end of your code\nSometimes creating a list and checking its length can be faster than creating a list and adding its components.\nFavour list comprehensions (and generator expressions, when possible) over \"for\" and \"while\" as well. For some constructs, map/reduce/filter may also speed up your code.\n\nUsing (some of) these guidelines, I've managed to pass INTEST. Still testing alternatives, though.\n",
"Hey, I got it to be within the time limit. I used the following:\n\nPsyco with Python 2.5. \na simple loop with a variable to keep count in\nmy code was all in a main() function (except the psyco import) which I called.\n\nThe last one is what made the difference. I believe that it has to do with variable visibility, but I'm not completely sure. My time was 10.81 seconds. You might get it to be faster with a list comprehension.\nEdit:\nUsing a list comprehension brought my time down to 8.23 seconds. Bringing the line from sys import stdin, stdout inside of the function shaved off a little too to bring my time down to 8.12 seconds.\n",
"Use psyco, it will JIT your code, very effective when there is big loop and calculations.\nEdit: Looks like third party modules are not allowed,\nSo, you may try converting your loop to list comprehensions, it supposed to be run at C level, so it should be faster a little bit.\nsum(1 if int(line) % k == 0 else 0 for line in sys.stdin)\n\n",
"Just recently Alex Martinelli said that invoking code inside a function, outperforms code run in the module ( I can't find the post though ) \nSo, why don't you try: \nimport sys\nimport psyco\n\npsyco.full1()\n\ndef main():\n\n first_in = raw_input()\n thing = first_in.split()\n n = int(thing[0])\n k = int(thing[1])\n total = 0\n i = 0\n\n total = sum(1 if int(line) % k == 0 else 0 for line in sys.stdin)\n\n print total\nif __name__ == \"__main__\":\n main()\n\nIIRC the reason was code inside a function can be optimized. \n",
"Using list comprehensions with psyco is counter productive.\nThis code:\n count = 0\n for l in sys.stdin:\n count += not int(l)%k\n\nruns twice as fast as\ncount = sum(not int(l)%k for l in sys.stdin)\n\nwhen using psyco.\n",
"For other readers, here is the INTEST problem statement. It's intended to be an I/O throughput test.\nOn my system, I was able to shave 15% off the execution time by replacing the loop with the following:\nprint sum(1 for line in sys.stdin if int(line) % k == 0)\n\n"
] | [
13,
8,
6,
3,
3,
2
] | [] | [] | [
"optimization",
"performance",
"python"
] | stackoverflow_0002650544_optimization_performance_python.txt |
Q:
Python 2.6.5 supports Unicode? How come listdir() doesn't but Python 3.1.2 does show Unicode?
Python 2.6.5 is said to support Unicode? How come listdir() doesn't in IDLE, but Python 3.1.2 does show Unicode in IDLE? (this is tested on Windows 7)
The following code is the same behavior:
for dirname, dirnames, filenames in os.walk('c:\path\somewhere'):
for subdirname in dirnames:
print (os.path.join(dirname, subdirname))
for filename in filenames:
print (os.path.join(dirname, filename))
Update: the unicode is in the filenames, not in the path...
A:
The syntax for Unicode strings changed from 2 to 3. Try specifying a Unicode string like this:
u'c:\\path\\somewhere'
If you want the syntax of Python 3 (string literals are by default Unicode unless the b prefix is given), use
from __future__ import unicode_literals
at the top of your file.
A:
Python 3 makes all strings Unicode by default that's probably why it works with Python 3 out of the box.
The documentation for listdir states
Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects.
So I guess you have to give your path as a Unicode string explicitly in Python 2 to get the result as Unicode.
A:
Python 2.x supports unicode but unicode isn't the default (as it is for 3.x).
In Python 2.x, Strings are 8bit byte arrays by default, so you'll see the UTF-8 encoded filenames when you work with the filesystem.
In Python 3.x all strings are in fact unicode by default, so the UTF-8 decoding happens in the IO subroutines.
| Python 2.6.5 supports Unicode? How come listdir() doesn't but Python 3.1.2 does show Unicode? | Python 2.6.5 is said to support Unicode? How come listdir() doesn't in IDLE, but Python 3.1.2 does show Unicode in IDLE? (this is tested on Windows 7)
The following code is the same behavior:
for dirname, dirnames, filenames in os.walk('c:\path\somewhere'):
for subdirname in dirnames:
print (os.path.join(dirname, subdirname))
for filename in filenames:
print (os.path.join(dirname, filename))
Update: the unicode is in the filenames, not in the path...
| [
"The syntax for Unicode strings changed from 2 to 3. Try specifying a Unicode string like this:\nu'c:\\\\path\\\\somewhere'\n\nIf you want the syntax of Python 3 (string literals are by default Unicode unless the b prefix is given), use\nfrom __future__ import unicode_literals\n\nat the top of your file.\n",
"Python 3 makes all strings Unicode by default that's probably why it works with Python 3 out of the box.\nThe documentation for listdir states\n\nChanged in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects.\n\nSo I guess you have to give your path as a Unicode string explicitly in Python 2 to get the result as Unicode.\n",
"Python 2.x supports unicode but unicode isn't the default (as it is for 3.x).\nIn Python 2.x, Strings are 8bit byte arrays by default, so you'll see the UTF-8 encoded filenames when you work with the filesystem.\nIn Python 3.x all strings are in fact unicode by default, so the UTF-8 decoding happens in the IO subroutines.\n"
] | [
5,
2,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0003132061_python_unicode.txt |
Q:
Timing function in python not giving accurate result
i have developed a scheme for signcryption, i want to test the time taken for modular exponentiation. i am using the below code for signcryption part
start = time.clock()
gamma = pow(g , x, p)
print ('The value of gamma is : '),gamma
Time_signcrypt = time.clock() - start
and for unsigncryption part i am calculating the time taken with this line of code
start = time.clock()
seed = (XA + x - XA)
gamma_new = pow(g , seed, p)
Time_new_gamma = time.clock() - start
The problem is using the same values, the results i get from both the timing function is different.
Signcryption values:
0.035299674
0.025940017
Unsigncryption values:
0.019342944
0.01727206
The values should be same as the same function is applied at both ends with same parameters. Another important things is that in unsigncryption part , one step is additional but still the time taken is less than the signcryption part. I cant get it what is wrong i have tested almost 35 times and the results vary most of the times :(
Please advice where am i going wrong ?
A:
To time methods, run them many times until the cumulated time is at least 10 seconds, then divide the time by the number of runs.
Otherwise, the timing will be very inaccurate because of various reasons:
Other processes which get the CPU
Interrupts running in the background
Thermal effects
Cosmic radiation
You get the idea.. ;-)
A:
There's a timeit module for doing exactly this kind of thing. It runs your code multiple times (1 million by default) and reports the stats for that run. Much more accurate than trying to time a single run, where your code can be subject to all sorts of issues.
A:
Because CPU's are constantly scheduling between different processes, the same piece of code will take a different time, every time it's executed.
The first function will be in general slower, because of the print statement, which takes "quite some" time.
| Timing function in python not giving accurate result | i have developed a scheme for signcryption, i want to test the time taken for modular exponentiation. i am using the below code for signcryption part
start = time.clock()
gamma = pow(g , x, p)
print ('The value of gamma is : '),gamma
Time_signcrypt = time.clock() - start
and for unsigncryption part i am calculating the time taken with this line of code
start = time.clock()
seed = (XA + x - XA)
gamma_new = pow(g , seed, p)
Time_new_gamma = time.clock() - start
The problem is using the same values, the results i get from both the timing function is different.
Signcryption values:
0.035299674
0.025940017
Unsigncryption values:
0.019342944
0.01727206
The values should be same as the same function is applied at both ends with same parameters. Another important things is that in unsigncryption part , one step is additional but still the time taken is less than the signcryption part. I cant get it what is wrong i have tested almost 35 times and the results vary most of the times :(
Please advice where am i going wrong ?
| [
"To time methods, run them many times until the cumulated time is at least 10 seconds, then divide the time by the number of runs.\nOtherwise, the timing will be very inaccurate because of various reasons:\n\nOther processes which get the CPU\nInterrupts running in the background\nThermal effects\nCosmic radiation\nYou get the idea.. ;-)\n\n",
"There's a timeit module for doing exactly this kind of thing. It runs your code multiple times (1 million by default) and reports the stats for that run. Much more accurate than trying to time a single run, where your code can be subject to all sorts of issues.\n",
"Because CPU's are constantly scheduling between different processes, the same piece of code will take a different time, every time it's executed.\nThe first function will be in general slower, because of the print statement, which takes \"quite some\" time.\n"
] | [
4,
3,
2
] | [] | [] | [
"python",
"timing"
] | stackoverflow_0003132137_python_timing.txt |
Q:
How to return a pointer to a structure in ctypes?
I try to pass a pointer of a structure which is given me as a return value from the function 'bar' to the function 'foo_write'. But I get the error message 'TypeError: must be a ctypes type' for line 'foo = POINTER(temp_foo)'. In the ctypes online help I found that 'ctypes.POINTER' only works with ctypes types. Do you know of another way? What would you recommend?
C:
typedef struct FOO_{
int i;
float *b1;
float (*w1)[];
}FOO;
foo *bar(int foo_parameter) {...
void foo_write(FOO *foo)
Python with ctypes:
class foo(Structure):
_fields_=[("i",c_int),
("b1",POINTER(c_int)),
("w1",POINTER(c_float))]
temp_foo=foo(0,None,None)
foo = POINTER(temp_foo)
foo=myclib.bar(foo_parameter)
myclib.foo_write(foo)
A:
Change
foo = POINTER(temp_foo)
to
foo = pointer(temp_foo)
can solve the problem.
Please see http://docs.python.org/library/ctypes.html#ctypes-pointers for more information.
A:
Your bar function has an incorrect definition, I guess you mean it is struct FOO_ *bar(int);?
The Python code is wrong in the sense that foo_parameter is never declared, so I'm not 100% sure what you want to do. I assume you want to pass a parameter of your python-declared foo, which is an instance of a struct FOO_, into the C bar(int) and get back a pointer to struct FOO_.
You don't need POINTER to do that, the following will work:
#!/usr/bin/env python
from ctypes import *
class foo(Structure):
_fields_=[("i",c_int),
("b1",POINTER(c_int)),
("w1",POINTER(c_float))]
myclib = cdll.LoadLibrary("./libexample.so")
temp_foo = foo(1,None,None)
foovar = myclib.bar(temp_foo.i)
myclib.foo_write(foovar)
Since CTypes will wrap the return type of bar() in a pointer-to-struct for you.
| How to return a pointer to a structure in ctypes? | I try to pass a pointer of a structure which is given me as a return value from the function 'bar' to the function 'foo_write'. But I get the error message 'TypeError: must be a ctypes type' for line 'foo = POINTER(temp_foo)'. In the ctypes online help I found that 'ctypes.POINTER' only works with ctypes types. Do you know of another way? What would you recommend?
C:
typedef struct FOO_{
int i;
float *b1;
float (*w1)[];
}FOO;
foo *bar(int foo_parameter) {...
void foo_write(FOO *foo)
Python with ctypes:
class foo(Structure):
_fields_=[("i",c_int),
("b1",POINTER(c_int)),
("w1",POINTER(c_float))]
temp_foo=foo(0,None,None)
foo = POINTER(temp_foo)
foo=myclib.bar(foo_parameter)
myclib.foo_write(foo)
| [
"Change\nfoo = POINTER(temp_foo)\n\nto\nfoo = pointer(temp_foo)\n\ncan solve the problem.\nPlease see http://docs.python.org/library/ctypes.html#ctypes-pointers for more information.\n",
"Your bar function has an incorrect definition, I guess you mean it is struct FOO_ *bar(int);?\nThe Python code is wrong in the sense that foo_parameter is never declared, so I'm not 100% sure what you want to do. I assume you want to pass a parameter of your python-declared foo, which is an instance of a struct FOO_, into the C bar(int) and get back a pointer to struct FOO_.\nYou don't need POINTER to do that, the following will work:\n#!/usr/bin/env python\nfrom ctypes import *\n\nclass foo(Structure):\n _fields_=[(\"i\",c_int),\n (\"b1\",POINTER(c_int)),\n (\"w1\",POINTER(c_float))]\n\nmyclib = cdll.LoadLibrary(\"./libexample.so\")\ntemp_foo = foo(1,None,None)\nfoovar = myclib.bar(temp_foo.i)\nmyclib.foo_write(foovar)\n\nSince CTypes will wrap the return type of bar() in a pointer-to-struct for you.\n"
] | [
9,
6
] | [] | [] | [
"c",
"ctypes",
"pointers",
"python",
"structure"
] | stackoverflow_0003131854_c_ctypes_pointers_python_structure.txt |
Q:
how to integrate spiders and scrapy-ctl.py
I am new to python and scrapy and hence am getting some basic doubts(please spare my ignorance about some fundamentals,which i m willing to learn :D).
Right now I am writing some spiders and implementing them using scrapy-ctl.py from the command line by typing:
C:\Python26\dmoz>python scrapy-ctl.py crawl spider
But I do not want two separate python codes and a command line to implement this.I want to somehow define a spider and make it crawl urls by writing and running a single python code.I could notice that in the file scrapy-ctl.py, 'execute' of type function is imported,but i am clueless as to how this function can be defined in the code containing spider.Could someone explain me how to do this, if it is possible because it greatly reduces the work.
Thanks in advance!!
A:
But I do not want two separate python codes and a command line to implement this. I want to somehow define a spider and make it crawl urls by writing and running a single python code.
I'm not sure the effort pays out, if you just want to scrape something. You have at least two options:
Dig into scrapy/cmdline.py. You'll see that this is a kind of dispatch script, finally handing over the work to the run method for the specified command, here crawl (in scrapy/commands/crawl.py). Look at line 54, I think scrapymanager.start() will begin your actual command, after some setup.
A little hacky method: use pythons subprocess module to have one your project and execution in one file (or project).
| how to integrate spiders and scrapy-ctl.py | I am new to python and scrapy and hence am getting some basic doubts(please spare my ignorance about some fundamentals,which i m willing to learn :D).
Right now I am writing some spiders and implementing them using scrapy-ctl.py from the command line by typing:
C:\Python26\dmoz>python scrapy-ctl.py crawl spider
But I do not want two separate python codes and a command line to implement this.I want to somehow define a spider and make it crawl urls by writing and running a single python code.I could notice that in the file scrapy-ctl.py, 'execute' of type function is imported,but i am clueless as to how this function can be defined in the code containing spider.Could someone explain me how to do this, if it is possible because it greatly reduces the work.
Thanks in advance!!
| [
"\nBut I do not want two separate python codes and a command line to implement this. I want to somehow define a spider and make it crawl urls by writing and running a single python code.\n\nI'm not sure the effort pays out, if you just want to scrape something. You have at least two options:\n\nDig into scrapy/cmdline.py. You'll see that this is a kind of dispatch script, finally handing over the work to the run method for the specified command, here crawl (in scrapy/commands/crawl.py). Look at line 54, I think scrapymanager.start() will begin your actual command, after some setup.\nA little hacky method: use pythons subprocess module to have one your project and execution in one file (or project).\n\n"
] | [
1
] | [] | [] | [
"python",
"scrapy",
"windows"
] | stackoverflow_0003132230_python_scrapy_windows.txt |
Q:
Maintaining relationships between objects in Python
Consider the following hypothetical people management system. Suppose each Person object belong to a number of Group objects and each Group contains a number of Person objects. We could represent it by adding a list to each Person and each Group object, but then we have to keep this in sync when we create, delete or modify an object. On change callbacks won't work well in this situation as they could lead to an infinite loop.
Now suppose each Group has a name and a description. The name is stored in a dict so that we can find which group uses which name and the description is indexed so that we can search it. These need to be updated whenever a group changes.
The application has a GUI which can display the Person and Group. Whenever a property of the object changes, the GUI needs to update.
Suppose we have to deal with a large number of effects like this. Keeping track of this is rather confusing. I could imagine these using properties, custom collections or maybe even metaclasses. Are there any design patterns/frameworks for dealing with these kind of systems?
A:
Most ORMs handles this. Just use an in-memory SQLite table, and let it do the hard work.
A:
This is quite tricky. Yes the Person and Group data could map to tables in a relational database, but the auto-updating views is more challenging.
Fortunately Qt (and therefore PyQT) has an MVC framework that automatically handles much of what you want. The data storage component can use database tables to store the Person and Group data. You can also create multiple views on the same underlying data model, and configure them to automatically update when the underlying data changes. This uses a Qt feature called Signals, the views subscribe to the model's signals to they get informed of the change.
The book Rapid GUI Programming with Python and QT has examples for very similar cases to this one, see chapters 14 and 15. There also may be other GUI frameworks that offer similar MVC functionality, with views that are automatically informed when the underlying data changes.
| Maintaining relationships between objects in Python | Consider the following hypothetical people management system. Suppose each Person object belong to a number of Group objects and each Group contains a number of Person objects. We could represent it by adding a list to each Person and each Group object, but then we have to keep this in sync when we create, delete or modify an object. On change callbacks won't work well in this situation as they could lead to an infinite loop.
Now suppose each Group has a name and a description. The name is stored in a dict so that we can find which group uses which name and the description is indexed so that we can search it. These need to be updated whenever a group changes.
The application has a GUI which can display the Person and Group. Whenever a property of the object changes, the GUI needs to update.
Suppose we have to deal with a large number of effects like this. Keeping track of this is rather confusing. I could imagine these using properties, custom collections or maybe even metaclasses. Are there any design patterns/frameworks for dealing with these kind of systems?
| [
"Most ORMs handles this. Just use an in-memory SQLite table, and let it do the hard work.\n",
"This is quite tricky. Yes the Person and Group data could map to tables in a relational database, but the auto-updating views is more challenging.\nFortunately Qt (and therefore PyQT) has an MVC framework that automatically handles much of what you want. The data storage component can use database tables to store the Person and Group data. You can also create multiple views on the same underlying data model, and configure them to automatically update when the underlying data changes. This uses a Qt feature called Signals, the views subscribe to the model's signals to they get informed of the change.\nThe book Rapid GUI Programming with Python and QT has examples for very similar cases to this one, see chapters 14 and 15. There also may be other GUI frameworks that offer similar MVC functionality, with views that are automatically informed when the underlying data changes.\n"
] | [
3,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003130172_oop_python.txt |
Q:
How to pass map into py?
I want to use c++ load py.
But one of parameters of a function is dict.
So, can I pass the map in C++ to dict in py?
A:
Your problem description is a little terse. If I understand correctly though, you'd like to embed a Python interpreter within a C++ application and, from C++, you want to be able to instruct the interpreter to load Python modules. If this is correct, then the answer is no. The Python C API expects a Python object whenever a dict is required. If you wish to use a C++ map, you'll have to use the Python C API and manually manage the coversion between the keys & values.
Depending on your needs, the Boost.Python library may be able to simplify some of the cross-language code for you.
| How to pass map into py? | I want to use c++ load py.
But one of parameters of a function is dict.
So, can I pass the map in C++ to dict in py?
| [
"Your problem description is a little terse. If I understand correctly though, you'd like to embed a Python interpreter within a C++ application and, from C++, you want to be able to instruct the interpreter to load Python modules. If this is correct, then the answer is no. The Python C API expects a Python object whenever a dict is required. If you wish to use a C++ map, you'll have to use the Python C API and manually manage the coversion between the keys & values.\nDepending on your needs, the Boost.Python library may be able to simplify some of the cross-language code for you.\n"
] | [
1
] | [] | [] | [
"c++",
"map",
"python"
] | stackoverflow_0003130927_c++_map_python.txt |
Q:
python compression function which returns 32 digit string?
I am using the md5 function to hash a string into a 32 digit string.
str_to_encode = 'this is a test string which I want to encode'
encoded = hashlib.md5(str_to_encode).hexdigest()
I want to be able to decode this string (i.e. encoded in the example above) back to its original value. I don't think this is possible using md5 (but if it is please let me know), but is there a compressionn function which I can use which will give me a 32 digit string at the end but which can be reverted?
EDIT:
The string being encoded is a url so will only be a couple of hundred characters max although in most cases it will be a lot less.
Thanks
A:
You seem to want two things that can't coexist:
Any string of any length is converted to exactly 32-bytes, even if it started as 4gb
The encoded string is decodable without loss of information
There's only so many bits in an MD5 hash, so by the pigeonhole principle it's impossible to reverse it. If it were reversible you could use a hash to compress information infinitely. Furthermore, irreversibility is the main point of a hash; they're intended to be one-way functions. Encryption algorithms are reversible, but require more bytes to store the ciphertext since decodability means they must be collision-free (two plaintexts can't encode to the same ciphertext, or the decode function wouldn't know which plaintext to output given that ciphertext)
A:
It seems to me that you aren't looking for a hash or encryption, you are looking for compression. Try zlib and base64 encoding:
s = 'Hello, world'
encoded = zlib.compress(s).encode('base64')
The length of the encoded data will grow as the input grows, but it may work for you.
Even restricting yourself to URLs, there's no way to reversibly map them to 32-character strings, there are just too many possible URLs.
| python compression function which returns 32 digit string? | I am using the md5 function to hash a string into a 32 digit string.
str_to_encode = 'this is a test string which I want to encode'
encoded = hashlib.md5(str_to_encode).hexdigest()
I want to be able to decode this string (i.e. encoded in the example above) back to its original value. I don't think this is possible using md5 (but if it is please let me know), but is there a compressionn function which I can use which will give me a 32 digit string at the end but which can be reverted?
EDIT:
The string being encoded is a url so will only be a couple of hundred characters max although in most cases it will be a lot less.
Thanks
| [
"You seem to want two things that can't coexist:\n\nAny string of any length is converted to exactly 32-bytes, even if it started as 4gb\nThe encoded string is decodable without loss of information\n\nThere's only so many bits in an MD5 hash, so by the pigeonhole principle it's impossible to reverse it. If it were reversible you could use a hash to compress information infinitely. Furthermore, irreversibility is the main point of a hash; they're intended to be one-way functions. Encryption algorithms are reversible, but require more bytes to store the ciphertext since decodability means they must be collision-free (two plaintexts can't encode to the same ciphertext, or the decode function wouldn't know which plaintext to output given that ciphertext)\n",
"It seems to me that you aren't looking for a hash or encryption, you are looking for compression. Try zlib and base64 encoding:\ns = 'Hello, world'\nencoded = zlib.compress(s).encode('base64')\n\nThe length of the encoded data will grow as the input grows, but it may work for you.\nEven restricting yourself to URLs, there's no way to reversibly map them to 32-character strings, there are just too many possible URLs.\n"
] | [
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0003133029_python.txt |
Q:
How to write data to an excel file?
I have some data that I'd like to save in an excel file. How does one do this in python?
A:
There's a great python module called XLWT. I'd recommend using that... it writes native Excel files instead of CSVs. Supports formulas, etc too.
Documentation (borrowed from Mark)
A:
I'll answer a slightly different question: "How can I write data so that Excel can read it?"
Use the csv module to write your data as a .csv file, and then open it in Excel.
import csv
csvout = csv.writer(open("mydata.csv", "wb"))
csvout.writerow(("Country", "Year"))
for coutry, year in my_data_iterable():
csvout.writerow((country, year))
A:
If you want a BIFF8 XLS file, I would use the excellent xlwt.
A:
if it's running on windows, try creating an instance of EXCEL.APPLICATION via COM
Use Excel Help for the object reference.
This way you can even format the data, write formulas, etc.
| How to write data to an excel file? | I have some data that I'd like to save in an excel file. How does one do this in python?
| [
"There's a great python module called XLWT. I'd recommend using that... it writes native Excel files instead of CSVs. Supports formulas, etc too.\nDocumentation (borrowed from Mark)\n",
"I'll answer a slightly different question: \"How can I write data so that Excel can read it?\"\nUse the csv module to write your data as a .csv file, and then open it in Excel.\nimport csv\ncsvout = csv.writer(open(\"mydata.csv\", \"wb\"))\ncsvout.writerow((\"Country\", \"Year\"))\nfor coutry, year in my_data_iterable():\n csvout.writerow((country, year))\n\n",
"If you want a BIFF8 XLS file, I would use the excellent xlwt.\n",
"if it's running on windows, try creating an instance of EXCEL.APPLICATION via COM\nUse Excel Help for the object reference.\nThis way you can even format the data, write formulas, etc.\n"
] | [
11,
5,
1,
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0003133142_excel_python.txt |
Q:
How does Python variable scoping works?
This wants me to dig deeper in Python sources, but since there are many people on SO that already done that, I would love to hear their pointers.
>>> import os
>>> def scope():
... print os
... import os
...
>>> scope()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in scope
UnboundLocalError: local variable 'os' referenced before assignment
It seems to me that when parser interprets the file, it automatically creates local scope for scope function, that makes os "detached" from global scope.
Is it true? Anyone care to point me where I can find more about scope implementation?
EDIT: Also, this is not special case of imports, this works for usual variables too.
A:
When you call scope() Python sees that you have a local variable called os used inside your method (from the import inside scope) so this masks the global os. However when you say print os you haven't reached the line and executed the local import yet so you see the error regarding reference before assignment. Here are a couple of other examples that might help:
>>> x = 3
>>> def printx():
... print x # will print the global x
...
>>> def printx2():
... print x # will try to print the local x
... x = 4
...
>>> printx()
3
>>> printx2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in printx2
UnboundLocalError: local variable 'x' referenced before assignment
And going back to your os example. Any assignment to os has the same effect:
>>> os
<module 'os' from 'C:\CDL_INSTALL\install\Python26\lib\os.pyc'>
>>> def bad_os():
... print os
... os = "assigning a string to local os"
...
>>> bad_os()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bad_os
UnboundLocalError: local variable 'os' referenced before assignment
Finally, compare these 2 examples:
>>> def example1():
... print never_used # will be interpreted as a global
...
>>> def example2():
... print used_later # will be interpreted as the local assigned later
... used_later = 42
...
>>> example1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example1
NameError: global name 'never_used' is not defined
>>> example2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example2
UnboundLocalError: local variable 'used_later' referenced before assignment
A:
Lexical scoping is a common thing and most well designed languages, whether interpreted or compiled use it.
I had not tried this in a while, but note the nifty "global" keyword, and its use below:
o = 1
def foo():
global o
o = 2
foo()
print o
Without the "global" line, the modification to o is localized, and "print o" prints 1. With the "global o" line included, it prints 2. We call this way that my function (without the global o) above would have its own variables. The global thing above is a way to specifically request an exception to the normal lexical scoping.
True lexical scoping is something that Python 1.0 lacked, and which Python has had for a long time (since at least 1.6, if I remember correctly). There were only two scopes, local and global, and any intermediate scopes were inaccessible.
A:
Any binding of a variable inside a function makes the variable local to that function. import, def and class are all equivalent to assignment in this respect.
So yes, when the compiler compiles your file it creates a local variable os which is scoped separately from the global os.
See the Python tutorial for more information. In particular http://docs.python.org/tutorial/classes.html section 9.2
| How does Python variable scoping works? | This wants me to dig deeper in Python sources, but since there are many people on SO that already done that, I would love to hear their pointers.
>>> import os
>>> def scope():
... print os
... import os
...
>>> scope()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in scope
UnboundLocalError: local variable 'os' referenced before assignment
It seems to me that when parser interprets the file, it automatically creates local scope for scope function, that makes os "detached" from global scope.
Is it true? Anyone care to point me where I can find more about scope implementation?
EDIT: Also, this is not special case of imports, this works for usual variables too.
| [
"When you call scope() Python sees that you have a local variable called os used inside your method (from the import inside scope) so this masks the global os. However when you say print os you haven't reached the line and executed the local import yet so you see the error regarding reference before assignment. Here are a couple of other examples that might help:\n>>> x = 3\n>>> def printx():\n... print x # will print the global x\n...\n>>> def printx2():\n... print x # will try to print the local x\n... x = 4\n...\n>>> printx()\n3\n>>> printx2()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in printx2\nUnboundLocalError: local variable 'x' referenced before assignment\n\nAnd going back to your os example. Any assignment to os has the same effect:\n>>> os\n<module 'os' from 'C:\\CDL_INSTALL\\install\\Python26\\lib\\os.pyc'>\n>>> def bad_os():\n... print os\n... os = \"assigning a string to local os\"\n...\n>>> bad_os()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in bad_os\nUnboundLocalError: local variable 'os' referenced before assignment\n\nFinally, compare these 2 examples:\n>>> def example1():\n... print never_used # will be interpreted as a global\n...\n>>> def example2():\n... print used_later # will be interpreted as the local assigned later\n... used_later = 42\n...\n>>> example1()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in example1\nNameError: global name 'never_used' is not defined\n>>> example2()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in example2\nUnboundLocalError: local variable 'used_later' referenced before assignment\n\n",
"Lexical scoping is a common thing and most well designed languages, whether interpreted or compiled use it.\nI had not tried this in a while, but note the nifty \"global\" keyword, and its use below:\no = 1\ndef foo():\n global o\n o = 2\nfoo()\nprint o\n\nWithout the \"global\" line, the modification to o is localized, and \"print o\" prints 1. With the \"global o\" line included, it prints 2. We call this way that my function (without the global o) above would have its own variables. The global thing above is a way to specifically request an exception to the normal lexical scoping.\nTrue lexical scoping is something that Python 1.0 lacked, and which Python has had for a long time (since at least 1.6, if I remember correctly). There were only two scopes, local and global, and any intermediate scopes were inaccessible.\n",
"Any binding of a variable inside a function makes the variable local to that function. import, def and class are all equivalent to assignment in this respect.\nSo yes, when the compiler compiles your file it creates a local variable os which is scoped separately from the global os.\nSee the Python tutorial for more information. In particular http://docs.python.org/tutorial/classes.html section 9.2\n"
] | [
5,
1,
0
] | [] | [] | [
"grammar",
"parsing",
"python",
"scope"
] | stackoverflow_0003131192_grammar_parsing_python_scope.txt |
Q:
Problem with import custun storage. Django
Hi I'm siting with my custom storage system 1 day. And now when I'm trying import it it gives me this Error.
I put in file models.py
from FTPStorage import FTPStorage
import datetime
from django.db import models
fs=FTPStorage()
class Upload(models.Model):
"""Uploaded files."""
file = models.FileField(upload_to='uploads', store=fs)
timestamp = models.DateTimeField(default=datetime.datetime.now)
notes = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ['-timestamp',]
def __unicode__(self):
return u"%s" % (self.file)
@property
def size(self):
return filesizeformat(self.file.size)
here is my views.py:
from forms import UploadForm
from models import Upload
import ftplib
import os
import datetime
from django.forms import save_instance
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from FTPStorage import FTPStorage
from django.core.files.storage import Storage
def initial(request):
data = {
'form': UploadForm(),
}
return render_to_response('upload.html', data, RequestContext(request))
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload()
upload.timestamp = datetime.datetime.now()
save_instance(form, upload)
return HttpResponseRedirect(reverse('initial'))
and file custom storage system FTPStorage.py is in direectory app
I have this problem:
Request Method: GET
Request URL: http://localhost:2121/
Exception Type: ViewDoesNotExist
Exception Value:
Could not import app.views. Error was: cannot import name FTPStorage
Exception Location: C:\BitNami DjangoStack\apps\django\django\core\urlresolvers.py in _get_callback, line 134
Please help me. I confuse.
A:
It seems to me that you need to update the PYTHONPATH for your runtime. Based on your error page I think you're using mod_python so try this setting in apache:
PythonPath "sys.path+['/mydir']"
Where /mydir is the full path to wherever the FTPStorage module resides.
| Problem with import custun storage. Django | Hi I'm siting with my custom storage system 1 day. And now when I'm trying import it it gives me this Error.
I put in file models.py
from FTPStorage import FTPStorage
import datetime
from django.db import models
fs=FTPStorage()
class Upload(models.Model):
"""Uploaded files."""
file = models.FileField(upload_to='uploads', store=fs)
timestamp = models.DateTimeField(default=datetime.datetime.now)
notes = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ['-timestamp',]
def __unicode__(self):
return u"%s" % (self.file)
@property
def size(self):
return filesizeformat(self.file.size)
here is my views.py:
from forms import UploadForm
from models import Upload
import ftplib
import os
import datetime
from django.forms import save_instance
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from FTPStorage import FTPStorage
from django.core.files.storage import Storage
def initial(request):
data = {
'form': UploadForm(),
}
return render_to_response('upload.html', data, RequestContext(request))
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload()
upload.timestamp = datetime.datetime.now()
save_instance(form, upload)
return HttpResponseRedirect(reverse('initial'))
and file custom storage system FTPStorage.py is in direectory app
I have this problem:
Request Method: GET
Request URL: http://localhost:2121/
Exception Type: ViewDoesNotExist
Exception Value:
Could not import app.views. Error was: cannot import name FTPStorage
Exception Location: C:\BitNami DjangoStack\apps\django\django\core\urlresolvers.py in _get_callback, line 134
Please help me. I confuse.
| [
"It seems to me that you need to update the PYTHONPATH for your runtime. Based on your error page I think you're using mod_python so try this setting in apache:\nPythonPath \"sys.path+['/mydir']\" \n\nWhere /mydir is the full path to wherever the FTPStorage module resides.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"storage",
"system"
] | stackoverflow_0003132953_django_python_storage_system.txt |
Q:
Python: always use __new__ instead of __init__?
I understand how both __init__ and __new__ work.
I'm wondering if there is anything __init__ can do that __new__ cannot?
i.e. can use of __init__ be replaced by the following pattern:
class MySubclass(object):
def __new__(cls, *args, **kwargs):
self = super(MySubclass, cls).__new__(cls, *args, **kwargs)
// Do __init__ stuff here
return self
I'm asking as I'd like to make this aspect of Python OO fit better in my head.
A:
So, the class of a class is typically type, and when you call Class() the __call__() method on Class's class handles that. I believe type.__call__() is implemented more or less like this:
def __call__(cls, *args, **kwargs):
# should do the same thing as type.__call__
obj = cls.__new__(cls, *args, **kwargs)
if isinstance(obj, cls):
obj.__init__(*args, **kwargs)
return obj
The direct answer to your question is no, the things that __init__() can do (change / "initialize" a specified instance) is a subset of the things that __new__() can do (create or otherwise select whatever object it wants, do anything to that object it wants before the object is returned).
It's convenient to have both methods to use, however. The use of __init__() is simpler (it doesn't have to create anything, it doesn't have to return anything), and I believe it is best practice to always use __init__() unless you have a specific reason to use __new__().
A:
One possible answer from guido's post (thanks @fraca7):
For example, in the pickle module, __new__ is used to create instances when unserializing objects. In this case, instances are created, but the __init__ method is not invoked.
Any other similar answers?
I'm accepting this answer as a 'yes' to my own question:
I'm wondering if there is anything __init__ can do that __new__ cannot?
Yes, unlike __new__, actions that you put in the __init__ method will not be performed during the unpickling process. __new__ cannot make this distinction.
A:
Well, looking for __new__ vs __init__ on google showed me this.
Long story short, __new__ returns a new object instance, while __init__ returns nothing and just initializes class members.
EDIT: To actually answer your question, you should never need to override __new__ unless you are subclassing immutable types.
| Python: always use __new__ instead of __init__? | I understand how both __init__ and __new__ work.
I'm wondering if there is anything __init__ can do that __new__ cannot?
i.e. can use of __init__ be replaced by the following pattern:
class MySubclass(object):
def __new__(cls, *args, **kwargs):
self = super(MySubclass, cls).__new__(cls, *args, **kwargs)
// Do __init__ stuff here
return self
I'm asking as I'd like to make this aspect of Python OO fit better in my head.
| [
"So, the class of a class is typically type, and when you call Class() the __call__() method on Class's class handles that. I believe type.__call__() is implemented more or less like this:\ndef __call__(cls, *args, **kwargs):\n # should do the same thing as type.__call__\n obj = cls.__new__(cls, *args, **kwargs)\n if isinstance(obj, cls):\n obj.__init__(*args, **kwargs)\n return obj\n\nThe direct answer to your question is no, the things that __init__() can do (change / \"initialize\" a specified instance) is a subset of the things that __new__() can do (create or otherwise select whatever object it wants, do anything to that object it wants before the object is returned).\nIt's convenient to have both methods to use, however. The use of __init__() is simpler (it doesn't have to create anything, it doesn't have to return anything), and I believe it is best practice to always use __init__() unless you have a specific reason to use __new__().\n",
"One possible answer from guido's post (thanks @fraca7): \n\nFor example, in the pickle module, __new__ is used to create instances when unserializing objects. In this case, instances are created, but the __init__ method is not invoked.\n\nAny other similar answers?\n\nI'm accepting this answer as a 'yes' to my own question:\n\nI'm wondering if there is anything __init__ can do that __new__ cannot?\n\nYes, unlike __new__, actions that you put in the __init__ method will not be performed during the unpickling process. __new__ cannot make this distinction.\n",
"Well, looking for __new__ vs __init__ on google showed me this.\nLong story short, __new__ returns a new object instance, while __init__ returns nothing and just initializes class members.\nEDIT: To actually answer your question, you should never need to override __new__ unless you are subclassing immutable types.\n"
] | [
23,
4,
2
] | [] | [] | [
"new_style_class",
"python"
] | stackoverflow_0003131488_new_style_class_python.txt |
Q:
How to 'catch' c printf in python with ctypes?
I hope this is trivial and I just didn't find it in the tutorials. I am writing python code that 'supervises' c code, aka I run the c code with ctypes from python. Now I want to 'catch' the c 'printfs' to process the data that is output by the c code. Any idea how one would do this?
Thanks
A:
You could intercept stdout before being written to from your C code, then process the output value.
import sys
import StringIO
buffer = StringIO.StringIO()
# redirect stdout to a buffer
sys.stdout = buffer
# call the c code with ctypes
# process the buffer
# recover the old stdout
sys.stdout = sys.__stdout__
However, it would be easier and nicer to pass a buffer to the C code, and instead of printf-ing the output values you would write them in the provided buffer.
Or, better yet, you could pass byref a c_char_p, allocate memory for it inside the C code, update the buffer with the output value then use the buffer in Python. Don't forget to deallocate the memory (you should make a ctypes wrapper for the free function).
A:
Well printf simply writes its output to whatever the stdout file pointer refers to. Im not sure how you're executing the C program, but it should be possible to redirect the C program's stdout to something that you can read in Python.
| How to 'catch' c printf in python with ctypes? | I hope this is trivial and I just didn't find it in the tutorials. I am writing python code that 'supervises' c code, aka I run the c code with ctypes from python. Now I want to 'catch' the c 'printfs' to process the data that is output by the c code. Any idea how one would do this?
Thanks
| [
"You could intercept stdout before being written to from your C code, then process the output value.\nimport sys\nimport StringIO\n\nbuffer = StringIO.StringIO()\n\n# redirect stdout to a buffer\nsys.stdout = buffer\n\n# call the c code with ctypes\n# process the buffer\n\n# recover the old stdout\nsys.stdout = sys.__stdout__\n\nHowever, it would be easier and nicer to pass a buffer to the C code, and instead of printf-ing the output values you would write them in the provided buffer.\nOr, better yet, you could pass byref a c_char_p, allocate memory for it inside the C code, update the buffer with the output value then use the buffer in Python. Don't forget to deallocate the memory (you should make a ctypes wrapper for the free function).\n",
"Well printf simply writes its output to whatever the stdout file pointer refers to. Im not sure how you're executing the C program, but it should be possible to redirect the C program's stdout to something that you can read in Python.\n"
] | [
2,
0
] | [] | [] | [
"c",
"ctypes",
"printf",
"python"
] | stackoverflow_0003131977_c_ctypes_printf_python.txt |
Q:
Convert Unix Timestamp to human format in Django with Python
I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks.
edit
I'm using the python function time.time() to generate the timestamp. According to the doc:
time.time()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that
even though the time is always
returned as a floating point number,
not all systems provide time with a
better precision than 1 second. While
this function normally returns
non-decreasing values, it can return a
lower value than a previous call if
the system clock has been set back
between the two calls.
A:
import datetime
datestring = "1277722499.82"
dt = datetime.datetime.fromtimestamp(float(datestring))
print(dt)
2010-06-28 11:54:59.820000
| Convert Unix Timestamp to human format in Django with Python | I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks.
edit
I'm using the python function time.time() to generate the timestamp. According to the doc:
time.time()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that
even though the time is always
returned as a floating point number,
not all systems provide time with a
better precision than 1 second. While
this function normally returns
non-decreasing values, it can return a
lower value than a previous call if
the system clock has been set back
between the two calls.
| [
"import datetime\ndatestring = \"1277722499.82\"\n\ndt = datetime.datetime.fromtimestamp(float(datestring))\nprint(dt)\n2010-06-28 11:54:59.820000\n \n\n"
] | [
19
] | [] | [] | [
"datetime",
"django",
"formatting",
"python",
"string"
] | stackoverflow_0003133486_datetime_django_formatting_python_string.txt |
Q:
Binding actions to a listbox in wxpython
Using wxwidgets with python, how do I bind an event to the listbox so that everytime a new list box entry is clicked, information about the list box entry is displayed in the textbox?
Here is my code:
import wx
from ConfigParser import *
class settings(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Frame aka window', size=(500,500))
panel=wx.Panel(self)
wx.StaticText(panel, -1, "Field Type:", pos=(200,20))
wx.TextCtrl(panel,-1,"",pos=(270,20))
for msg_num in self.ACTIVE_MESSAGES:
self.MESSAGE_FIELDS[msg_num] = configuration.get("MESSAGE_FIELDS", msg_num).replace(' ', '').split(',')
self.MESSAGE_FIELD_TYPES[msg_num] = configuration.get("MESSAGE_TYPES", msg_num).replace(' ', '').split(',')
cont=wx.ListBox(panel, -1, (20,20), (150,400), self.MESSAGE_FIELDS['1'], wx.LB_SINGLE)
cont.SetSelection(3)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=settings(parent=None, id=-1)
frame.Show()
app.MainLoop()
A:
This is the solution that I came up with:
import wx
from ConfigParser import *
class settings(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Frame aka window', size=(500,500))
panel=wx.Panel(self)
configuration = ConfigParser()
configuration.read('SerialReader.conf')
self.ACTIVE_MESSAGES = configuration.get("GENERAL_SETTINGS", "ACTIVE_MESSAGES").split(',')
self.fieldLabel = wx.StaticText(panel, -1, "Field Type:", pos=(200,20))
self.text = wx.TextCtrl(panel,-1,"",pos=(270,20))
self.MESSAGE_FIELDS = {}
self.MESSAGE_FIELD_TYPES = {}
for msg_num in self.ACTIVE_MESSAGES:
self.MESSAGE_FIELDS[msg_num] = configuration.get("MESSAGE_FIELDS", msg_num).replace(' ', '').split(',')
self.MESSAGE_FIELD_TYPES[msg_num] = configuration.get("MESSAGE_TYPES", msg_num).replace(' ', '').split(',')
cont=wx.ListBox(panel, 26, (20,20), (150,400), self.MESSAGE_FIELDS['1'], wx.LB_SINGLE)
cont.SetSelection(3)
self.Bind(wx.EVT_LISTBOX, self.OnSelect, id = 26)
def OnSelect(self, event):
index = event.GetSelection()
self.text.SetValue(self.MESSAGE_FIELD_TYPES['1'][index])
if __name__=='__main__':
app=wx.PySimpleApp()
frame=settings(parent=None, id=-1)
frame.Show()
app.MainLoop()
| Binding actions to a listbox in wxpython | Using wxwidgets with python, how do I bind an event to the listbox so that everytime a new list box entry is clicked, information about the list box entry is displayed in the textbox?
Here is my code:
import wx
from ConfigParser import *
class settings(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Frame aka window', size=(500,500))
panel=wx.Panel(self)
wx.StaticText(panel, -1, "Field Type:", pos=(200,20))
wx.TextCtrl(panel,-1,"",pos=(270,20))
for msg_num in self.ACTIVE_MESSAGES:
self.MESSAGE_FIELDS[msg_num] = configuration.get("MESSAGE_FIELDS", msg_num).replace(' ', '').split(',')
self.MESSAGE_FIELD_TYPES[msg_num] = configuration.get("MESSAGE_TYPES", msg_num).replace(' ', '').split(',')
cont=wx.ListBox(panel, -1, (20,20), (150,400), self.MESSAGE_FIELDS['1'], wx.LB_SINGLE)
cont.SetSelection(3)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=settings(parent=None, id=-1)
frame.Show()
app.MainLoop()
| [
"This is the solution that I came up with:\nimport wx\nfrom ConfigParser import *\nclass settings(wx.Frame):\n\n def __init__(self,parent,id):\n wx.Frame.__init__(self,parent,id,'Frame aka window', size=(500,500))\n panel=wx.Panel(self)\n\n\n\n\n configuration = ConfigParser()\n configuration.read('SerialReader.conf')\n self.ACTIVE_MESSAGES = configuration.get(\"GENERAL_SETTINGS\", \"ACTIVE_MESSAGES\").split(',')\n\n\n self.fieldLabel = wx.StaticText(panel, -1, \"Field Type:\", pos=(200,20))\n self.text = wx.TextCtrl(panel,-1,\"\",pos=(270,20)) \n\n self.MESSAGE_FIELDS = {}\n self.MESSAGE_FIELD_TYPES = {}\n for msg_num in self.ACTIVE_MESSAGES:\n self.MESSAGE_FIELDS[msg_num] = configuration.get(\"MESSAGE_FIELDS\", msg_num).replace(' ', '').split(',')\n self.MESSAGE_FIELD_TYPES[msg_num] = configuration.get(\"MESSAGE_TYPES\", msg_num).replace(' ', '').split(',')\n\n cont=wx.ListBox(panel, 26, (20,20), (150,400), self.MESSAGE_FIELDS['1'], wx.LB_SINGLE)\n cont.SetSelection(3)\n\n self.Bind(wx.EVT_LISTBOX, self.OnSelect, id = 26)\n\n def OnSelect(self, event):\n index = event.GetSelection()\n self.text.SetValue(self.MESSAGE_FIELD_TYPES['1'][index])\n\n\n\n\nif __name__=='__main__':\n app=wx.PySimpleApp()\n frame=settings(parent=None, id=-1)\n frame.Show()\n app.MainLoop()\n\n"
] | [
1
] | [] | [] | [
"listbox",
"python",
"wxpython"
] | stackoverflow_0003133038_listbox_python_wxpython.txt |
Q:
Find "best" complete subgraphs
While optimizing performance of an app of mine, I ran across a huge performance bottleneck in few lines of (Python) code.
I have N tokens. each token has a value assigned to it. Some of the tokens contradict (e.g. tokens 8 and 12 cannot "live together"). My job is to find the k-best token-groups. The value of a group of tokens is simply the sum of the values of the tokens in it.
Naïve algorithm (which I have implemented...):
find all 2^N token-group permutations of the tokens
Eliminate the token-groups that have contradictions in them
Calculate the value of all remaining token-groups
Sort token-groups by value
Choose top K token-groups
Real world numbers - I need top 10 token groups from a group of 20 tokens (for which I calculated the 1,000,000 permutations (!)), narrowed down to 3500 non-contradicting token groups. This took 5 seconds on my laptop...
I'm sure I can optimize steps 1+2 somehow by generating just the non-contradicting token-groups.
I'm also pretty sure I can somehow magically find the best token-group in a single search and find a way to traverse the token-groups by diminishing value, thus finding just the 10-best I am looking for....
my actual code:
all_possibilities = sum((list(itertools.combinations(token_list, i)) for i in xrange(len(token_list)+1)), [])
all_possibilities = [list(option) for option in all_possibilities if self._no_contradiction(option)]
all_possibilities = [(option, self._probability(option)) for option in all_possibilities]
all_possibilities.sort(key = lambda result: -result[1]) # sort by descending probability
Please help?
Tal.
A:
A simple approach at steps 1+2 could look like this: first, define a list of tokens and a dictionary of contradictions (each key is a token and each value is a set of tokens). Then, for each token take two actions:
add it to the result if it is not already contradicting, and increase the conflicting set with tokens that contradict the currently added token
don't add it to the result (choose to ignore it) and move to the next token.
So here's a sample code:
token_list = ['a', 'b', 'c']
contradictions = {
'a': set(['b']),
'b': set(['a']),
'c': set()
}
class Generator(object):
def __init__(self, token_list, contradictions):
self.list = token_list
self.contradictions = contradictions
self.max_start = len(self.list) - 1
def add_no(self, start, result, conflicting):
if start < self.max_start:
for g in self.gen(start + 1, result, conflicting):
yield g
else:
yield result[:]
def add_yes(self, token, start, result, conflicting):
result.append(token)
new_conflicting = conflicting | self.contradictions[token]
for g in self.add_no(start, result, new_conflicting):
yield g
result.pop()
def gen(self, start, result, conflicting):
token = self.list[start]
if token not in conflicting:
for g in self.add_yes(token, start, result, conflicting):
yield g
for g in self.add_no(start, result, conflicting):
yield g
def go(self):
return self.gen(0, [], set())
Sample usage:
g = Generator(token_list, contradictions)
for x in g.go():
print x
This is a recursive algorithm, so it won't work for more than a few thousand tokens (because of Python's stack limit), but you could easily create a non-recursive one.
A:
An O(n (log n)) or O(n + m) solution for n tokens and string-length m
What differentiates your problem from the NP-complete clique problem is the fact that your "conflict" graph has structure - namely that it can be projected onto 1 dimension (it can be sorted).
That means you can divide and conquer; after all, non-overlapping ranges have no effect on each other, so there is no need to explore the complete state-space. In particular, a dynamic programming solution will work.
The outline of an algorithm
Assume a token's position is represented as [start, end) (i.e. inclusive start, exclusive end). Sort the token-list by token end, we'll be iterating over them.
You will be extending subsets of these tokens. These sets of tokens will have an end (no token can be added to the subset if it starts before the subset's end), and a cumulative value. The end of a subset of tokens is the maximum of the ends of all tokens in the subset.
You're going to maintain a mapping (e.g. via a hashtable or array) from the index into the sorted array of tokens up to which everything's been processed to the resultant best-yet subset of non-conflicting tokens. That means that the best-yet subset stored in the mapping for index J must can only include tokens of index less than or equal to J
At each step, you'll be computing the best subset for some position J, and then one of three things can occur: you may have already cached this computation in the mapping (easy), or the best subset includes the item J, or the best subset exludes item J. If you haven't cached it, you can only find out it the best subset includes or excludes J by trying both options.
Now, the trick is in the cache - you need to try both options, and that looks like a recursive (exponential) search, but it needn't be.
If the best subset for index J includes token[J] then it can't include any tokens that overlap that token - and in particular, since we sorted by token.end, there is a last token K in that list such that K < J and token[K].end <= token[J].start: and for that token K we can compute the best subset too (or maybe we already have it cached).
On the other hand, it may exclude token[J], but then the best subset is simply token[J-1].
In either case, a special case token[-1] with token[-1].end = 0 and subset value 0 can form the base case.
Since you only need to do this computation once for each token index, this part is actually linear in the number of tokens. However, sorting the tokens naively (which I'd recommend) is O(n log(n)) and finding a last token index given an string position is O(log(n)) - repeated n times; so the overall running time is O(n log(n)). You can reduce this to O(n) by observing that you don't need to sort an arbitrary list - the maximal string position is limited and small so you can do the sorting by indexing in the string, but it's almost certainly not worth it. Similarly, although finding one token by binary search is log n you can do this by aligning two lists instead - one sorted on token end, the other on token start - thus permitting an O(n + m) implementation. Unless n can really get huge, it's not worth it.
If you iterate from the front of the string to the end, since all lookups look "back", you can remove the recursion entirely and simply directly lookup the result for a given index since it must have been calculated already anyhow.
Does this rather vague explanation help? It's a basic application of dynamic programming, which is just a fancy word for caching; so if you're confused, that's what you should read up on.
Extending this to the top k-best solutions
If you want to find the top-K best solutions, you'll need a messy but doable extension that maps index-of token not to the single best subset, but to the best-K subsets so far - obviously at increased computational cost and a bit of extra code. Essentially, rather than picking to either include or not include token[J], you'll take the set union and trim down to the k-best options at each token-index. That's O(n log(n) + n k log(k)) if implemented straightforwardly.
A:
Here's a possible "heuristically optimized" approach and a small sample:
import itertools
# tokens in decreasing order of value (must all be > 0)
toks = 12, 11, 8, 7, 6, 2, 1
# contradictions (dict highestvaltok -> set of incompatible ones)
cont = {12: set([11, 8, 7, 2]),
11: set([8, 7, 6]),
7: set([2]),
2: set([1]),
}
rec_calls = 0
def bestgroup(toks, contdict, arein=(), contset=()):
"""Recursively compute the highest-valued non-contradictory subset of toks."""
global rec_calls
toks = list(toks)
while toks:
# find the top token compatible w/the ones in `arein`
toptok = toks.pop(0)
if toptok in contset:
continue
# try to extend with and without this toptok
without_top = bestgroup(toks, contdict, arein, contset)
contset = set(contset).union(c for c in contdict.get(toptok, ()))
newarein = arein + (toptok,)
with_top = bestgroup(toks, contdict, newarein, contset)
rec_calls += 1
if sum(with_top) > sum(without_top):
return with_top
else:
return without_top
return arein
def noncongroups(toks, contdict):
"""Count possible, non-contradictory subsets of toks."""
tot = 0
for l in range(1, len(toks) + 1):
for c in itertools.combinations(toks, l):
if any(cont[k].intersection(c) for k in c if k in contdict): continue
tot += 1
return tot
print bestgroup(toks, cont)
print 'calls: %d (vs %d of %d)' % (rec_calls, noncongroups(toks, cont), 2**len(toks))
I believe this always makes as many recursive calls as feasible (non-contradictory) subsets exist, but haven't proven it (so I'm just counting both -- the noncongroups of course has nothing to do with the solution, it's there just to check that behavioral property;-).
If this produces an acceptable speedup on your "actual use cases" benchmarks, then further optimization may introduce alpha-pruning (so you can stop recursion along paths that you know to be unproductive -- that's the motivation for the descending order in the tokens;-) and recursion elimination (using an explicit stack within the function instead). But I wanted to keep this first version simple, so it can easily be understood and verified (also, the further optimizations I have in mind are only going to help marginally, I suspect -- say, at best, halving the typical runtime, if even that much).
A:
A really simple way to get all the non-contradicting token-groups:
#!/usr/bin/env python
token_list = ['a', 'b', 'c']
contradictions = {
'a': set(['b']),
'b': set(['a']),
'c': set()
}
result = []
while token_list:
token = token_list.pop()
new = [set([token])]
for r in result:
if token not in contradictions or not r & contradictions[token]:
new.append(r | set([token]))
result.extend(new)
print result
A:
The following solution generates all maximal non-contradicting subsets, taking advantage of the fact that there's no point omitting an element from the solution unless it contradicts another element in the solution.
The simple optimization to avoid the second recursion in the case that the element t doesn't contradict any of the remaining elements should help make this solution efficient if the number of contradictions is small.
def solve(tokens, contradictions):
if not tokens:
yield set()
else:
tokens = set(tokens)
t = tokens.pop()
for solution in solve(tokens - contradictions[t], contradictions):
yield solution | set([t])
if contradictions[t] & tokens:
for solution in solve(tokens, contradictions):
if contradictions[t] & solution:
yield solution
This solution also demonstrates that dynamic programming (aka memoization) may be helpful to improve the performance of the solution further for some types of inputs.
| Find "best" complete subgraphs | While optimizing performance of an app of mine, I ran across a huge performance bottleneck in few lines of (Python) code.
I have N tokens. each token has a value assigned to it. Some of the tokens contradict (e.g. tokens 8 and 12 cannot "live together"). My job is to find the k-best token-groups. The value of a group of tokens is simply the sum of the values of the tokens in it.
Naïve algorithm (which I have implemented...):
find all 2^N token-group permutations of the tokens
Eliminate the token-groups that have contradictions in them
Calculate the value of all remaining token-groups
Sort token-groups by value
Choose top K token-groups
Real world numbers - I need top 10 token groups from a group of 20 tokens (for which I calculated the 1,000,000 permutations (!)), narrowed down to 3500 non-contradicting token groups. This took 5 seconds on my laptop...
I'm sure I can optimize steps 1+2 somehow by generating just the non-contradicting token-groups.
I'm also pretty sure I can somehow magically find the best token-group in a single search and find a way to traverse the token-groups by diminishing value, thus finding just the 10-best I am looking for....
my actual code:
all_possibilities = sum((list(itertools.combinations(token_list, i)) for i in xrange(len(token_list)+1)), [])
all_possibilities = [list(option) for option in all_possibilities if self._no_contradiction(option)]
all_possibilities = [(option, self._probability(option)) for option in all_possibilities]
all_possibilities.sort(key = lambda result: -result[1]) # sort by descending probability
Please help?
Tal.
| [
"A simple approach at steps 1+2 could look like this: first, define a list of tokens and a dictionary of contradictions (each key is a token and each value is a set of tokens). Then, for each token take two actions:\n\nadd it to the result if it is not already contradicting, and increase the conflicting set with tokens that contradict the currently added token\ndon't add it to the result (choose to ignore it) and move to the next token.\n\nSo here's a sample code:\ntoken_list = ['a', 'b', 'c']\n\ncontradictions = {\n 'a': set(['b']),\n 'b': set(['a']),\n 'c': set()\n}\n\nclass Generator(object):\n def __init__(self, token_list, contradictions):\n self.list = token_list\n self.contradictions = contradictions\n self.max_start = len(self.list) - 1\n\n def add_no(self, start, result, conflicting):\n if start < self.max_start:\n for g in self.gen(start + 1, result, conflicting):\n yield g\n else:\n yield result[:]\n\n def add_yes(self, token, start, result, conflicting):\n result.append(token)\n new_conflicting = conflicting | self.contradictions[token]\n for g in self.add_no(start, result, new_conflicting):\n yield g\n result.pop()\n\n def gen(self, start, result, conflicting):\n token = self.list[start]\n if token not in conflicting:\n for g in self.add_yes(token, start, result, conflicting):\n yield g\n for g in self.add_no(start, result, conflicting):\n yield g\n\n def go(self):\n return self.gen(0, [], set())\n\nSample usage:\ng = Generator(token_list, contradictions)\nfor x in g.go():\n print x\n\nThis is a recursive algorithm, so it won't work for more than a few thousand tokens (because of Python's stack limit), but you could easily create a non-recursive one.\n",
"An O(n (log n)) or O(n + m) solution for n tokens and string-length m\nWhat differentiates your problem from the NP-complete clique problem is the fact that your \"conflict\" graph has structure - namely that it can be projected onto 1 dimension (it can be sorted).\nThat means you can divide and conquer; after all, non-overlapping ranges have no effect on each other, so there is no need to explore the complete state-space. In particular, a dynamic programming solution will work.\nThe outline of an algorithm\n\nAssume a token's position is represented as [start, end) (i.e. inclusive start, exclusive end). Sort the token-list by token end, we'll be iterating over them.\nYou will be extending subsets of these tokens. These sets of tokens will have an end (no token can be added to the subset if it starts before the subset's end), and a cumulative value. The end of a subset of tokens is the maximum of the ends of all tokens in the subset.\nYou're going to maintain a mapping (e.g. via a hashtable or array) from the index into the sorted array of tokens up to which everything's been processed to the resultant best-yet subset of non-conflicting tokens. That means that the best-yet subset stored in the mapping for index J must can only include tokens of index less than or equal to J\nAt each step, you'll be computing the best subset for some position J, and then one of three things can occur: you may have already cached this computation in the mapping (easy), or the best subset includes the item J, or the best subset exludes item J. If you haven't cached it, you can only find out it the best subset includes or excludes J by trying both options.\n\nNow, the trick is in the cache - you need to try both options, and that looks like a recursive (exponential) search, but it needn't be. \n\nIf the best subset for index J includes token[J] then it can't include any tokens that overlap that token - and in particular, since we sorted by token.end, there is a last token K in that list such that K < J and token[K].end <= token[J].start: and for that token K we can compute the best subset too (or maybe we already have it cached). \nOn the other hand, it may exclude token[J], but then the best subset is simply token[J-1].\nIn either case, a special case token[-1] with token[-1].end = 0 and subset value 0 can form the base case.\n\nSince you only need to do this computation once for each token index, this part is actually linear in the number of tokens. However, sorting the tokens naively (which I'd recommend) is O(n log(n)) and finding a last token index given an string position is O(log(n)) - repeated n times; so the overall running time is O(n log(n)). You can reduce this to O(n) by observing that you don't need to sort an arbitrary list - the maximal string position is limited and small so you can do the sorting by indexing in the string, but it's almost certainly not worth it. Similarly, although finding one token by binary search is log n you can do this by aligning two lists instead - one sorted on token end, the other on token start - thus permitting an O(n + m) implementation. Unless n can really get huge, it's not worth it.\nIf you iterate from the front of the string to the end, since all lookups look \"back\", you can remove the recursion entirely and simply directly lookup the result for a given index since it must have been calculated already anyhow.\nDoes this rather vague explanation help? It's a basic application of dynamic programming, which is just a fancy word for caching; so if you're confused, that's what you should read up on.\nExtending this to the top k-best solutions\nIf you want to find the top-K best solutions, you'll need a messy but doable extension that maps index-of token not to the single best subset, but to the best-K subsets so far - obviously at increased computational cost and a bit of extra code. Essentially, rather than picking to either include or not include token[J], you'll take the set union and trim down to the k-best options at each token-index. That's O(n log(n) + n k log(k)) if implemented straightforwardly.\n",
"Here's a possible \"heuristically optimized\" approach and a small sample:\nimport itertools\n\n# tokens in decreasing order of value (must all be > 0)\ntoks = 12, 11, 8, 7, 6, 2, 1\n\n# contradictions (dict highestvaltok -> set of incompatible ones)\ncont = {12: set([11, 8, 7, 2]),\n 11: set([8, 7, 6]),\n 7: set([2]),\n 2: set([1]),\n }\n\nrec_calls = 0\n\ndef bestgroup(toks, contdict, arein=(), contset=()):\n \"\"\"Recursively compute the highest-valued non-contradictory subset of toks.\"\"\"\n global rec_calls\n toks = list(toks)\n while toks:\n # find the top token compatible w/the ones in `arein`\n toptok = toks.pop(0)\n if toptok in contset:\n continue\n # try to extend with and without this toptok\n without_top = bestgroup(toks, contdict, arein, contset)\n contset = set(contset).union(c for c in contdict.get(toptok, ()))\n newarein = arein + (toptok,)\n with_top = bestgroup(toks, contdict, newarein, contset)\n rec_calls += 1\n if sum(with_top) > sum(without_top):\n return with_top\n else:\n return without_top\n return arein\n\ndef noncongroups(toks, contdict):\n \"\"\"Count possible, non-contradictory subsets of toks.\"\"\"\n tot = 0\n for l in range(1, len(toks) + 1):\n for c in itertools.combinations(toks, l):\n if any(cont[k].intersection(c) for k in c if k in contdict): continue\n tot += 1\n return tot\n\n\nprint bestgroup(toks, cont)\nprint 'calls: %d (vs %d of %d)' % (rec_calls, noncongroups(toks, cont), 2**len(toks))\n\nI believe this always makes as many recursive calls as feasible (non-contradictory) subsets exist, but haven't proven it (so I'm just counting both -- the noncongroups of course has nothing to do with the solution, it's there just to check that behavioral property;-).\nIf this produces an acceptable speedup on your \"actual use cases\" benchmarks, then further optimization may introduce alpha-pruning (so you can stop recursion along paths that you know to be unproductive -- that's the motivation for the descending order in the tokens;-) and recursion elimination (using an explicit stack within the function instead). But I wanted to keep this first version simple, so it can easily be understood and verified (also, the further optimizations I have in mind are only going to help marginally, I suspect -- say, at best, halving the typical runtime, if even that much).\n",
"A really simple way to get all the non-contradicting token-groups:\n#!/usr/bin/env python\n\ntoken_list = ['a', 'b', 'c']\n\ncontradictions = {\n 'a': set(['b']),\n 'b': set(['a']),\n 'c': set()\n}\n\nresult = []\n\nwhile token_list:\n token = token_list.pop()\n new = [set([token])]\n for r in result:\n if token not in contradictions or not r & contradictions[token]:\n new.append(r | set([token]))\n result.extend(new)\n\nprint result\n\n",
"The following solution generates all maximal non-contradicting subsets, taking advantage of the fact that there's no point omitting an element from the solution unless it contradicts another element in the solution.\nThe simple optimization to avoid the second recursion in the case that the element t doesn't contradict any of the remaining elements should help make this solution efficient if the number of contradictions is small.\ndef solve(tokens, contradictions):\n if not tokens:\n yield set()\n else:\n tokens = set(tokens)\n t = tokens.pop()\n for solution in solve(tokens - contradictions[t], contradictions):\n yield solution | set([t])\n if contradictions[t] & tokens:\n for solution in solve(tokens, contradictions):\n if contradictions[t] & solution:\n yield solution\n\nThis solution also demonstrates that dynamic programming (aka memoization) may be helpful to improve the performance of the solution further for some types of inputs.\n"
] | [
3,
3,
2,
2,
0
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0003132802_graph_python.txt |
Q:
How to iterate through a MySQL table with Python?
I have a Python script which uses the MySQLdb interface to load various CSV files into MySQL tables.
In my code, I use Python's standard CSV library to read the CSV, then I insert each field into the table one at a time, using an INSERT query. I do this rather than using LOAD DATA so that I can convert null values and other minor clean-ups on a per-field basis.
Example table format:
`id_number` | `iteration` | `date` | `value`
102 | 1 | 2010-01-01 | 63
102 | 2 | 2010-01-02 | NULL
102 | 3 | 2010-01-03 | 65
The null value in the second iteration of id_number = 102 represents a case where value hasn't changed from the previous day i.e. value remains 63.
Basically, I need to convert these null values to their correct values. I can imagine 4 ways of doing this:
Once everything is inserted into the table, run a MySQL query that does the iterating and replacing all by itself.
Once everything is inserted into the table, run a MySQL query to send some data back to Python, process in Python then run a MySQL query to update the correct values.
Do the processing in Python on a per-field basis before each insert.
Insert into a temporary table and use SQL to insert into the main table.
I could probably work out how to do #2, and maybe #3, but have no idea how to do #1 or #4, which I think are the best methods as it then requires no fundamental changes to the Python code.
My question is A) which of the above methods is "best" and "cleanest"? (Speed not really an issue.) and B) how would I achieve #1 or #4?
Thanks in advance :)
A:
I think you would have the most control and the least amount of work with your #3 option, Especially if you want to keep existing values over null values, I think you risk overwriting those with #1.
If speed is not an issue, for every record in your CSV, compare it to the existing record, and update or insert your record with your preferred values.
| How to iterate through a MySQL table with Python? | I have a Python script which uses the MySQLdb interface to load various CSV files into MySQL tables.
In my code, I use Python's standard CSV library to read the CSV, then I insert each field into the table one at a time, using an INSERT query. I do this rather than using LOAD DATA so that I can convert null values and other minor clean-ups on a per-field basis.
Example table format:
`id_number` | `iteration` | `date` | `value`
102 | 1 | 2010-01-01 | 63
102 | 2 | 2010-01-02 | NULL
102 | 3 | 2010-01-03 | 65
The null value in the second iteration of id_number = 102 represents a case where value hasn't changed from the previous day i.e. value remains 63.
Basically, I need to convert these null values to their correct values. I can imagine 4 ways of doing this:
Once everything is inserted into the table, run a MySQL query that does the iterating and replacing all by itself.
Once everything is inserted into the table, run a MySQL query to send some data back to Python, process in Python then run a MySQL query to update the correct values.
Do the processing in Python on a per-field basis before each insert.
Insert into a temporary table and use SQL to insert into the main table.
I could probably work out how to do #2, and maybe #3, but have no idea how to do #1 or #4, which I think are the best methods as it then requires no fundamental changes to the Python code.
My question is A) which of the above methods is "best" and "cleanest"? (Speed not really an issue.) and B) how would I achieve #1 or #4?
Thanks in advance :)
| [
"I think you would have the most control and the least amount of work with your #3 option, Especially if you want to keep existing values over null values, I think you risk overwriting those with #1.\nIf speed is not an issue, for every record in your CSV, compare it to the existing record, and update or insert your record with your preferred values.\n"
] | [
2
] | [] | [] | [
"csv",
"iterator",
"mysql",
"python"
] | stackoverflow_0003134245_csv_iterator_mysql_python.txt |
Q:
what happens when a sqlite3 db write is interupted?
Question: When does the actual writing to the sqlite3 db file take place and what happens if it is interrupted?
Info:
I have this program in python that I've been working on for a few weeks that uses sqlite3 to store large amounts of data from the simulation it is running. But there are two situations I'm worried about.
We've been having a lot of thunderstorms recently and this has knocked out power a few times, also I'm updating the file that writes to the db with some frequency, and to do so I have to kill the current running thread of the simulation. in both of these cases, especially the former, I worry about what happens when this thread gets interrupted. what if I happen to interrupt it or lose power while it is writing from the log file into the db? will the information just not get there? will it get there but corrupt? will it corrupt the whole sqlite3 db file?
Basically I want to know when does the data actually get writen to the file and not just the log file. and if this writing process does not finish for any reason, what happens to the log and the db file?
~n
A:
SQLite uses atomic commits, so either everything or nothing is committed.
If you're concerned about the database being left in an invalid state, you need to make sure you wrap the entire "transitional" state in a BEGIN TRANSACTION ... COMMIT block.
The fine details of writing to the journal files, etc. (including through failures) are in the document "File Locking and Concurrency in SQLite Version 3".
| what happens when a sqlite3 db write is interupted? | Question: When does the actual writing to the sqlite3 db file take place and what happens if it is interrupted?
Info:
I have this program in python that I've been working on for a few weeks that uses sqlite3 to store large amounts of data from the simulation it is running. But there are two situations I'm worried about.
We've been having a lot of thunderstorms recently and this has knocked out power a few times, also I'm updating the file that writes to the db with some frequency, and to do so I have to kill the current running thread of the simulation. in both of these cases, especially the former, I worry about what happens when this thread gets interrupted. what if I happen to interrupt it or lose power while it is writing from the log file into the db? will the information just not get there? will it get there but corrupt? will it corrupt the whole sqlite3 db file?
Basically I want to know when does the data actually get writen to the file and not just the log file. and if this writing process does not finish for any reason, what happens to the log and the db file?
~n
| [
"SQLite uses atomic commits, so either everything or nothing is committed.\nIf you're concerned about the database being left in an invalid state, you need to make sure you wrap the entire \"transitional\" state in a BEGIN TRANSACTION ... COMMIT block.\nThe fine details of writing to the journal files, etc. (including through failures) are in the document \"File Locking and Concurrency in SQLite Version 3\".\n"
] | [
4
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003134279_python_sqlite.txt |
Q:
Python using derived class's method in parent class?
Can I force a parent class to call a derived class's version of a function?
class Base(object):
attr1 = ''
attr2 = ''
def virtual(self):
pass # doesn't do anything in the parent class
def func(self):
print "%s, %s" % (self.attr1, self.attr2)
self.virtual()
and a class that derives from it
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def virtual(self):
# do stuff...
# do stuff...
Clearing up vagueness:
d = Derived()
d.func() # calls self.virtual() which is Base::virtual(),
# and I need it to be Derived::virtual()
A:
If you instantiate a Derived (say d = Derived()), the .virtual that's called by d.func() is Derived.virtual. If there is no instance of Derived involved, then there's no suitable self for Derived.virtual and so of course it's impossible to call it.
A:
It isn't impossible -- there is a way around this actually, and you don't have to pass in the function or anything like that. I am working on a project myself where this exact problem came up. Here is the solution:
class Base(): # no need to explicitly derive object for it to work
attr1 = 'I am in class Base'
attr2 = 'halb halb'
def virtual(self):
print "Base's Method"
def func(self):
print "%s, %s" % (self.attr1, self.attr2)
self.virtual()
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def __init__(self):
# only way I've found so far is to edit the dict like this
Base.__dict__['_Base_virtual'] = self.virtual
def virtual(self):
print "Derived's Method"
if __name__ == '__main__':
d = Derived()
d.func()
| Python using derived class's method in parent class? | Can I force a parent class to call a derived class's version of a function?
class Base(object):
attr1 = ''
attr2 = ''
def virtual(self):
pass # doesn't do anything in the parent class
def func(self):
print "%s, %s" % (self.attr1, self.attr2)
self.virtual()
and a class that derives from it
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def virtual(self):
# do stuff...
# do stuff...
Clearing up vagueness:
d = Derived()
d.func() # calls self.virtual() which is Base::virtual(),
# and I need it to be Derived::virtual()
| [
"If you instantiate a Derived (say d = Derived()), the .virtual that's called by d.func() is Derived.virtual. If there is no instance of Derived involved, then there's no suitable self for Derived.virtual and so of course it's impossible to call it.\n",
"It isn't impossible -- there is a way around this actually, and you don't have to pass in the function or anything like that. I am working on a project myself where this exact problem came up. Here is the solution:\n\nclass Base(): # no need to explicitly derive object for it to work\n attr1 = 'I am in class Base'\n attr2 = 'halb halb'\n\n def virtual(self):\n print \"Base's Method\"\n\n def func(self):\n print \"%s, %s\" % (self.attr1, self.attr2)\n self.virtual()\n\nclass Derived(Base):\n attr1 = 'I am in class Derived'\n attr2 = 'blah blah'\n\n def __init__(self):\n # only way I've found so far is to edit the dict like this\n Base.__dict__['_Base_virtual'] = self.virtual\n\n def virtual(self):\n print \"Derived's Method\"\n\nif __name__ == '__main__':\n d = Derived()\n d.func()\n\n\n"
] | [
9,
5
] | [] | [] | [
"inheritance",
"new_style_class",
"python"
] | stackoverflow_0002297843_inheritance_new_style_class_python.txt |
Q:
Python Google App Engine: Call specific method from yaml file?
I am new to database programming with Google App Engine and am programming in Python. I was wondering if I am allowed to have one Python file with several request handler classes, each of which has get and post methods. I know that the yaml file allows me to specify which scripts are run with specific urls, like the example below:
handlers:
- url: /.*
script: helloworld.py
How would I tell it to run a specific method that is in one of the classes in the .py file? Is that even possible/allowed? Do I need to separate the different request handler classes into different python files? My understanding of databases is rather shallow at the moment, so I could be making no sense.
Thanks.
A:
I was wondering if I am allowed to
have one Python file with several
request handler classes, each of which
has get and post methods.
Sure! That app.yaml just transfers control to helloworld.py, which will run the main function defined in that file -- and that function typically sets up a WSGI app which dispatches appropriately, depending on the URL, to the right handler class. For example, look at the sample code here, very early on in the tutorial:
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
I'm not copying the import statements and class definitions, because they don't matter: this is an example of how a single .py file dispatches to various handler classes (two in this case).
This doesn't mean the yaml file lets you call any method whatsoever, of course: rather, it hands control to a .py file, whose main is responsible for all that follows (and e.g. with the webapp mini-framework that comes with App Engine, it will always be get or post method [[or put, delete, ..., etc, if you also support those -- few do unless they're being especially RESTful;-)]] being called depending on the exact HTTP method and URL in the incoming request.
| Python Google App Engine: Call specific method from yaml file? | I am new to database programming with Google App Engine and am programming in Python. I was wondering if I am allowed to have one Python file with several request handler classes, each of which has get and post methods. I know that the yaml file allows me to specify which scripts are run with specific urls, like the example below:
handlers:
- url: /.*
script: helloworld.py
How would I tell it to run a specific method that is in one of the classes in the .py file? Is that even possible/allowed? Do I need to separate the different request handler classes into different python files? My understanding of databases is rather shallow at the moment, so I could be making no sense.
Thanks.
| [
"\nI was wondering if I am allowed to\n have one Python file with several\n request handler classes, each of which\n has get and post methods.\n\nSure! That app.yaml just transfers control to helloworld.py, which will run the main function defined in that file -- and that function typically sets up a WSGI app which dispatches appropriately, depending on the URL, to the right handler class. For example, look at the sample code here, very early on in the tutorial:\napplication = webapp.WSGIApplication(\n [('/', MainPage),\n ('/sign', Guestbook)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n\nI'm not copying the import statements and class definitions, because they don't matter: this is an example of how a single .py file dispatches to various handler classes (two in this case).\nThis doesn't mean the yaml file lets you call any method whatsoever, of course: rather, it hands control to a .py file, whose main is responsible for all that follows (and e.g. with the webapp mini-framework that comes with App Engine, it will always be get or post method [[or put, delete, ..., etc, if you also support those -- few do unless they're being especially RESTful;-)]] being called depending on the exact HTTP method and URL in the incoming request.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"yaml"
] | stackoverflow_0003134320_google_app_engine_python_yaml.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.