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 ... | 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 fou... | [
"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 th... | [
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.... | 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 ... | [
"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 mod... | 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 d... | [
"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 (un... | [
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 er... | 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 e... | [
"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 ca... | [
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),
... | 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()),
)
... | [
"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, d... | [
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.UserP... | 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.Mod... | [] | [] | [
"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... | [
-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 ho... | 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 indi... | [
"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 ... | [
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 criti... | 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 commun... | [
"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 o... | [
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 passingcu... | 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... | [
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 dja... | 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 wo... | [
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 g... | 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... | [
"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 ... | 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 ... | [
"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 direc... | [
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 t... | 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... | [
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 > ... | 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="checkb... | [
"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 me... | 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 functiona... | [
"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 vi... | [
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 ch... | 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 stat... | [
"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 up... | [
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 l... | 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 ... | [
"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"... | [
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 ... | [
-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 sim... | 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... | [
"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_threa... | [
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 hav... | 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... | [
"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\nanima... | [
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... | 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 ... | [
"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 ar... | [
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.CharF... | 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 th... | [
"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 d... | 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 calculato... | 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 c... | [
"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 en... | [
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,... | 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):... | [
"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.... | [
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... | 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... | [
"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 an... | 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 som... | 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... | [
"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... | [
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... | 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 someon... | [
"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 t... | [
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... | 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,... | [
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 facili... | 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 eve... | [
"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
impo... | 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.req... | [
"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 ... | [
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... | 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 ab... | [
"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 \... | [
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 p... | 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 co... | [
"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 a... | [
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?
E... | 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.f... | [
"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, ... | [
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, h... | 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,
... | [
"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... | [
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 fro... | 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 produc... | [
"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 CCpro... | [
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... | 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... | [
"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 se... | [
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 t... | 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)... | [
"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.framewo... | 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... | [
"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 developm... | 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 ht... | [
"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 ... | [
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... | 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 fr... | [
"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 ... | [
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 ctyp... | 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 ... | [
"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... | [
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 w... | 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 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 ... | 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 dictio... | [
"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... | [
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 char... | 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 wo... | [
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 prob... | 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 doe... | [
"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:
imp... | 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
excep... | [
"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_ = ((\"head... | [
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)
... | 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)
],
... | [
"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... | [
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?
applicat... | 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__ 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 o... | [
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... | 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. T... | [
"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
... | 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/code... | [
"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... | [
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')
... | 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')
... | [
"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?... | [
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... | 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 refre... | [
"\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 irrelevan... | [
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 ... | 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 th... | [
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 n... | 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 ... | [
"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... | [
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 tuto... | 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.scip... | [
"(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 ... | [
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 dele... | 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):
... | [
"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:
A... | 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-201006... | [
"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 crede... | 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 dat... | [
"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_... | 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 mode... | [
"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 ca... | [
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
... | 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.... | [
"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/l... | [
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, $... | 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 = $db... | [
"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 o... | [
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... | 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... | [
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 ... | 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 proble... | 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"
bu... | [
"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 c... | [
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, ... | 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), i... | [
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... | 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 i... | [
"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 filte... | [
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->... | 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). Af... | [
"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 commu... | [
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 ... | 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 t... | [
"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... | [
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 li... | 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 a... | [
"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 b... | 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... | [
"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++; Py... | [
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 mod... | 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... | [
"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 import... | [
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: 'Sect... | 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 ... | [
"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', 'leve... | [
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:
AddHa... | 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 ^(... | [
"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 r... | [
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>>");
... | 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",tm... | [
"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 ... | 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.histogr... | 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, ... | [
"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 th... | [
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 ... | 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 crea... | [
"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 JS... | 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... | [
"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 Non... | [
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... | 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 ... | [
"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 wer... | 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 i... | [
"[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 ... | [
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, file... | 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(... | [
"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",
"Pyt... | [
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.c... | 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 calculati... | [
"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... | [
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... | 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 ... | [
"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... | [
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:\Python2... | 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 ... | [
"\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/cmdl... | [
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 ... | 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 mo... | [
"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 automatic... | [
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 ... | 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 ... | [
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 abov... | 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 u... | [
"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 ... | [
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:
... | 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 you... | [
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 "<st... | 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>", ... | [
"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. He... | [
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):
"""Uploade... | 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_t... | [
"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 = sup... | 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)
... | [
"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, **kwar... | [
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 on... | 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... | [
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... | 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() t... | [
"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 __... | 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.__ini... | [
"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 confi... | [
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... | 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 ... | [
"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 to... | [
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... | 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 ... | [
"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 you... | [
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 ... | 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 abou... | [
"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. (includ... | [
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"... | 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 ... | [
"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... | [
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... | 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 ex... | [
"\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 w... | [
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.