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:
How to deploy highly iterative updates
I have a set of binary assets (swf files) each about 150Kb in size. I am developing them locally on my home computer and I want to periodically deploy them for review. My current strategy is:
Copy the .swf's into a transfer directory that is also a hg (mercurial) repo.
hg push the changes to my slicehost VPN
ssh onto my slicehost VPN
cd to my transfer directory and hg up
su www and cp the changed files into my public folder for viewing.
I would like to automate the process. Best case scenario is something close to:
Copy the .swf's into a "quick deploy" directory
Run a single local script to do all of the above.
I am interested in:
advice on where to put passwords since I need to su www to transfer files into the public web directories.
how the division of responsibility between local machine and server is handled.
I think using rsync is a better tool than hg since I don't really need a revision history of these types of changes. I can write this as a python script, a shell script or however is considered a best practice.
Eventually I would like to build this into a system that can handle my modest deployment needs. Perhaps there is an open-source deployment system that handles this and other types of situations? I'll probably roll-my-own for this current need but long term I'd like something relatively flexible.
Note: My home development computer is OS X and the target server is some recent flavour of Ubuntu. I'd prefer a python based solution but if this is best handled from the shell I have no problems putting it together that way.
A:
to avoid su www I see two easy choices.
make a folder writable to you and readable by www's group in some path that the web-server will be able to serve, then you can rsync to that folder from somewhere on your local machine.
put your public ssh key in www's authorized_keys and rsync to the www user (a bit less security in some setups perhaps, but not much, and usually more convenient).
working around su www by putting your or its password in some file would seem far less secure.
A script to invoke "rsync -avz --partial /some/path www@server:some/other/path" should be quick to write in python (although I do not python well).
A:
If you're at all comfortable in Python, I recommend Fabric for automated deployment scripts.
In addition to group permissions or ssh-ing as www (with key-based auth), a third solution to the permissions issue would be to add your user to /etc/sudoers and use sudo (you can specify the exact command your user is allowed to use sudo for, so you can make the security implications minimal).
|
How to deploy highly iterative updates
|
I have a set of binary assets (swf files) each about 150Kb in size. I am developing them locally on my home computer and I want to periodically deploy them for review. My current strategy is:
Copy the .swf's into a transfer directory that is also a hg (mercurial) repo.
hg push the changes to my slicehost VPN
ssh onto my slicehost VPN
cd to my transfer directory and hg up
su www and cp the changed files into my public folder for viewing.
I would like to automate the process. Best case scenario is something close to:
Copy the .swf's into a "quick deploy" directory
Run a single local script to do all of the above.
I am interested in:
advice on where to put passwords since I need to su www to transfer files into the public web directories.
how the division of responsibility between local machine and server is handled.
I think using rsync is a better tool than hg since I don't really need a revision history of these types of changes. I can write this as a python script, a shell script or however is considered a best practice.
Eventually I would like to build this into a system that can handle my modest deployment needs. Perhaps there is an open-source deployment system that handles this and other types of situations? I'll probably roll-my-own for this current need but long term I'd like something relatively flexible.
Note: My home development computer is OS X and the target server is some recent flavour of Ubuntu. I'd prefer a python based solution but if this is best handled from the shell I have no problems putting it together that way.
|
[
"to avoid su www I see two easy choices.\n\nmake a folder writable to you and readable by www's group in some path that the web-server will be able to serve, then you can rsync to that folder from somewhere on your local machine.\nput your public ssh key in www's authorized_keys and rsync to the www user (a bit less security in some setups perhaps, but not much, and usually more convenient).\n\nworking around su www by putting your or its password in some file would seem far less secure.\nA script to invoke \"rsync -avz --partial /some/path www@server:some/other/path\" should be quick to write in python (although I do not python well).\n",
"If you're at all comfortable in Python, I recommend Fabric for automated deployment scripts.\nIn addition to group permissions or ssh-ing as www (with key-based auth), a third solution to the permissions issue would be to add your user to /etc/sudoers and use sudo (you can specify the exact command your user is allowed to use sudo for, so you can make the security implications minimal).\n"
] |
[
1,
1
] |
[] |
[] |
[
"deployment",
"macos",
"python",
"rsync",
"ubuntu"
] |
stackoverflow_0002084969_deployment_macos_python_rsync_ubuntu.txt
|
Q:
Database password requested when running "manage.py test"
When I try to run
manage.py test
a database password prompt shows.
Previously, tests would run without me having to enter the db password manaually.
I just updated my database to postgres 8.4. I assume it's some setting I'm forgetting.
How can I configure it to run tests without asking for the password?
Additional Info:
I created the database with the user 'postgres', but am accessing in django with the user, 'postgis'. I checked the permissions of these users, and they are the same.
When running the test the db and tables get created fine (no password requested).
It's only when it installs 'Custom SQL' that the password is requested.
RESOLUTION
As Carl pointed out the ~/.pgpass file [*nix] and %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile) [windows] allows you to configure databases so you don't need to enter a password each time.
See the postgres documentation: The Password File
I checked my configuration and it looks like this file was/is auto-created. I updated my password file and now django tests run without the need to manually enter a password on each custom sql installation.
A:
Django tests use a different database; your DATABASE_NAME setting with "_test" appended. My first guess would be that somewhere in your Postgres authentication config (either in pg_hba.conf or in a ~/.pgpass file), you are allowing access to DATABASE_NAME with no password, but you don't have the same config for DATABASE_NAME_test.
A:
I assume it's some setting I'm
forgetting.
Not trying to make a fool out of you, but sometimes simple solutions are overlooked:
Did you set the DATABASE_PASSWORD setting in your settings.py file?
|
Database password requested when running "manage.py test"
|
When I try to run
manage.py test
a database password prompt shows.
Previously, tests would run without me having to enter the db password manaually.
I just updated my database to postgres 8.4. I assume it's some setting I'm forgetting.
How can I configure it to run tests without asking for the password?
Additional Info:
I created the database with the user 'postgres', but am accessing in django with the user, 'postgis'. I checked the permissions of these users, and they are the same.
When running the test the db and tables get created fine (no password requested).
It's only when it installs 'Custom SQL' that the password is requested.
RESOLUTION
As Carl pointed out the ~/.pgpass file [*nix] and %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile) [windows] allows you to configure databases so you don't need to enter a password each time.
See the postgres documentation: The Password File
I checked my configuration and it looks like this file was/is auto-created. I updated my password file and now django tests run without the need to manually enter a password on each custom sql installation.
|
[
"Django tests use a different database; your DATABASE_NAME setting with \"_test\" appended. My first guess would be that somewhere in your Postgres authentication config (either in pg_hba.conf or in a ~/.pgpass file), you are allowing access to DATABASE_NAME with no password, but you don't have the same config for DATABASE_NAME_test.\n",
"\nI assume it's some setting I'm\n forgetting.\n\nNot trying to make a fool out of you, but sometimes simple solutions are overlooked:\nDid you set the DATABASE_PASSWORD setting in your settings.py file?\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002085002_django_python.txt
|
Q:
How to find out whether a function defined for an instance of a class in Python?
I want to know if a function is defined for an instance of a class
class c(object):
def func(self): pass
cc = c()
>>> is_function_defined_for_instance(cc,'func')
True
>>> is_function_defined_for_instance(cc,'cnuf')
False
my cleanest attempts at the function is:
def is_function_defined_for_instance(instance,function):
return callable(getattr(instance,function,None))
# returns True iff function is defined for class of instance (not super classes)
def is_function_defined_for_instance(instance,function):
return bool(instance.__class__.__dict__.get(function))
is there a built-in or a nicer way to accomplish what I'm looking for?
A:
In Python 2.6 or better, the recommended approach is:
import collections
def is_func(instance, func):
return isinstance(getattr(instance, func, None), collections.Callable)
The new ABCs (Abstract Base Classes) in the collections module are the correct way, in Python 2.6+ and 3.any, to perform this kind of "duck-typing-like type checks" -- much more elegant, unform, and future-proof than older approaches such as the callable built-in, operator.isCallable, or checking for the presence of specific special methods such as __call__. Since isinstance can now be overloaded, leave it up to the ABCs to overload it and perform the checks by encapsulating whatever lower-level approaches work best!
The elegance and advantages of the new approach are such that, if you need to make your code portable between older and newer versions of Python, I recommend encapsulating the "duck-typing tests" that you require in a module that can define its function depending on the sys.version -- using isinstance(x, collections.Y) in 2.6 or better, and older approaches such as hasattr(x, '__somespecialmethod__') or callable(x) in 2.5 or worse.
Most importantly, and more generally, don't pollute your new, mainline application code with the old, inferior ways -- if backwards-portability requirements force your overall system to have some "garbage" (in order to keep running on old Python versions), at least hide that garbage decently in its own "compartment" (where one day you may be able to easily sweep it away if your app's deployment constraints permit!-).
A:
>>> def is_func(instance, func):
test = getattr(instance, func, None)
if test and hasattr(test, '__call__'):
return True
>>> is_func('', 'len')
>>> is_func({}, 'fromkeys')
True
or you could use inspect module:
>>> import inspect
>>> test = getattr(cc, 'func', None)
>>> inspect.ismethod(test)
True
A:
Can you throw some sort of custom exception if the method is missing? (I'm coming from Ruby land here :) )
|
How to find out whether a function defined for an instance of a class in Python?
|
I want to know if a function is defined for an instance of a class
class c(object):
def func(self): pass
cc = c()
>>> is_function_defined_for_instance(cc,'func')
True
>>> is_function_defined_for_instance(cc,'cnuf')
False
my cleanest attempts at the function is:
def is_function_defined_for_instance(instance,function):
return callable(getattr(instance,function,None))
# returns True iff function is defined for class of instance (not super classes)
def is_function_defined_for_instance(instance,function):
return bool(instance.__class__.__dict__.get(function))
is there a built-in or a nicer way to accomplish what I'm looking for?
|
[
"In Python 2.6 or better, the recommended approach is:\nimport collections\n\ndef is_func(instance, func):\n return isinstance(getattr(instance, func, None), collections.Callable)\n\nThe new ABCs (Abstract Base Classes) in the collections module are the correct way, in Python 2.6+ and 3.any, to perform this kind of \"duck-typing-like type checks\" -- much more elegant, unform, and future-proof than older approaches such as the callable built-in, operator.isCallable, or checking for the presence of specific special methods such as __call__. Since isinstance can now be overloaded, leave it up to the ABCs to overload it and perform the checks by encapsulating whatever lower-level approaches work best!\nThe elegance and advantages of the new approach are such that, if you need to make your code portable between older and newer versions of Python, I recommend encapsulating the \"duck-typing tests\" that you require in a module that can define its function depending on the sys.version -- using isinstance(x, collections.Y) in 2.6 or better, and older approaches such as hasattr(x, '__somespecialmethod__') or callable(x) in 2.5 or worse.\nMost importantly, and more generally, don't pollute your new, mainline application code with the old, inferior ways -- if backwards-portability requirements force your overall system to have some \"garbage\" (in order to keep running on old Python versions), at least hide that garbage decently in its own \"compartment\" (where one day you may be able to easily sweep it away if your app's deployment constraints permit!-).\n",
">>> def is_func(instance, func):\n test = getattr(instance, func, None)\n if test and hasattr(test, '__call__'):\n return True\n\n>>> is_func('', 'len')\n>>> is_func({}, 'fromkeys')\nTrue\n\nor you could use inspect module:\n>>> import inspect\n>>> test = getattr(cc, 'func', None)\n>>> inspect.ismethod(test)\nTrue\n\n",
"Can you throw some sort of custom exception if the method is missing? (I'm coming from Ruby land here :) )\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"function",
"python",
"reflection"
] |
stackoverflow_0002087911_function_python_reflection.txt
|
Q:
Why is my Facebook application with error 104 ("invalid signature")?
I am trying to develop a Facebook application using PyFacebook (hosted on Google App Engine). It's an FBML application (runs in a Facebook canvas instead of an iframe). I'm having problems getting any API calls to function. The sequence looks like this:
fb = facebook.Faceboook(api_key, secret_key)
fb.session_key = cherrypy.request.params['fb_sig_session_key']
fb.uid =cherrypy.request.params['fb_sig_user']
Then if I try, for example:
user = fb.users.getLoggedInUser()
This will fail with:
Error 104: Incorrect signature
I'm not sure where I'm going wrong. I've verified that the api_key and secret_key are correct (many, many times). The application has been added to my account. I've even been able to get a desktop application working; my problem is only with this web-hosted version.
Thanks for your help!
A:
Deleting the Facebook application and re-creating it, then configuring my code with the new API key and secret key, resolved this problem.
|
Why is my Facebook application with error 104 ("invalid signature")?
|
I am trying to develop a Facebook application using PyFacebook (hosted on Google App Engine). It's an FBML application (runs in a Facebook canvas instead of an iframe). I'm having problems getting any API calls to function. The sequence looks like this:
fb = facebook.Faceboook(api_key, secret_key)
fb.session_key = cherrypy.request.params['fb_sig_session_key']
fb.uid =cherrypy.request.params['fb_sig_user']
Then if I try, for example:
user = fb.users.getLoggedInUser()
This will fail with:
Error 104: Incorrect signature
I'm not sure where I'm going wrong. I've verified that the api_key and secret_key are correct (many, many times). The application has been added to my account. I've even been able to get a desktop application working; my problem is only with this web-hosted version.
Thanks for your help!
|
[
"Deleting the Facebook application and re-creating it, then configuring my code with the new API key and secret key, resolved this problem.\n"
] |
[
1
] |
[] |
[] |
[
"authentication",
"cherrypy",
"facebook",
"pyfacebook",
"python"
] |
stackoverflow_0002087672_authentication_cherrypy_facebook_pyfacebook_python.txt
|
Q:
Java equivalent of Pythons urllib.urlencode(HashMap based UrlEncode)
From
Whats the java equivalent of Python’s urllib.urlencode?
Like
>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'
Where I can pass a HashMap of key values and it encodes and gives me the url string ..
Edit: I wanted to avoid this scenario
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
of manually concatenating the strings with
=
and
&
A:
java.net.URLEncoder should work for you - though you would have to extend it to accept the hashmap - but that is not very difficult.
|
Java equivalent of Pythons urllib.urlencode(HashMap based UrlEncode)
|
From
Whats the java equivalent of Python’s urllib.urlencode?
Like
>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'
Where I can pass a HashMap of key values and it encodes and gives me the url string ..
Edit: I wanted to avoid this scenario
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
of manually concatenating the strings with
=
and
&
|
[
"java.net.URLEncoder should work for you - though you would have to extend it to accept the hashmap - but that is not very difficult. \n"
] |
[
2
] |
[] |
[] |
[
"encoding",
"java",
"python",
"url",
"urlencode"
] |
stackoverflow_0002088502_encoding_java_python_url_urlencode.txt
|
Q:
Storing system-wide DB connection password for a Python module
I have a written a Python module which due to its specifics needs to have a MySQL database connection. Right now, details of this connection (host, database, username and password to connect with) are stored in /etc/mymodule.conf in plaintext, which is obviously not a good idea.
Supposedly, the /etc/mymodule.conf file is edited by the root user after the module is installed, since the module and its database may be used by all users of a Unix system.
How should I securely store the password instead?
A:
Your constraints set a very difficult problem: every user on the system must be able to access that password (since that's the only way for users to access that database)... yet they must not (except when running that script, and presumably only when running it without e.g. a python -i session that would let them set a breakpoint just before the connect call and look all through memory, so definitely able to look at the password).
You could write a daemon process that runs as root (so can read mymodule.conf, which you'd make readable only by root) and accepts requests, somehow validates that the request comes from a "good" process (one that's running the exact module in question and not interactive), and only then supplies the password. That's fragile, mostly because of the need to determine whether a process may or may not have a breakpoint set at the crucial point of execution.
Alternatively, you could further raise the technological stakes by having the daemon return, not the password, but rather the open socket ready to be wrapped in a DB-API compliant wrapper; some Unix systems allow open file descriptors to be sent between unrelated processes (a prereq for this approach) -- and of course you'd have to substantially rework the MySQL-based DB API to allow opening a connection around an already-open socket rather than a freshly made one. Note that a validated requesting process that happens to be interactive would still be able to get the connection object, once built, and send totally arbitrary requests -- they wouldn't be able to see the password, technically, but that's not much consolation. So it's unlikely that the large effort required here is warranted.
So the next possible architecture is to mediate all db interaction via the validating daemon: a process would "log into" the daemon, get validated, and, if all's OK, gain a proxy connection to (e.g.) an XMLRPC server exposing the DB connection and functionality (the daemon would probably fork each such proxy process, right after reading the password from the root-only-readable file, and drop privileges immediately, just on general security ground).
The plus wrt the previous alternative, in addition to probably easier implementation, is that the proxy would also get a look at every SQL request that's about to be sent to the MySQL db, and be able to validate and censor those requests as well (presumably on a default-deny basis, again for general security principles), thus seriously limiting the amount of damage a "rogue" client process (running interactively with a debugger) can do... one hopes;-).
Yes, no easy solutions here -- but then, the problem your constraints pose is so far from easy that it borders on a self-contradictory impossibility;-). BTW, the problem's not particularly Python-related, it's essentially about choosing a secure architecture that comes close to "squaring the circle"-hard contradictory constraints on access permissions!-)
A:
Why not create a default MySQL user account with restricted permissions? You
could set it up so it can only read the particular database. You could also
restrict the default user to only being able to SELECT, with no ability to INSERT,UPDATE or
DELETE. The particular privileges you should set of course depend on your situation.
The syntax for restricting/granting privileges is covered here:
http://dev.mysql.com/doc/refman/5.1/en/grant.html
By creating a default, restricted MySQL user, you could perhaps put the password
in a plain text file with no harm done.
Meanwhile, if you add user and password as optional parameters to your module's connection function, then more privileged users could supply their own password to be able to interact with the database with greater privileges.
Of course, this just amounts to questioning the original premise of your post.
If that direction is not viable, feel free to ignore! :)
Regards,
unutbu
|
Storing system-wide DB connection password for a Python module
|
I have a written a Python module which due to its specifics needs to have a MySQL database connection. Right now, details of this connection (host, database, username and password to connect with) are stored in /etc/mymodule.conf in plaintext, which is obviously not a good idea.
Supposedly, the /etc/mymodule.conf file is edited by the root user after the module is installed, since the module and its database may be used by all users of a Unix system.
How should I securely store the password instead?
|
[
"Your constraints set a very difficult problem: every user on the system must be able to access that password (since that's the only way for users to access that database)... yet they must not (except when running that script, and presumably only when running it without e.g. a python -i session that would let them set a breakpoint just before the connect call and look all through memory, so definitely able to look at the password).\nYou could write a daemon process that runs as root (so can read mymodule.conf, which you'd make readable only by root) and accepts requests, somehow validates that the request comes from a \"good\" process (one that's running the exact module in question and not interactive), and only then supplies the password. That's fragile, mostly because of the need to determine whether a process may or may not have a breakpoint set at the crucial point of execution.\nAlternatively, you could further raise the technological stakes by having the daemon return, not the password, but rather the open socket ready to be wrapped in a DB-API compliant wrapper; some Unix systems allow open file descriptors to be sent between unrelated processes (a prereq for this approach) -- and of course you'd have to substantially rework the MySQL-based DB API to allow opening a connection around an already-open socket rather than a freshly made one. Note that a validated requesting process that happens to be interactive would still be able to get the connection object, once built, and send totally arbitrary requests -- they wouldn't be able to see the password, technically, but that's not much consolation. So it's unlikely that the large effort required here is warranted.\nSo the next possible architecture is to mediate all db interaction via the validating daemon: a process would \"log into\" the daemon, get validated, and, if all's OK, gain a proxy connection to (e.g.) an XMLRPC server exposing the DB connection and functionality (the daemon would probably fork each such proxy process, right after reading the password from the root-only-readable file, and drop privileges immediately, just on general security ground).\nThe plus wrt the previous alternative, in addition to probably easier implementation, is that the proxy would also get a look at every SQL request that's about to be sent to the MySQL db, and be able to validate and censor those requests as well (presumably on a default-deny basis, again for general security principles), thus seriously limiting the amount of damage a \"rogue\" client process (running interactively with a debugger) can do... one hopes;-).\nYes, no easy solutions here -- but then, the problem your constraints pose is so far from easy that it borders on a self-contradictory impossibility;-). BTW, the problem's not particularly Python-related, it's essentially about choosing a secure architecture that comes close to \"squaring the circle\"-hard contradictory constraints on access permissions!-)\n",
"Why not create a default MySQL user account with restricted permissions? You\ncould set it up so it can only read the particular database. You could also\nrestrict the default user to only being able to SELECT, with no ability to INSERT,UPDATE or\nDELETE. The particular privileges you should set of course depend on your situation.\nThe syntax for restricting/granting privileges is covered here:\nhttp://dev.mysql.com/doc/refman/5.1/en/grant.html\nBy creating a default, restricted MySQL user, you could perhaps put the password\nin a plain text file with no harm done. \nMeanwhile, if you add user and password as optional parameters to your module's connection function, then more privileged users could supply their own password to be able to interact with the database with greater privileges. \nOf course, this just amounts to questioning the original premise of your post.\nIf that direction is not viable, feel free to ignore! :)\nRegards,\nunutbu\n"
] |
[
4,
1
] |
[] |
[] |
[
"python",
"security"
] |
stackoverflow_0002087920_python_security.txt
|
Q:
Local installation of python
I want to install python to my local direcotory:
./configure --prefix=/home/alex/local-install && make && make install
When i import sqlite3 i get the following:
ImportError: No module named _sqlite3
the reason: there is no _sqlite3.so in /home/alex/local-install/lib/python2.6/lib-dynload.
How can i force python to build bindings for sqlite and other libraries (zlib for example)?
P.S. By the way: if i install sqlite3 to my local directory /home/alex/local-install before installing python - import sqlite3 works fine. That could be a solution: but in that case i have to install manually lots of libraries those i want to bind with python. Brrrrr :-[
A:
You need to install the development headers and libraries for sqlite somewhere where the Python build can find them. You didn't say what OS you have. On Linux you usually have to install additional -dev[el] packages to be able to build against a library.
|
Local installation of python
|
I want to install python to my local direcotory:
./configure --prefix=/home/alex/local-install && make && make install
When i import sqlite3 i get the following:
ImportError: No module named _sqlite3
the reason: there is no _sqlite3.so in /home/alex/local-install/lib/python2.6/lib-dynload.
How can i force python to build bindings for sqlite and other libraries (zlib for example)?
P.S. By the way: if i install sqlite3 to my local directory /home/alex/local-install before installing python - import sqlite3 works fine. That could be a solution: but in that case i have to install manually lots of libraries those i want to bind with python. Brrrrr :-[
|
[
"You need to install the development headers and libraries for sqlite somewhere where the Python build can find them. You didn't say what OS you have. On Linux you usually have to install additional -dev[el] packages to be able to build against a library.\n"
] |
[
3
] |
[] |
[] |
[
"installation",
"makefile",
"python",
"sqlite"
] |
stackoverflow_0002089054_installation_makefile_python_sqlite.txt
|
Q:
How to get more search results than the server's sizelimit with Python LDAP?
I am using the python-ldap module to (amongst other things) search for groups, and am running into the server's size limit and getting a SIZELIMIT_EXCEEDED exception. I have tried both synchronous and asynchronous searches and hit the problem both ways.
You are supposed to be able to work round this by setting a paging control on the search, but according to the python-ldap docs these controls are not yet implemented for search_ext(). Is there a way to do this in Python? If the python-ldap library does not support it, is there another Python library that does?
A:
Here are some links related to paging in python-ldap.
Documentation: http://www.python-ldap.org/doc/html/ldap-controls.html#ldap.controls.SimplePagedResultsControl
Example code using paging: http://www.novell.com/coolsolutions/tip/18274.html
More example code: http://google-apps-for-your-domain-ldap-sync.googlecode.com/svn/trunk/ldap_ctxt.py
A:
After some discussion on the python-ldap-dev mailing list, I can answer my own question.
Page controls ARE supported by the Python lDAP module, but the docs had not been updated for search_ext to show that. The example linked by Gorgapor shows how to use the ldap.controls.SimplePagedResultsControl to read the results in pages.
However there is a gotcha. This will work with Microsoft Active Directory servers, but not with OpenLDAP servers (and possibly others, such as Sun's). The LDAP controls RFC is ambiguous as to whether paged controls should be allowed to override the server's sizelimit setting. On ActiveDirectory servers they can by default while on OpenLDAP they cannot, but I think there is a server setting that will allow them to.
So even if you implement the paged control, there is still no guarantee that it will get all the objects that you want. Sigh
Also paged controls are only available with LDAP v3, but I doubt that there are many v2 servers in use.
|
How to get more search results than the server's sizelimit with Python LDAP?
|
I am using the python-ldap module to (amongst other things) search for groups, and am running into the server's size limit and getting a SIZELIMIT_EXCEEDED exception. I have tried both synchronous and asynchronous searches and hit the problem both ways.
You are supposed to be able to work round this by setting a paging control on the search, but according to the python-ldap docs these controls are not yet implemented for search_ext(). Is there a way to do this in Python? If the python-ldap library does not support it, is there another Python library that does?
|
[
"Here are some links related to paging in python-ldap.\n\nDocumentation: http://www.python-ldap.org/doc/html/ldap-controls.html#ldap.controls.SimplePagedResultsControl\nExample code using paging: http://www.novell.com/coolsolutions/tip/18274.html\nMore example code: http://google-apps-for-your-domain-ldap-sync.googlecode.com/svn/trunk/ldap_ctxt.py\n\n",
"After some discussion on the python-ldap-dev mailing list, I can answer my own question. \nPage controls ARE supported by the Python lDAP module, but the docs had not been updated for search_ext to show that. The example linked by Gorgapor shows how to use the ldap.controls.SimplePagedResultsControl to read the results in pages.\nHowever there is a gotcha. This will work with Microsoft Active Directory servers, but not with OpenLDAP servers (and possibly others, such as Sun's). The LDAP controls RFC is ambiguous as to whether paged controls should be allowed to override the server's sizelimit setting. On ActiveDirectory servers they can by default while on OpenLDAP they cannot, but I think there is a server setting that will allow them to.\nSo even if you implement the paged control, there is still no guarantee that it will get all the objects that you want. Sigh\nAlso paged controls are only available with LDAP v3, but I doubt that there are many v2 servers in use.\n"
] |
[
17,
8
] |
[] |
[] |
[
"ldap",
"python"
] |
stackoverflow_0002073574_ldap_python.txt
|
Q:
How do I get cx_Oracle to work on 64-bit Itanium Windows?
I'm running Windows Server 2003 on a 64-bit Itanium server which is also running 64-bit Oracle 10.2, and I'd like to install cx_Oracle for Python 2.5. I've used cx_Oracle before many times on both Windows and Linux, and I've also compiled it before on 32 bit versions of those platforms, but I've never tried an IA64 compile.
None of the binary builds of cx_Oracle at http://cx-oracle.sourceforge.net/ are 64 bit, and I get an error after installing any of them when trying to run import cx_Oracle so I figure the thing to do is to compile it from source.
When running python setup.py build then I get the error that Python was built with Visual Studio 2003 and that I need something which can produce compatible binaries. I have Visual Studio 2005, which apparently doesn't fit the bill due to linking against a different version of the C standard library, and probably for other reasons as well. Unfortunately, Visual Studio 2003 is no longer available for download, and I'm not sure where to get it.
So I download MinGW from http://sourceforge.net/projects/mingw/files/ but this is also only available in 32 bit form. I go ahead and give it a try anyway, but it gives me an error during compilation about one of the Oracle DLLs I'm linking against having an invalid file format.
At this point I've got a lot of options, and I'm not sure where to place my efforts:
I could download the 64 bit MinGW from http://sourceforge.net/projects/mingw-w64/ and try using that, except that it only seems to be available as source, so I'd have to compile the compiler, probably using Visual Studio 2005.
I could try using an x86 32 bit build of Python and then download the Oracle Instant Client SDK from http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html and then use that to build cx_Oracle. I'd probably have to set my ORACLE_HOME to the client so that it didn't try linking against the 64 bit server DLLs, but this seems like it might work.
I could try compiling Python itself from source, using Visual Studio 2005, so that I could then use Visual Studio 2005 to build cx_Oracle and not worry about binary compatibility issues. I've compiled Python from source many times on Linux and never had any problems, so I'd like to believe that it's just as simple on Windows.
I could try to figure out how to make Visual Studio 2005 link against the right DLLs and thus produce compatible binaries in that manner without needing Visual Studio 2003. Intuitively it seems like Visual Studio should be able to produce compatible binaries with older versions of itself, but almost all of my compiler experience is with gcc so I don't really know.
I'm just really not sure where to direct my efforts. Does anyone have any suggestions about where to go next? I can copy/paste some of the specific error messages I've gotten if that would be helpful.
I'd especially love to hear from anyone who's ever gotten cx_Oracle to work on a 64 bit Itanium version of Windows - I can't be the first to try this.
A:
I ended up going with Option #2: I downloaded the 32-bit Oracle Instant Client, then compiled cx_Oracle for 32-bit Python with the instant client. So everything involved is 32-bit, and I'm just not using any IA64-bit executables, and this works just fine.
If I had an IA64 compiler, I'd try Option #3, but it turns out that Visual Studio Pro doesn't support the IA64 platform, and we'd need to spend a lot of money to upgrade to whatever's higher than Pro.
A:
I read this yesterday and am not suprised to see that nobody has answered. It is a very specific and complex question. While I do not have direct experience with many of the tools you are dealing with I have delt with the issues surrounding incompatabilities with different compilers and binaries. For what its worth 3. sounds like your best bet.
|
How do I get cx_Oracle to work on 64-bit Itanium Windows?
|
I'm running Windows Server 2003 on a 64-bit Itanium server which is also running 64-bit Oracle 10.2, and I'd like to install cx_Oracle for Python 2.5. I've used cx_Oracle before many times on both Windows and Linux, and I've also compiled it before on 32 bit versions of those platforms, but I've never tried an IA64 compile.
None of the binary builds of cx_Oracle at http://cx-oracle.sourceforge.net/ are 64 bit, and I get an error after installing any of them when trying to run import cx_Oracle so I figure the thing to do is to compile it from source.
When running python setup.py build then I get the error that Python was built with Visual Studio 2003 and that I need something which can produce compatible binaries. I have Visual Studio 2005, which apparently doesn't fit the bill due to linking against a different version of the C standard library, and probably for other reasons as well. Unfortunately, Visual Studio 2003 is no longer available for download, and I'm not sure where to get it.
So I download MinGW from http://sourceforge.net/projects/mingw/files/ but this is also only available in 32 bit form. I go ahead and give it a try anyway, but it gives me an error during compilation about one of the Oracle DLLs I'm linking against having an invalid file format.
At this point I've got a lot of options, and I'm not sure where to place my efforts:
I could download the 64 bit MinGW from http://sourceforge.net/projects/mingw-w64/ and try using that, except that it only seems to be available as source, so I'd have to compile the compiler, probably using Visual Studio 2005.
I could try using an x86 32 bit build of Python and then download the Oracle Instant Client SDK from http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html and then use that to build cx_Oracle. I'd probably have to set my ORACLE_HOME to the client so that it didn't try linking against the 64 bit server DLLs, but this seems like it might work.
I could try compiling Python itself from source, using Visual Studio 2005, so that I could then use Visual Studio 2005 to build cx_Oracle and not worry about binary compatibility issues. I've compiled Python from source many times on Linux and never had any problems, so I'd like to believe that it's just as simple on Windows.
I could try to figure out how to make Visual Studio 2005 link against the right DLLs and thus produce compatible binaries in that manner without needing Visual Studio 2003. Intuitively it seems like Visual Studio should be able to produce compatible binaries with older versions of itself, but almost all of my compiler experience is with gcc so I don't really know.
I'm just really not sure where to direct my efforts. Does anyone have any suggestions about where to go next? I can copy/paste some of the specific error messages I've gotten if that would be helpful.
I'd especially love to hear from anyone who's ever gotten cx_Oracle to work on a 64 bit Itanium version of Windows - I can't be the first to try this.
|
[
"I ended up going with Option #2: I downloaded the 32-bit Oracle Instant Client, then compiled cx_Oracle for 32-bit Python with the instant client. So everything involved is 32-bit, and I'm just not using any IA64-bit executables, and this works just fine.\nIf I had an IA64 compiler, I'd try Option #3, but it turns out that Visual Studio Pro doesn't support the IA64 platform, and we'd need to spend a lot of money to upgrade to whatever's higher than Pro.\n",
"I read this yesterday and am not suprised to see that nobody has answered. It is a very specific and complex question. While I do not have direct experience with many of the tools you are dealing with I have delt with the issues surrounding incompatabilities with different compilers and binaries. For what its worth 3. sounds like your best bet.\n"
] |
[
1,
0
] |
[] |
[] |
[
"64_bit",
"cx_oracle",
"itanium",
"python",
"windows"
] |
stackoverflow_0002024016_64_bit_cx_oracle_itanium_python_windows.txt
|
Q:
How do I resolve a "Too many open files" error in Bazaar?
I am using Bazaar v2.0.1 on Max OS X 10.6.2
When I perform a commit after moving a large number of files/directories (over 10,000) I get the following error message:
bzr: ERROR: [Errno 24] open: Too many
open files: '.'
My first work-around was to break the commit up into several sub-sets. However, this is not ideal and I'm afraid there may be a point where one change (that cannot be broken up into sub-sets) will give me the same error.
[Update]
After doing some research this is what I have found:
It looks like:
Errno 24 "open: Too many open files"
is a Python error.
According to this blog post, the limit on the number of files open can be changed from within a Python script with resource.setrlimit. However, I was really looking for a way to change the default value so Bazaar would automatically run with a higher value (BTW, it looks like my default setting was 2560).
According to the apple documentation for the setrlimit system call there is a sh built-in command called ulimit which can be used to change the setting. Any process started from the shell would then inherit this value.
My current work-around is to add ulimit -n 10240 to ~/.profile. This way when I run bzr commit from the shell it will be able to open 10240 files. I selected 10240 files because this is the maximum allowed for a user process in Mac OS X.
It doesn't seem like Bazaar should need that many files open at once. I am worried that if I ever move more files that this may come back to bite me again. Is this a bug in Bazaar? Is there anything else I can do?
A:
You can use lsof to see all open files. You might try grepping for the pid of the bazaar process, or monitoring the number of open files.
Note that you may or may not need to be root to see all files / processes relevant for your situation.
A:
Try ulimit -n 1024 (or more) before running bazaar, if your shell supports it (it's a bash builtin).
Jinx! edit: you can put it in your ~/.profile if there is one, or ~/.bash_profile.
|
How do I resolve a "Too many open files" error in Bazaar?
|
I am using Bazaar v2.0.1 on Max OS X 10.6.2
When I perform a commit after moving a large number of files/directories (over 10,000) I get the following error message:
bzr: ERROR: [Errno 24] open: Too many
open files: '.'
My first work-around was to break the commit up into several sub-sets. However, this is not ideal and I'm afraid there may be a point where one change (that cannot be broken up into sub-sets) will give me the same error.
[Update]
After doing some research this is what I have found:
It looks like:
Errno 24 "open: Too many open files"
is a Python error.
According to this blog post, the limit on the number of files open can be changed from within a Python script with resource.setrlimit. However, I was really looking for a way to change the default value so Bazaar would automatically run with a higher value (BTW, it looks like my default setting was 2560).
According to the apple documentation for the setrlimit system call there is a sh built-in command called ulimit which can be used to change the setting. Any process started from the shell would then inherit this value.
My current work-around is to add ulimit -n 10240 to ~/.profile. This way when I run bzr commit from the shell it will be able to open 10240 files. I selected 10240 files because this is the maximum allowed for a user process in Mac OS X.
It doesn't seem like Bazaar should need that many files open at once. I am worried that if I ever move more files that this may come back to bite me again. Is this a bug in Bazaar? Is there anything else I can do?
|
[
"You can use lsof to see all open files. You might try grepping for the pid of the bazaar process, or monitoring the number of open files.\nNote that you may or may not need to be root to see all files / processes relevant for your situation.\n",
"Try ulimit -n 1024 (or more) before running bazaar, if your shell supports it (it's a bash builtin).\nJinx! edit: you can put it in your ~/.profile if there is one, or ~/.bash_profile.\n"
] |
[
3,
2
] |
[] |
[] |
[
"bazaar",
"python"
] |
stackoverflow_0002089353_bazaar_python.txt
|
Q:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
How do I set the timezone of a datetime instance that just came out of the datastore?
When it first comes out it is in UTC. I want to change it to EST.
I'm trying, for example:
class Book( db.Model ):
creationTime = db.DateTimeProperty()
When a Book is retrieved, I want to set its tzinfo immediately:
book.creationTime.tzinfo = EST
Where I use this example for my EST object
However I get:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
I've seen a number of answers that recommend pytz and python-dateutil, but I really want an answer to this question.
A:
datetime's objects are immutable, so you never change any of their attributes -- you make a new object with some attributes the same, and some different, and assign it to whatever you need to assign it to.
I.e., in your case, instead of
book.creationTime.tzinfo = EST
you have to code
book.creationTime = book.creationTime.replace(tzinfo=EST)
A:
If you're receiving a datetime that's in EST, but doesn't have its tzinfo field set, use dt.replace(tzinfo=tz) to assign a tzinfo without modifying the time. (Your database should be doing this for you.)
If you're receiving a datetime that's in UDT, and you want it in EST, then you need astimezone. http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
In the vast majority of cases, your database should be storing and returning data in UDT, and you shouldn't need to use replace (except possibly to assign a UDT tzinfo).
A:
What you want is right there in the docs.
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
DSTSTART = datetime(1, 4, 1, 2)
DSTEND = datetime(1, 10, 25, 1)
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
# Find first Sunday in April & the last in October.
start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
now = datetime.now()
print now
print now.tzinfo
Eastern = USTimeZone(-5, 'Eastern', 'EST', 'EDT')
now_tz_aware = now.replace(tzinfo=Eastern)
print now_tz_aware
output:
2010-01-18 17:08:02.741482
None
2010-01-18 17:08:02.741482-05:00
|
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
|
How do I set the timezone of a datetime instance that just came out of the datastore?
When it first comes out it is in UTC. I want to change it to EST.
I'm trying, for example:
class Book( db.Model ):
creationTime = db.DateTimeProperty()
When a Book is retrieved, I want to set its tzinfo immediately:
book.creationTime.tzinfo = EST
Where I use this example for my EST object
However I get:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
I've seen a number of answers that recommend pytz and python-dateutil, but I really want an answer to this question.
|
[
"datetime's objects are immutable, so you never change any of their attributes -- you make a new object with some attributes the same, and some different, and assign it to whatever you need to assign it to.\nI.e., in your case, instead of\nbook.creationTime.tzinfo = EST\n\nyou have to code\nbook.creationTime = book.creationTime.replace(tzinfo=EST)\n\n",
"If you're receiving a datetime that's in EST, but doesn't have its tzinfo field set, use dt.replace(tzinfo=tz) to assign a tzinfo without modifying the time. (Your database should be doing this for you.)\nIf you're receiving a datetime that's in UDT, and you want it in EST, then you need astimezone. http://docs.python.org/library/datetime.html#datetime.datetime.astimezone\nIn the vast majority of cases, your database should be storing and returning data in UDT, and you shouldn't need to use replace (except possibly to assign a UDT tzinfo).\n",
"What you want is right there in the docs.\nfrom datetime import tzinfo, timedelta, datetime\n\nZERO = timedelta(0)\nHOUR = timedelta(hours=1)\nDSTSTART = datetime(1, 4, 1, 2)\nDSTEND = datetime(1, 10, 25, 1)\n\ndef first_sunday_on_or_after(dt):\n days_to_go = 6 - dt.weekday()\n if days_to_go:\n dt += timedelta(days_to_go)\n return dt\n\nclass USTimeZone(tzinfo):\n\n def __init__(self, hours, reprname, stdname, dstname):\n self.stdoffset = timedelta(hours=hours)\n self.reprname = reprname\n self.stdname = stdname\n self.dstname = dstname\n\n def __repr__(self):\n return self.reprname\n\n def tzname(self, dt):\n if self.dst(dt):\n return self.dstname\n else:\n return self.stdname\n\n def utcoffset(self, dt):\n return self.stdoffset + self.dst(dt)\n\n def dst(self, dt):\n if dt is None or dt.tzinfo is None:\n # An exception may be sensible here, in one or both cases.\n # It depends on how you want to treat them. The default\n # fromutc() implementation (called by the default astimezone()\n # implementation) passes a datetime with dt.tzinfo is self.\n return ZERO\n assert dt.tzinfo is self\n\n # Find first Sunday in April & the last in October.\n start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))\n end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))\n\n # Can't compare naive to aware objects, so strip the timezone from\n # dt first.\n if start <= dt.replace(tzinfo=None) < end:\n return HOUR\n else:\n return ZERO\n\nnow = datetime.now()\nprint now\nprint now.tzinfo\n\nEastern = USTimeZone(-5, 'Eastern', 'EST', 'EDT')\nnow_tz_aware = now.replace(tzinfo=Eastern)\nprint now_tz_aware\n\noutput:\n2010-01-18 17:08:02.741482\nNone\n2010-01-18 17:08:02.741482-05:00\n\n"
] |
[
64,
7,
0
] |
[] |
[] |
[
"datetime",
"google_app_engine",
"python",
"tzinfo"
] |
stackoverflow_0002089419_datetime_google_app_engine_python_tzinfo.txt
|
Q:
Python NameError
list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
for item in list1:
print item
Not sure why the above code is throwing this error:
NameError: "name 'a' is not defined"
A:
In addition to using quotes properly, don't retype the alphabet.
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> L = list(string.ascii_lowercase)
>>> print L
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ...
>>> help(string)
A:
You have to put strings into (double) quotes
list1 = ["a","b","c",...]
should work
A:
String literal should be enclosed in quotes :)
list1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
A:
Picking and choosing the best of the previous posts this is how I would do it since a string can be iterated.
>>> import string
>>> for letter in string.ascii_lowercase:
... print(letter)
...
A:
python interprets the members in your list as variables,you shoud enclose them in
' or
"
A:
Every language needs to differentiate between constants and names/variables. The most confusing is when you have to differentiate between string constants and identifiers/names/variables.
A shell (sh, bash, ksh, csh, cmd.com etc) tends to use constants; so you can just type a constant and you prefix a name/variable with a special character ($ for unix shells, % for cmd.com etc) when you want its value.
$ echo hello
hello
$ echo $PWD
/home/tzot
$ cd /tmp
$ cd $OLDPWD
Most other generic programming languages tend to use variables much more than constants, so it's the other way around: you just type the name of a variable and you (typically) enclose string constants in quotes ('', "", [] etc):
# assumed: a_name= "the object it points to"
>>> print ("a constant")
a constant
>>> print (a_name)
the object it points to
A:
When I need to make a list of characters, if they aren't already available in something defined in the std lib, and if I really need a list and not just a string, I use this form:
punc = list(r";:`~!@#$%^&*()_-+=[]{}\|,./<?>")
vowels = list("aeiou") # or sometimes list("aeiouy")
Much simpler than all those extra quotes and commas, and it's clear to the reader that I really meant I wanted a list, and not just a string.
|
Python NameError
|
list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
for item in list1:
print item
Not sure why the above code is throwing this error:
NameError: "name 'a' is not defined"
|
[
"In addition to using quotes properly, don't retype the alphabet.\n>>> import string\n>>> string.ascii_lowercase\n'abcdefghijklmnopqrstuvwxyz'\n>>> L = list(string.ascii_lowercase)\n>>> print L\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ...\n>>> help(string)\n\n",
"You have to put strings into (double) quotes\nlist1 = [\"a\",\"b\",\"c\",...] \n\nshould work\n",
"String literal should be enclosed in quotes :)\nlist1 = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n\n",
"Picking and choosing the best of the previous posts this is how I would do it since a string can be iterated.\n>>> import string\n>>> for letter in string.ascii_lowercase:\n... print(letter)\n... \n\n",
"python interprets the members in your list as variables,you shoud enclose them in \n\n' or \n \"\n\n",
"Every language needs to differentiate between constants and names/variables. The most confusing is when you have to differentiate between string constants and identifiers/names/variables.\nA shell (sh, bash, ksh, csh, cmd.com etc) tends to use constants; so you can just type a constant and you prefix a name/variable with a special character ($ for unix shells, % for cmd.com etc) when you want its value.\n$ echo hello\nhello\n$ echo $PWD\n/home/tzot\n$ cd /tmp\n$ cd $OLDPWD\n\nMost other generic programming languages tend to use variables much more than constants, so it's the other way around: you just type the name of a variable and you (typically) enclose string constants in quotes ('', \"\", [] etc):\n# assumed: a_name= \"the object it points to\"\n\n>>> print (\"a constant\")\na constant\n>>> print (a_name)\nthe object it points to\n\n",
"When I need to make a list of characters, if they aren't already available in something defined in the std lib, and if I really need a list and not just a string, I use this form:\npunc = list(r\";:`~!@#$%^&*()_-+=[]{}\\|,./<?>\")\nvowels = list(\"aeiou\") # or sometimes list(\"aeiouy\")\n\nMuch simpler than all those extra quotes and commas, and it's clear to the reader that I really meant I wanted a list, and not just a string.\n"
] |
[
12,
7,
2,
1,
1,
1,
0
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0002081168_python_syntax.txt
|
Q:
Server Setup for iPhone Push Notifications
I'm new to the whole push notifications thing, and was wondering if somebody could walk me through the process of getting a simple application up and running. I currently rent a server that I use to serve my website that runs cPanel X.
How would I go about setting up the service? What software do I need to install on the server? How do I upload code to the server?
Sorry if these are really dumb questions - I'm not really a web developer.
Thanks in advance!
A:
I would go to the Apple Developer Forums. They have many questions and answers regarding this. For my apps, I use a Ruby On Rails plugin called apn_on_rails, but this is probably not an option for you on a shared host with some sort of admin gui. Your shared host probably runs php so I would look for a php implementation.
|
Server Setup for iPhone Push Notifications
|
I'm new to the whole push notifications thing, and was wondering if somebody could walk me through the process of getting a simple application up and running. I currently rent a server that I use to serve my website that runs cPanel X.
How would I go about setting up the service? What software do I need to install on the server? How do I upload code to the server?
Sorry if these are really dumb questions - I'm not really a web developer.
Thanks in advance!
|
[
"I would go to the Apple Developer Forums. They have many questions and answers regarding this. For my apps, I use a Ruby On Rails plugin called apn_on_rails, but this is probably not an option for you on a shared host with some sort of admin gui. Your shared host probably runs php so I would look for a php implementation.\n"
] |
[
3
] |
[] |
[] |
[
"iphone",
"push_notification",
"python",
"ruby_on_rails"
] |
stackoverflow_0002089701_iphone_push_notification_python_ruby_on_rails.txt
|
Q:
Rotate a quad around a centre point in OpenGL
I'm making a 2D game. I want to be able to render a texture on the screen after rotating it a certain amount around a centre point. Basically this is for a level rotation around a player. The player position being the rotation point and the direction of the player as the angle. This code wont work:
def draw_texture(texture,offset,size,a,rounded,rotation,point):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glColor4f(1,1,1,float(a)/255.0)
glTranslatef(point[0],point[1],0)
glRotatef(rotation,0,0,1)
glBindTexture(GL_TEXTURE_2D, texture)
if rounded == 0:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2i(*offset) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2i(offset[0],offset[1] + size[1]) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2i(offset[0] + size[0],offset[1] + size[1]) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2i(offset[0] + size[0],offset[1]) #Top, Right
glEnd()
else:
#Nothing important here
glEnd()
Any way to get it working? Thank you.
A:
try reversing
glTranslatef(point[0],point[1],0)
and
glRotatef(rotation,0,0,1)
you're translating to the player, but then rotating about the origin (not the player)
Illustration from the red book:
A:
Unless you have a good reason to do otherwise, I'd leave the drawing code alone, and just change the camera angle. Probably the easiest way to do that is use gluLookAt. In your case, you'll apparently be looking at the player's position, and just change the "up direction", which is given in the last two parameters.
|
Rotate a quad around a centre point in OpenGL
|
I'm making a 2D game. I want to be able to render a texture on the screen after rotating it a certain amount around a centre point. Basically this is for a level rotation around a player. The player position being the rotation point and the direction of the player as the angle. This code wont work:
def draw_texture(texture,offset,size,a,rounded,rotation,point):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glColor4f(1,1,1,float(a)/255.0)
glTranslatef(point[0],point[1],0)
glRotatef(rotation,0,0,1)
glBindTexture(GL_TEXTURE_2D, texture)
if rounded == 0:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2i(*offset) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2i(offset[0],offset[1] + size[1]) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2i(offset[0] + size[0],offset[1] + size[1]) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2i(offset[0] + size[0],offset[1]) #Top, Right
glEnd()
else:
#Nothing important here
glEnd()
Any way to get it working? Thank you.
|
[
"try reversing\nglTranslatef(point[0],point[1],0)\n\nand\nglRotatef(rotation,0,0,1)\n\nyou're translating to the player, but then rotating about the origin (not the player)\nIllustration from the red book: \n",
"Unless you have a good reason to do otherwise, I'd leave the drawing code alone, and just change the camera angle. Probably the easiest way to do that is use gluLookAt. In your case, you'll apparently be looking at the player's position, and just change the \"up direction\", which is given in the last two parameters.\n"
] |
[
2,
0
] |
[] |
[] |
[
"opengl",
"primitive",
"python",
"rotation",
"textures"
] |
stackoverflow_0002089849_opengl_primitive_python_rotation_textures.txt
|
Q:
Interpreter that ignores leading >>> characters and ellipsis
I am studying some examples in a tutorial where there are a lot of leading >>> characters and ellipsis in the text. This makes it hard to cut and paste into the IPython interpreter since it doesn't like these strings.
Is there another interpreter I could use that will appropriately ignore and interpret these leading terms?
For example, I cannot paste the following directly into the interpreter:
>>> d = dict(x.__array_interface__)
>>> d['shape'] = (3, 2, 5)
>>> d['strides'] = (20, 20, 4)
>>> class Arr:
... __array_interface__ = d
... base = x
A:
IPython can do this (look at the %paste magic command)
A:
In any case, a way to clean up such stuff by python code:
import re
matcher= re.compile("(?m)^[.>]{3} ")
def cleanup(text):
return matcher.sub('', text)
Example use:
>>> print (cleanup(""">>> d = dict(x.__array_interface__)
>>> d['shape'] = (3, 2, 5)
>>> d['strides'] = (20, 20, 4)
>>> class Arr:
... __array_interface__ = d
... base = x"""))
|
Interpreter that ignores leading >>> characters and ellipsis
|
I am studying some examples in a tutorial where there are a lot of leading >>> characters and ellipsis in the text. This makes it hard to cut and paste into the IPython interpreter since it doesn't like these strings.
Is there another interpreter I could use that will appropriately ignore and interpret these leading terms?
For example, I cannot paste the following directly into the interpreter:
>>> d = dict(x.__array_interface__)
>>> d['shape'] = (3, 2, 5)
>>> d['strides'] = (20, 20, 4)
>>> class Arr:
... __array_interface__ = d
... base = x
|
[
"IPython can do this (look at the %paste magic command)\n",
"In any case, a way to clean up such stuff by python code:\nimport re\nmatcher= re.compile(\"(?m)^[.>]{3} \")\ndef cleanup(text):\n return matcher.sub('', text)\n\nExample use:\n>>> print (cleanup(\"\"\">>> d = dict(x.__array_interface__)\n>>> d['shape'] = (3, 2, 5)\n>>> d['strides'] = (20, 20, 4)\n\n>>> class Arr:\n... __array_interface__ = d\n... base = x\"\"\"))\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"ide",
"interpreter",
"python"
] |
stackoverflow_0002066061_ide_interpreter_python.txt
|
Q:
Python 3 Library for Realtime Midi Communication
Can anyone suggest a good Python 3 Library for sending / receiving reatime MIDI?
A:
Why Python 3? It generally doesn't have many libraries yet. Generally you want to look into high-level C-libraries with Python wrappers. I doubt many of these work under Python 3 at the moment.
|
Python 3 Library for Realtime Midi Communication
|
Can anyone suggest a good Python 3 Library for sending / receiving reatime MIDI?
|
[
"Why Python 3? It generally doesn't have many libraries yet. Generally you want to look into high-level C-libraries with Python wrappers. I doubt many of these work under Python 3 at the moment. \n"
] |
[
1
] |
[] |
[] |
[
"midi",
"python",
"python_3.x"
] |
stackoverflow_0001742382_midi_python_python_3.x.txt
|
Q:
How to format search autocompletion part lists?
I'm currently working on an AppEngine project, and I'd like to implement autocompletion of search terms. The items that can be searched for are reasonably unambiguous and short, so I was thinking of implementing it by giving each item a list of incomplete typings. So foobar would get a list like [f, fo, foo, foob, fooba, foobar]. The user's text in the searchbox is then compared to this list, and positive matches are suggested.
There are a couple of possible optimizations in this list that I was thinking of:
Removing spaces punctuation from search terms. Foo. Bar to FooBar.
Removing capital letters
Removing leading particles like "the", "a", "an". The Guy would be guy, and indexed as [g, gu, guy].
Only adding substring longer than 2 or 3 to the indexing list. So The Guy would be indexed as [gu, guy]. I thought that suggestions that only match the first letter would not be so relevant.
The users search term would also be formatted in this way, after which the DB is searched. Upon suggesting a search term, the particles, punctuation, and capital letters would be added according to the suggested object's full name. So searching for "the" would give no suggestions, but searching for "The Gu.." or "gu" would suggest "The Guy".
Is this a good idea? Mainly: would this formatting help, or only cause trouble?
A:
I have already run into the same problem and the solution that I adopted was very similar to your idea. I split the items into words, convert them to lowercase, remove accents, and create a list of startings. For instance, "Báz Bar" would become ['b', 'ba', 'bar', 'baz'].
I have posted the code in this thread. The search box of this site is using it. Feel free to use it if you like.
|
How to format search autocompletion part lists?
|
I'm currently working on an AppEngine project, and I'd like to implement autocompletion of search terms. The items that can be searched for are reasonably unambiguous and short, so I was thinking of implementing it by giving each item a list of incomplete typings. So foobar would get a list like [f, fo, foo, foob, fooba, foobar]. The user's text in the searchbox is then compared to this list, and positive matches are suggested.
There are a couple of possible optimizations in this list that I was thinking of:
Removing spaces punctuation from search terms. Foo. Bar to FooBar.
Removing capital letters
Removing leading particles like "the", "a", "an". The Guy would be guy, and indexed as [g, gu, guy].
Only adding substring longer than 2 or 3 to the indexing list. So The Guy would be indexed as [gu, guy]. I thought that suggestions that only match the first letter would not be so relevant.
The users search term would also be formatted in this way, after which the DB is searched. Upon suggesting a search term, the particles, punctuation, and capital letters would be added according to the suggested object's full name. So searching for "the" would give no suggestions, but searching for "The Gu.." or "gu" would suggest "The Guy".
Is this a good idea? Mainly: would this formatting help, or only cause trouble?
|
[
"I have already run into the same problem and the solution that I adopted was very similar to your idea. I split the items into words, convert them to lowercase, remove accents, and create a list of startings. For instance, \"Báz Bar\" would become ['b', 'ba', 'bar', 'baz']. \nI have posted the code in this thread. The search box of this site is using it. Feel free to use it if you like.\n"
] |
[
2
] |
[] |
[] |
[
"autocomplete",
"autosuggest",
"google_app_engine",
"python",
"search"
] |
stackoverflow_0002089917_autocomplete_autosuggest_google_app_engine_python_search.txt
|
Q:
How to send a string from a python script at Google App Engine to the browser client as a file
I have a python web-application running inside the Google App Engine.
The application creates on user-demand a string and I want the string to be send to the browser client (application/octet-stream?) as a file.
How can i realize this?
A:
If you're using App Engine's own, simple webapp framework, the simplest approach is to have as the get method of your request handler object something like:
def get(self):
thestring = 'helloworld' # or however else it's synthesized;-)
self.response.headers.add_header(
'content-disposition', 'attachment', filename='hw.txt')
self.response.out.write(thestring)
Of course, you can use more sophisticated approaches, if you have other different goals, but this meets your goal as stated.
A:
Setting a content-disposition: attachment header will cause most browsers to download whatever you send them as a file. Safari sometimes ignores it.
|
How to send a string from a python script at Google App Engine to the browser client as a file
|
I have a python web-application running inside the Google App Engine.
The application creates on user-demand a string and I want the string to be send to the browser client (application/octet-stream?) as a file.
How can i realize this?
|
[
"If you're using App Engine's own, simple webapp framework, the simplest approach is to have as the get method of your request handler object something like:\ndef get(self):\n thestring = 'helloworld' # or however else it's synthesized;-)\n self.response.headers.add_header(\n 'content-disposition', 'attachment', filename='hw.txt')\n self.response.out.write(thestring)\n\nOf course, you can use more sophisticated approaches, if you have other different goals, but this meets your goal as stated.\n",
"Setting a content-disposition: attachment header will cause most browsers to download whatever you send them as a file. Safari sometimes ignores it.\n"
] |
[
3,
0
] |
[] |
[] |
[
"google_app_engine",
"html",
"mime_types",
"python"
] |
stackoverflow_0002089635_google_app_engine_html_mime_types_python.txt
|
Q:
Printing correct time using timezones, Python
Extends
Ok, we are not having a good day today.
When you attach the correct tzinfo object to a datetime instance, and then you strftime() it, it STILL comes out in UTC, seemingly ignoring the beautiful tzinfo object I attached to it.
# python 2.5.4
now = datetime.now()
print now.strftime( "%a %b %d %X" ) # %X is "locale's appropriate time rep"
pst = now.replace( tzinfo=Pacific )
print pst.strftime( "%a %b %d %X" )
We get:
Mon Jan 18 17:30:16
Mon Jan 18 17:30:16
I found if I add %z, I can add the difference its supposed to have computed:
Mon Jan 18 17:32:38
Mon Jan 18 17:32:38 -0800
It just tacks on the -8 there, as if to say, "you do it yourself, foo."
But I want strftime() to simply give me a string WITH PRECOMPUTED LOCAL TIME.
How can I get strftime() to do the hour subtraction math for me when I strftime() it?
The full code I'm using is below.
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
# A class capturing the platform's idea of local time.
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
# In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.
# which is the first Sunday on or after Oct 25.
DSTEND = datetime(1, 10, 25, 1)
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
# Find first Sunday in April & the last in October.
start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
#Central = USTimeZone(-6, "Central", "CST", "CDT")
#Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
now = datetime.now()
print now.strftime( "%a %b %d %X %z" )
pst = now.replace( tzinfo=Pacific )
print pst.strftime( "%a %b %d %X %z" )
A:
.replace does no computation: it simply replaces one or more field in the new returned object, while copying all others from the object it's called on.
If I understand your situation correctly, you start with a datetime object which you know (through other means) is UTC, but doesn't know that itself (is has a tzinfo attribute of None, meaning "I'm totally clueless regarding what timezone I'm in).
So, first, you make a timezone-aware from your input timezone-naive object, in order to inform it that it's in timezone UTC (all other fields just get copied over):
aware = naive.replace(tzinfo=utc)
Then, you can request computations regarding timezones, and printing in consequence:
print aware.astimezone(Pacific).strftime('%a %b %d %X %z')
A:
With dt.replace(tzinfo=tz) you're not really converting the time value, you're just saying 'hey no, wait, this time was actually in PDT, not in UTC'. You'll probably want to use datetime.astimezone(tz) instead.
A:
I think Wim had the right idea, just backwards. If you want to know what your time would be in UTC, use:
print pst.astimezone(UTC).strftime( "%a %b %d %X" )
You'll have to dig up a definition for a UTC timezone class. I understand why Python didn't want to supply a default implementation of every possible tzinfo, but UTC should have been included in the base package.
|
Printing correct time using timezones, Python
|
Extends
Ok, we are not having a good day today.
When you attach the correct tzinfo object to a datetime instance, and then you strftime() it, it STILL comes out in UTC, seemingly ignoring the beautiful tzinfo object I attached to it.
# python 2.5.4
now = datetime.now()
print now.strftime( "%a %b %d %X" ) # %X is "locale's appropriate time rep"
pst = now.replace( tzinfo=Pacific )
print pst.strftime( "%a %b %d %X" )
We get:
Mon Jan 18 17:30:16
Mon Jan 18 17:30:16
I found if I add %z, I can add the difference its supposed to have computed:
Mon Jan 18 17:32:38
Mon Jan 18 17:32:38 -0800
It just tacks on the -8 there, as if to say, "you do it yourself, foo."
But I want strftime() to simply give me a string WITH PRECOMPUTED LOCAL TIME.
How can I get strftime() to do the hour subtraction math for me when I strftime() it?
The full code I'm using is below.
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
# A class capturing the platform's idea of local time.
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
# In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.
# which is the first Sunday on or after Oct 25.
DSTEND = datetime(1, 10, 25, 1)
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
# Find first Sunday in April & the last in October.
start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
#Central = USTimeZone(-6, "Central", "CST", "CDT")
#Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
now = datetime.now()
print now.strftime( "%a %b %d %X %z" )
pst = now.replace( tzinfo=Pacific )
print pst.strftime( "%a %b %d %X %z" )
|
[
".replace does no computation: it simply replaces one or more field in the new returned object, while copying all others from the object it's called on.\nIf I understand your situation correctly, you start with a datetime object which you know (through other means) is UTC, but doesn't know that itself (is has a tzinfo attribute of None, meaning \"I'm totally clueless regarding what timezone I'm in).\nSo, first, you make a timezone-aware from your input timezone-naive object, in order to inform it that it's in timezone UTC (all other fields just get copied over):\naware = naive.replace(tzinfo=utc)\n\nThen, you can request computations regarding timezones, and printing in consequence:\nprint aware.astimezone(Pacific).strftime('%a %b %d %X %z')\n\n",
"With dt.replace(tzinfo=tz) you're not really converting the time value, you're just saying 'hey no, wait, this time was actually in PDT, not in UTC'. You'll probably want to use datetime.astimezone(tz) instead.\n",
"I think Wim had the right idea, just backwards. If you want to know what your time would be in UTC, use:\nprint pst.astimezone(UTC).strftime( \"%a %b %d %X\" )\n\nYou'll have to dig up a definition for a UTC timezone class. I understand why Python didn't want to supply a default implementation of every possible tzinfo, but UTC should have been included in the base package.\n"
] |
[
15,
5,
2
] |
[] |
[] |
[
"datetime",
"python",
"tzinfo"
] |
stackoverflow_0002089706_datetime_python_tzinfo.txt
|
Q:
Google app engine after refresh from datastore
I want to set the .tzinfo of every datetime instance automatically as soon as it comes out of the datastore.
So if I have
class Message( db.Model ):
creationTime = db.DateTimeProperty()
someOtherTime = db.DateTimeProperty()
## I really want to define a method like this,
## that runs immediately AFTER an instance has
## been refreshed from the datastore
def wakeup( self ):
self.creationTime.tzinfo = self.creationTime.replace( tzinfo=EST )
self.someOtherTime.tzinfo = self.creationTime.replace( tzinfo=EST )
Is it possible to do this in GAE?
A:
I think the best approach is for you to subclass the DateTimeProperty class and override its method make_value_from_datastore:
class EstDateTimeProperty(db.DateTimeProperty):
def make_value_from_datastore(self, value):
naive_utc = db.DateTimeProperty(self, value)
aware_utc = naive_utc.replace(tzinfo=UTC)
return aware_utc.astimezone(EST)
given suitable tzinfo objects UTC and EST of course (built by pytz or whatever). Of course you could also build a more generic "smart datetime" property class and let it set the timezone of interest from a keyword argument in its __init__, for example, if you need several different datetime attributes to use different timezones.
A:
IMHO, this is not the best way to handle timezones in GAE. From the docs:
If the datetime value has a tzinfo attribute, it will be converted to the UTC time zone for storage. Values come back from the datastore as UTC, with a tzinfo of None. An application that needs date and time values to be in a particular time zone must set tzinfo correctly when updating the value, and convert values to the timezone when accessing the value.
So,
To handle creation dates or last modification dates, use auto_now and auto_now_add arguments.
To display dates to users, convert them like this pacific_time = utc_time.astimezone(Pacific_tzinfo())
When updating the datastore, set the tzinfo attribute using the replace function: date_from_user.replace(tzinfo=EST)
|
Google app engine after refresh from datastore
|
I want to set the .tzinfo of every datetime instance automatically as soon as it comes out of the datastore.
So if I have
class Message( db.Model ):
creationTime = db.DateTimeProperty()
someOtherTime = db.DateTimeProperty()
## I really want to define a method like this,
## that runs immediately AFTER an instance has
## been refreshed from the datastore
def wakeup( self ):
self.creationTime.tzinfo = self.creationTime.replace( tzinfo=EST )
self.someOtherTime.tzinfo = self.creationTime.replace( tzinfo=EST )
Is it possible to do this in GAE?
|
[
"I think the best approach is for you to subclass the DateTimeProperty class and override its method make_value_from_datastore:\nclass EstDateTimeProperty(db.DateTimeProperty):\n def make_value_from_datastore(self, value):\n naive_utc = db.DateTimeProperty(self, value)\n aware_utc = naive_utc.replace(tzinfo=UTC)\n return aware_utc.astimezone(EST)\n\ngiven suitable tzinfo objects UTC and EST of course (built by pytz or whatever). Of course you could also build a more generic \"smart datetime\" property class and let it set the timezone of interest from a keyword argument in its __init__, for example, if you need several different datetime attributes to use different timezones.\n",
"IMHO, this is not the best way to handle timezones in GAE. From the docs:\n\nIf the datetime value has a tzinfo attribute, it will be converted to the UTC time zone for storage. Values come back from the datastore as UTC, with a tzinfo of None. An application that needs date and time values to be in a particular time zone must set tzinfo correctly when updating the value, and convert values to the timezone when accessing the value.\n\nSo, \n\nTo handle creation dates or last modification dates, use auto_now and auto_now_add arguments.\nTo display dates to users, convert them like this pacific_time = utc_time.astimezone(Pacific_tzinfo())\nWhen updating the datastore, set the tzinfo attribute using the replace function: date_from_user.replace(tzinfo=EST)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002089746_google_app_engine_python.txt
|
Q:
How can I process xml asynchronously in python?
I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available node off the queue and process it.
I have the following (it should have locks, I know - it will, later)
import sys, time
import xml.parsers.expat
import threading
q = []
def start_handler(name, attrs):
q.append(name)
def do_expat():
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_handler
p.buffer_text = True
print("opening {0}".format(sys.argv[1]))
with open(sys.argv[1]) as f:
print("file is open")
p.ParseFile(f)
print("parsing complete")
t = threading.Thread(group=None, target=do_expat)
t.start()
while True:
print(q)
time.sleep(1)
The problem is that the body of the while block gets called only once, and then I can't even ctrl-C interrupt it. On smaller files, the output is as expected, but that seems to indicate that the handler only gets called when the document is fully parsed, which seems to defeat the purpose of a SAX parser.
I'm sure it's my own ignorance, but I don't see where I'm making the mistake.
PS: I also tried changing start_handler thus:
def start_handler(name, attrs):
def app():
q.append(name)
u = threading.Thread(group=None, target=app)
u.start()
No love, though.
A:
I'm not too sure about this problem. I'm guessing the call to ParseFile is blocking and only the parsing thread is being run because of the GIL. A way around this would be to use multiprocessing instead. It's designed to work with queues, anyway.
You make a Process and you can pass it a Queue:
import sys, time
import xml.parsers.expat
import multiprocessing
import Queue
def do_expat(q):
p = xml.parsers.expat.ParserCreate()
def start_handler(name, attrs):
q.put(name)
p.StartElementHandler = start_handler
p.buffer_text = True
print("opening {0}".format(sys.argv[1]))
with open(sys.argv[1]) as f:
print("file is open")
p.ParseFile(f)
print("parsing complete")
if __name__ == '__main__':
q = multiprocessing.Queue()
process = multiprocessing.Process(target=do_expat, args=(q,))
process.start()
elements = []
while True:
while True:
try:
elements.append(q.get_nowait())
except Queue.Empty:
break
print elements
time.sleep(1)
I've included an elements list, just to replicate your original script. Your final solution will probably use get_nowait and a Pool or something similar.
A:
ParseFile, as you've noticed, just "gulps down" everything -- no good for the incremental parsing you want to do! So, just feed the file to the parser a bit at a time, making sure to conditionally yield control to other threads as you go -- e.g.:
while True:
data = f.read(BUFSIZE)
if not data:
p.Parse('', True)
break
p.Parse(data, False)
time.sleep(0.0)
the time.sleep(0.0) call is Python's way to say "yield to other threads if any are ready and waiting"; the Parse method is documented here.
The second point is, forget locks for this usage! -- use Queue.Queue instead, it's intrinsically threadsafe and almost invariably the best and simplest way to coordinate multiple threads in Python. Just make a Queue instance q, q.put(name) on it, and have worked threads block on q.get() waiting to get some more work to do -- it's SO simple!
(There are several auxiliary strategies you can use to coordinate the termination of worker threads when there's no more work for them to do, but the simplest, absent special requirements, is to just make them daemon threads, so they will all terminate when the main thread does -- see the docs).
A:
The only thing I see is wrong is that you are accessing q simultaneously from different threads - no locking as you write indeed. That is asking for trouble - and you're probably getting trouble in the form of the Python interpreter locking up on you. :)
Try locking, it's really not very difficult:
import sys, time
import xml.parsers.expat
import threading
q = []
q_lock = threading.Lock() <---
def start_handler(name, attrs):
q_lock.acquire() <---
q.append(name)
q_lock.release() <---
def do_expat():
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_handler
p.buffer_text = True
print("opening {0}".format(sys.argv[1]))
with open(sys.argv[1]) as f:
print("file is open")
p.ParseFile(f)
print("parsing complete")
t = threading.Thread(group=None, target=do_expat)
t.start()
while True:
q_lock.acquire() <---
print(q)
q_lock.release() <---
time.sleep(1)
You see, it was really simple, we just created a lock variable to guard our object, and acquire that lock every time before we use the object and release every time after we finished our task on the object. This way we guaranteed that q.append(name) will never overlap with print(q).
(With newer versions of Python there is also a "with .... " syntax that helps you not to release locks or close files or other cleanups one frequently forgets.)
A:
I do not know a whole lot about the implementation, but if the parse is C code that executes until complete, other Python threads will not run. If the parser is calling back out to Python code, the GIL may be released for other threads to run, but I am not sure about that. You might want to check those details.
|
How can I process xml asynchronously in python?
|
I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available node off the queue and process it.
I have the following (it should have locks, I know - it will, later)
import sys, time
import xml.parsers.expat
import threading
q = []
def start_handler(name, attrs):
q.append(name)
def do_expat():
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_handler
p.buffer_text = True
print("opening {0}".format(sys.argv[1]))
with open(sys.argv[1]) as f:
print("file is open")
p.ParseFile(f)
print("parsing complete")
t = threading.Thread(group=None, target=do_expat)
t.start()
while True:
print(q)
time.sleep(1)
The problem is that the body of the while block gets called only once, and then I can't even ctrl-C interrupt it. On smaller files, the output is as expected, but that seems to indicate that the handler only gets called when the document is fully parsed, which seems to defeat the purpose of a SAX parser.
I'm sure it's my own ignorance, but I don't see where I'm making the mistake.
PS: I also tried changing start_handler thus:
def start_handler(name, attrs):
def app():
q.append(name)
u = threading.Thread(group=None, target=app)
u.start()
No love, though.
|
[
"I'm not too sure about this problem. I'm guessing the call to ParseFile is blocking and only the parsing thread is being run because of the GIL. A way around this would be to use multiprocessing instead. It's designed to work with queues, anyway.\nYou make a Process and you can pass it a Queue:\nimport sys, time\nimport xml.parsers.expat\nimport multiprocessing\nimport Queue\n\ndef do_expat(q):\n p = xml.parsers.expat.ParserCreate()\n\n def start_handler(name, attrs):\n q.put(name)\n\n p.StartElementHandler = start_handler\n p.buffer_text = True\n print(\"opening {0}\".format(sys.argv[1]))\n with open(sys.argv[1]) as f:\n print(\"file is open\")\n p.ParseFile(f)\n print(\"parsing complete\")\n\nif __name__ == '__main__':\n q = multiprocessing.Queue()\n process = multiprocessing.Process(target=do_expat, args=(q,))\n process.start()\n\n elements = []\n while True:\n while True:\n try:\n elements.append(q.get_nowait())\n except Queue.Empty:\n break\n\n print elements\n time.sleep(1)\n\nI've included an elements list, just to replicate your original script. Your final solution will probably use get_nowait and a Pool or something similar.\n",
"ParseFile, as you've noticed, just \"gulps down\" everything -- no good for the incremental parsing you want to do! So, just feed the file to the parser a bit at a time, making sure to conditionally yield control to other threads as you go -- e.g.:\nwhile True:\n data = f.read(BUFSIZE)\n if not data:\n p.Parse('', True)\n break\n p.Parse(data, False)\n time.sleep(0.0)\n\nthe time.sleep(0.0) call is Python's way to say \"yield to other threads if any are ready and waiting\"; the Parse method is documented here.\nThe second point is, forget locks for this usage! -- use Queue.Queue instead, it's intrinsically threadsafe and almost invariably the best and simplest way to coordinate multiple threads in Python. Just make a Queue instance q, q.put(name) on it, and have worked threads block on q.get() waiting to get some more work to do -- it's SO simple!\n(There are several auxiliary strategies you can use to coordinate the termination of worker threads when there's no more work for them to do, but the simplest, absent special requirements, is to just make them daemon threads, so they will all terminate when the main thread does -- see the docs).\n",
"The only thing I see is wrong is that you are accessing q simultaneously from different threads - no locking as you write indeed. That is asking for trouble - and you're probably getting trouble in the form of the Python interpreter locking up on you. :)\nTry locking, it's really not very difficult:\nimport sys, time\nimport xml.parsers.expat\nimport threading\n\nq = []\nq_lock = threading.Lock() <---\n\ndef start_handler(name, attrs):\n q_lock.acquire() <---\n q.append(name)\n q_lock.release() <---\n\ndef do_expat():\n p = xml.parsers.expat.ParserCreate()\n p.StartElementHandler = start_handler\n p.buffer_text = True\n print(\"opening {0}\".format(sys.argv[1]))\n with open(sys.argv[1]) as f:\n print(\"file is open\")\n p.ParseFile(f)\n print(\"parsing complete\")\n\n\nt = threading.Thread(group=None, target=do_expat)\nt.start()\n\nwhile True:\n q_lock.acquire() <---\n print(q)\n q_lock.release() <---\n time.sleep(1)\n\nYou see, it was really simple, we just created a lock variable to guard our object, and acquire that lock every time before we use the object and release every time after we finished our task on the object. This way we guaranteed that q.append(name) will never overlap with print(q).\n\n(With newer versions of Python there is also a \"with .... \" syntax that helps you not to release locks or close files or other cleanups one frequently forgets.)\n",
"I do not know a whole lot about the implementation, but if the parse is C code that executes until complete, other Python threads will not run. If the parser is calling back out to Python code, the GIL may be released for other threads to run, but I am not sure about that. You might want to check those details.\n"
] |
[
8,
8,
1,
0
] |
[] |
[] |
[
"multithreading",
"python",
"sax",
"xml"
] |
stackoverflow_0002090096_multithreading_python_sax_xml.txt
|
Q:
python search replace using wildcards
somewhat confused.. but trying to do a search/repace using wildcards
if i have something like:
<blah.... ssf ff>
<bl.... ssf dfggg ff>
<b.... ssf ghhjj fhf>
and i want to replace all of the above strings with say,
<hh >t
any thoughts/comments on how this can be accomplished?
thanks
update (thanks for the comments!)
i'm missing something...
my initial sample text are:
Soo Choi</span>LONGEDITBOX">Apryl Berney
Soo Choi</span>LONGEDITBOX">Joel Franks
Joel Franks</span>GEDITBOX">Alexander Yamato
and i'm trying to get
Soo Choi foo Apryl Berney
Soo Choi foo Joel Franks
Joel Franks foo Alexander Yamato
i've tried derivations of
name=re.sub("</s[^>]*\">"," foo ",name)
but i'm missing something...
thoughts... thanks
A:
How about like this, with regex
import re
YOURTEXT=re.sub("<b[^>]*>","<hh >t",YOURTEXT)
A:
See the rather usable Python Regular Expression manual here, or for a more hands-on approach a Regular Expression HOWTO section 5.2 Search and Replace.
A:
don't have to use regex
for line in open("file"):
if "<" in line and ">" in line:
s=line.rstrip().split(">")
for n,i in enumerate(s):
if "<" in i:
ind=i.find("<")
s[n]=i[:ind] +"<hh "
print '>t'.join(s)
output
$ cat file
blah <blah.... ssf ff> blah
blah <bl.... ssf dfggg ff> blah <bl.... ssf dfggg ff>
blah <b.... ssf ghhjj fhf>
$ ./python.py
blah <hh >t blah
blah <hh >t blah <hh >t
blah <hh >t
A:
Sounds like a job for the "re" module, here's a little sample function for you although you could just use the one re.sub() line.
Use the "re" module, a simple re.sub should do the trick:
import re
def subit(msg):
# Use the below if the string is multiline
# subbed = re.compile("(<.*?>)" re.DOTALL).sub("(<hh >t", msg)
subbed = re.sub("(<.*?>)", "<hh >t", msg)
return subbed
# Your messages bundled into a list
msgs = ["blah <blah.... ssf ff> blah",
"blah <bl.... ssf dfggg ff> blah <bl.... ssf dfggg ff>",
"blah <b.... ssf ghhjj fhf>"]
# Iterate the messages and print the substitution results
for msg in msgs:
print subit(msg)
I would suggest taking a look at the docs for the "re" module, it is well documented and might help you achieve more accurate text manipulation/replacement.
|
python search replace using wildcards
|
somewhat confused.. but trying to do a search/repace using wildcards
if i have something like:
<blah.... ssf ff>
<bl.... ssf dfggg ff>
<b.... ssf ghhjj fhf>
and i want to replace all of the above strings with say,
<hh >t
any thoughts/comments on how this can be accomplished?
thanks
update (thanks for the comments!)
i'm missing something...
my initial sample text are:
Soo Choi</span>LONGEDITBOX">Apryl Berney
Soo Choi</span>LONGEDITBOX">Joel Franks
Joel Franks</span>GEDITBOX">Alexander Yamato
and i'm trying to get
Soo Choi foo Apryl Berney
Soo Choi foo Joel Franks
Joel Franks foo Alexander Yamato
i've tried derivations of
name=re.sub("</s[^>]*\">"," foo ",name)
but i'm missing something...
thoughts... thanks
|
[
"How about like this, with regex\nimport re\n\nYOURTEXT=re.sub(\"<b[^>]*>\",\"<hh >t\",YOURTEXT)\n\n",
"See the rather usable Python Regular Expression manual here, or for a more hands-on approach a Regular Expression HOWTO section 5.2 Search and Replace.\n",
"don't have to use regex\nfor line in open(\"file\"):\n if \"<\" in line and \">\" in line:\n s=line.rstrip().split(\">\")\n for n,i in enumerate(s):\n if \"<\" in i:\n ind=i.find(\"<\")\n s[n]=i[:ind] +\"<hh \"\n print '>t'.join(s)\n\noutput\n$ cat file\nblah <blah.... ssf ff> blah\nblah <bl.... ssf dfggg ff> blah <bl.... ssf dfggg ff>\nblah <b.... ssf ghhjj fhf>\n\n$ ./python.py\nblah <hh >t blah\nblah <hh >t blah <hh >t\nblah <hh >t\n\n",
"Sounds like a job for the \"re\" module, here's a little sample function for you although you could just use the one re.sub() line.\nUse the \"re\" module, a simple re.sub should do the trick:\nimport re\n\ndef subit(msg):\n # Use the below if the string is multiline\n # subbed = re.compile(\"(<.*?>)\" re.DOTALL).sub(\"(<hh >t\", msg)\n subbed = re.sub(\"(<.*?>)\", \"<hh >t\", msg)\n return subbed\n\n# Your messages bundled into a list\nmsgs = [\"blah <blah.... ssf ff> blah\",\n \"blah <bl.... ssf dfggg ff> blah <bl.... ssf dfggg ff>\",\n \"blah <b.... ssf ghhjj fhf>\"]\n\n# Iterate the messages and print the substitution results\nfor msg in msgs:\n print subit(msg)\n\nI would suggest taking a look at the docs for the \"re\" module, it is well documented and might help you achieve more accurate text manipulation/replacement.\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex",
"replace",
"search",
"wildcard"
] |
stackoverflow_0002090100_python_regex_replace_search_wildcard.txt
|
Q:
GObject.add_emission_hook usage
I was kindly directed to use GObject's "add_emission_hook" following a recent question on SO but I can't seem to find a usage example.
Does anyone have one to share, please?
A:
After a discussion with helpful folks on IRC #pygtk, here is what I came up with:
import gobject
class Signals(gobject.GObject):
__gsignals__ = {
"lastfm_username_changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) #@UndefinedVariable
}
def __init__(self):
gobject.GObject.__init__(self)
class Bus(object):
"""
Message Bus - Borg pattern
"""
_signals=Signals()
@classmethod
def emit(cls, name, *pa, **kwa):
cls._signals.emit(name, *pa, **kwa)
@classmethod
def add_emission_hook(cls, name, callback):
gobject.add_emission_hook(cls._signals, name, callback)
if __name__=="__main__":
def callback(self, data):
print "callback: data=%s" % data
Bus.add_emission_hook("lastfm_username_changed", callback)
Bus.emit("lastfm_username_changed", "jldupont")
|
GObject.add_emission_hook usage
|
I was kindly directed to use GObject's "add_emission_hook" following a recent question on SO but I can't seem to find a usage example.
Does anyone have one to share, please?
|
[
"After a discussion with helpful folks on IRC #pygtk, here is what I came up with:\nimport gobject\n\nclass Signals(gobject.GObject):\n\n __gsignals__ = {\n \"lastfm_username_changed\": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) #@UndefinedVariable\n }\n\n def __init__(self):\n gobject.GObject.__init__(self)\n\n\nclass Bus(object):\n \"\"\"\n Message Bus - Borg pattern\n \"\"\"\n _signals=Signals()\n\n @classmethod\n def emit(cls, name, *pa, **kwa):\n cls._signals.emit(name, *pa, **kwa)\n\n @classmethod\n def add_emission_hook(cls, name, callback):\n gobject.add_emission_hook(cls._signals, name, callback)\n\n\nif __name__==\"__main__\":\n\n def callback(self, data):\n print \"callback: data=%s\" % data\n\n Bus.add_emission_hook(\"lastfm_username_changed\", callback)\n\n Bus.emit(\"lastfm_username_changed\", \"jldupont\")\n\n"
] |
[
0
] |
[] |
[] |
[
"gobject",
"pygobject",
"python"
] |
stackoverflow_0002088451_gobject_pygobject_python.txt
|
Q:
Problems enabling a quit function in Python
I'm pretty new to programming in general and I'm creating a small game for my younger sister...
I have a while loop in which I want to have an option to quit the game, but none of the quitting techniques I know of seem to work:
#main game:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
if input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
if input_quit == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_event_quit == 'Quit':
sys.exit(1)
grateful for any help.
Thanks
-----UPDATE-----
Thanks for the advice, but it's still not working:
here's the updated code:
#import the required modules:
import easygui as gui
import os
#-----CLASS-----------------------------------
#Class:
class PotatoHead:
#Atributes:
def __init__(self):
self.data = game_data
self.first_name = self.data[0]
self.last_name = self.data[1]
self.gender = self.data[2]
self.colour = self.data[3]
self.fav_thing = self.data[4]
self.toys = []
self.toys.append(self.data[5])
self.age = '0.0'
self.hunger = '0.0'
self.health = '0.0'
self.fitness = '0.0'
self.education = '0.0'
self.happiness = '0.0'
self.tiredness = '0.0'
def check_p_h_stats(self):
self.toys_string = str(self.toys)
gui.msgbox(
msg = '''
Name: ''' + self.first_name + ' ' + self.last_name + '''
Gender: ''' + self.gender + '''
Colour: ''' + self.colour + '''
Favourite Thing: ''' + self.colour + '''
Toys:''' + self.toys_string + '''
Age: ''' + self.age + '''
Hunger: ''' + self.hunger + '''
Health: ''' + self.health + '''
Fitness: ''' + self.fitness + '''
Education: ''' + self.education + '''
Happiness: ''' + self.happiness + '''
Tiredness: ''' + self.tiredness + '''
''',
title = 'Potato Head Stats',
ok_button = 'Continue')
def change_favourite_thing(self):
new_fav_thing = gui.enterbox(
msg = 'Enter the new favourite thing:',
title = 'Change Favourite Thing',
default = 'Type Here')
self.fav_thing = new_fav_thing
#Methods:
#-----MAIN PROGRAM----------------------------
#set up game:
image = 'nest.gif'
game_choice = gui.ynbox(
msg = """Would you like to start a new game,
or load a previously saved one?""",
title = 'Start/Load Game',
choices = ('New Game', 'Load Game'),
image = image)
if game_choice == 1:
fieldNames = ['First Name', 'Last Name', 'Gender', 'Colour', 'Favourite Thing', 'First Toy']
new_p_head_data = []
new_p_head_data = gui.multenterbox(
msg = 'Fill in the starting information about your Potato Head:',
title = 'New Game',
fields = fieldNames,
values = ('', '', 'Male/Female', 'Red, Green, Blue, Yellow, White, Black', '', 'Choose either Rattle, Pacifier, Teddy, Doll, or Soft Ball'))
game_data = new_p_head_data
else:
gui.msgbox('This function is not yet supported, please start again...')
myPotatoHead = PotatoHead()
#main game:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
elif input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 'Quit':
sys.exit(1)
Am using PYthon 2.5.4 for Mac
and am using Easygui 0.83
Again, thanks for any advice
A:
I think this is your problem:
if input_quit == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
should be
if input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
Edit: the reason it's still not working, according to the EasyGui tutorial, is that ynbox returns 0 or 1, rather than the string values of the choices. So change to
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 1:
sys.exit(1)
A:
I think maybe your code
if input_quit == 'Quit':
should be
if input_event_1 == 'Quit':
just like your other checks? I'm not familiar with that buttonbox thingy but the discrepancy between this one check and the others is immediately jarring and jumps to the eye...
Edit: ah, found it, it's from easygui (mentioning what frameworks you're using would be helpful!-) -- yep, it returns the string associated to the button, so the change I suggested above is definitely the key point.
Also, changing all the if input_event_1 after the first one to elif input_event_1 (since it can't be equal to more than one string, why keep checking once you've found the one string it does equal?-), while not strictly necessary, would be an improvement.
A:
It is more elegant this way:
she_wants_to_play = true
while she_wants_to_play:
ask input
if input == quit:
she_wants_to_play = false
So you nicely quit the while loop, instead of hitting the system with a 10000 Ton weight.
A:
Few checkpoints
Did you import sys?
if input_event_quit == 'Quit': should be if input_quit == 'Quit':
|
Problems enabling a quit function in Python
|
I'm pretty new to programming in general and I'm creating a small game for my younger sister...
I have a while loop in which I want to have an option to quit the game, but none of the quitting techniques I know of seem to work:
#main game:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
if input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
if input_quit == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_event_quit == 'Quit':
sys.exit(1)
grateful for any help.
Thanks
-----UPDATE-----
Thanks for the advice, but it's still not working:
here's the updated code:
#import the required modules:
import easygui as gui
import os
#-----CLASS-----------------------------------
#Class:
class PotatoHead:
#Atributes:
def __init__(self):
self.data = game_data
self.first_name = self.data[0]
self.last_name = self.data[1]
self.gender = self.data[2]
self.colour = self.data[3]
self.fav_thing = self.data[4]
self.toys = []
self.toys.append(self.data[5])
self.age = '0.0'
self.hunger = '0.0'
self.health = '0.0'
self.fitness = '0.0'
self.education = '0.0'
self.happiness = '0.0'
self.tiredness = '0.0'
def check_p_h_stats(self):
self.toys_string = str(self.toys)
gui.msgbox(
msg = '''
Name: ''' + self.first_name + ' ' + self.last_name + '''
Gender: ''' + self.gender + '''
Colour: ''' + self.colour + '''
Favourite Thing: ''' + self.colour + '''
Toys:''' + self.toys_string + '''
Age: ''' + self.age + '''
Hunger: ''' + self.hunger + '''
Health: ''' + self.health + '''
Fitness: ''' + self.fitness + '''
Education: ''' + self.education + '''
Happiness: ''' + self.happiness + '''
Tiredness: ''' + self.tiredness + '''
''',
title = 'Potato Head Stats',
ok_button = 'Continue')
def change_favourite_thing(self):
new_fav_thing = gui.enterbox(
msg = 'Enter the new favourite thing:',
title = 'Change Favourite Thing',
default = 'Type Here')
self.fav_thing = new_fav_thing
#Methods:
#-----MAIN PROGRAM----------------------------
#set up game:
image = 'nest.gif'
game_choice = gui.ynbox(
msg = """Would you like to start a new game,
or load a previously saved one?""",
title = 'Start/Load Game',
choices = ('New Game', 'Load Game'),
image = image)
if game_choice == 1:
fieldNames = ['First Name', 'Last Name', 'Gender', 'Colour', 'Favourite Thing', 'First Toy']
new_p_head_data = []
new_p_head_data = gui.multenterbox(
msg = 'Fill in the starting information about your Potato Head:',
title = 'New Game',
fields = fieldNames,
values = ('', '', 'Male/Female', 'Red, Green, Blue, Yellow, White, Black', '', 'Choose either Rattle, Pacifier, Teddy, Doll, or Soft Ball'))
game_data = new_p_head_data
else:
gui.msgbox('This function is not yet supported, please start again...')
myPotatoHead = PotatoHead()
#main game:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
elif input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 'Quit':
sys.exit(1)
Am using PYthon 2.5.4 for Mac
and am using Easygui 0.83
Again, thanks for any advice
|
[
"I think this is your problem:\nif input_quit == 'Quit':\n input_quit = gui.ynbox(\n msg = 'Are you sure you want to quit?',\n\nshould be\nif input_event_1 == 'Quit':\n input_quit = gui.ynbox(\n msg = 'Are you sure you want to quit?',\n\nEdit: the reason it's still not working, according to the EasyGui tutorial, is that ynbox returns 0 or 1, rather than the string values of the choices. So change to\n elif input_event_1 == 'Quit':\n input_quit = gui.ynbox(\n msg = 'Are you sure you want to quit?',\n title = 'Confirm quit',\n choices = ('Quit', 'Cancel'))\n if input_quit == 1:\n sys.exit(1)\n\n",
"I think maybe your code\n if input_quit == 'Quit':\n\nshould be\n if input_event_1 == 'Quit':\n\njust like your other checks? I'm not familiar with that buttonbox thingy but the discrepancy between this one check and the others is immediately jarring and jumps to the eye...\nEdit: ah, found it, it's from easygui (mentioning what frameworks you're using would be helpful!-) -- yep, it returns the string associated to the button, so the change I suggested above is definitely the key point.\nAlso, changing all the if input_event_1 after the first one to elif input_event_1 (since it can't be equal to more than one string, why keep checking once you've found the one string it does equal?-), while not strictly necessary, would be an improvement.\n",
"It is more elegant this way:\nshe_wants_to_play = true\nwhile she_wants_to_play:\n ask input\n if input == quit:\n she_wants_to_play = false\n\nSo you nicely quit the while loop, instead of hitting the system with a 10000 Ton weight.\n",
"Few checkpoints\n\nDid you import sys?\nif input_event_quit == 'Quit': should be if input_quit == 'Quit':\n\n"
] |
[
2,
2,
0,
0
] |
[] |
[] |
[
"python",
"quit"
] |
stackoverflow_0002090582_python_quit.txt
|
Q:
how to drag image in a wxpython frame
what is the easiest way to drag an image ( or text) in a wx window ?
i need steps or a small example on how to do that.
thanx in advance
A:
Take a look at the PseudoDC example in the wxPython demo. The sample displays some random shapes within the window which you can grab and move around, you should be able to apply the concepts for an image.
You can download the win32-docs-demos from here
A:
Install wxpython demos, there is DragImage demostration in it.
|
how to drag image in a wxpython frame
|
what is the easiest way to drag an image ( or text) in a wx window ?
i need steps or a small example on how to do that.
thanx in advance
|
[
"Take a look at the PseudoDC example in the wxPython demo. The sample displays some random shapes within the window which you can grab and move around, you should be able to apply the concepts for an image. \nYou can download the win32-docs-demos from here\n",
"Install wxpython demos, there is DragImage demostration in it.\n"
] |
[
1,
0
] |
[] |
[] |
[
"drag_and_drop",
"drawing",
"gdi",
"python",
"wxpython"
] |
stackoverflow_0002062864_drag_and_drop_drawing_gdi_python_wxpython.txt
|
Q:
wxpython systray icon menu
I'm designing an application that I want to run in the background. There isn't any user interaction necessary, so I want the app to run invisibly save for a systray icon. I want that icon to have a menu that just opens the config/help files in notepad. Could someone point me in the right direction or provide an example?
A:
You can probably do this more cleanly but I have using some samples a while back I was able to create myself a class to handle the basic contruction of a taskbar icon.
TaskBarIcon.py
import wx
ID_SHOW_OPTION = wx.NewId()
ID_EDIT_OPTION = wx.NewId()
class Icon(wx.TaskBarIcon):
def __init__(self, parent, icon, tooltip):
wx.TaskBarIcon.__init__(self)
self.SetIcon(icon, tooltip)
self.parent = parent
self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnLeftDClick)
self.CreateMenu()
def CreateMenu(self):
self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnPopup)
self.menu = wx.Menu()
self.menu.Append(ID_SHOW_OPTION, '&Show Option 1')
self.menu.Append(ID_EDIT_OPTION, '&Edit Option 2')
self.menu.AppendSeparator()
self.menu.Append(wx.ID_EXIT, 'E&xit')
def OnPopup(self, event):
self.PopupMenu(self.menu)
def OnLeftDClick(self, event):
if self.parent.IsIconized():
self.parent.Iconize(False)
if not self.parent.IsShown():
self.parent.Show(True)
self.parent.Raise()
Within your Frame's init(), add the two lines below:
self.TrayIcon = tbi.Icon(self, wx.Icon("C:\\YourIcon.png", wx.BITMAP_TYPE_PNG), "ToolTip Help Text Here")
self.Bind(wx.EVT_ICONIZE, self.OnIconify)
And now just add this function to your frame and you should be set:
def OnIconify(self, event):
self.Hide()
Just remember to edit the items in the Icon class to suit your needs.
A:
Have you considered running this application as a windows service? Many users will consider a system tray icon with little to no functionality a nuisance. You could still provide links to help/config files as a start menu entry.
The python win32 extensions package should have support for python services.
Of course, there are still reasons why you may want to run this as a system tray icon. I'm sorry that I don't have any experience with that.
A:
You want the wx.TaskBarIcon:
http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html
The wxPython Demo has example code you can look at.
|
wxpython systray icon menu
|
I'm designing an application that I want to run in the background. There isn't any user interaction necessary, so I want the app to run invisibly save for a systray icon. I want that icon to have a menu that just opens the config/help files in notepad. Could someone point me in the right direction or provide an example?
|
[
"You can probably do this more cleanly but I have using some samples a while back I was able to create myself a class to handle the basic contruction of a taskbar icon.\nTaskBarIcon.py\nimport wx\n\n\nID_SHOW_OPTION = wx.NewId()\nID_EDIT_OPTION = wx.NewId()\n\n\nclass Icon(wx.TaskBarIcon):\n\n def __init__(self, parent, icon, tooltip):\n wx.TaskBarIcon.__init__(self)\n self.SetIcon(icon, tooltip)\n self.parent = parent\n self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnLeftDClick)\n self.CreateMenu()\n\n def CreateMenu(self):\n self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnPopup)\n self.menu = wx.Menu()\n self.menu.Append(ID_SHOW_OPTION, '&Show Option 1')\n self.menu.Append(ID_EDIT_OPTION, '&Edit Option 2')\n self.menu.AppendSeparator()\n self.menu.Append(wx.ID_EXIT, 'E&xit')\n\n def OnPopup(self, event):\n self.PopupMenu(self.menu)\n\n def OnLeftDClick(self, event):\n if self.parent.IsIconized():\n self.parent.Iconize(False)\n if not self.parent.IsShown():\n self.parent.Show(True)\n self.parent.Raise()\n\nWithin your Frame's init(), add the two lines below:\nself.TrayIcon = tbi.Icon(self, wx.Icon(\"C:\\\\YourIcon.png\", wx.BITMAP_TYPE_PNG), \"ToolTip Help Text Here\")\nself.Bind(wx.EVT_ICONIZE, self.OnIconify)\n\nAnd now just add this function to your frame and you should be set:\ndef OnIconify(self, event):\n self.Hide()\n\nJust remember to edit the items in the Icon class to suit your needs.\n",
"Have you considered running this application as a windows service? Many users will consider a system tray icon with little to no functionality a nuisance. You could still provide links to help/config files as a start menu entry.\nThe python win32 extensions package should have support for python services.\nOf course, there are still reasons why you may want to run this as a system tray icon. I'm sorry that I don't have any experience with that.\n",
"You want the wx.TaskBarIcon:\nhttp://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html\nThe wxPython Demo has example code you can look at.\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002015969_python_wxpython.txt
|
Q:
Symbolic Group Names (like in Python) in Ruby Regular Expression
Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp
(?P<id>[a-zA-Z_]\w*)
I can refer to the matched data as
m.group('id')
(Full documentation: look for "symbolic group name" here)
In Ruby, we can access the matched references using $1, $2 or using the MatchData object (m[1], m[2] etc.). Is there something similar to Python's Symbolic Group Names in Ruby?
A:
Older Ruby releases didn't have named groups (tx Alan for pointing this out in a comment!), but, if you're using Ruby 1.9...:
(?<name>subexp) expresses a named group in Ruby expressions too; \k<name> is the way you back-reference a named group in substitution, if that's what you're looking for!
A:
Ruby 1.9 introduced named captures:
m = /(?<prefix>[A-Z]+)(?<hyphen>-?)(?<digits>\d+)/.match("THX1138.")
m.names # => ["prefix", "hyphen", "digits"]
m.captures # => ["THX", "", "1138"]
m[:prefix] # => "THX"
You can use \k<prefix>, etc, for back-references.
|
Symbolic Group Names (like in Python) in Ruby Regular Expression
|
Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp
(?P<id>[a-zA-Z_]\w*)
I can refer to the matched data as
m.group('id')
(Full documentation: look for "symbolic group name" here)
In Ruby, we can access the matched references using $1, $2 or using the MatchData object (m[1], m[2] etc.). Is there something similar to Python's Symbolic Group Names in Ruby?
|
[
"Older Ruby releases didn't have named groups (tx Alan for pointing this out in a comment!), but, if you're using Ruby 1.9...:\n(?<name>subexp) expresses a named group in Ruby expressions too; \\k<name> is the way you back-reference a named group in substitution, if that's what you're looking for!\n",
"Ruby 1.9 introduced named captures:\nm = /(?<prefix>[A-Z]+)(?<hyphen>-?)(?<digits>\\d+)/.match(\"THX1138.\")\nm.names # => [\"prefix\", \"hyphen\", \"digits\"]\nm.captures # => [\"THX\", \"\", \"1138\"]\nm[:prefix] # => \"THX\"\n\nYou can use \\k<prefix>, etc, for back-references. \n"
] |
[
12,
10
] |
[] |
[] |
[
"python",
"regex",
"ruby"
] |
stackoverflow_0002090424_python_regex_ruby.txt
|
Q:
Python dictionary key order when printing
s={
'userName': "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'userNameMin': "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57",
'userNameMax': "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57",
'userNameExist': "\u8be5\u7528\u6237\u540d\u5df2\u88ab\u6ce8\u518c\u4e86\uff0c\u8bf7\u6362\u6362",
'userNameInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'userNameStartInvalid': "\u7528\u6237\u540d\u4e0d\u80fd\u4ee5\u4e0b\u5212\u7ebf\u5f00\u5934",
'nickName': "6\u4f4d\u4ee5\u5185\u4e2d\u6587\u621612\u4f4d\u4ee5\u5185\u82f1\u6587\u5b57\u7b26",
'nickNameMin': "\u4e0d\u80fd\u5c0f\u4e8e1\u4e2a\u5b57",
'nickNameMax': "\u4e0d\u80fd\u8d85\u8fc76\u4e2a\u6c49\u5b57\u621612\u4e2a\u82f1\u6587\u5b57\u7b26",
'nickNameExist': "\u8be5\u540d\u5b57\u5df2\u88ab\u5360\u7528\uff0c\u8bf7\u6362\u6362",
'nickNameInvalid': "\u53ea\u652f\u6301\u4e2d\u6587\u3001\u5b57\u6bcd\u6216\u6570\u5b57\uff0c\u4e0d\u652f\u6301\u7a7a\u683c\u548c\u7279\u6b8a\u7b26\u53f7",
'nickNameError': "\u540d\u5b57\u4e2d\u542b\u6709\u8fdd\u7981\u8bcd\uff0c\u8bf7\u4fee\u6539\uff0c\u671b\u8c05\u89e3",
'password': "6-16\u4f4d\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'passwordMin': "\u4e0d\u80fd\u5c0f\u4e8e6\u4e2a\u5b57\u7b26",
'passwordMax': "\u4e0d\u80fd\u8d85\u8fc716\u4e2a\u5b57\u7b26",
'passwordInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'password1': "\u8bf7\u518d\u786e\u8ba4\u4e00\u6b21\u4f60\u8f93\u5165\u7684\u5bc6\u7801",
'password1Invalid': "\u4e24\u6b21\u5bc6\u7801\u8f93\u5165\u4e0d\u4e00\u81f4",
'email': "\u8bf7\u8f93\u5165\u4f60\u5e38\u7528\u7684Email",
'emailExist': "\u8be5Email\u5df2\u88ab\u6ce8\u518c",
'emailInvalid': "Email\u683c\u5f0f\u4e0d\u6b63\u786e",
'sex': "\u8bf7\u9009\u62e9\u4f60\u7684\u6027\u522b",
'validateCode': "\u8bf7\u8f93\u5165\u56fe\u50cf\u4e2d\u7684\u6587\u5b57",
'validateCodeInvalid': "\u9a8c\u8bc1\u7801\u9519\u8bef",
'loading': '<img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> \u6b63\u5728\u68c0\u67e5\u552f\u4e00\u6027',
'checkCode': '<img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> \u6b63\u5728\u68c0\u67e5\u9a8c\u8bc1\u7801',
'ok': '<img align="absmiddle" alt="ok" src="http://images.digu.com/web_res_v1/images/ico_valid.gif" />',
'required': "\u5fc5\u586b"
}
for i,j in s.items():
print i,j.decode('unicode-escape')
output:
password1 请再确认一次你输入的密码
required 必填
userNameExist 该用户名已被注册了,请换换
nickNameMax 不能超过6个汉字或12个英文字符
checkCode <img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> 正在检查验证码
userNameMin 不能小于4个字
userNameMax 不能超过12个字
userNameInvalid 只支持英文字母、数字和下划线
sex 请选择你的性别
nickNameExist 该名字已被占用,请换换
emailExist 该Email已被注册
passwordMax 不能超过16个字符
emailInvalid Email格式不正确
loading <img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> 正在检查唯一性
userNameStartInvalid 用户名不能以下划线开头
passwordInvalid 只支持英文字母、数字和下划线
validateCode 请输入图像中的文字
passwordMin 不能小于6个字符
nickName 6位以内中文或12位以内英文字符
email 请输入你常用的Email
nickNameError 名字中含有违禁词,请修改,望谅解
password 6-16位英文字母、数字和下划线
userName 4-12个英文字母、数字和下划线
ok <img align="absmiddle" alt="ok" src="http://images.digu.com/web_res_v1/images/ico_valid.gif" />
nickNameMin 不能小于1个字
password1Invalid 两次密码输入不一致
nickNameInvalid 只支持中文、字母或数字,不支持空格和特殊符号
validateCodeInvalid 验证码错误
My question is: the order is disturbed
how does Output sequence.
thanks
A:
Use OrderedDict on python 2.7+
Or change dict to tuple or list, something like this
[
('userName', "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"),
('userNameMin', "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57"),
....
]
And use s instead of s.items()
for i,j in s:
print i,j.decode('unicode-escape')
A:
dicts are unsorted. If you need keys to be output in a specific order then use a list to hold them, then index the dict by each of the keys in order.
A:
you could always do a sort before you print ?
for k in sorted(s.keys()):
print k,s[k].decode('unicode-escape')
A:
Use tuple () or array [] instead of dictionary/map {} - tuples and arrays keep their sequence but do not allow using keys, dictionaries do not keep their sequence but allow using keys.
s=(
('userName', "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"),
('userNameMin', "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57"),
('userNameMax', "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57"),
.
.
.
)
for (i,j) in s:
print i,j.decode('unicode-escape')
|
Python dictionary key order when printing
|
s={
'userName': "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'userNameMin': "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57",
'userNameMax': "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57",
'userNameExist': "\u8be5\u7528\u6237\u540d\u5df2\u88ab\u6ce8\u518c\u4e86\uff0c\u8bf7\u6362\u6362",
'userNameInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'userNameStartInvalid': "\u7528\u6237\u540d\u4e0d\u80fd\u4ee5\u4e0b\u5212\u7ebf\u5f00\u5934",
'nickName': "6\u4f4d\u4ee5\u5185\u4e2d\u6587\u621612\u4f4d\u4ee5\u5185\u82f1\u6587\u5b57\u7b26",
'nickNameMin': "\u4e0d\u80fd\u5c0f\u4e8e1\u4e2a\u5b57",
'nickNameMax': "\u4e0d\u80fd\u8d85\u8fc76\u4e2a\u6c49\u5b57\u621612\u4e2a\u82f1\u6587\u5b57\u7b26",
'nickNameExist': "\u8be5\u540d\u5b57\u5df2\u88ab\u5360\u7528\uff0c\u8bf7\u6362\u6362",
'nickNameInvalid': "\u53ea\u652f\u6301\u4e2d\u6587\u3001\u5b57\u6bcd\u6216\u6570\u5b57\uff0c\u4e0d\u652f\u6301\u7a7a\u683c\u548c\u7279\u6b8a\u7b26\u53f7",
'nickNameError': "\u540d\u5b57\u4e2d\u542b\u6709\u8fdd\u7981\u8bcd\uff0c\u8bf7\u4fee\u6539\uff0c\u671b\u8c05\u89e3",
'password': "6-16\u4f4d\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'passwordMin': "\u4e0d\u80fd\u5c0f\u4e8e6\u4e2a\u5b57\u7b26",
'passwordMax': "\u4e0d\u80fd\u8d85\u8fc716\u4e2a\u5b57\u7b26",
'passwordInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
'password1': "\u8bf7\u518d\u786e\u8ba4\u4e00\u6b21\u4f60\u8f93\u5165\u7684\u5bc6\u7801",
'password1Invalid': "\u4e24\u6b21\u5bc6\u7801\u8f93\u5165\u4e0d\u4e00\u81f4",
'email': "\u8bf7\u8f93\u5165\u4f60\u5e38\u7528\u7684Email",
'emailExist': "\u8be5Email\u5df2\u88ab\u6ce8\u518c",
'emailInvalid': "Email\u683c\u5f0f\u4e0d\u6b63\u786e",
'sex': "\u8bf7\u9009\u62e9\u4f60\u7684\u6027\u522b",
'validateCode': "\u8bf7\u8f93\u5165\u56fe\u50cf\u4e2d\u7684\u6587\u5b57",
'validateCodeInvalid': "\u9a8c\u8bc1\u7801\u9519\u8bef",
'loading': '<img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> \u6b63\u5728\u68c0\u67e5\u552f\u4e00\u6027',
'checkCode': '<img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> \u6b63\u5728\u68c0\u67e5\u9a8c\u8bc1\u7801',
'ok': '<img align="absmiddle" alt="ok" src="http://images.digu.com/web_res_v1/images/ico_valid.gif" />',
'required': "\u5fc5\u586b"
}
for i,j in s.items():
print i,j.decode('unicode-escape')
output:
password1 请再确认一次你输入的密码
required 必填
userNameExist 该用户名已被注册了,请换换
nickNameMax 不能超过6个汉字或12个英文字符
checkCode <img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> 正在检查验证码
userNameMin 不能小于4个字
userNameMax 不能超过12个字
userNameInvalid 只支持英文字母、数字和下划线
sex 请选择你的性别
nickNameExist 该名字已被占用,请换换
emailExist 该Email已被注册
passwordMax 不能超过16个字符
emailInvalid Email格式不正确
loading <img align="absmiddle" alt="" src="http://images.digu.com/web_res_v1/images/ico_loading16.gif" /> 正在检查唯一性
userNameStartInvalid 用户名不能以下划线开头
passwordInvalid 只支持英文字母、数字和下划线
validateCode 请输入图像中的文字
passwordMin 不能小于6个字符
nickName 6位以内中文或12位以内英文字符
email 请输入你常用的Email
nickNameError 名字中含有违禁词,请修改,望谅解
password 6-16位英文字母、数字和下划线
userName 4-12个英文字母、数字和下划线
ok <img align="absmiddle" alt="ok" src="http://images.digu.com/web_res_v1/images/ico_valid.gif" />
nickNameMin 不能小于1个字
password1Invalid 两次密码输入不一致
nickNameInvalid 只支持中文、字母或数字,不支持空格和特殊符号
validateCodeInvalid 验证码错误
My question is: the order is disturbed
how does Output sequence.
thanks
|
[
"Use OrderedDict on python 2.7+\nOr change dict to tuple or list, something like this\n[\n ('userName', \"4-12\\u4e2a\\u82f1\\u6587\\u5b57\\u6bcd\\u3001\\u6570\\u5b57\\u548c\\u4e0b\\u5212\\u7ebf\"),\n ('userNameMin', \"\\u4e0d\\u80fd\\u5c0f\\u4e8e4\\u4e2a\\u5b57\"),\n ....\n]\n\nAnd use s instead of s.items()\nfor i,j in s:\n print i,j.decode('unicode-escape')\n\n",
"dicts are unsorted. If you need keys to be output in a specific order then use a list to hold them, then index the dict by each of the keys in order.\n",
"you could always do a sort before you print ?\nfor k in sorted(s.keys()):\n print k,s[k].decode('unicode-escape')\n\n",
"Use tuple () or array [] instead of dictionary/map {} - tuples and arrays keep their sequence but do not allow using keys, dictionaries do not keep their sequence but allow using keys.\ns=(\n ('userName', \"4-12\\u4e2a\\u82f1\\u6587\\u5b57\\u6bcd\\u3001\\u6570\\u5b57\\u548c\\u4e0b\\u5212\\u7ebf\"),\n ('userNameMin', \"\\u4e0d\\u80fd\\u5c0f\\u4e8e4\\u4e2a\\u5b57\"),\n ('userNameMax', \"\\u4e0d\\u80fd\\u8d85\\u8fc712\\u4e2a\\u5b57\"),\n .\n .\n .\n)\n\nfor (i,j) in s:\n print i,j.decode('unicode-escape')\n\n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002090564_python.txt
|
Q:
Change keyboard input method to unicode?
I am going to create an application called 'khmer keyboard input method'
the khmer just come in unicode standard (Range: 1780–17FF).
reference http://www.unicode.org/charts/PDF/U1780.pdf
this application it will allow cambodian to switch from English to Khmer by press
the definded shortcut key (F10 for example).
the application I will improve GUI.
for example
if keypress is 'k':
return unicode(u'\u1780')#KHMER LETTER KA
if keypress is shift+k or is 'K':
return unicode(u'\u1782')#KHMER LETTER KO
#.....................
if keypress is 'F10':
switch_to_english_keyboard
thank for S.Mark that told me
Hooking keys and sendkeys is different
way for Windows and Linux, so you have
to do it seperately. In Windows, you
can use combination of PyHook and
SendKeys
For Linux,I have done to this
Anybody here Know to do this in python(tips,sample,..)
(Just for WINDOWS )?
it will be great if there are a simple code or any open source that make it more easy.
***ABOUT KHMER KEYBOARD LAYOUT
http://en.wikipedia.org/wiki/Keyboard_layout#Khmer
A:
There is no single way. Each IME has its own way of picking a different engine/method.
|
Change keyboard input method to unicode?
|
I am going to create an application called 'khmer keyboard input method'
the khmer just come in unicode standard (Range: 1780–17FF).
reference http://www.unicode.org/charts/PDF/U1780.pdf
this application it will allow cambodian to switch from English to Khmer by press
the definded shortcut key (F10 for example).
the application I will improve GUI.
for example
if keypress is 'k':
return unicode(u'\u1780')#KHMER LETTER KA
if keypress is shift+k or is 'K':
return unicode(u'\u1782')#KHMER LETTER KO
#.....................
if keypress is 'F10':
switch_to_english_keyboard
thank for S.Mark that told me
Hooking keys and sendkeys is different
way for Windows and Linux, so you have
to do it seperately. In Windows, you
can use combination of PyHook and
SendKeys
For Linux,I have done to this
Anybody here Know to do this in python(tips,sample,..)
(Just for WINDOWS )?
it will be great if there are a simple code or any open source that make it more easy.
***ABOUT KHMER KEYBOARD LAYOUT
http://en.wikipedia.org/wiki/Keyboard_layout#Khmer
|
[
"There is no single way. Each IME has its own way of picking a different engine/method.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002090886_python.txt
|
Q:
How to set value of current Numbers cell using Py-Appscript
This seems like a straightforward operation but I am stumped.
How do you set value of current Numbers cell using Py-Appscript?
A:
Pretty tediously, but working:
>>> from appscript import *
>>> app('Numbers').documents.first.sheets.first.tables.first.selection_range.cells.first.value.set(to=42)
That's assuming a simple document. More generally, you can select items by name:
>>> app('Numbers').documents['MyDocument.numbers'].sheets['MySheet'].tables['MyTable'].selection_range.cells.first.value.set(to='abc')
|
How to set value of current Numbers cell using Py-Appscript
|
This seems like a straightforward operation but I am stumped.
How do you set value of current Numbers cell using Py-Appscript?
|
[
"Pretty tediously, but working:\n>>> from appscript import *\n>>> app('Numbers').documents.first.sheets.first.tables.first.selection_range.cells.first.value.set(to=42)\n\nThat's assuming a simple document. More generally, you can select items by name:\n>>> app('Numbers').documents['MyDocument.numbers'].sheets['MySheet'].tables['MyTable'].selection_range.cells.first.value.set(to='abc')\n\n"
] |
[
2
] |
[] |
[] |
[
"iwork",
"python",
"sourceforge_appscript"
] |
stackoverflow_0002090921_iwork_python_sourceforge_appscript.txt
|
Q:
What is the maximum packet size a python socket can handle?
i am new to network programming in python. I wanted to know that what is the maximum size packet we can transmit or receive on python socket? and how to find out it?
A:
The actual amount of data that can be sent in a single packet depends on what the Maximum Transmission Unit (MTU) is for the protocol you're using. Read the Wikipedia article for more information.
This is generally something you don't have to worry about, though - if you send a TCP packet that's too big, the operating system will fragment it (turn it into multiple packets) for you and it will be reassembled at the host.
By the way, Python's socket library uses the operating system's sockets, so it's nothing particular to Python.
A:
I don't think there's any Python-specific limits. UDP packets have a theoretical limit of circa 65kb and TCP no upper limit, but you'll have flow control problems if you use packets much more than a few kilobytes.
A:
i think they are not at the same level, if you want to manipulate the raw package, take a look at dpkt & scapy.
|
What is the maximum packet size a python socket can handle?
|
i am new to network programming in python. I wanted to know that what is the maximum size packet we can transmit or receive on python socket? and how to find out it?
|
[
"The actual amount of data that can be sent in a single packet depends on what the Maximum Transmission Unit (MTU) is for the protocol you're using. Read the Wikipedia article for more information.\nThis is generally something you don't have to worry about, though - if you send a TCP packet that's too big, the operating system will fragment it (turn it into multiple packets) for you and it will be reassembled at the host.\nBy the way, Python's socket library uses the operating system's sockets, so it's nothing particular to Python.\n",
"I don't think there's any Python-specific limits. UDP packets have a theoretical limit of circa 65kb and TCP no upper limit, but you'll have flow control problems if you use packets much more than a few kilobytes.\n",
"i think they are not at the same level, if you want to manipulate the raw package, take a look at dpkt & scapy.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"network_programming",
"python",
"sockets"
] |
stackoverflow_0002091097_network_programming_python_sockets.txt
|
Q:
Weird pynotify behaviour in Ubuntu 9.10
I wrote a small app and I am using pynotify to show some messages to the user.
It all works fine here in arch, but when I tested it in Ubuntu, the behaviour was very weird.
Because of the way Ubuntu shows notifications (as what seems to be a rip of of growl), I can't click on them, or interact with them in any way, for that matter.
The biggest problem, however, is that it only shows one notification at a time, and has to wait (a long time, by default) untill one of them goes away to show the next one.
Given the nature of the little app I'm writing (a simple monitor that runs a command every time a file is changed), the results must appear to the user in real time.
I have tried to set a small timeout with message.set_timeout(), but Ubuntu just seems to ignore it.
--
So, here is my question: Am I the only one to notice that? Am I doing something wrong?
If not, is there any way to change that behaviour in Ubuntu? Any workaround?
Thanks in advance for your time
A:
Yes, Ubuntu 9.10 replaced upstream's notification-daemon with their own notify-osd, and generally made a mess of things.
You can ensure notification-daemon is installed (via whatever your favorite package manager front-end is) and use it in favor of notify-osd:
$ sudo mv /usr/share/dbus-1/services/org.freedesktop.Notifications.service /usr/share/dbus-1/services/org.freedesktop.Notifications.service.disabled
$ sudo mv /usr/share/dbus-1/services/org.freedesktop.Notifications.service.notify-osd /usr/share/dbus-1/services/org.freedesktop.Notifications.service
Unfortunately this will get overwritten whenever the package is updated... it's already using a dpkg-diversion so it's hard to re-divert it permanently.
|
Weird pynotify behaviour in Ubuntu 9.10
|
I wrote a small app and I am using pynotify to show some messages to the user.
It all works fine here in arch, but when I tested it in Ubuntu, the behaviour was very weird.
Because of the way Ubuntu shows notifications (as what seems to be a rip of of growl), I can't click on them, or interact with them in any way, for that matter.
The biggest problem, however, is that it only shows one notification at a time, and has to wait (a long time, by default) untill one of them goes away to show the next one.
Given the nature of the little app I'm writing (a simple monitor that runs a command every time a file is changed), the results must appear to the user in real time.
I have tried to set a small timeout with message.set_timeout(), but Ubuntu just seems to ignore it.
--
So, here is my question: Am I the only one to notice that? Am I doing something wrong?
If not, is there any way to change that behaviour in Ubuntu? Any workaround?
Thanks in advance for your time
|
[
"Yes, Ubuntu 9.10 replaced upstream's notification-daemon with their own notify-osd, and generally made a mess of things.\nYou can ensure notification-daemon is installed (via whatever your favorite package manager front-end is) and use it in favor of notify-osd:\n\n$ sudo mv /usr/share/dbus-1/services/org.freedesktop.Notifications.service /usr/share/dbus-1/services/org.freedesktop.Notifications.service.disabled\n$ sudo mv /usr/share/dbus-1/services/org.freedesktop.Notifications.service.notify-osd /usr/share/dbus-1/services/org.freedesktop.Notifications.service\n\nUnfortunately this will get overwritten whenever the package is updated... it's already using a dpkg-diversion so it's hard to re-divert it permanently.\n"
] |
[
3
] |
[] |
[] |
[
"linux",
"pynotify",
"python",
"ubuntu",
"ubuntu_9.10"
] |
stackoverflow_0002090273_linux_pynotify_python_ubuntu_ubuntu_9.10.txt
|
Q:
Regular expression for urlpattern
I need a regexp for a URL like:
/slug/#slug/slug/
I know it should be something like:
r'^(?P<slug1>[-\w]+)/#(?P<slug2>[-\w]+)/(?P<slug3>[-\w]+)/$'
But I am having problems with the character #
A:
Parameter after # character is not send to server, so cannot catch in server side script like django.
A:
The URL fragment (everything after the #) is not sent to the server in a request.
|
Regular expression for urlpattern
|
I need a regexp for a URL like:
/slug/#slug/slug/
I know it should be something like:
r'^(?P<slug1>[-\w]+)/#(?P<slug2>[-\w]+)/(?P<slug3>[-\w]+)/$'
But I am having problems with the character #
|
[
"Parameter after # character is not send to server, so cannot catch in server side script like django.\n",
"The URL fragment (everything after the #) is not sent to the server in a request.\n"
] |
[
5,
2
] |
[] |
[] |
[
"django",
"django_urls",
"python",
"regex"
] |
stackoverflow_0002091449_django_django_urls_python_regex.txt
|
Q:
Sorting CSV in Python
I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields.
How would one go about sorting a relatively large CSV file (tens of thousand lines) on multiple fields, in order?
Python code samples would be appreciated.
A:
Python's sort works in-memory only; however, tens of thousands of lines should fit in memory easily on a modern machine. So:
import csv
def sortcsvbymanyfields(csvfilename, themanyfieldscolumnnumbers):
with open(csvfilename, 'rb') as f:
readit = csv.reader(f)
thedata = list(readit)
thedata.sort(key=operator.itemgetter(*themanyfieldscolumnnumbers))
with open(csvfilename, 'wb') as f:
writeit = csv.writer(f)
writeit.writerows(thedata)
A:
Here's Alex's answer, reworked to support column data types:
import csv
import operator
def sort_csv(csv_filename, types, sort_key_columns):
"""sort (and rewrite) a csv file.
types: data types (conversion functions) for each column in the file
sort_key_columns: column numbers of columns to sort by"""
data = []
with open(csv_filename, 'rb') as f:
for row in csv.reader(f):
data.append(convert(types, row))
data.sort(key=operator.itemgetter(*sort_key_columns))
with open(csv_filename, 'wb') as f:
csv.writer(f).writerows(data)
Edit:
I did a stupid. I was playing with various things in IDLE and wrote a convert function a couple of days ago. I forgot I'd written it, and I haven't closed IDLE in a good long while - so when I wrote the above, I thought convert was a built-in function. Sadly no.
Here's my implementation, though John Machin's is nicer:
def convert(types, values):
return [t(v) for t, v in zip(types, values)]
Usage:
import datetime
def date(s):
return datetime.strptime(s, '%m/%d/%y')
>>> convert((int, date, str), ('1', '2/15/09', 'z'))
[1, datetime.datetime(2009, 2, 15, 0, 0), 'z']
A:
Here's the convert() that's missing from Robert's fix of Alex's answer:
>>> def convert(convert_funcs, seq):
... return [
... item if func is None else func(item)
... for func, item in zip(convert_funcs, seq)
... ]
...
>>> convert(
... (None, float, lambda x: x.strip().lower()),
... [" text ", "123.45", " TEXT "]
... )
[' text ', 123.45, 'text']
>>>
I've changed the name of the first arg to highlight that the per-columns function can do what you need, not merely type-coercion. None is used to indicate no conversion.
|
Sorting CSV in Python
|
I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields.
How would one go about sorting a relatively large CSV file (tens of thousand lines) on multiple fields, in order?
Python code samples would be appreciated.
|
[
"Python's sort works in-memory only; however, tens of thousands of lines should fit in memory easily on a modern machine. So:\nimport csv\n\ndef sortcsvbymanyfields(csvfilename, themanyfieldscolumnnumbers):\n with open(csvfilename, 'rb') as f:\n readit = csv.reader(f)\n thedata = list(readit)\n thedata.sort(key=operator.itemgetter(*themanyfieldscolumnnumbers))\n with open(csvfilename, 'wb') as f:\n writeit = csv.writer(f)\n writeit.writerows(thedata)\n\n",
"Here's Alex's answer, reworked to support column data types:\nimport csv\nimport operator\n\ndef sort_csv(csv_filename, types, sort_key_columns):\n \"\"\"sort (and rewrite) a csv file.\n types: data types (conversion functions) for each column in the file\n sort_key_columns: column numbers of columns to sort by\"\"\"\n data = []\n with open(csv_filename, 'rb') as f:\n for row in csv.reader(f):\n data.append(convert(types, row))\n data.sort(key=operator.itemgetter(*sort_key_columns))\n with open(csv_filename, 'wb') as f:\n csv.writer(f).writerows(data)\n\nEdit:\nI did a stupid. I was playing with various things in IDLE and wrote a convert function a couple of days ago. I forgot I'd written it, and I haven't closed IDLE in a good long while - so when I wrote the above, I thought convert was a built-in function. Sadly no.\nHere's my implementation, though John Machin's is nicer:\ndef convert(types, values):\n return [t(v) for t, v in zip(types, values)]\n\nUsage:\nimport datetime\ndef date(s):\n return datetime.strptime(s, '%m/%d/%y')\n\n>>> convert((int, date, str), ('1', '2/15/09', 'z'))\n[1, datetime.datetime(2009, 2, 15, 0, 0), 'z']\n\n",
"Here's the convert() that's missing from Robert's fix of Alex's answer:\n>>> def convert(convert_funcs, seq):\n... return [\n... item if func is None else func(item)\n... for func, item in zip(convert_funcs, seq)\n... ]\n...\n>>> convert(\n... (None, float, lambda x: x.strip().lower()),\n... [\" text \", \"123.45\", \" TEXT \"]\n... )\n[' text ', 123.45, 'text']\n>>>\n\nI've changed the name of the first arg to highlight that the per-columns function can do what you need, not merely type-coercion. None is used to indicate no conversion.\n"
] |
[
10,
4,
2
] |
[
"You bring up 3 issues:\n\nfile size\ncsv data\nsorting on multiple fields\n\nHere is a solution for the third part. You can handle csv data in a more sophisticated way.\n>>> data = 'a,b,c\\nb,b,a\\nb,c,a\\n'\n>>> lines = [e.split(',') for e in data.strip().split('\\n')]\n>>> lines\n[['a', 'b', 'c'], ['b', 'b', 'a'], ['b', 'c', 'a']]\n>>> def f(e):\n... field_order = [2,1]\n... return [e[i] for i in field_order]\n... \n>>> sorted(lines, key=f)\n[['b', 'b', 'a'], ['b', 'c', 'a'], ['a', 'b', 'c']]\n\nEdited to use a list comprehension, generator does not work as I had expected it to.\n"
] |
[
-1
] |
[
"csv",
"python",
"sorting"
] |
stackoverflow_0002089036_csv_python_sorting.txt
|
Q:
unidentified com_error in python
I've encountered the following error while scripting in Python.
ERROR Tue 19. Jan 14:51:21 2010 C:\Python24\Lib\site-packages\win32com\client\util.py:0: Script Error
com_error: (-2147217385, 'OLE error 0x80041017', None, None)
Unfortunately, I don't know what it means, or even what other information I might need to find out. Does anyone have any insight into this?
A:
Here's a page at the Microsoft site which might shed some light:
WBEM_E_INVALID_QUERY
2147749911 (0x80041017)
Query was not syntactically valid.
A:
When doing python COM programming, I sometimes use VBA (in Excel) to test code that gives errors.
That way, I can see if the problem is in the Python-COM layer, or if I get the same error when using VBA. I have sometimes seen that the error messages in VBA have descriptions that the Python exception lacks.
VBA is quite nice for doing COM programming. You have tab completion/intellisense in the editor.
|
unidentified com_error in python
|
I've encountered the following error while scripting in Python.
ERROR Tue 19. Jan 14:51:21 2010 C:\Python24\Lib\site-packages\win32com\client\util.py:0: Script Error
com_error: (-2147217385, 'OLE error 0x80041017', None, None)
Unfortunately, I don't know what it means, or even what other information I might need to find out. Does anyone have any insight into this?
|
[
"Here's a page at the Microsoft site which might shed some light:\n\nWBEM_E_INVALID_QUERY\n2147749911 (0x80041017)\nQuery was not syntactically valid.\n\n",
"When doing python COM programming, I sometimes use VBA (in Excel) to test code that gives errors.\nThat way, I can see if the problem is in the Python-COM layer, or if I get the same error when using VBA. I have sometimes seen that the error messages in VBA have descriptions that the Python exception lacks.\nVBA is quite nice for doing COM programming. You have tab completion/intellisense in the editor.\n"
] |
[
1,
0
] |
[] |
[] |
[
"com",
"python"
] |
stackoverflow_0002090950_com_python.txt
|
Q:
How do I access an object's properties by name?
class a(type):
def __str__(self):
return 'aaa'
def __new__(cls, name, bases, attrs):
attrs['cool']='cool!!!!'
new_class = super(a,cls).__new__(cls, name, bases, attrs)
#if 'media' not in attrs:
#new_class.media ='media'
return new_class
class b(object):
__metaclass__=a
def __str__(self):
return 'bbb'
print b
print b()['cool']#how can i print 'cool!!!!'
A:
print b().cool
attrs in your __new__ method becomes the object's dictionary. Properties of Python objects are referenced with the . syntax.
A:
print "cool!!!"
Or did I miss something?
|
How do I access an object's properties by name?
|
class a(type):
def __str__(self):
return 'aaa'
def __new__(cls, name, bases, attrs):
attrs['cool']='cool!!!!'
new_class = super(a,cls).__new__(cls, name, bases, attrs)
#if 'media' not in attrs:
#new_class.media ='media'
return new_class
class b(object):
__metaclass__=a
def __str__(self):
return 'bbb'
print b
print b()['cool']#how can i print 'cool!!!!'
|
[
"print b().cool\n\nattrs in your __new__ method becomes the object's dictionary. Properties of Python objects are referenced with the . syntax.\n",
"print \"cool!!!\"\n\nOr did I miss something?\n"
] |
[
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002092002_python.txt
|
Q:
Variables as a part of calling a method in python
I'm pretty new to programming and I'm creating a python game for my little sister.
I'm having trouble, because I want the variable value to be a part of the method name
Is there any way this is possible?
def play_with_toy(self):
toy = gui.buttonbox(
msg = 'Choose a toy for your potato head to play with:',
title = 'Choose a Toy',
choices = self.toys)
method_name = 'play_' + toy + '()'
myPotatoHead.method_name
Using Python 2.5.4 for Mac (IDLE) and easygui 0.83
Thanks for any help
A:
method = getattr(myPotatoHead, 'play_' + toy)
method()
A:
getattr(myPotatoHead,"play_"+toy)()
A:
Try this:
method = getAttr(myPotatoHead, 'play_' + toy)
method()
(sorry about the semi-colons! I was programming in javascript all day).
|
Variables as a part of calling a method in python
|
I'm pretty new to programming and I'm creating a python game for my little sister.
I'm having trouble, because I want the variable value to be a part of the method name
Is there any way this is possible?
def play_with_toy(self):
toy = gui.buttonbox(
msg = 'Choose a toy for your potato head to play with:',
title = 'Choose a Toy',
choices = self.toys)
method_name = 'play_' + toy + '()'
myPotatoHead.method_name
Using Python 2.5.4 for Mac (IDLE) and easygui 0.83
Thanks for any help
|
[
"method = getattr(myPotatoHead, 'play_' + toy)\nmethod()\n\n",
"getattr(myPotatoHead,\"play_\"+toy)()\n\n",
"Try this: \nmethod = getAttr(myPotatoHead, 'play_' + toy)\nmethod()\n\n(sorry about the semi-colons! I was programming in javascript all day). \n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"function",
"python"
] |
stackoverflow_0002092059_function_python.txt
|
Q:
Uploading files in RESTful way?
I'm designing a RESTful API that should handle binary file uploads.
Should this be done the same way as html form upload or is there a better way?
A:
Take a look at the Amazon api for an idea. It uses a PUT query and then through sendREST it sends the content.
Uploading files to Amazon S3 with REST API
A:
A good way is to upload the binary information using streams. You could have a look at the JeCARS client project. To be exact the JC_RESTComm.java class performs the upload.
|
Uploading files in RESTful way?
|
I'm designing a RESTful API that should handle binary file uploads.
Should this be done the same way as html form upload or is there a better way?
|
[
"Take a look at the Amazon api for an idea. It uses a PUT query and then through sendREST it sends the content. \nUploading files to Amazon S3 with REST API\n",
"A good way is to upload the binary information using streams. You could have a look at the JeCARS client project. To be exact the JC_RESTComm.java class performs the upload.\n"
] |
[
3,
1
] |
[] |
[] |
[
"file",
"file_upload",
"java",
"python",
"rest"
] |
stackoverflow_0002092249_file_file_upload_java_python_rest.txt
|
Q:
How do I get js and css to display in Django?
I've got a template, a.html, which looks like this:
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript" src="reg.js"></script>
Why doesn't this work?
A:
Try:
<script type="text/javascript" src="{{ MEDIA_URL }}jquery-1.4.min.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}reg.js"></script>
You'll need to make sure you're serving static files correctly, and you'll need "django.core.context_processors.media" in the TEMPLATE_CONTEXT_PROCESSORS setting.
A:
Because you didn't set up your web server to alias those to their corresponding static media.
A:
Since your URLs can have arbitrary path depths, you need to get absolute path to your JS. e.g.
<script type="text/javascript" src="/js/jquery-1.4.min.js"></script>
<script type="text/javascript" src="/js/reg.js"></script>
|
How do I get js and css to display in Django?
|
I've got a template, a.html, which looks like this:
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript" src="reg.js"></script>
Why doesn't this work?
|
[
"Try:\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}jquery-1.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}reg.js\"></script>\n\nYou'll need to make sure you're serving static files correctly, and you'll need \"django.core.context_processors.media\" in the TEMPLATE_CONTEXT_PROCESSORS setting.\n",
"Because you didn't set up your web server to alias those to their corresponding static media.\n",
"Since your URLs can have arbitrary path depths, you need to get absolute path to your JS. e.g.\n<script type=\"text/javascript\" src=\"/js/jquery-1.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"/js/reg.js\"></script>\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002092346_django_python.txt
|
Q:
Run a C++ Program from Django Framework
I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ?
A:
Compile that C++ program to executable and call with subprocess module from python
A:
You can use swig to create a C++ module that can be imported in python.
An alternative is boost::python (but personnaly, I prefer swig).
A:
One way of doing this would be to use os.popen. Assuming your C++ executable is in the system wide path and is named mycpp, you would do something like:
results = os.popen('mycpp %s' % user_input).read()
However, this could get computationally expensive real fast if you're invoking this command often 'cause os.popen basically forks off a subprocess. Also, as noted in the docs, it's been deprecated since Python 2.6 so proceed with caution.
A:
Assuming you are on *nix, compile your C++ program and store it somewhere on your system, say /home/rishabh/myexe.
Now from your django app call the executable using commands module:
import commands
status, res = commands.getstatusoutput("/home/rishabh/myexe")
# status contains process status (0 for success, non-zero for unsuccesful termination) and res contains the output of the process
|
Run a C++ Program from Django Framework
|
I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ?
|
[
"Compile that C++ program to executable and call with subprocess module from python\n",
"You can use swig to create a C++ module that can be imported in python.\nAn alternative is boost::python (but personnaly, I prefer swig).\n",
"One way of doing this would be to use os.popen. Assuming your C++ executable is in the system wide path and is named mycpp, you would do something like:\nresults = os.popen('mycpp %s' % user_input).read()\n\nHowever, this could get computationally expensive real fast if you're invoking this command often 'cause os.popen basically forks off a subprocess. Also, as noted in the docs, it's been deprecated since Python 2.6 so proceed with caution.\n",
"Assuming you are on *nix, compile your C++ program and store it somewhere on your system, say /home/rishabh/myexe.\nNow from your django app call the executable using commands module:\nimport commands\n\nstatus, res = commands.getstatusoutput(\"/home/rishabh/myexe\")\n\n# status contains process status (0 for success, non-zero for unsuccesful termination) and res contains the output of the process\n\n"
] |
[
10,
1,
0,
0
] |
[] |
[] |
[
"c++",
"django",
"python"
] |
stackoverflow_0002091294_c++_django_python.txt
|
Q:
Equivalent to django Form to show object contents
Is there any Django class used to show the contents of an object model in a non-modifiable way? Something like this for forms to edit the objects from a model:
class TestForm(forms.ModelForm):
class Meta:
model = models.Test
using it as:
def generic_view(request):
form = TestForm()
return render_to_response('generic/generic_view.html', {
'form': form,
})
and then in the template:
{{ form.as_p }}
but showing just the contents of an object instead of a form?
A:
Calling repr() against the model instance will get you a (admittedly ugly) representation of the instance fields.
A:
I would take a look at the source of Databrowse to see how it does it. It introspects models and displays the data of objects with minimal configuration, so it probably has a component that does what you want.
|
Equivalent to django Form to show object contents
|
Is there any Django class used to show the contents of an object model in a non-modifiable way? Something like this for forms to edit the objects from a model:
class TestForm(forms.ModelForm):
class Meta:
model = models.Test
using it as:
def generic_view(request):
form = TestForm()
return render_to_response('generic/generic_view.html', {
'form': form,
})
and then in the template:
{{ form.as_p }}
but showing just the contents of an object instead of a form?
|
[
"Calling repr() against the model instance will get you a (admittedly ugly) representation of the instance fields.\n",
"I would take a look at the source of Databrowse to see how it does it. It introspects models and displays the data of objects with minimal configuration, so it probably has a component that does what you want.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002092242_django_python.txt
|
Q:
Categorize a list of lists by 1 element in python
An example list of lists:
[
["url","name","date","category"]
["hello","world","2010","one category"]
["foo","bar","2010","another category"]
["asdfasdf","adfasdf","2010","one category"]
["qwer","req","2010","another category"]
]
What I wish do to is create a dictionary -> category : [ list of entries ].
The resultant dictionary would be:
{"category" : [["url","name","date","category"]],
"one category" : [["hello","world","2010","one category"],["asdfasdf","adfasdf","2010","one category"]],
"another category" : [["foo","bar","2010","another category"], ["qwer","req","2010","another category"]]}
A:
dict((category, list(l)) for category, l
in itertools.groupby(l, operator.itemgetter(3))
The main thing here is the usage of itertools.groupby. It simply returns iterables instead of lists, which is why there's a call for list(l), which means that if you're ok with that, you can simply write dict(itertools.groupby(l, operator.itemgetter(3)))
A:
newdict = collections.defaultdict(list)
for entry in biglist:
newdict[entry[3]].append(entry)
A:
A variation on ghostdog74's answer, which fully uses the semantics of setdefaults:
result={}
for li in list_of_lists:
result.setdefault(li[-1], []).append(li)
A:
list_of_lists=[
["url","name","date","category"],
["hello","world","2010","one category"],
["foo","bar","2010","another category"],
["asdfasdf","adfasdf","2010","one category"],
["qwer","req","2010","another category"]
]
d={}
for li in list_of_lists:
d.setdefault(li[-1], [])
d[ li[-1] ].append(li)
for i,j in d.iteritems():
print i,j
A:
d = {}
for e in l:
if e[3] in d:
d[e[3]].append(e)
else:
d[e[3]] = [e]
|
Categorize a list of lists by 1 element in python
|
An example list of lists:
[
["url","name","date","category"]
["hello","world","2010","one category"]
["foo","bar","2010","another category"]
["asdfasdf","adfasdf","2010","one category"]
["qwer","req","2010","another category"]
]
What I wish do to is create a dictionary -> category : [ list of entries ].
The resultant dictionary would be:
{"category" : [["url","name","date","category"]],
"one category" : [["hello","world","2010","one category"],["asdfasdf","adfasdf","2010","one category"]],
"another category" : [["foo","bar","2010","another category"], ["qwer","req","2010","another category"]]}
|
[
"dict((category, list(l)) for category, l \n in itertools.groupby(l, operator.itemgetter(3))\n\nThe main thing here is the usage of itertools.groupby. It simply returns iterables instead of lists, which is why there's a call for list(l), which means that if you're ok with that, you can simply write dict(itertools.groupby(l, operator.itemgetter(3)))\n",
"newdict = collections.defaultdict(list)\nfor entry in biglist:\n newdict[entry[3]].append(entry)\n\n",
"A variation on ghostdog74's answer, which fully uses the semantics of setdefaults:\nresult={}\nfor li in list_of_lists:\n result.setdefault(li[-1], []).append(li)\n\n",
"list_of_lists=[\n[\"url\",\"name\",\"date\",\"category\"],\n[\"hello\",\"world\",\"2010\",\"one category\"],\n[\"foo\",\"bar\",\"2010\",\"another category\"],\n[\"asdfasdf\",\"adfasdf\",\"2010\",\"one category\"],\n[\"qwer\",\"req\",\"2010\",\"another category\"]\n]\nd={}\nfor li in list_of_lists:\n d.setdefault(li[-1], [])\n d[ li[-1] ].append(li)\nfor i,j in d.iteritems():\n print i,j\n\n",
"\nd = {}\nfor e in l:\n if e[3] in d:\n d[e[3]].append(e)\n else:\n d[e[3]] = [e]\n\n"
] |
[
7,
5,
2,
1,
1
] |
[
">>> l = [\n... [\"url\",\"name\",\"date\",\"category\"],\n... [\"hello\",\"world\",\"2010\",\"one category\"],\n... [\"foo\",\"bar\",\"2010\",\"another category\"],\n... [\"asdfasdf\",\"adfasdf\",\"2010\",\"one category\"],\n... [\"qwer\",\"req\",\"2010\",\"another category\"],\n... ]\n#Intermediate list to generate a more dictionary oriented data\n>>> dl = [ (li[3],li[:3]) for li in l ]\n>>> dl\n[('category', ['url', 'name', 'date']), \n ('one category', ['hello', 'world', '2010']), \n ('another category', ['foo', 'bar', '2010']), \n ('one category', ['asdfasdf', 'adfasdf', '2010']), \n ('another category', ['qwer', 'req', '2010'])]\n#Final dictionary\n>>> d = {}\n>>> for cat, data in dl:\n... if cat in d:\n... d[cat] = d[cat] + [ data ]\n... else:\n... d[cat] = [ data ]\n...\n>>> d\n{'category': [['url', 'name', 'date']], \n 'one category': [['hello', 'world', '2010'], ['asdfasdf', 'adfasdf', '2010']], \n 'another category': [['foo', 'bar', '2010'], ['qwer', 'req', '2010']]}\n\nThe final data it's a little different as I haven't included on the data the category (seems quite pointless to me), but you can add it easily, if needed...\n"
] |
[
-2
] |
[
"dictionary",
"list",
"map",
"python",
"sorting"
] |
stackoverflow_0002092380_dictionary_list_map_python_sorting.txt
|
Q:
Linking to boost unit test framework with boost build
Using boost build, if I can link to a boost python library with this in my jamfile:
project myProject : requirement
/boost/python//boost_python ;
how can I link to boost test? I have built the boost test library.
I don't want to use file paths since my code is portable. Thanks
Si
A:
If you have standard (or prebuilt) libraries installed in a location which can vary between different machines, you may consider using site-config. Then the site-config can be adapted on each machine but the project Jamfile remains the same.
See the Boost Build documentation: Targets in site-config.jam for details.
|
Linking to boost unit test framework with boost build
|
Using boost build, if I can link to a boost python library with this in my jamfile:
project myProject : requirement
/boost/python//boost_python ;
how can I link to boost test? I have built the boost test library.
I don't want to use file paths since my code is portable. Thanks
Si
|
[
"If you have standard (or prebuilt) libraries installed in a location which can vary between different machines, you may consider using site-config. Then the site-config can be adapted on each machine but the project Jamfile remains the same.\nSee the Boost Build documentation: Targets in site-config.jam for details.\n"
] |
[
1
] |
[] |
[] |
[
"bjam",
"boost",
"build",
"python",
"testing"
] |
stackoverflow_0002088924_bjam_boost_build_python_testing.txt
|
Q:
How to know requested module name in Django
In Django if a request is made to another module. Can we know where the request has made from through the request variable...
In the below example I have to know that the request was made from a.html ort that corresponding module
Ex:
a.html
<html>
<form onsubmit=/b>
</form>
</html>
A:
In your view code you can do something like this:
def my_view(request)
referer = request.META.get('HTTP_REFERER', '')
if referer == 'absolute/path/to/somepage.html':
# do something
...
else:
# do something else
...
Note that you probably want to avoid hard-coding URLs in your view code (as I've done above for the sake of simplicity, you probably want to use reverse().
|
How to know requested module name in Django
|
In Django if a request is made to another module. Can we know where the request has made from through the request variable...
In the below example I have to know that the request was made from a.html ort that corresponding module
Ex:
a.html
<html>
<form onsubmit=/b>
</form>
</html>
|
[
"In your view code you can do something like this:\ndef my_view(request)\n referer = request.META.get('HTTP_REFERER', '')\n if referer == 'absolute/path/to/somepage.html':\n # do something\n ...\n else:\n # do something else\n ...\n\nNote that you probably want to avoid hard-coding URLs in your view code (as I've done above for the sake of simplicity, you probably want to use reverse().\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002092920_django_python.txt
|
Q:
Python RegEx Discrepancy vs Kodos and RegExr: Can't Filter Specific Character in Python
I'm using Python 2.6.3. When I do:
import re, urllib
f = urllib.urlopen(website)
z = f.read()
a = re.findall(r'(\b\d*\SLegos\b)[^\\/bLegos\b]', z)
print a
I get:
['/Legos', '/Legos', '525Legos', '53Legos', '11Legos', '8Legos', '10Legos', '2Legos', '0Legos', '0Legos', '0Legos', '0Legos', '9Legos', '1Legos', '0Legos', '0Legos', '0Legos', '/Legos']
If I put the website as source code into either Kodos or RegExr by gSkinner and use my above RegEx code they both say I should get:
'525Legos', '53Legos', '11Legos', '8Legos', '10Legos', '2Legos', '0Legos', '0Legos', '0Legos', '0Legos', '9Legos', '1Legos', '0Legos', '0Legos', '0Legos'
Which is much closer to the data I want.
How do I drop the '/Legos' from returning in my Python regex?
Thanks,
Adrian
A:
your regex is too complicated and erroneous, you could just use:
\b(\d+Legos)\b
if you don't really need Legos in your output, you could of course simply move it out of the brackets:
\b(\d+)Legos\b
|
Python RegEx Discrepancy vs Kodos and RegExr: Can't Filter Specific Character in Python
|
I'm using Python 2.6.3. When I do:
import re, urllib
f = urllib.urlopen(website)
z = f.read()
a = re.findall(r'(\b\d*\SLegos\b)[^\\/bLegos\b]', z)
print a
I get:
['/Legos', '/Legos', '525Legos', '53Legos', '11Legos', '8Legos', '10Legos', '2Legos', '0Legos', '0Legos', '0Legos', '0Legos', '9Legos', '1Legos', '0Legos', '0Legos', '0Legos', '/Legos']
If I put the website as source code into either Kodos or RegExr by gSkinner and use my above RegEx code they both say I should get:
'525Legos', '53Legos', '11Legos', '8Legos', '10Legos', '2Legos', '0Legos', '0Legos', '0Legos', '0Legos', '9Legos', '1Legos', '0Legos', '0Legos', '0Legos'
Which is much closer to the data I want.
How do I drop the '/Legos' from returning in my Python regex?
Thanks,
Adrian
|
[
"your regex is too complicated and erroneous, you could just use:\n\\b(\\d+Legos)\\b\n\nif you don't really need Legos in your output, you could of course simply move it out of the brackets:\n\\b(\\d+)Legos\\b\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002092956_python_regex.txt
|
Q:
how-to apache 2.2 mod_fcgid set python path
i have trouble with seting the python path or any other enviroment variable for mod_fcgid (solaris 10, glassfish apache 2.2)
I have it set in apache, but nothing in os.environ in the fcgi script:
SetEnv PYTHONPATH "/opt/uusis/lib/python2.4/site-packages/:/usr/lib/python2.4/"
And other stuff(for example ORACLE_HOME) and I need to access them in the fcgi script.
I know i can use this to set the python path.
sys.path.insert(0, "/opt/uusis/lib/python2.4/site-packages")
sys.path.insert(1, "/usr/lib/python2.4/")
Is there a way to pass the enviroment values from apache?
A:
not quite sure if this help. http://httpd.apache.org/docs/2.0/env.html
A:
I found out that Solaris 10 glassfish apache 2.2 mod_fcgid has "DefaultInitEnv"
This is not documented in the apache mod_fcgid ...
Example:
DefaultInitEnv PYTHONPATH "/opt/something/lib/python2.4/site-packages/:/usr/lib/python2.4/"
|
how-to apache 2.2 mod_fcgid set python path
|
i have trouble with seting the python path or any other enviroment variable for mod_fcgid (solaris 10, glassfish apache 2.2)
I have it set in apache, but nothing in os.environ in the fcgi script:
SetEnv PYTHONPATH "/opt/uusis/lib/python2.4/site-packages/:/usr/lib/python2.4/"
And other stuff(for example ORACLE_HOME) and I need to access them in the fcgi script.
I know i can use this to set the python path.
sys.path.insert(0, "/opt/uusis/lib/python2.4/site-packages")
sys.path.insert(1, "/usr/lib/python2.4/")
Is there a way to pass the enviroment values from apache?
|
[
"not quite sure if this help. http://httpd.apache.org/docs/2.0/env.html\n",
"I found out that Solaris 10 glassfish apache 2.2 mod_fcgid has \"DefaultInitEnv\"\nThis is not documented in the apache mod_fcgid ...\nExample:\nDefaultInitEnv PYTHONPATH \"/opt/something/lib/python2.4/site-packages/:/usr/lib/python2.4/\"\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"apache2",
"environment_variables",
"mod_fcgid",
"python"
] |
stackoverflow_0002085369_apache2_environment_variables_mod_fcgid_python.txt
|
Q:
SQLAlchemy Column to Row Transformation and vice versa -- is it possible?
I'm looking for a SQLAlchemy only solution for converting a dict received from a form submission into a series of rows in the database, one for each field submitted. This is to handle preferences and settings that vary widely across applications. But, it's very likely applicable to creating pivot table like functionality. I've seen this type of thing in ETL tools but I was looking for a way to do it directly in the ORM. I couldn't find any documentation on it but maybe I missed something.
Example:
Submitted from form: {"UniqueId":1, "a":23, "b":"Hello", "c":"World"}
I would like it to be transformed (in the ORM) so that it is recorded in the database like this:
_______________________________________
|UniqueId| ItemName | ItemValue |
---------------------------------------
| 1 | a | 23 |
---------------------------------------
| 1 | b | Hello |
---------------------------------------
| 1 | c | World |
---------------------------------------
Upon a select the result would be transformed (in the ORM) back into a row of data from each of the individual values.
---------------------------------------------------
| UniqueId | a | b | c |
---------------------------------------------------
| 1 | 23 | Hello | World |
---------------------------------------------------
I would assume on an update that the best course of action would be to wrap a delete/create in a transaction so the current records would be removed and the new ones inserted.
The definitive list of ItemNames will be maintained in a separate table.
Totally open to more elegant solutions but would like to keep out of the database side if at all possible.
I'm using the declarative_base approach with SQLAlchemy.
Thanks in advance...
Cheers,
Paul
A:
Here is a slightly modified example from documentation to work with such table structure mapped to dictionary in model:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relation, sessionmaker
metadata = MetaData()
Base = declarative_base(metadata=metadata, name='Base')
class Item(Base):
__tablename__ = 'Item'
UniqueId = Column(Integer, ForeignKey('ItemSet.UniqueId'),
primary_key=True)
ItemSet = relation('ItemSet')
ItemName = Column(String(10), primary_key=True)
ItemValue = Column(Text) # Use PickleType?
def _create_item(ItemName, ItemValue):
return Item(ItemName=ItemName, ItemValue=ItemValue)
class ItemSet(Base):
__tablename__ = 'ItemSet'
UniqueId = Column(Integer, primary_key=True)
_items = relation(Item,
collection_class=attribute_mapped_collection('ItemName'))
items = association_proxy('_items', 'ItemValue', creator=_create_item)
engine = create_engine('sqlite://', echo=True)
metadata.create_all(engine)
session = sessionmaker(bind=engine)()
data = {"UniqueId": 1, "a": 23, "b": "Hello", "c": "World"}
s = ItemSet(UniqueId=data.pop("UniqueId"))
s.items = data
session.add(s)
session.commit()
|
SQLAlchemy Column to Row Transformation and vice versa -- is it possible?
|
I'm looking for a SQLAlchemy only solution for converting a dict received from a form submission into a series of rows in the database, one for each field submitted. This is to handle preferences and settings that vary widely across applications. But, it's very likely applicable to creating pivot table like functionality. I've seen this type of thing in ETL tools but I was looking for a way to do it directly in the ORM. I couldn't find any documentation on it but maybe I missed something.
Example:
Submitted from form: {"UniqueId":1, "a":23, "b":"Hello", "c":"World"}
I would like it to be transformed (in the ORM) so that it is recorded in the database like this:
_______________________________________
|UniqueId| ItemName | ItemValue |
---------------------------------------
| 1 | a | 23 |
---------------------------------------
| 1 | b | Hello |
---------------------------------------
| 1 | c | World |
---------------------------------------
Upon a select the result would be transformed (in the ORM) back into a row of data from each of the individual values.
---------------------------------------------------
| UniqueId | a | b | c |
---------------------------------------------------
| 1 | 23 | Hello | World |
---------------------------------------------------
I would assume on an update that the best course of action would be to wrap a delete/create in a transaction so the current records would be removed and the new ones inserted.
The definitive list of ItemNames will be maintained in a separate table.
Totally open to more elegant solutions but would like to keep out of the database side if at all possible.
I'm using the declarative_base approach with SQLAlchemy.
Thanks in advance...
Cheers,
Paul
|
[
"Here is a slightly modified example from documentation to work with such table structure mapped to dictionary in model:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.orm import relation, sessionmaker\n\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata, name='Base')\n\nclass Item(Base):\n\n __tablename__ = 'Item'\n UniqueId = Column(Integer, ForeignKey('ItemSet.UniqueId'),\n primary_key=True)\n ItemSet = relation('ItemSet')\n ItemName = Column(String(10), primary_key=True)\n ItemValue = Column(Text) # Use PickleType?\n\ndef _create_item(ItemName, ItemValue):\n return Item(ItemName=ItemName, ItemValue=ItemValue)\n\nclass ItemSet(Base):\n\n __tablename__ = 'ItemSet'\n UniqueId = Column(Integer, primary_key=True)\n _items = relation(Item,\n collection_class=attribute_mapped_collection('ItemName'))\n items = association_proxy('_items', 'ItemValue', creator=_create_item)\n\nengine = create_engine('sqlite://', echo=True)\nmetadata.create_all(engine)\n\nsession = sessionmaker(bind=engine)()\ndata = {\"UniqueId\": 1, \"a\": 23, \"b\": \"Hello\", \"c\": \"World\"}\ns = ItemSet(UniqueId=data.pop(\"UniqueId\"))\ns.items = data\nsession.add(s)\nsession.commit()\n\n"
] |
[
9
] |
[] |
[] |
[
"orm",
"pivot_table",
"python",
"sqlalchemy",
"transformation"
] |
stackoverflow_0002089661_orm_pivot_table_python_sqlalchemy_transformation.txt
|
Q:
Retrieving Values with p.expect
I have a program that logs into a server and issues commands. The results are printed out at the end of the script. The below code shows the script I have created to pass commands through ssh.
import pexpect
ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line
p=pexpect.spawn('ssh user@00.00.00.00')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
print "I have entered the password. I will now flip camera through ",
p.sendline("user")
i=p.expect('user@hol-NA:')
p.sendline("cd /opt/ad/bin")
i=p.expect('user@hol-NA:')
p.sendline("./ptzflip")
i=p.expect('user@hol-NA:')
elif i==2:
print "I either got key or connection timeout"
pass
results = p.before # print out the result
print results
The results that the program prints out is:
Value = 1800
Min = 0
Max = 3600
Step = 1
I want to capture the values that are printed out.
In reponse to the questions below. I want to capture eg. 'Value' as a variable and '1800' as its value. I have tried to separate it in a dictionary as mentioned below but I get an error. When I enter:
results_dict = {}
for line in results:
name, val = line.split(' = ')
results_dict[name] = val
I get an error:
Traceback (most recent call last):
File "ptest.py", line 30, in <module>
name, val = line.split(' = ')
ValueError: need more than 1 value to unpack
When I check this code in Python it stores these values as a string. It stores it as:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
Can anyone help in this problem. Thanks
A:
do you mean save it to a file?? then try this
open("output.txt","w").write(results)
or when you run the script on the command line:
$ python script.py > output.txt
otherwise, define what you mean by "capture"
A:
Are Value = 1800 etc. the contents of results? And you want to "capture" that?
Do you mean you want to parse those results? Or execute them as python?
If the former you could do something like (untested, unclean, doesn't deal carefully with whitespace):
results_dict = {}
for line in results.splitlines():
try:
name, val = line.split(' = ')
except ValueError:
continue
results_dict[name] = val
This gives you a python dictionary that you can use. If you know that the values are always numbers, you could convert them with int(val) or float(val)... (The try...except ignores lines of the incorrect form; there may be more robust ways to do this, such as if " = " in line)
If you actually want to end up with a variable named Value with the value 1800, you could use eval(results) [or a safer alternative], although this would need to remove lines without the right format first.
A:
After each call to p.expect returns, whatever the child process emitted just before the matched part (any number of lines), and the matched part itself, are accessible as the before and after properties of p -- that's your "capture" for you!
I.e., as the docs put it:
After each call to expect() the before
and after properties will be set to
the text printed by child application.
The before property will contain all
text up to the expected string
pattern. The after string will contain
the text that was matched by the
expected pattern. The match property
is set to the re MatchObject.
The example code in the docs right after this part can be helpful to understand this -- after establishing an FTP session with the interactive ftp client,
child.sendline('ls /pub/OpenBSD/')
child.expect('ftp> ')
print child.before # Print the result of the ls command.
A:
Whenever this happens to me, it's because the string I'm splitting does not have the value I expected. Why not look at it directly?
for line in results:
print line
name, val = line.split(' = ')
results_dict[name] = val
If it were what you think it is, this would work (now in the interpreter):
>>> 'Value = 1800'.split(' = ')
['Value', '1800']
|
Retrieving Values with p.expect
|
I have a program that logs into a server and issues commands. The results are printed out at the end of the script. The below code shows the script I have created to pass commands through ssh.
import pexpect
ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line
p=pexpect.spawn('ssh user@00.00.00.00')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
print "I have entered the password. I will now flip camera through ",
p.sendline("user")
i=p.expect('user@hol-NA:')
p.sendline("cd /opt/ad/bin")
i=p.expect('user@hol-NA:')
p.sendline("./ptzflip")
i=p.expect('user@hol-NA:')
elif i==2:
print "I either got key or connection timeout"
pass
results = p.before # print out the result
print results
The results that the program prints out is:
Value = 1800
Min = 0
Max = 3600
Step = 1
I want to capture the values that are printed out.
In reponse to the questions below. I want to capture eg. 'Value' as a variable and '1800' as its value. I have tried to separate it in a dictionary as mentioned below but I get an error. When I enter:
results_dict = {}
for line in results:
name, val = line.split(' = ')
results_dict[name] = val
I get an error:
Traceback (most recent call last):
File "ptest.py", line 30, in <module>
name, val = line.split(' = ')
ValueError: need more than 1 value to unpack
When I check this code in Python it stores these values as a string. It stores it as:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
Can anyone help in this problem. Thanks
|
[
"do you mean save it to a file?? then try this\nopen(\"output.txt\",\"w\").write(results)\n\nor when you run the script on the command line: \n$ python script.py > output.txt\n\notherwise, define what you mean by \"capture\"\n",
"Are Value = 1800 etc. the contents of results? And you want to \"capture\" that? \nDo you mean you want to parse those results? Or execute them as python?\nIf the former you could do something like (untested, unclean, doesn't deal carefully with whitespace):\nresults_dict = {}\nfor line in results.splitlines():\n try:\n name, val = line.split(' = ')\n except ValueError:\n continue\n results_dict[name] = val\n\nThis gives you a python dictionary that you can use. If you know that the values are always numbers, you could convert them with int(val) or float(val)... (The try...except ignores lines of the incorrect form; there may be more robust ways to do this, such as if \" = \" in line)\nIf you actually want to end up with a variable named Value with the value 1800, you could use eval(results) [or a safer alternative], although this would need to remove lines without the right format first.\n",
"After each call to p.expect returns, whatever the child process emitted just before the matched part (any number of lines), and the matched part itself, are accessible as the before and after properties of p -- that's your \"capture\" for you!\nI.e., as the docs put it:\n\nAfter each call to expect() the before\n and after properties will be set to\n the text printed by child application.\n The before property will contain all\n text up to the expected string\n pattern. The after string will contain\n the text that was matched by the\n expected pattern. The match property\n is set to the re MatchObject.\n\nThe example code in the docs right after this part can be helpful to understand this -- after establishing an FTP session with the interactive ftp client,\n child.sendline('ls /pub/OpenBSD/')\n child.expect('ftp> ')\n print child.before # Print the result of the ls command.\n\n",
"Whenever this happens to me, it's because the string I'm splitting does not have the value I expected. Why not look at it directly?\nfor line in results:\n print line\n name, val = line.split(' = ') \n results_dict[name] = val\n\nIf it were what you think it is, this would work (now in the interpreter):\n>>> 'Value = 1800'.split(' = ')\n['Value', '1800']\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002087795_python.txt
|
Q:
Doing something *after* handling a request in Google App Engine
I would like the GAE to do something else once my app has sent a response.
The handler would look like this:
class FooHandler(webapp.RequestHandler):
def post(self):
self.response.out.write('Bar')
send_response() # this is where I need help!
do_something_else() # at this point, the response should have been sent
In case you wonder why I try to do this:
I need thread-like behaviour, which is not allowed by GAE's sandboxed environment. So, a function sends several requests whithout caring about the response. Each request starts a time-consuming operation (fetching resources) and saves the result into the datastore, where it can be used by the first function.
Note: The request handler has to send a response. If you do not provide any, it will wait for the post function to complete and then return default headers (which is not the behaviour I'm looking for, of course)
If that can help, the solution might be to use a custom wsgi middeleware, but I have no idea how it works (yet)...
A:
Maybe you can use the Task Queues.
A:
As already mentioned, you can use task queues or the deferred API. Another option is outlined by Rafe Kaplan towards the end of his section in this talk here: you can do an asynchronous API call with a result hook function to process the result, and the result hook will be called when the call finishes, after the response is returned to the user!
A:
Presuming you have access to the WSGI layer, you can wrap the WSGI application and provide a callback to be executed once response sent. For how to do this see:
http://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode
Although that is from the mod_wsgi documentation, the cleanup at end of request example should work for any WSGI compliant stack.
|
Doing something *after* handling a request in Google App Engine
|
I would like the GAE to do something else once my app has sent a response.
The handler would look like this:
class FooHandler(webapp.RequestHandler):
def post(self):
self.response.out.write('Bar')
send_response() # this is where I need help!
do_something_else() # at this point, the response should have been sent
In case you wonder why I try to do this:
I need thread-like behaviour, which is not allowed by GAE's sandboxed environment. So, a function sends several requests whithout caring about the response. Each request starts a time-consuming operation (fetching resources) and saves the result into the datastore, where it can be used by the first function.
Note: The request handler has to send a response. If you do not provide any, it will wait for the post function to complete and then return default headers (which is not the behaviour I'm looking for, of course)
If that can help, the solution might be to use a custom wsgi middeleware, but I have no idea how it works (yet)...
|
[
"Maybe you can use the Task Queues.\n",
"As already mentioned, you can use task queues or the deferred API. Another option is outlined by Rafe Kaplan towards the end of his section in this talk here: you can do an asynchronous API call with a result hook function to process the result, and the result hook will be called when the call finishes, after the response is returned to the user!\n",
"Presuming you have access to the WSGI layer, you can wrap the WSGI application and provide a callback to be executed once response sent. For how to do this see:\nhttp://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode\nAlthough that is from the mod_wsgi documentation, the cleanup at end of request example should work for any WSGI compliant stack.\n"
] |
[
9,
2,
1
] |
[
"You can't GAE sends it's response when the RequestHandler returns if you actually need Threads you will need to write your web application at another hosting company. \n"
] |
[
-1
] |
[
"google_app_engine",
"python",
"wsgi"
] |
stackoverflow_0002069713_google_app_engine_python_wsgi.txt
|
Q:
C++ I/O with Python
I am writing a module in Python which runs a C++ Program using subprocess module. Once I get the output from C++, I need to store the that in Python List . How do I do that ?
A:
Here is a quick and dirty method that I have used.
def run_cpp_thing(parameters):
proc = subprocess.Popen('mycpp' + parameters,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
so, se = proc.communicate()
# print se # the stderr stream
# print so # the stdio stream
# I'm going to assume so =
# "1 2 3 4 5"
# Now parse the stdio stream.
# you will obvious do much more error checking :)
# **updated to make them all numbers**
return [float(x) for x in so.next().split()]
A:
one dirty method:
You can use Python to read (raw_input) from stdin (if there is not input, it will wait). the C++ program writes to stdout.
A:
Based upon your comment, assuming data contains the output:
numbers = [int(x) for x in data.split()]
I am assuming that the numbers are separated by whitespace, and that you already got the string in Python from your C++ program (i.e., you know how to use the subprocess module).
Edit: Let's say your C++ program is:
$ cat a.cpp
#include <iostream>
int main()
{
int a[] = { 1, 2, 3, 4 };
for (int i=0; i < sizeof a / sizeof a[0]; ++i) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
return 0;
}
$ g++ a.cpp -o test
$ ./test
1 2 3 4
$
Then, you can do this in Python:
import subprocess
data = subprocess.Popen('./test', stdout=subprocess.PIPE).communicate()[0]
numbers = [int(x) for x in data.split()]
(It doesn't matter if your C++ program outputs the numbers with newline as a separator, or any combination of white-space for that matter.)
A:
In the command for the process you could do a redirect to a temporary file. Then read that file when the process returns.
|
C++ I/O with Python
|
I am writing a module in Python which runs a C++ Program using subprocess module. Once I get the output from C++, I need to store the that in Python List . How do I do that ?
|
[
"Here is a quick and dirty method that I have used. \ndef run_cpp_thing(parameters):\n\n proc = subprocess.Popen('mycpp' + parameters,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE)\n\n so, se = proc.communicate()\n\n # print se # the stderr stream\n # print so # the stdio stream\n\n # I'm going to assume so = \n # \"1 2 3 4 5\"\n\n # Now parse the stdio stream. \n # you will obvious do much more error checking :)\n # **updated to make them all numbers**\n return [float(x) for x in so.next().split()]\n\n",
"one dirty method:\nYou can use Python to read (raw_input) from stdin (if there is not input, it will wait). the C++ program writes to stdout. \n",
"Based upon your comment, assuming data contains the output:\nnumbers = [int(x) for x in data.split()]\n\nI am assuming that the numbers are separated by whitespace, and that you already got the string in Python from your C++ program (i.e., you know how to use the subprocess module).\nEdit: Let's say your C++ program is:\n$ cat a.cpp\n#include <iostream>\n\nint main()\n{\n int a[] = { 1, 2, 3, 4 };\n for (int i=0; i < sizeof a / sizeof a[0]; ++i) {\n std::cout << a[i] << \" \";\n }\n std::cout << std::endl;\n return 0;\n}\n$ g++ a.cpp -o test\n$ ./test\n1 2 3 4\n$\n\nThen, you can do this in Python:\nimport subprocess\ndata = subprocess.Popen('./test', stdout=subprocess.PIPE).communicate()[0]\nnumbers = [int(x) for x in data.split()]\n\n(It doesn't matter if your C++ program outputs the numbers with newline as a separator, or any combination of white-space for that matter.)\n",
"In the command for the process you could do a redirect to a temporary file. Then read that file when the process returns.\n"
] |
[
6,
2,
1,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0002093411_c++_python.txt
|
Q:
how to erase lines with wxpython
I'm trying to make a paint tool in wxpython. and i couldn't find a way to make an ( Eraser ) . how can i make an eraser tool - just like the one in windows paint - in wxpython ?
please help .
the idea or small code sample would be very helpful
thanks in advance
A:
Have you made a Pen tool? Just set its colour to the canvas' background colour ;)
by the way I actively develop my own wxpython painting program that you may want to check out; see http://code.google.com/p/whyteboard/
|
how to erase lines with wxpython
|
I'm trying to make a paint tool in wxpython. and i couldn't find a way to make an ( Eraser ) . how can i make an eraser tool - just like the one in windows paint - in wxpython ?
please help .
the idea or small code sample would be very helpful
thanks in advance
|
[
"Have you made a Pen tool? Just set its colour to the canvas' background colour ;)\nby the way I actively develop my own wxpython painting program that you may want to check out; see http://code.google.com/p/whyteboard/\n"
] |
[
3
] |
[] |
[] |
[
"gdi",
"python",
"wxpython"
] |
stackoverflow_0002091999_gdi_python_wxpython.txt
|
Q:
Django/GAE anonymous users data
in my application I have per-user models, let me explain with a simple example:
class Item(db.Model):
master = db.ReferenceProperty(User,collection_name="items")
name = db.StringProperty()
description = db.StringProperty()
value = db.StringProperty()
def __unicode__(self):
return u"%s"%self.name
So I can store informations on the database only if the user is authenticated. ( well, only if there is an user)
I'm looking for a way to let the anonymous/temporary users to register "personal items" in the session that expires after a certain amount of time.
Any idea?
A:
You could create an Item-like lightweight class and store instances of it in the session. If the user registers later on and you want to sync with what you have in the database, you can pick up what you've stored in the session and convert to the real Item objects (and then save() them).
You can also do it all with the Item objects, leaving master reference as None.
|
Django/GAE anonymous users data
|
in my application I have per-user models, let me explain with a simple example:
class Item(db.Model):
master = db.ReferenceProperty(User,collection_name="items")
name = db.StringProperty()
description = db.StringProperty()
value = db.StringProperty()
def __unicode__(self):
return u"%s"%self.name
So I can store informations on the database only if the user is authenticated. ( well, only if there is an user)
I'm looking for a way to let the anonymous/temporary users to register "personal items" in the session that expires after a certain amount of time.
Any idea?
|
[
"You could create an Item-like lightweight class and store instances of it in the session. If the user registers later on and you want to sync with what you have in the database, you can pick up what you've stored in the session and convert to the real Item objects (and then save() them).\nYou can also do it all with the Item objects, leaving master reference as None.\n"
] |
[
0
] |
[] |
[] |
[
"authentication",
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002093115_authentication_django_google_app_engine_python.txt
|
Q:
Extracting Values from a String
I am trying to extract values from a string, I have tried to get re.match working but have not had any luck. The string is:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
I have tried:
map(int,re.search("Value\s*=\s*").group(1))
and also:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'.split(' = ')
I am not sure what else to add or do. I want to retrieve the attributes 'Value, Max, Step' and their values. Is there anyway to do this?
Thanks for any help
A:
For that particular string, the following parses it into a dictionary:
s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
d = {}
for pair in [val.split('=') for val in s.split('\r\n')[1:-1]]:
d[pair[0]] = int(pair[1])
A:
>>> s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
>>> bits = s.split('\r\n')
>>> val, max_val, step = [int(bits[i].partition(' = ')[2]) for i in [1, 3, 4]]
>>> val
1800
>>> max_val
3600
>>> step
1
A:
s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
data = {}
for l in s.split('\r\n'):
if " = " in l:
k,v = l.split(" = ")
data[k] = int(v)
print data
A:
You are trying to use regexp, but I think you can simply split it by \r\n and then use values with =.
Something like:
s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
dct = {}
arr = [ss for ss in s.split('\r\n') if '=' in ss]
for e in arr:
k, v = e.split(' = ')
dct[k] = v
print dct
|
Extracting Values from a String
|
I am trying to extract values from a string, I have tried to get re.match working but have not had any luck. The string is:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
I have tried:
map(int,re.search("Value\s*=\s*").group(1))
and also:
'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'.split(' = ')
I am not sure what else to add or do. I want to retrieve the attributes 'Value, Max, Step' and their values. Is there anyway to do this?
Thanks for any help
|
[
"For that particular string, the following parses it into a dictionary:\ns = '/opt/ad/bin$ ./ptzflip\\r\\nValue = 1800\\r\\nMin = 0\\r\\nMax = 3600\\r\\nStep = 1\\r\\n'\nd = {}\nfor pair in [val.split('=') for val in s.split('\\r\\n')[1:-1]]:\n d[pair[0]] = int(pair[1])\n\n",
">>> s = '/opt/ad/bin$ ./ptzflip\\r\\nValue = 1800\\r\\nMin = 0\\r\\nMax = 3600\\r\\nStep = 1\\r\\n'\n>>> bits = s.split('\\r\\n')\n>>> val, max_val, step = [int(bits[i].partition(' = ')[2]) for i in [1, 3, 4]]\n>>> val\n1800\n>>> max_val\n3600\n>>> step\n1\n\n",
"s = '/opt/ad/bin$ ./ptzflip\\r\\nValue = 1800\\r\\nMin = 0\\r\\nMax = 3600\\r\\nStep = 1\\r\\n'\ndata = {}\n\nfor l in s.split('\\r\\n'):\n if \" = \" in l:\n k,v = l.split(\" = \")\n data[k] = int(v)\n\nprint data\n\n",
"You are trying to use regexp, but I think you can simply split it by \\r\\n and then use values with =.\nSomething like:\ns = '/opt/ad/bin$ ./ptzflip\\r\\nValue = 1800\\r\\nMin = 0\\r\\nMax = 3600\\r\\nStep = 1\\r\\n'\ndct = {}\narr = [ss for ss in s.split('\\r\\n') if '=' in ss]\nfor e in arr:\n k, v = e.split(' = ')\n dct[k] = v\nprint dct\n\n"
] |
[
6,
3,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002093812_python_string.txt
|
Q:
"WindowsError: exception: access violation..." - ctypes question
Here is the prototype for a C function that resides in a DLL:
extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*);
In another thread, I asked about how to properly create and send the necessary arguments to this function.
Here is the thread:
How do I wrap this C function, with multiple arguments, with ctypes?
So I have used the good information in the thread above, but now I am getting this error:
WindowsError: exception: access violation writing 0x00001001
I am unsure as to how to proceed. I'm on Windows XP - if I log into the administrator account, would that fix the problem? Or is this a problem with Python's memory objects being immutable?
Thanks all!
Edited with relevant Python:
FROGPCGPMonitorDLL = windll.LoadLibrary('C:\Program Files\MesaPhotonics\VideoFROG 7.0\PCGPMonitor.dll')
#Function argument:double* pulse
sizePULSE = 2 ##Manual is super unclear here
pulse = c_double * sizePULSE
ptrpulse = pulse()
#Function argument:double* tdl
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE == 0 :
sizeTRACE = 1 #Manually set size to 1 for testing purposes
print "Size of FROG trace is zero. Probably not right."
tdl = c_double*sizeTRACE
ptrtdl = tdl()
#Function argument:double* tdP
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
tdP = c_double*sizeTRACE
ptrtdP = tdP()
#Function Argument:double* fdl
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
fdl = c_double*sizeTRACE
ptrfdl = fdl()
#Function Argument: double* fdP
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
fdP = c_double*sizeTRACE
ptrfdP = fdP()
FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP)
Edited to add some relevant code!
I'm just writing a simple script to get each of the device's functions working first. The variable sizeTRACE can be reused, I know, but its just test code right now and the device isn't hooked up, so GetSize() is returning zero. Multiplying by zero would kill my buzz, so I'm forcing it to 1 for now. If this isn't clear, I apologize and will try to edit this post.
Second edit:
It was suggested to plug in the device and see if that helped. I just plugged in the FROG, but I'm still getting the same error. Very strange, and I'm rather clueless. In any event, thanks again all!
A:
The error you're getting is not related to Administrative rights. The problem is you're using C and inadvertently performing illegal operations (the kind of operations that if went unchecked would probably crash your system).
The error you get indicates that your program is trying to write to memory address 1001, but isn't supposed to be writing to that memory address.
This could happen for any number of reasons.
One possible reason is that the double* you're passing to ReturnPulse aren't as big as ReturnPulse expects them to be. You probably need to at least get GetSize to work properly... you might be able to work around it by just allocating a very large array instead of calling GetSize. i.e.
ptrfdP = (c_double*100000)()
That will allocate 100,000 doubles, which may be more appropriate for capturing a digital Pulse.
The other issue is that the type conversion may not be happening as expected.
You might have better luck if ctypes knows that ReturnPulse takes five double pointers. i.e.
# sometime before calling ReturnPulse
FROGPCGPMonitorDLL.ReturnPulse.argtypes = [POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double)]
If neither of these techniques works, send the usage documentation on ReturnPulse, which should help us recognize the intended use.
Or better yet, send sample code that's supposed to work in C and I'll translate that to the equivalent implementation in ctypes.
Edit: adding example implementation of ReturnPulse and ctypes usage.
I have implemented something like what I expect ReturnPulse to be doing in a C DLL:
void ReturnPulse(double *a, double*b,double*c,double*d,double*e)
{
// write some values to the memory pointed-to by a-e
// a-e should have enough memory allocated for the loop
for(int i = 0; i < 20; i++)
{
a[i] = 1.0*i;
b[i] = 3.0*i;
c[i] = 5.0*i;
d[i] = 7.0*i;
e[i] = 13.0*i;
}
}
I compile this into a DLL (which I call examlib), and then call it using ctypes with the following code:
LP_c_double = ctypes.POINTER(ctypes.c_double)
examlib.ReturnPulse.argtypes = [LP_c_double, LP_c_double, LP_c_double, LP_c_double, LP_c_double, ]
a = (ctypes.c_double*20)()
b = (ctypes.c_double*20)()
c = (ctypes.c_double*20)()
d = (ctypes.c_double*20)()
e = (ctypes.c_double*20)()
examlib.ReturnPulse(a,b,c,d,e)
print 'values are'
for array in (a,b,c,d,e):
print '\t'.join(map(str, array[:5]))
The resulting output is
values are
0.0 1.0 2.0 3.0 4.0
0.0 3.0 6.0 9.0 12.0
0.0 5.0 10.0 15.0 20.0
0.0 7.0 14.0 21.0 28.0
0.0 13.0 26.0 39.0 52.0
Indeed, even without setting ReturnPulse.argtypes, the code runs without errors.
A:
ptrpulse and friends are python identifiers that point to various ctypes objects (I guess they are all c_double*2). They either need to be wrapped with a ctypes pointer object, or passed to the C function using ctypes.byref.
|
"WindowsError: exception: access violation..." - ctypes question
|
Here is the prototype for a C function that resides in a DLL:
extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*);
In another thread, I asked about how to properly create and send the necessary arguments to this function.
Here is the thread:
How do I wrap this C function, with multiple arguments, with ctypes?
So I have used the good information in the thread above, but now I am getting this error:
WindowsError: exception: access violation writing 0x00001001
I am unsure as to how to proceed. I'm on Windows XP - if I log into the administrator account, would that fix the problem? Or is this a problem with Python's memory objects being immutable?
Thanks all!
Edited with relevant Python:
FROGPCGPMonitorDLL = windll.LoadLibrary('C:\Program Files\MesaPhotonics\VideoFROG 7.0\PCGPMonitor.dll')
#Function argument:double* pulse
sizePULSE = 2 ##Manual is super unclear here
pulse = c_double * sizePULSE
ptrpulse = pulse()
#Function argument:double* tdl
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE == 0 :
sizeTRACE = 1 #Manually set size to 1 for testing purposes
print "Size of FROG trace is zero. Probably not right."
tdl = c_double*sizeTRACE
ptrtdl = tdl()
#Function argument:double* tdP
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
tdP = c_double*sizeTRACE
ptrtdP = tdP()
#Function Argument:double* fdl
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
fdl = c_double*sizeTRACE
ptrfdl = fdl()
#Function Argument: double* fdP
sizeTRACE = FROGPCGPMonitorDLL.GetSize()
if sizeTRACE==0:
sizeTRACE=1
print "Size of FROG trace is zero. Probably not right."
fdP = c_double*sizeTRACE
ptrfdP = fdP()
FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP)
Edited to add some relevant code!
I'm just writing a simple script to get each of the device's functions working first. The variable sizeTRACE can be reused, I know, but its just test code right now and the device isn't hooked up, so GetSize() is returning zero. Multiplying by zero would kill my buzz, so I'm forcing it to 1 for now. If this isn't clear, I apologize and will try to edit this post.
Second edit:
It was suggested to plug in the device and see if that helped. I just plugged in the FROG, but I'm still getting the same error. Very strange, and I'm rather clueless. In any event, thanks again all!
|
[
"The error you're getting is not related to Administrative rights. The problem is you're using C and inadvertently performing illegal operations (the kind of operations that if went unchecked would probably crash your system).\nThe error you get indicates that your program is trying to write to memory address 1001, but isn't supposed to be writing to that memory address.\nThis could happen for any number of reasons.\nOne possible reason is that the double* you're passing to ReturnPulse aren't as big as ReturnPulse expects them to be. You probably need to at least get GetSize to work properly... you might be able to work around it by just allocating a very large array instead of calling GetSize. i.e.\nptrfdP = (c_double*100000)()\n\nThat will allocate 100,000 doubles, which may be more appropriate for capturing a digital Pulse.\nThe other issue is that the type conversion may not be happening as expected.\nYou might have better luck if ctypes knows that ReturnPulse takes five double pointers. i.e.\n# sometime before calling ReturnPulse\nFROGPCGPMonitorDLL.ReturnPulse.argtypes = [POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double)]\n\nIf neither of these techniques works, send the usage documentation on ReturnPulse, which should help us recognize the intended use.\nOr better yet, send sample code that's supposed to work in C and I'll translate that to the equivalent implementation in ctypes.\nEdit: adding example implementation of ReturnPulse and ctypes usage.\nI have implemented something like what I expect ReturnPulse to be doing in a C DLL:\nvoid ReturnPulse(double *a, double*b,double*c,double*d,double*e)\n{\n // write some values to the memory pointed-to by a-e\n // a-e should have enough memory allocated for the loop\n for(int i = 0; i < 20; i++)\n {\n a[i] = 1.0*i;\n b[i] = 3.0*i;\n c[i] = 5.0*i;\n d[i] = 7.0*i;\n e[i] = 13.0*i;\n }\n}\n\nI compile this into a DLL (which I call examlib), and then call it using ctypes with the following code:\nLP_c_double = ctypes.POINTER(ctypes.c_double)\nexamlib.ReturnPulse.argtypes = [LP_c_double, LP_c_double, LP_c_double, LP_c_double, LP_c_double, ]\n\na = (ctypes.c_double*20)()\nb = (ctypes.c_double*20)()\nc = (ctypes.c_double*20)()\nd = (ctypes.c_double*20)()\ne = (ctypes.c_double*20)()\n\nexamlib.ReturnPulse(a,b,c,d,e)\n\nprint 'values are'\nfor array in (a,b,c,d,e):\n print '\\t'.join(map(str, array[:5]))\n\nThe resulting output is\nvalues are\n0.0 1.0 2.0 3.0 4.0\n0.0 3.0 6.0 9.0 12.0\n0.0 5.0 10.0 15.0 20.0\n0.0 7.0 14.0 21.0 28.0\n0.0 13.0 26.0 39.0 52.0\n\nIndeed, even without setting ReturnPulse.argtypes, the code runs without errors.\n",
"ptrpulse and friends are python identifiers that point to various ctypes objects (I guess they are all c_double*2). They either need to be wrapped with a ctypes pointer object, or passed to the C function using ctypes.byref.\n"
] |
[
13,
0
] |
[] |
[] |
[
"access_violation",
"ctypes",
"python",
"windowserror"
] |
stackoverflow_0001382076_access_violation_ctypes_python_windowserror.txt
|
Q:
Django Admin site TemplateSyntaxError at /admin/: name not defined
I have an issue where, when I log in to the Django admin site, I get a template syntax error in /Library/Python/2.6/site-packages/django/template/debug.py in render_node, line 81.
I can't find out how to solve this as it is part of Django, I didn't write the code and I have no idea how it works.
This did work fine up until a few days ago when I last tried it.
The error is:
Caught an exception while rendering: name 'pest' is not defined
Where pest is the name of my project. As far as I know, I have all the apps in my project installed correctly.
Thanks in advance!
A:
It seems like an error in the admin.py file for your app.
It may be a missing import, or even a typo, but it's hard to tell without any code. It would be great if you could post your admin.py file so we can take a look.
TemplateSyntaxErrors in Django are terrible, they almost never tell you what the real problem is. In this case, for example, the template is part of Django, but the error is probably something in your admin file, which Django reads to create the admin interface. The traceback is too deep to find out right away where in your code the problem is.
A:
It turns out it was a rather simple thing, I am just not experienced enough with Python and I was calling on my .NET experience. Bad mistake.
I called project.settings.SETTING where I should have imported project.settings and then accessed settings.SETTING.
In .NET the imports act just shortcuts so you don't have to type the whole 'path' to the function or setting, whereas in Python it seems that you must have the things you are using imported.
I don't know if that makes any sense, or if it even correct, but it now works. Thanks for everyone's help, you are always a great help and I wouldn't be able to do this development and advance my knowledge without the resources here.
|
Django Admin site TemplateSyntaxError at /admin/: name not defined
|
I have an issue where, when I log in to the Django admin site, I get a template syntax error in /Library/Python/2.6/site-packages/django/template/debug.py in render_node, line 81.
I can't find out how to solve this as it is part of Django, I didn't write the code and I have no idea how it works.
This did work fine up until a few days ago when I last tried it.
The error is:
Caught an exception while rendering: name 'pest' is not defined
Where pest is the name of my project. As far as I know, I have all the apps in my project installed correctly.
Thanks in advance!
|
[
"It seems like an error in the admin.py file for your app.\nIt may be a missing import, or even a typo, but it's hard to tell without any code. It would be great if you could post your admin.py file so we can take a look.\nTemplateSyntaxErrors in Django are terrible, they almost never tell you what the real problem is. In this case, for example, the template is part of Django, but the error is probably something in your admin file, which Django reads to create the admin interface. The traceback is too deep to find out right away where in your code the problem is.\n",
"It turns out it was a rather simple thing, I am just not experienced enough with Python and I was calling on my .NET experience. Bad mistake.\nI called project.settings.SETTING where I should have imported project.settings and then accessed settings.SETTING. \nIn .NET the imports act just shortcuts so you don't have to type the whole 'path' to the function or setting, whereas in Python it seems that you must have the things you are using imported.\nI don't know if that makes any sense, or if it even correct, but it now works. Thanks for everyone's help, you are always a great help and I wouldn't be able to do this development and advance my knowledge without the resources here.\n"
] |
[
1,
0
] |
[] |
[] |
[
"admin",
"django",
"python"
] |
stackoverflow_0002086016_admin_django_python.txt
|
Q:
Why can't Python decorators be chained across definitions?
Why arn't the following two scripts equivalent?
(Taken from another question: Understanding Python Decorators)
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## returns <b><i>hello world</i></b>
and with a decorated decorator:
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
@makebold
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeitalic
def hello():
return "hello world"
print hello() ## TypeError: wrapped() takes no arguments (1 given)
Why do I want to know? I've written a retry decorator to catch MySQLdb exceptions - if the exception is transient (e.g. Timeout) it will re-call the function after sleeping a bit.
I've also got a modifies_db decorator which takes care of some cache-related housekeeping. modifies_db is decorated with retry, so I assumed that all functions decorated with modifies_db would also retry implicitly. Where did I go wrong?
A:
The problem with the second example is that
@makebold
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
is trying to decorate makeitalic, the decorator, and not wrapped, the function it returns.
You can do what I think you intend with something like this:
def makeitalic(fn):
@makebold
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
Here makeitalic uses makebold to decorate wrapped.
A:
The reason is because wrapped() inside of makebold doesn't accept any arguments.
When you use the decorator like that it can cause some issues, I'll post an example of how to achieve what you're wanting though, give me just a moment.
Here is a working example of what you need.
def makebold(rewrap=False):
if rewrap:
def inner(decorator):
def rewrapper(func):
def wrapped(*args, **kwargs):
return "<b>%s</b>" % decorator(func)(*args,**kwargs)
return wrapped
return rewrapper
return inner
else:
def inner(func):
def wrapped(*args, **kwargs):
return "<b>%s</b>" % func(*args, **kwargs)
return wrapped
return inner
@makebold(rewrap=True)
def makeitalic(fn):
def wrapped(*args, **kwargs):
return "<i>%s</i>" % fn(*args, **kwargs)
return wrapped
@makeitalic
def hello():
return "hello world"
@makebold()
def hello2():
return "Bob Dole"
if __name__ == "__main__":
print hello()
print hello2()
makebold is kinda ugly, but it shows you how to write a decorator that can optionally wrap another decorator.
Here is the output from the above script:
<b><i>hello world</i></b>
<b>Bob Dole</b>
Note that makebold is the only recursive decorator. Also note the subtle difference in usage: @makebold() vs @makeitalic.
A:
The problem is replacing "makeitalic" (which takes one argument) with the "wrapped"-function in "makebold" which takes zero arguments.
Use *args, **kwargs to pass on arguments further down the chain:
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
|
Why can't Python decorators be chained across definitions?
|
Why arn't the following two scripts equivalent?
(Taken from another question: Understanding Python Decorators)
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## returns <b><i>hello world</i></b>
and with a decorated decorator:
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
@makebold
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeitalic
def hello():
return "hello world"
print hello() ## TypeError: wrapped() takes no arguments (1 given)
Why do I want to know? I've written a retry decorator to catch MySQLdb exceptions - if the exception is transient (e.g. Timeout) it will re-call the function after sleeping a bit.
I've also got a modifies_db decorator which takes care of some cache-related housekeeping. modifies_db is decorated with retry, so I assumed that all functions decorated with modifies_db would also retry implicitly. Where did I go wrong?
|
[
"The problem with the second example is that\n@makebold\ndef makeitalic(fn):\n def wrapped():\n return \"<i>\" + fn() + \"</i>\"\n return wrapped\n\nis trying to decorate makeitalic, the decorator, and not wrapped, the function it returns.\nYou can do what I think you intend with something like this:\ndef makeitalic(fn):\n @makebold\n def wrapped():\n return \"<i>\" + fn() + \"</i>\"\n return wrapped\n\nHere makeitalic uses makebold to decorate wrapped.\n",
"The reason is because wrapped() inside of makebold doesn't accept any arguments. \nWhen you use the decorator like that it can cause some issues, I'll post an example of how to achieve what you're wanting though, give me just a moment.\nHere is a working example of what you need.\ndef makebold(rewrap=False):\n if rewrap:\n def inner(decorator):\n def rewrapper(func):\n def wrapped(*args, **kwargs):\n return \"<b>%s</b>\" % decorator(func)(*args,**kwargs)\n return wrapped\n return rewrapper\n return inner\n\n else:\n def inner(func):\n def wrapped(*args, **kwargs):\n return \"<b>%s</b>\" % func(*args, **kwargs) \n return wrapped\n return inner\n\n@makebold(rewrap=True)\ndef makeitalic(fn):\n def wrapped(*args, **kwargs):\n return \"<i>%s</i>\" % fn(*args, **kwargs)\n return wrapped\n\n@makeitalic\ndef hello():\n return \"hello world\"\n\n@makebold()\ndef hello2():\n return \"Bob Dole\" \n\nif __name__ == \"__main__\":\n print hello() \n print hello2()\n\nmakebold is kinda ugly, but it shows you how to write a decorator that can optionally wrap another decorator.\nHere is the output from the above script:\n<b><i>hello world</i></b>\n<b>Bob Dole</b>\n\nNote that makebold is the only recursive decorator. Also note the subtle difference in usage: @makebold() vs @makeitalic. \n",
"The problem is replacing \"makeitalic\" (which takes one argument) with the \"wrapped\"-function in \"makebold\" which takes zero arguments.\nUse *args, **kwargs to pass on arguments further down the chain:\ndef wrapped(*args, **kwargs):\n return \"<b>\" + fn(*args, **kwargs) + \"</b>\"\n\n"
] |
[
9,
1,
0
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002094008_decorator_python.txt
|
Q:
How do I write a Django view that can be called by jQuery's $.getJSON()?
The javascript:
$.getJSON('/jsonView', {
tag: "userName",
userName: 'zjm1126'
}, function (H) {
if (H.result == "successName") {
F.showOk(h.ok);
} else {
if (H.result == "existName") {
F.showErr(h.userNameExist);
}
}
});
The view:
def jsonView(request):
# What would go here?
def json_view(request):
import json
username=request.GET.get('username')
result='successName'
if username:
try:
user=User.objects.get(username=username)
result='existName'
except User.DoesNotExist:
pass
return HttpResponse(json.dumps({'result': result}))
it makes 500 INTERNAL SERVER ERROR.
why???
A:
I suggest you work your way through James Bennett's tutorial on using AJAX with Django - he includes details on writing views that return JSON.
A:
This is relatively straightforward
def json_view(request):
username=request.GET.get('username')
result='successName'
if username:
try:
user=User.objects.get(username=username)
result='existName'
except User.DoesNotExist:
pass
return HttpResponse(simplejson.dumps({'result': result}))
A:
It's pretty simple:
Retrieve GET data from request.GET
Do stuff
Return a response with mimetype application/javascript
1 and 2 are like any other view. If you don't know how to do 3, check out django.http.HttpResponse.__init__
|
How do I write a Django view that can be called by jQuery's $.getJSON()?
|
The javascript:
$.getJSON('/jsonView', {
tag: "userName",
userName: 'zjm1126'
}, function (H) {
if (H.result == "successName") {
F.showOk(h.ok);
} else {
if (H.result == "existName") {
F.showErr(h.userNameExist);
}
}
});
The view:
def jsonView(request):
# What would go here?
def json_view(request):
import json
username=request.GET.get('username')
result='successName'
if username:
try:
user=User.objects.get(username=username)
result='existName'
except User.DoesNotExist:
pass
return HttpResponse(json.dumps({'result': result}))
it makes 500 INTERNAL SERVER ERROR.
why???
|
[
"I suggest you work your way through James Bennett's tutorial on using AJAX with Django - he includes details on writing views that return JSON.\n",
"This is relatively straightforward\ndef json_view(request):\n username=request.GET.get('username')\n result='successName'\n if username:\n try:\n user=User.objects.get(username=username)\n result='existName'\n except User.DoesNotExist:\n pass\n return HttpResponse(simplejson.dumps({'result': result}))\n\n",
"It's pretty simple:\n\nRetrieve GET data from request.GET\nDo stuff\nReturn a response with mimetype application/javascript\n\n1 and 2 are like any other view. If you don't know how to do 3, check out django.http.HttpResponse.__init__\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002092566_django_python.txt
|
Q:
What permissions are required for subprocess.Popen?
The following code:
gb = self.request.form['groupby']
typ = self.request.form['type']
tbl = self.request.form['table']
primary = self.request.form.get('primary', None)
if primary is not None:
create = False
else:
create = True
mdb = tempfile.NamedTemporaryFile()
mdb.write(self.request.form['mdb'].read())
mdb.seek(0)
csv = tempfile.TemporaryFile()
conversion = subprocess.Popen(("/Users/jondoe/development/mdb-export", mdb.name, tbl,),stdout=csv)
Causes the this error when calling the last line i.e. 'conversion =' in OS X.
Traceback (innermost last):
Module ZPublisher.Publish, line 119, in publish
Module ZPublisher.mapply, line 88, in mapply
Module ZPublisher.Publish, line 42, in call_object
Module circulartriangle.mdbtoat.mdb, line 62, in __call__
Module subprocess, line 543, in __init__
Module subprocess, line 975, in _execute_child
OSError: [Errno 13] Permission denied
I've tried chmod 777 /Users/jondoe/development/mdb-export - what else might be required?
A:
Assuming that permissions on parent folders are correct (i.e. all parent folders should have +x permission), try adding:
shell=True
to the Popen command such as:
subprocess.Popen(("/Users/jondoe/development/mdb-export", mdb.name, tbl,), stdout=csv, shell=True)
A:
It seems the 'Permissions denied error' was orginally coming from Popen trying to execute mdb-export from the wrong location (and to compound things, with the wrong permissions).
If mdbtools is installed, the following works fine and inherits the correct permissions without the need for sudo etc.
subprocess.Popen(("mdb-export", mdb.name, tbl,),stdout=csv)
(Worth noting, I got myself into a muddle for a while, having forgotten that Popen is for opening executables, not folders or non-exectable files in folders)
Thanks for all your responses, they all made for interesting reading regardless :)
A:
Can you feed "sudo" to subprocess? See this SO thread.
@Jon Hadley, from the interpreter:
>>> import subprocess
>>> p = subprocess.call(['sudo','/usr/bin/env'])
PASSWORD:
[snip]
USER=root
USERNAME=root
SUDO_COMMAND=/usr/bin/env
SUDO_USER=telliott99
SUDO_UID=501
SUDO_GID=20
From Terminal on OS X, I have to do sudo when I run the script:
$ sudo python test.py
then this (in test.py) gives the same output as before:
import subprocess
p = subprocess.Popen('/usr/bin/env')
Getting subprocess to directly handle the authentication from a script is probably not a good idea, since it hides the privilege escalation. But you could look at pexpect and this SO answer.
A:
You also need to ensure read and execute permissions for the user running that code on the directories up the chain - /Users, /Users/jondoe and /Users/jondoe/development.
|
What permissions are required for subprocess.Popen?
|
The following code:
gb = self.request.form['groupby']
typ = self.request.form['type']
tbl = self.request.form['table']
primary = self.request.form.get('primary', None)
if primary is not None:
create = False
else:
create = True
mdb = tempfile.NamedTemporaryFile()
mdb.write(self.request.form['mdb'].read())
mdb.seek(0)
csv = tempfile.TemporaryFile()
conversion = subprocess.Popen(("/Users/jondoe/development/mdb-export", mdb.name, tbl,),stdout=csv)
Causes the this error when calling the last line i.e. 'conversion =' in OS X.
Traceback (innermost last):
Module ZPublisher.Publish, line 119, in publish
Module ZPublisher.mapply, line 88, in mapply
Module ZPublisher.Publish, line 42, in call_object
Module circulartriangle.mdbtoat.mdb, line 62, in __call__
Module subprocess, line 543, in __init__
Module subprocess, line 975, in _execute_child
OSError: [Errno 13] Permission denied
I've tried chmod 777 /Users/jondoe/development/mdb-export - what else might be required?
|
[
"Assuming that permissions on parent folders are correct (i.e. all parent folders should have +x permission), try adding:\nshell=True\n\nto the Popen command such as:\nsubprocess.Popen((\"/Users/jondoe/development/mdb-export\", mdb.name, tbl,), stdout=csv, shell=True)\n\n",
"It seems the 'Permissions denied error' was orginally coming from Popen trying to execute mdb-export from the wrong location (and to compound things, with the wrong permissions). \nIf mdbtools is installed, the following works fine and inherits the correct permissions without the need for sudo etc.\nsubprocess.Popen((\"mdb-export\", mdb.name, tbl,),stdout=csv)\n\n(Worth noting, I got myself into a muddle for a while, having forgotten that Popen is for opening executables, not folders or non-exectable files in folders)\nThanks for all your responses, they all made for interesting reading regardless :)\n",
"Can you feed \"sudo\" to subprocess? See this SO thread.\n@Jon Hadley, from the interpreter:\n>>> import subprocess\n>>> p = subprocess.call(['sudo','/usr/bin/env'])\nPASSWORD:\n[snip]\n\nUSER=root\nUSERNAME=root\nSUDO_COMMAND=/usr/bin/env\nSUDO_USER=telliott99\nSUDO_UID=501\nSUDO_GID=20\n\nFrom Terminal on OS X, I have to do sudo when I run the script:\n$ sudo python test.py\n\nthen this (in test.py) gives the same output as before:\nimport subprocess\np = subprocess.Popen('/usr/bin/env')\n\nGetting subprocess to directly handle the authentication from a script is probably not a good idea, since it hides the privilege escalation. But you could look at pexpect and this SO answer.\n",
"You also need to ensure read and execute permissions for the user running that code on the directories up the chain - /Users, /Users/jondoe and /Users/jondoe/development.\n"
] |
[
17,
8,
2,
0
] |
[] |
[] |
[
"macos",
"popen",
"python",
"subprocess"
] |
stackoverflow_0002066068_macos_popen_python_subprocess.txt
|
Q:
Split a string at newline characters
I have a string, say
a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"
How do we split the above with the delimiter \n (a newline)?
The result should be
['Show details1', 'Show details2', ..., 'Show details5']
A:
Use a.splitlines(). This will return you a list of the separate lines. To get your "should be" result, add " ".join(a.splitlines()), and to get all in lower case as shown, the whole enchilada looks like " ".join(a.splitlines()).lower().
A:
If you are concerned only with the trailing newline, you can do:
a.rstrip().split('\n')
See, str.lstrip() and str.strip() for variations.
If you are more generally concerned by superfluous newlines producing empty items, you can do:
filter(None, a.split('\n'))
A:
split method:
a.split('\n')[:-1]
A:
a.split('\n')
would return an empty entry as the last member of the list.so use
a.split('\n')[:-1]
A:
try:
a.split('\n')
|
Split a string at newline characters
|
I have a string, say
a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"
How do we split the above with the delimiter \n (a newline)?
The result should be
['Show details1', 'Show details2', ..., 'Show details5']
|
[
"Use a.splitlines(). This will return you a list of the separate lines. To get your \"should be\" result, add \" \".join(a.splitlines()), and to get all in lower case as shown, the whole enchilada looks like \" \".join(a.splitlines()).lower().\n",
"If you are concerned only with the trailing newline, you can do:\na.rstrip().split('\\n')\n\nSee, str.lstrip() and str.strip() for variations.\nIf you are more generally concerned by superfluous newlines producing empty items, you can do:\nfilter(None, a.split('\\n'))\n\n",
"split method:\na.split('\\n')[:-1]\n\n",
" a.split('\\n')\n\nwould return an empty entry as the last member of the list.so use\n\na.split('\\n')[:-1]\n\n",
"try:\na.split('\\n')\n\n"
] |
[
21,
18,
6,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002094176_python_string.txt
|
Q:
Python functional programming snippets
I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site.
Thanks.
A:
Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readability and understandability later on.
If you like functional programming, learn Haskell, ML, or F#. You will be amazed at what those languages offer (pure functions to start with).
A:
There are some nice functional style snippets in here: Functional Programming HOWTO
A:
Be careful when programming python in functional style. The only reason to ever do so is for readability. If the algorithm is more elegantly expressed functionally than imperatively, and it doesn't cause performance problems (it usually doesn't), then go right ahead.
However, python does not optimize tail recursion, and has a fixed recursion limit of 1000, so you generally can't do O(n) recursion, only O(log(n)).
Also, reduce() is removed in python 3, for good reason ( http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ). Most non-trivial uses of reduce are more readable as a normal loop instead of a reduction, and sum() is already built in.
A:
Here is quick sort:
def qsort (list):
if (len(list) > 1):
list = qsort(filter (lambda x: x <= list[0], list[1:])) + [list[0]] + qsort(filter (lambda x: x > list[0], list[1:]))
return list
This one is a solution to a programming puzzle of finding a missing number among the integers from 1 to 100:
from random import randint
nos = range(1,101)
to_remove = randint(1,100)
nos.remove(to_remove)
print "Removed %d from list" % to_remove
found = 5050 - reduce (lambda x,y: x+y, nos)
print "You removed %d " % found
|
Python functional programming snippets
|
I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site.
Thanks.
|
[
"Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readability and understandability later on.\nIf you like functional programming, learn Haskell, ML, or F#. You will be amazed at what those languages offer (pure functions to start with).\n",
"There are some nice functional style snippets in here: Functional Programming HOWTO\n",
"Be careful when programming python in functional style. The only reason to ever do so is for readability. If the algorithm is more elegantly expressed functionally than imperatively, and it doesn't cause performance problems (it usually doesn't), then go right ahead.\nHowever, python does not optimize tail recursion, and has a fixed recursion limit of 1000, so you generally can't do O(n) recursion, only O(log(n)).\nAlso, reduce() is removed in python 3, for good reason ( http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ). Most non-trivial uses of reduce are more readable as a normal loop instead of a reduction, and sum() is already built in.\n",
"Here is quick sort:\ndef qsort (list):\n if (len(list) > 1):\n list = qsort(filter (lambda x: x <= list[0], list[1:])) + [list[0]] + qsort(filter (lambda x: x > list[0], list[1:]))\n return list\n\nThis one is a solution to a programming puzzle of finding a missing number among the integers from 1 to 100:\nfrom random import randint\nnos = range(1,101)\nto_remove = randint(1,100)\nnos.remove(to_remove)\nprint \"Removed %d from list\" % to_remove\n\nfound = 5050 - reduce (lambda x,y: x+y, nos)\nprint \"You removed %d \" % found\n\n"
] |
[
7,
5,
3,
2
] |
[] |
[] |
[
"functional_programming",
"python"
] |
stackoverflow_0002093388_functional_programming_python.txt
|
Q:
Reverse loop inside a loop with same list
num = list(str(1234567))
for n1 in num:
print(n1)
for n2 in reversed(num):
print('\t', n2)
On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?
Thanks
A:
Simplest way is to just zip the forward and reverse lists together:
for n1, n2 in zip(num, reversed(num)):
print(n1, '\t', n2)
A:
Here's a feeble attempt. Is this the kind of thing you're looking for?
for idx,i in enumerate(x):
print(i,"\t",x[-(idx+1)])
A:
Do you mean like this?
num = list(str(1234567))
for i in range(len(num)):
print(num[i], '\t', num[-(i+1)])
Output is:
1 7
2 6
3 5
4 4
5 3
6 2
7 1
A:
You should make a second list:
>>> num_rev = num[:]
>>> num_rev.reverse()
>>> num_rev
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Then do something like:
>>> for n1,n2 in zip(num,num_rev):
... print(n1, n2)
...
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
9 0
A:
Nothing to do with Python, but here it is in Haskell :)
myDie = [1,2,3,4,5,6]
sevens = [ (x,y) | x <- myDie, y <- myDie, x+y == 7]
|
Reverse loop inside a loop with same list
|
num = list(str(1234567))
for n1 in num:
print(n1)
for n2 in reversed(num):
print('\t', n2)
On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?
Thanks
|
[
"Simplest way is to just zip the forward and reverse lists together:\nfor n1, n2 in zip(num, reversed(num)):\n print(n1, '\\t', n2)\n\n",
"Here's a feeble attempt. Is this the kind of thing you're looking for?\n for idx,i in enumerate(x):\n print(i,\"\\t\",x[-(idx+1)])\n\n",
"Do you mean like this?\nnum = list(str(1234567))\nfor i in range(len(num)):\n print(num[i], '\\t', num[-(i+1)])\n\nOutput is:\n1 7 \n2 6 \n3 5 \n4 4 \n5 3 \n6 2 \n7 1 \n\n",
"You should make a second list:\n>>> num_rev = num[:]\n>>> num_rev.reverse()\n>>> num_rev\n[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n\nThen do something like:\n>>> for n1,n2 in zip(num,num_rev): \n... print(n1, n2)\n... \n0 9\n1 8\n2 7\n3 6\n4 5\n5 4\n6 3\n7 2\n8 1\n9 0\n\n",
"Nothing to do with Python, but here it is in Haskell :)\nmyDie = [1,2,3,4,5,6]\nsevens = [ (x,y) | x <- myDie, y <- myDie, x+y == 7]\n\n"
] |
[
7,
1,
1,
0,
0
] |
[] |
[] |
[
"for_loop",
"loops",
"python",
"reverse"
] |
stackoverflow_0002095068_for_loop_loops_python_reverse.txt
|
Q:
Python newbie - Input strings, return a value to a web page
I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash.
The problems I'm having here are that
I don't know how to get this code on the web. I have a server, but is it as easy as throwing pytext.py onto my server?
I don't know how to write a form for the input to this script and how to get the HTML to work with this program. If possible, it would be nice to make it a multi-line input box... but it's not necessary.
I want to return a value to a web page to let the user know if the password authenticated successfully or failed.
dtest
import sys
import time
import getopt
import hashlib
h = hashlib.new('md5')
var = sys.argv[1]
print "Password: ", var
h.update(var)
print h.hexdigest()
trial = h.hexdigest()
check = "86fe2288ac154c500983a8b89dbcf288"
if trial == check:
print "Password success"
time_stamp = time.strftime('%Y-%m-%d_%H-%M-%S', (time.localtime(time.time())))
strFile = "txt_" + str(time_stamp) + ".txt"
print "File created: txt_" + str(time_stamp) + ".txt"
#print 'The command line arguments are:'
#for i in sys.argv:
#print i
text_file = open(strFile, "w")
text_file.write(str(time_stamp) + "\n")
for i in range(2, len(sys.argv)):
text_file.write(sys.argv[i] + "\n")
#print 'Debug to file:', sys.argv[i]
text_file.close()
else:
print "Password failure"
A:
You'll need to read up on mod_python (if you're using Apache) and the Python CGI module.
A:
Take a look at django. It's an excellent web framework that can accomplish exactly what you are asking. It also has an authentication module that handles password hashing and logins for you.
|
Python newbie - Input strings, return a value to a web page
|
I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash.
The problems I'm having here are that
I don't know how to get this code on the web. I have a server, but is it as easy as throwing pytext.py onto my server?
I don't know how to write a form for the input to this script and how to get the HTML to work with this program. If possible, it would be nice to make it a multi-line input box... but it's not necessary.
I want to return a value to a web page to let the user know if the password authenticated successfully or failed.
dtest
import sys
import time
import getopt
import hashlib
h = hashlib.new('md5')
var = sys.argv[1]
print "Password: ", var
h.update(var)
print h.hexdigest()
trial = h.hexdigest()
check = "86fe2288ac154c500983a8b89dbcf288"
if trial == check:
print "Password success"
time_stamp = time.strftime('%Y-%m-%d_%H-%M-%S', (time.localtime(time.time())))
strFile = "txt_" + str(time_stamp) + ".txt"
print "File created: txt_" + str(time_stamp) + ".txt"
#print 'The command line arguments are:'
#for i in sys.argv:
#print i
text_file = open(strFile, "w")
text_file.write(str(time_stamp) + "\n")
for i in range(2, len(sys.argv)):
text_file.write(sys.argv[i] + "\n")
#print 'Debug to file:', sys.argv[i]
text_file.close()
else:
print "Password failure"
|
[
"You'll need to read up on mod_python (if you're using Apache) and the Python CGI module.\n",
"Take a look at django. It's an excellent web framework that can accomplish exactly what you are asking. It also has an authentication module that handles password hashing and logins for you.\n"
] |
[
2,
1
] |
[] |
[] |
[
"html",
"python",
"return_value"
] |
stackoverflow_0002095227_html_python_return_value.txt
|
Q:
First Python Program - Multiple Errors
I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am checking for resides in my ~/ directory. Any ideas would be great.
#!/usr/bin/python
import tarfile
import os
def open_tar(file):
if tarfile.is_tarfile(file):
try:
tar = tarfile.open("file")
tar.extractall()
tar.close()
except ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except CompressionError:
print "Compression method is not supported or data cannot be decoded"
except StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
if __name__ == '__main__':
file = "xampp-linux-1.7.3a.tar.gz"
print os.getcwd()
print file
open_tar(file)
Here are the errors. IF I comment out the Read Error, I just get teh same error on the next exception as well.
tux@crosnet:~$ python openall.py
/home/tux
xampp-linux-1.7.3a.tar.gz
Traceback (most recent call last):
File "openall.py", line 25, in <module>
open_tar(file)
File "openall.py", line 12, in open_tar
except ReadError:
NameError: global name 'ReadError' is not defined
tux@crosnet:~$
A:
You can clearly see in your error it states
NameError: global name 'ReadError' is not defined
ReadError is not a global python name. If you look at the tarfile documentation you will see ReadError is part of that modules exceptions. So in this case, you would want to do:
except tarfile.ReadError:
# rest of your code
And you will need to do the same for the rest of those errors. Also, if all those errors will generate the same result (an error message of some sort, or a pass) you can simply do:
except (tarfile.ReadError, tarfile.StreamError) # and so on
Instead of doing them each on a seperate line. That's only if they will give the same exception
A:
You would need to use except tarfile.ReadError or alternatively use from tarfile import is_tarfile, open, ReadError, CompressionError, etc. and put that inside the open_tar function instead of globally.
A:
I think you might need tarfile.ReadError rather than just ReadError?
A:
Okay. All your exceptions (ReadError, CompressionError etc.) are inside the tarfile module and so you'll have to say except tarfile.ReadError instead of just except ReadError.
|
First Python Program - Multiple Errors
|
I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am checking for resides in my ~/ directory. Any ideas would be great.
#!/usr/bin/python
import tarfile
import os
def open_tar(file):
if tarfile.is_tarfile(file):
try:
tar = tarfile.open("file")
tar.extractall()
tar.close()
except ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except CompressionError:
print "Compression method is not supported or data cannot be decoded"
except StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
if __name__ == '__main__':
file = "xampp-linux-1.7.3a.tar.gz"
print os.getcwd()
print file
open_tar(file)
Here are the errors. IF I comment out the Read Error, I just get teh same error on the next exception as well.
tux@crosnet:~$ python openall.py
/home/tux
xampp-linux-1.7.3a.tar.gz
Traceback (most recent call last):
File "openall.py", line 25, in <module>
open_tar(file)
File "openall.py", line 12, in open_tar
except ReadError:
NameError: global name 'ReadError' is not defined
tux@crosnet:~$
|
[
"You can clearly see in your error it states\nNameError: global name 'ReadError' is not defined\n\nReadError is not a global python name. If you look at the tarfile documentation you will see ReadError is part of that modules exceptions. So in this case, you would want to do:\nexcept tarfile.ReadError:\n # rest of your code\n\nAnd you will need to do the same for the rest of those errors. Also, if all those errors will generate the same result (an error message of some sort, or a pass) you can simply do:\nexcept (tarfile.ReadError, tarfile.StreamError) # and so on\n\nInstead of doing them each on a seperate line. That's only if they will give the same exception\n",
"You would need to use except tarfile.ReadError or alternatively use from tarfile import is_tarfile, open, ReadError, CompressionError, etc. and put that inside the open_tar function instead of globally.\n",
"I think you might need tarfile.ReadError rather than just ReadError?\n",
"Okay. All your exceptions (ReadError, CompressionError etc.) are inside the tarfile module and so you'll have to say except tarfile.ReadError instead of just except ReadError.\n"
] |
[
10,
2,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002095298_python.txt
|
Q:
Extended Form silently fails
I have customized one of my forms and now it does not pass the is_valid() test. No form.errors are visible. Any ideas for where I went wrong?
Form:
class SearchForm(forms.Form):
param = forms.CharField(required=False, max_length = 500, label = 'Search for')
sets = forms.ModelMultipleChoiceField(queryset=Set.objects.all())
onlyDiffer = forms.BooleanField(required=False, label = 'Display varying only')
def __init__(self, userN = False, *args, **kwargs):
super(SearchForm,self).__init__(*args,**kwargs)
self.userN = userN
self.fields['sets'].queryset=Set.objects.filter(Q(owner = None) | Q(owner=self.userN))
View:
def search(request):
template = 'search.html'
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
(..do search..)
else:
return direct_to_template(request, template, {'form' : SearchForm(), 'errors' : form.errors})
else:
usr = request.user
form = SearchForm(usr)
return direct_to_template(request, template, { 'form': form })
Thank you!
A:
gruzczy has the right idea, but a better way to do it is to avoid changing the function signature of __init__ in the first place.
def __init__(self, *args, **kwargs):
self.userN = kwargs.pop('userN', None)
super(SearchForm,self).__init__(*args,**kwargs)
...etc...
A:
That's probably because you pass request.POST onto userN parameter. If you have keyword argument first it doesn't mean, that request.POST will automatically be put into args - quite contrary, it will be put onto userN. Try this:
form = SearchForm(False, request.POST)
|
Extended Form silently fails
|
I have customized one of my forms and now it does not pass the is_valid() test. No form.errors are visible. Any ideas for where I went wrong?
Form:
class SearchForm(forms.Form):
param = forms.CharField(required=False, max_length = 500, label = 'Search for')
sets = forms.ModelMultipleChoiceField(queryset=Set.objects.all())
onlyDiffer = forms.BooleanField(required=False, label = 'Display varying only')
def __init__(self, userN = False, *args, **kwargs):
super(SearchForm,self).__init__(*args,**kwargs)
self.userN = userN
self.fields['sets'].queryset=Set.objects.filter(Q(owner = None) | Q(owner=self.userN))
View:
def search(request):
template = 'search.html'
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
(..do search..)
else:
return direct_to_template(request, template, {'form' : SearchForm(), 'errors' : form.errors})
else:
usr = request.user
form = SearchForm(usr)
return direct_to_template(request, template, { 'form': form })
Thank you!
|
[
"gruzczy has the right idea, but a better way to do it is to avoid changing the function signature of __init__ in the first place.\ndef __init__(self, *args, **kwargs):\n self.userN = kwargs.pop('userN', None)\n super(SearchForm,self).__init__(*args,**kwargs)\n ...etc...\n\n",
"That's probably because you pass request.POST onto userN parameter. If you have keyword argument first it doesn't mean, that request.POST will automatically be put into args - quite contrary, it will be put onto userN. Try this:\nform = SearchForm(False, request.POST)\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002095213_django_django_forms_python.txt
|
Q:
How to use one app to satisfy multiple URLs in Django
I'm trying to use one app to satisfy multiple url paths. That is to say, I want the url /blog/ and /job/ to use the same app, but different views. There are a number of ways to do this I'm sure, but none of them seem very clean. Here's what I'm doing right now
# /urls.py
urlpatterns = patterns("",
(r"^(blog|job)/", include("myproject.myapp.urls")),
)
# /myapp/urls.py
urlpatterns = patterns("myproject.myapp.views",
(r"^(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"),
(r"^(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"),
(r"^(?P<id>\d+)/update/$", "myproject.myapp.views.update"),
(r"^insert/$", "myproject.myapp.views.insert"),
)
urlpatterns += patterns("",
(r"^(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"),
(r"^/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"),
)
# /myapp/views.py
def edit(request, type, id):
if (type == "blog"):
editBlog(request, id)
else (type == "job")
editJob(request, id)
def editBlog(request, id):
# some code
def editJob(request, id):
# some code
I've ended up breaking all of this into multiple model and view files to make the code cleaner but the above example doesn't account for things like reverse url lookups which breaks all of my template {% url %} calls.
Originally, I had blogs, jobs, events, contests, etc all living in their own apps, but all of their functionality is so similar, that it didn't make sense to leave it that way, so I attempted to combine them... and this happened. You see those "NOIDEA-detail" and "NOIDEA-community" url names on my generic views? Yeah, I don't know what to use there :-(
A:
You can have more than one modules defining URLs. You can have /blog/ URLs in myapp/urls.py and /job/ URLs in myapp/job_urls.py. Or you can have two modules within a urls subpackage.
Alternatively you can manually prefix your url definitions:
urlpatterns = patterns("myproject.myapp.views",
(r"^jobs/(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"),
(r"^jobs/(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"),
(r"^jobs/(?P<id>\d+)/update/$", "myproject.myapp.views.update"),
(r"^jobs/insert/$", "myproject.myapp.views.insert"),
)
urlpatterns += patterns("",
(r"^blog/(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"),
(r"^blog/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"),
)
And then mount them as:
urlpatterns = patterns("",
(r"", include("myapp.urls")),
)
Personally I would go for more RESTful URL definitions though. Such as blog/(?P<post_id>\d+)/edit/$.
A:
Looks pretty good to me. If you want reverse lookups, just have a different reverse name for each url format, even if they end up pointing to the same view.
|
How to use one app to satisfy multiple URLs in Django
|
I'm trying to use one app to satisfy multiple url paths. That is to say, I want the url /blog/ and /job/ to use the same app, but different views. There are a number of ways to do this I'm sure, but none of them seem very clean. Here's what I'm doing right now
# /urls.py
urlpatterns = patterns("",
(r"^(blog|job)/", include("myproject.myapp.urls")),
)
# /myapp/urls.py
urlpatterns = patterns("myproject.myapp.views",
(r"^(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"),
(r"^(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"),
(r"^(?P<id>\d+)/update/$", "myproject.myapp.views.update"),
(r"^insert/$", "myproject.myapp.views.insert"),
)
urlpatterns += patterns("",
(r"^(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"),
(r"^/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"),
)
# /myapp/views.py
def edit(request, type, id):
if (type == "blog"):
editBlog(request, id)
else (type == "job")
editJob(request, id)
def editBlog(request, id):
# some code
def editJob(request, id):
# some code
I've ended up breaking all of this into multiple model and view files to make the code cleaner but the above example doesn't account for things like reverse url lookups which breaks all of my template {% url %} calls.
Originally, I had blogs, jobs, events, contests, etc all living in their own apps, but all of their functionality is so similar, that it didn't make sense to leave it that way, so I attempted to combine them... and this happened. You see those "NOIDEA-detail" and "NOIDEA-community" url names on my generic views? Yeah, I don't know what to use there :-(
|
[
"You can have more than one modules defining URLs. You can have /blog/ URLs in myapp/urls.py and /job/ URLs in myapp/job_urls.py. Or you can have two modules within a urls subpackage.\nAlternatively you can manually prefix your url definitions:\nurlpatterns = patterns(\"myproject.myapp.views\",\n (r\"^jobs/(?P<id>\\d+)/edit/$\", \"myproject.myapp.views.edit\"),\n (r\"^jobs/(?P<id>\\d+)/delete/$\", \"myproject.myapp.views.delete\"),\n (r\"^jobs/(?P<id>\\d+)/update/$\", \"myproject.myapp.views.update\"),\n (r\"^jobs/insert/$\", \"myproject.myapp.views.insert\"),\n)\n\nurlpatterns += patterns(\"\",\n (r\"^blog/(?P<object_id>\\d+)/$\", \"django.views.generic.list_detail.object_detail\", info_dict, \"NOIDEA-detail\"),\n (r\"^blog/$\", \"django.views.generic.list_detail.object_list\", info_dict, \"NOIDEA-community\"),\n)\n\nAnd then mount them as:\nurlpatterns = patterns(\"\",\n (r\"\", include(\"myapp.urls\")),\n)\n\nPersonally I would go for more RESTful URL definitions though. Such as blog/(?P<post_id>\\d+)/edit/$.\n",
"Looks pretty good to me. If you want reverse lookups, just have a different reverse name for each url format, even if they end up pointing to the same view.\n"
] |
[
4,
0
] |
[] |
[] |
[
"django",
"django_urls",
"python"
] |
stackoverflow_0002094952_django_django_urls_python.txt
|
Q:
Python: arguments for using itertools to split a list into groups
This is a question about the relative merits of fast code that uses the standard library but is obscure (at least to me) versus a hand-rolled alternative. In this thread (and others that it duplicates), it seems the "Pythonic" way to split a list into groups is to use itertools, as in the first function in the code example below (modified slightly from ΤΖΩΤΖΙΟΥ).
The reason I prefer the second function is that I can understand how it works, and if I don't need padding (turning a DNA sequence into codons, say), I can reproduce it from memory in an instant.
The speed is better with itertools. Particularly if we don't want a list back, or we want to pad the last entry, itertools is faster.
What other arguments are there in favor of the standard library solution?
from itertools import izip_longest
def groupby_itertools(iterable, n=3, padvalue='x'):
"groupby_itertools('abcde', 3, 'x') --> ('a','b','c'), ('d','e','x')"
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
def groupby_my(L, n=3, pad=None):
"groupby_my(list('abcde'), n=3, pad='x') --> [['a','b','c'], ['d','e','x']]"
R = xrange(0,len(L),n)
rL = [L[i:i+n] for i in R]
if pad:
last = rL[-1]
x = n - len(last)
if isinstance(last,list):
rL[-1].extend([pad] * x)
elif isinstance(last,str):
rL[-1] += pad * x
return rL
timing:
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_my(L)'
100000 loops, best of 3: 2.39 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_my(L[:-1],pad="x")'
100000 loops, best of 3: 4.67 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_itertools(L)'
1000000 loops, best of 3: 1.46 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'list(groupby_itertools(L))'
100000 loops, best of 3: 3.99 usec per loop
Edit: I would change the function names here (see Alex's answer), but there are so many I decided to post this warning instead.
A:
When you reuse tools from the standard library, rather than "reinventing the wheel" by coding them yourself from scratch, you're not only getting well-optimized and tuned software (sometimes amazingly so, as often in the case of itertools components): more importantly, you're getting large amounts of functionality that you don't have to test, debug and maintain yourself -- you're leveraging all the testing, debugging and maintenance work of many splendid programmers who contribute to the standard library!
The investment in understanding what the standard library offers you therefore repays itself rapidly, and many times over -- and you'll be able to "reproduce from memory" just as well as for reinvented-wheel code, indeed probably better thanks to the higher amount of reuse.
By the way, the term "group by" has a well defined, idiomatic meaning for most programmers, thanks to its use in SQL (and the similar use in itertools itself): I would therefore suggest you avoid using it for something completely different -- that's only going to breed confusion any time you're collaborating with anybody else (hopefully often, since the heyday of the solo, "cowboy" programmer is long gone -- another argument in favor of standards and against wheel reinvention;-).
Lastly, your docstring doesn't match your functions' signature -- arguments-order error;-).
A:
Time spent learning the fundamentals of Python will pay off in spades later on.
Therefore, learn itertools, and how groupby works.
Not only is using itertools likely to be faster than any hand-rolled solutions,
it will help you write better code in the future.
|
Python: arguments for using itertools to split a list into groups
|
This is a question about the relative merits of fast code that uses the standard library but is obscure (at least to me) versus a hand-rolled alternative. In this thread (and others that it duplicates), it seems the "Pythonic" way to split a list into groups is to use itertools, as in the first function in the code example below (modified slightly from ΤΖΩΤΖΙΟΥ).
The reason I prefer the second function is that I can understand how it works, and if I don't need padding (turning a DNA sequence into codons, say), I can reproduce it from memory in an instant.
The speed is better with itertools. Particularly if we don't want a list back, or we want to pad the last entry, itertools is faster.
What other arguments are there in favor of the standard library solution?
from itertools import izip_longest
def groupby_itertools(iterable, n=3, padvalue='x'):
"groupby_itertools('abcde', 3, 'x') --> ('a','b','c'), ('d','e','x')"
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
def groupby_my(L, n=3, pad=None):
"groupby_my(list('abcde'), n=3, pad='x') --> [['a','b','c'], ['d','e','x']]"
R = xrange(0,len(L),n)
rL = [L[i:i+n] for i in R]
if pad:
last = rL[-1]
x = n - len(last)
if isinstance(last,list):
rL[-1].extend([pad] * x)
elif isinstance(last,str):
rL[-1] += pad * x
return rL
timing:
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_my(L)'
100000 loops, best of 3: 2.39 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_my(L[:-1],pad="x")'
100000 loops, best of 3: 4.67 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'groupby_itertools(L)'
1000000 loops, best of 3: 1.46 usec per loop
$ python -mtimeit -s 'from groups import groupby_my, groupby_itertools; L = list("abcdefghijk")' 'list(groupby_itertools(L))'
100000 loops, best of 3: 3.99 usec per loop
Edit: I would change the function names here (see Alex's answer), but there are so many I decided to post this warning instead.
|
[
"When you reuse tools from the standard library, rather than \"reinventing the wheel\" by coding them yourself from scratch, you're not only getting well-optimized and tuned software (sometimes amazingly so, as often in the case of itertools components): more importantly, you're getting large amounts of functionality that you don't have to test, debug and maintain yourself -- you're leveraging all the testing, debugging and maintenance work of many splendid programmers who contribute to the standard library!\nThe investment in understanding what the standard library offers you therefore repays itself rapidly, and many times over -- and you'll be able to \"reproduce from memory\" just as well as for reinvented-wheel code, indeed probably better thanks to the higher amount of reuse.\nBy the way, the term \"group by\" has a well defined, idiomatic meaning for most programmers, thanks to its use in SQL (and the similar use in itertools itself): I would therefore suggest you avoid using it for something completely different -- that's only going to breed confusion any time you're collaborating with anybody else (hopefully often, since the heyday of the solo, \"cowboy\" programmer is long gone -- another argument in favor of standards and against wheel reinvention;-).\nLastly, your docstring doesn't match your functions' signature -- arguments-order error;-).\n",
"Time spent learning the fundamentals of Python will pay off in spades later on.\nTherefore, learn itertools, and how groupby works.\nNot only is using itertools likely to be faster than any hand-rolled solutions,\nit will help you write better code in the future.\n"
] |
[
16,
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002095637_python.txt
|
Q:
Serializing objects containing django querysets
Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?
I want to serialize the following dictionary:
dictionary = { 'alfa': queryset1, 'beta': queryset2, }
I decided to do this using simplejson (comes with django).
I extended simplejson.JSONEncoder the following way:
from django.utils import simplejson
from django.core import serializers
class HandleQuerySets(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("json", obj, ensure_ascii=False)
return simplejson.JSONEncoder.default(self, obj)
Then I do: simplejson.dumps( dictionary, cls=HandleQuerySets), but the returned dicionary looks like this:
{ "alfa": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]",
"beta": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]" }
Django-generated JSON is inserted to the dictionary as string, not JSON. What am I doing wrong?
A:
The correct way to do this would be:
from django.utils import simplejson
from django.core import serializers
from django.db.models.query import QuerySet
class HandleQuerySets(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("python", obj, ensure_ascii=False)
return simplejson.JSONEncoder.default(self, obj)
Because serializers.serialize("json", [...]) returns a string ; if you ask for the python serializer, you get a dictionnary, and json encodes whatever is returned by your encoder's default method. Look at the json documentation for details.
You will have to handle more types in your encoder class (such as datetime objects), but you get the idea.
|
Serializing objects containing django querysets
|
Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?
I want to serialize the following dictionary:
dictionary = { 'alfa': queryset1, 'beta': queryset2, }
I decided to do this using simplejson (comes with django).
I extended simplejson.JSONEncoder the following way:
from django.utils import simplejson
from django.core import serializers
class HandleQuerySets(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("json", obj, ensure_ascii=False)
return simplejson.JSONEncoder.default(self, obj)
Then I do: simplejson.dumps( dictionary, cls=HandleQuerySets), but the returned dicionary looks like this:
{ "alfa": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]",
"beta": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]" }
Django-generated JSON is inserted to the dictionary as string, not JSON. What am I doing wrong?
|
[
"The correct way to do this would be:\nfrom django.utils import simplejson\nfrom django.core import serializers\nfrom django.db.models.query import QuerySet\n\nclass HandleQuerySets(simplejson.JSONEncoder):\n \"\"\" simplejson.JSONEncoder extension: handle querysets \"\"\"\n def default(self, obj):\n if isinstance(obj, QuerySet):\n return serializers.serialize(\"python\", obj, ensure_ascii=False)\n return simplejson.JSONEncoder.default(self, obj)\n\nBecause serializers.serialize(\"json\", [...]) returns a string ; if you ask for the python serializer, you get a dictionnary, and json encodes whatever is returned by your encoder's default method. Look at the json documentation for details.\nYou will have to handle more types in your encoder class (such as datetime objects), but you get the idea.\n"
] |
[
10
] |
[] |
[] |
[
"django",
"json",
"python"
] |
stackoverflow_0002093840_django_json_python.txt
|
Q:
How to create twisted.words.xish.domish.Element entirely from raw XML
I was surprised that XML basic object (twisted.words.xish.domish.Element) could not be created entirely from XML string. The most alike way is:
msg = "<iq to='juick@juick.com' id='id123' type='get'> \
<query xmlns='http://juick.com/query#messages' mid='123456'/> \
</iq>"
iq = domish.Element(('',''))
iq.addRawXml(msg)
But it generates:
iq.toXml()
u"<><iq to='juick@juick.com' id='id123' type='get'> <query xmlns='http://juick.com/query#messages' mid='123456'/> </iq></>"
Is there any way to use raw XML except writing my own IElement implementation?
A:
This is what I use for fragments, adapted from something found on the web somewhere.
from twisted.words.xish import domish
class ElementParser(object):
"callable class to parse XML string into Element"
def __call__(self, s):
self.result = None
def onStart(el):
self.result = el
def onEnd():
pass
def onElement(el):
self.result.addChild(el)
parser = domish.elementStream()
parser.DocumentStartEvent = onStart
parser.ElementEvent = onElement
parser.DocumentEndEvent = onEnd
tmp = domish.Element(("", "s"))
tmp.addRawXml(s)
parser.parse(tmp.toXml())
return self.result.firstChildElement()
|
How to create twisted.words.xish.domish.Element entirely from raw XML
|
I was surprised that XML basic object (twisted.words.xish.domish.Element) could not be created entirely from XML string. The most alike way is:
msg = "<iq to='juick@juick.com' id='id123' type='get'> \
<query xmlns='http://juick.com/query#messages' mid='123456'/> \
</iq>"
iq = domish.Element(('',''))
iq.addRawXml(msg)
But it generates:
iq.toXml()
u"<><iq to='juick@juick.com' id='id123' type='get'> <query xmlns='http://juick.com/query#messages' mid='123456'/> </iq></>"
Is there any way to use raw XML except writing my own IElement implementation?
|
[
"This is what I use for fragments, adapted from something found on the web somewhere.\nfrom twisted.words.xish import domish\n\nclass ElementParser(object):\n \"callable class to parse XML string into Element\"\n\n def __call__(self, s):\n self.result = None\n def onStart(el):\n self.result = el\n def onEnd():\n pass\n def onElement(el):\n self.result.addChild(el)\n\n parser = domish.elementStream()\n parser.DocumentStartEvent = onStart\n parser.ElementEvent = onElement\n parser.DocumentEndEvent = onEnd\n tmp = domish.Element((\"\", \"s\"))\n tmp.addRawXml(s)\n parser.parse(tmp.toXml())\n return self.result.firstChildElement() \n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"twisted",
"twisted.words",
"xml"
] |
stackoverflow_0002093400_python_twisted_twisted.words_xml.txt
|
Q:
module level garbage collection in python
Let's say I have a module mod_x like the following:
class X:
pass
x=X()
Now, let's say I have another module that just performs import mod_x, and goes about its business. The module variable x will not be referenced further during the lifecycle of the interpreter.
Will the class instance x get garbage collected at any point except at the termination of the interpreter?
A:
No, the variable will never get garbage-collected (until the end of the process), because the module object will stay in sys.modules['mod_x'] and it will have a reference to mod_x.x -- the reference count will never drop to 0 (until all modules are removed at the end of the program) and it's not an issue of "cyclycal garbage" -- it's a perfectly valid live reference, and proving that nobody every does (e.g.) a getattr(sys.modules[a], b) where string variables a and b happen to be worth 'mod_x' and 'x' respectively is at least as hard as solving the halting problem;-). ("At least" since more code may be about to be dynamically loaded at any time...!-).
A:
Only if something else does a del mod_x.x or a rebind at some point, or if the module itself becomes fully deleted.
A:
Once the module is imported it will be in the sys.modules dict so unless it is removed from there (which is possible though not standard practice) it will not be garbage collected.
So if you have a reason for wanting a module that has been loaded to be garbage collected you have to mess with sys.modules.
|
module level garbage collection in python
|
Let's say I have a module mod_x like the following:
class X:
pass
x=X()
Now, let's say I have another module that just performs import mod_x, and goes about its business. The module variable x will not be referenced further during the lifecycle of the interpreter.
Will the class instance x get garbage collected at any point except at the termination of the interpreter?
|
[
"No, the variable will never get garbage-collected (until the end of the process), because the module object will stay in sys.modules['mod_x'] and it will have a reference to mod_x.x -- the reference count will never drop to 0 (until all modules are removed at the end of the program) and it's not an issue of \"cyclycal garbage\" -- it's a perfectly valid live reference, and proving that nobody every does (e.g.) a getattr(sys.modules[a], b) where string variables a and b happen to be worth 'mod_x' and 'x' respectively is at least as hard as solving the halting problem;-). (\"At least\" since more code may be about to be dynamically loaded at any time...!-).\n",
"Only if something else does a del mod_x.x or a rebind at some point, or if the module itself becomes fully deleted.\n",
"Once the module is imported it will be in the sys.modules dict so unless it is removed from there (which is possible though not standard practice) it will not be garbage collected.\nSo if you have a reason for wanting a module that has been loaded to be garbage collected you have to mess with sys.modules.\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"garbage_collection",
"python"
] |
stackoverflow_0002095907_garbage_collection_python.txt
|
Q:
Using Third-Party Modules with Python in an Automator Service
I have installed Py-Appscript on my machine and it can be used with the Python installation at /Library/Frameworks/Python.framework/Versions/Current/bin/python.
I am trying to use this installation of Py-Appscript with an Automator service. To do this, I use the Run Shell Script action and then set the Shell to usr/bin/python (which is my only choice for Python, unfortunately).
The usr/bin/python does not appear to have access to my third-party modules and crashes on the line:
from appscript import *
Is there a way for me to give usr/bin/python access to my third-party modules?
OR
Is there a way to tell Automator to use /Library/Frameworks/Python.framework/Versions/Current/bin/python instead?
I need Automator to run the Python directly from the Run Shell Script action. Any action that calls Python scripts that are external to Automator (via bin/bash, for example) does not perform quickly enough to be useful.
A:
Okay, I was able to get it working using a hack found at How do I execute a PHP shell script as an Automator action on Mac OS X.
Inside of the Run Shell Script action, I used the /bin/sh/ shell with <<EOF ... EOF to the proper Python installation.
So for example, entering
/Library/Frameworks/Python.framework/Versions/Current/bin/python <<EOF
from appscript import *
Numbers = app('Numbers')
EOF
Into the code section of the Run Shell Script action will work. So one can call the proper installation (/Library/Frameworks/Python.framework/Versions/Current/bin/python above) and put their program between the <<EOF ... EOF delimeters.
Alfred
This trick works with Alfred also. If you want to use appscript with Alfred, just make sure that you pass {query} to the python version above, like this:
/Library/Frameworks/Python.framework/Versions/Current/bin/python script.py {query}
A:
When you install modules, you typically install them per Python instance. So in this case you have installed them for the Python in /Library/Frameworks/Python.framework/Versions/Current/bin/python, and it will then be available only for that Python. /usr/bin/python is then apparently another Python installation (I'm not an OS X expert).
To make it available for the /usr/bin/python installation, install it for /usr/bin/python.
|
Using Third-Party Modules with Python in an Automator Service
|
I have installed Py-Appscript on my machine and it can be used with the Python installation at /Library/Frameworks/Python.framework/Versions/Current/bin/python.
I am trying to use this installation of Py-Appscript with an Automator service. To do this, I use the Run Shell Script action and then set the Shell to usr/bin/python (which is my only choice for Python, unfortunately).
The usr/bin/python does not appear to have access to my third-party modules and crashes on the line:
from appscript import *
Is there a way for me to give usr/bin/python access to my third-party modules?
OR
Is there a way to tell Automator to use /Library/Frameworks/Python.framework/Versions/Current/bin/python instead?
I need Automator to run the Python directly from the Run Shell Script action. Any action that calls Python scripts that are external to Automator (via bin/bash, for example) does not perform quickly enough to be useful.
|
[
"Okay, I was able to get it working using a hack found at How do I execute a PHP shell script as an Automator action on Mac OS X.\nInside of the Run Shell Script action, I used the /bin/sh/ shell with <<EOF ... EOF to the proper Python installation.\nSo for example, entering\n/Library/Frameworks/Python.framework/Versions/Current/bin/python <<EOF\nfrom appscript import *\nNumbers = app('Numbers')\nEOF\n\nInto the code section of the Run Shell Script action will work. So one can call the proper installation (/Library/Frameworks/Python.framework/Versions/Current/bin/python above) and put their program between the <<EOF ... EOF delimeters.\nAlfred\nThis trick works with Alfred also. If you want to use appscript with Alfred, just make sure that you pass {query} to the python version above, like this:\n/Library/Frameworks/Python.framework/Versions/Current/bin/python script.py {query}\n\n",
"When you install modules, you typically install them per Python instance. So in this case you have installed them for the Python in /Library/Frameworks/Python.framework/Versions/Current/bin/python, and it will then be available only for that Python. /usr/bin/python is then apparently another Python installation (I'm not an OS X expert).\nTo make it available for the /usr/bin/python installation, install it for /usr/bin/python.\n"
] |
[
3,
0
] |
[] |
[] |
[
"automator",
"python"
] |
stackoverflow_0002093837_automator_python.txt
|
Q:
Interaction with twisted.internet.reactor
I am learning Twisted, especially its XMPP side. I am writing a Jabber client which must send and recieve messages. Here is my code: http://pastebin.com/m71225776
As I understood the workflow is like this:
1. I create handlers for important network events (i.e. connecting, message recieving, disconnecting, etc)
2. I run reactor. At this moment starts the loop which is waiting for any event. When event happens it is passed to specified handler.
The problem is in sending messages. Sending is not associated with any network event so I can't create handler for it. Also I can't do anything with reactor until its loop stops working. But the goal is "To send messages when I need and recieve data when it comes".
I think am not fully understand philosophy of twisted, so give me a right way please.
A:
You just need to find what events will trigger sending a message.
For example, in a GUI client, sending happens when the user types something. You should integrate with a graphics toolkit, using the Twisted reactor for its mainloop (there's a Gtk+ Twisted reactor for example). Then you'll be able to listen for some interface events, like the user typing enter in a text area; and you'll be able to react to that event by sending a message.
Other sources of events could be Twisted timers, any kind of protocol, including IPC, webhooks…
Incidentally, if you need a higher-level library for XMPP with Twisted, have a look at Wokkel.
A:
More accurately, you can't do anything with the reactor until it calls one of your callbacks. You don't call twisted, twisted calls you.
One way to experiment is to have one of your setup handlers which you know will be called (or just test code put in after you start the reactor) call callLater() or loopingCall().
|
Interaction with twisted.internet.reactor
|
I am learning Twisted, especially its XMPP side. I am writing a Jabber client which must send and recieve messages. Here is my code: http://pastebin.com/m71225776
As I understood the workflow is like this:
1. I create handlers for important network events (i.e. connecting, message recieving, disconnecting, etc)
2. I run reactor. At this moment starts the loop which is waiting for any event. When event happens it is passed to specified handler.
The problem is in sending messages. Sending is not associated with any network event so I can't create handler for it. Also I can't do anything with reactor until its loop stops working. But the goal is "To send messages when I need and recieve data when it comes".
I think am not fully understand philosophy of twisted, so give me a right way please.
|
[
"You just need to find what events will trigger sending a message.\nFor example, in a GUI client, sending happens when the user types something. You should integrate with a graphics toolkit, using the Twisted reactor for its mainloop (there's a Gtk+ Twisted reactor for example). Then you'll be able to listen for some interface events, like the user typing enter in a text area; and you'll be able to react to that event by sending a message.\nOther sources of events could be Twisted timers, any kind of protocol, including IPC, webhooks…\nIncidentally, if you need a higher-level library for XMPP with Twisted, have a look at Wokkel.\n",
"More accurately, you can't do anything with the reactor until it calls one of your callbacks. You don't call twisted, twisted calls you.\nOne way to experiment is to have one of your setup handlers which you know will be called (or just test code put in after you start the reactor) call callLater() or loopingCall(). \n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0002080757_python_twisted.txt
|
Q:
Closest language to Python's syntax that is more low level language!
I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much...
A:
cython may be pretty close to what you want: syntax just about identical to Python, and you can basically write C-level code in it. It's tuned to generate Python-usable extensions, but you could then "freeze" them into a stand-alone executable.
boo is another language with very Python-like syntax, and semantics to about the level of C# (also .NET oriented, but there's a JVM-oriented version in the works, I hear).
A:
Cython is a lower-level language with a syntax similar to Python's.
A:
Cobra compiles to C#. Variables get typed after their first usage. Performance is about the same as C#.
A:
Google's Go language was designed with Python syntax in mind though its got a hell of a lot of C in its genes too.
A:
Genie could be what you are looking for. Is a python-like language (at least no semicolons) that compiles to c.
|
Closest language to Python's syntax that is more low level language!
|
I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much...
|
[
"cython may be pretty close to what you want: syntax just about identical to Python, and you can basically write C-level code in it. It's tuned to generate Python-usable extensions, but you could then \"freeze\" them into a stand-alone executable.\nboo is another language with very Python-like syntax, and semantics to about the level of C# (also .NET oriented, but there's a JVM-oriented version in the works, I hear).\n",
"Cython is a lower-level language with a syntax similar to Python's.\n",
"Cobra compiles to C#. Variables get typed after their first usage. Performance is about the same as C#. \n",
"Google's Go language was designed with Python syntax in mind though its got a hell of a lot of C in its genes too.\n",
"Genie could be what you are looking for. Is a python-like language (at least no semicolons) that compiles to c.\n"
] |
[
15,
12,
6,
3,
0
] |
[] |
[] |
[
"low_level",
"programming_languages",
"python",
"syntax"
] |
stackoverflow_0002096015_low_level_programming_languages_python_syntax.txt
|
Q:
How can I find out why PIL isn't drawing the font correctly?
Here's the code I'm using:
from PIL import Image
import ImageFont, ImageDraw
import sys
import pdb
img = Image.new("RGBA",(300,300))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(sys.argv[1],30)
draw.text((0,100),"world",font=font,fill="red")
del draw
img.save(sys.argv[2],"PNG")
and here's the image that results:
img http://www.freeimagehosting.net/image.php?976a0d3eaa.png ( for some reason, I can't make it show on SO, so the link is http://www.freeimagehosting.net/image.php?976a0d3eaa.png )
The thing is, I don't understand why it isn't drawing the font correctly? I should be able to read the word "world" off of it. It's like the picture's been cut in half or something. Does anyone have any clue?
EDIT: after balpha's comment, I decided to try another font. I'm only interested in ttf fonts, so I tried with another one, and it worked. This is kind of strange. The original font I tried to run this with is Beautiful ES. I'm curious if you guys can reproduce the same image on your computers, and if you happen to know the reason for why that is.
A:
PIL uses the freetype2 library, so most possibly it is an issue with the font file; for example, it could have bad metrics defined (e.g see the OS/2 related ones opening the font with FontForge).
|
How can I find out why PIL isn't drawing the font correctly?
|
Here's the code I'm using:
from PIL import Image
import ImageFont, ImageDraw
import sys
import pdb
img = Image.new("RGBA",(300,300))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(sys.argv[1],30)
draw.text((0,100),"world",font=font,fill="red")
del draw
img.save(sys.argv[2],"PNG")
and here's the image that results:
img http://www.freeimagehosting.net/image.php?976a0d3eaa.png ( for some reason, I can't make it show on SO, so the link is http://www.freeimagehosting.net/image.php?976a0d3eaa.png )
The thing is, I don't understand why it isn't drawing the font correctly? I should be able to read the word "world" off of it. It's like the picture's been cut in half or something. Does anyone have any clue?
EDIT: after balpha's comment, I decided to try another font. I'm only interested in ttf fonts, so I tried with another one, and it worked. This is kind of strange. The original font I tried to run this with is Beautiful ES. I'm curious if you guys can reproduce the same image on your computers, and if you happen to know the reason for why that is.
|
[
"PIL uses the freetype2 library, so most possibly it is an issue with the font file; for example, it could have bad metrics defined (e.g see the OS/2 related ones opening the font with FontForge).\n"
] |
[
1
] |
[] |
[] |
[
"fonts",
"python",
"python_imaging_library"
] |
stackoverflow_0002095189_fonts_python_python_imaging_library.txt
|
Q:
Execute sql query with Elixir
I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how?
VACUUM FULL ANALYZE table
Update
The error is: "UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session". And the same result with session.close() issued before. I did try doing metadata.bind.execute() and that worked for a simple select. But for the VACUUM it said - "InternalError: (InternalError) VACUUM cannot run inside a transaction block", so now I'm trying to figure out how to turn that off.
Update 2
I can get the query to execute, but I'm still getting the same error - even when I create a new session and close the previous one.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# ... insert stuff
old_session.commit()
old_session.close()
new_sess = sessionmaker(autocommit=True)
new_sess.configure(bind=create_engine('postgres://user:pw@host/db', echo=True))
sess = new_sess()
sess.execute('VACUUM FULL ANALYZE table')
sess.close()
and the output I get is
2009-12-10 10:00:16,769 INFO sqlalchemy.engine.base.Engine.0x...05ac VACUUM FULL ANALYZE table
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac {}
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac ROLLBACK
finishing failed run, (InternalError) VACUUM cannot run inside a transaction block
'VACUUM FULL ANALYZE table' {}
Update 3
Thanks to everyone who responded. I wasn't able to find the solution I wanted, but I think I'm just going to go with the one described here PostgreSQL - how to run VACUUM from code outside transaction block?. It's not ideal, but it works.
A:
Dammit. I knew the answer was going to be right under my nose. Assuming you setup your connection like I did.
metadata.bind = 'postgres://user:pw@host/db'
The solution to this was as simple as
conn = metadata.bind.engine.connect()
old_lvl = conn.connection.isolation_level
conn.connection.set_isolation_level(0)
conn.execute('vacuum analyze table')
conn.connection.set_isolation_level(old_lvl)
This is similar to what was suggested here PostgreSQL - how to run VACUUM from code outside transaction block?
because underneath it all, sqlalchemy uses psycopg to make the connection to postgres. Connection.connection is a proxy to the psycopg connection. Once I realized this, this problem came back to mind and I decided to take another whack at it.
Hopefully this helps someone.
A:
You need to bind the session to an engine
session.bind = metadata.bind
session.execute('YOUR SQL STATEMENT')
A:
UnboundExecutionError says that your session is not bound to an engine and there is no way to discover engine from query passed to execute(). You can either use engine.execute() directly or pass additional mapper parameter (either mapper or mapped model corresponding to table used in query) to session.execute() to help SQLAlchemy discover proper engine.
The InternalError says that you are trying to execute this statement inside explicitly (with BEGIN statement) started transaction. Have you issued some statements before it without calling commit()? If so, just call commit() or rollback() method to close transaction before doing VACUUM. Also note, that there are several parameter to sessionmaker() that tell SQLAlchemy when transaction should be started.
A:
If you have access to SQLAlchemy session, you can execute arbitrary SQL statements via its execute method:
session.execute("VACUUM FULL ANALYZE table")
A:
(Depending on the Postgres version) you most likely do not want to run "VACUUM FULL".
|
Execute sql query with Elixir
|
I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how?
VACUUM FULL ANALYZE table
Update
The error is: "UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session". And the same result with session.close() issued before. I did try doing metadata.bind.execute() and that worked for a simple select. But for the VACUUM it said - "InternalError: (InternalError) VACUUM cannot run inside a transaction block", so now I'm trying to figure out how to turn that off.
Update 2
I can get the query to execute, but I'm still getting the same error - even when I create a new session and close the previous one.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# ... insert stuff
old_session.commit()
old_session.close()
new_sess = sessionmaker(autocommit=True)
new_sess.configure(bind=create_engine('postgres://user:pw@host/db', echo=True))
sess = new_sess()
sess.execute('VACUUM FULL ANALYZE table')
sess.close()
and the output I get is
2009-12-10 10:00:16,769 INFO sqlalchemy.engine.base.Engine.0x...05ac VACUUM FULL ANALYZE table
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac {}
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac ROLLBACK
finishing failed run, (InternalError) VACUUM cannot run inside a transaction block
'VACUUM FULL ANALYZE table' {}
Update 3
Thanks to everyone who responded. I wasn't able to find the solution I wanted, but I think I'm just going to go with the one described here PostgreSQL - how to run VACUUM from code outside transaction block?. It's not ideal, but it works.
|
[
"Dammit. I knew the answer was going to be right under my nose. Assuming you setup your connection like I did.\nmetadata.bind = 'postgres://user:pw@host/db'\n\nThe solution to this was as simple as \nconn = metadata.bind.engine.connect()\n\nold_lvl = conn.connection.isolation_level\nconn.connection.set_isolation_level(0)\nconn.execute('vacuum analyze table')\nconn.connection.set_isolation_level(old_lvl)\n\nThis is similar to what was suggested here PostgreSQL - how to run VACUUM from code outside transaction block?\nbecause underneath it all, sqlalchemy uses psycopg to make the connection to postgres. Connection.connection is a proxy to the psycopg connection. Once I realized this, this problem came back to mind and I decided to take another whack at it. \nHopefully this helps someone.\n",
"You need to bind the session to an engine\nsession.bind = metadata.bind\nsession.execute('YOUR SQL STATEMENT')\n\n",
"UnboundExecutionError says that your session is not bound to an engine and there is no way to discover engine from query passed to execute(). You can either use engine.execute() directly or pass additional mapper parameter (either mapper or mapped model corresponding to table used in query) to session.execute() to help SQLAlchemy discover proper engine.\nThe InternalError says that you are trying to execute this statement inside explicitly (with BEGIN statement) started transaction. Have you issued some statements before it without calling commit()? If so, just call commit() or rollback() method to close transaction before doing VACUUM. Also note, that there are several parameter to sessionmaker() that tell SQLAlchemy when transaction should be started.\n",
"If you have access to SQLAlchemy session, you can execute arbitrary SQL statements via its execute method:\nsession.execute(\"VACUUM FULL ANALYZE table\")\n\n",
"(Depending on the Postgres version) you most likely do not want to run \"VACUUM FULL\".\n"
] |
[
10,
2,
1,
0,
0
] |
[] |
[] |
[
"postgresql",
"python",
"python_elixir",
"sqlalchemy"
] |
stackoverflow_0001875885_postgresql_python_python_elixir_sqlalchemy.txt
|
Q:
Fetch certain .html files from web server
I would like to fetch certain .html files from a web server. My intention is to fetch .html files from a web site (http://www.thetabworld.com/) that has a word "metallica" on file name. How is that possible using python? I have heard about urllib2 but as a python noob, I don't have a slightest idea how to use it.
A:
You need to use urllib2 together with a HTML parser such as lxml or BeautifulSoup in order to extract the links from the retrieved pages in order to crawl the site.
A:
"I have heard about urllib2 but as a
python noob, I don't have a slightest
idea how to use it."
well if you don't know how to use urllib2, reading some docs would be a good start.
the following are excellent resources (with examples):
official python docs for urllib2
urllib2 - the missing manual
urllib2 cookbook
PMOTW - urllib2
|
Fetch certain .html files from web server
|
I would like to fetch certain .html files from a web server. My intention is to fetch .html files from a web site (http://www.thetabworld.com/) that has a word "metallica" on file name. How is that possible using python? I have heard about urllib2 but as a python noob, I don't have a slightest idea how to use it.
|
[
"You need to use urllib2 together with a HTML parser such as lxml or BeautifulSoup in order to extract the links from the retrieved pages in order to crawl the site.\n",
"\n\"I have heard about urllib2 but as a\n python noob, I don't have a slightest\n idea how to use it.\"\n\nwell if you don't know how to use urllib2, reading some docs would be a good start.\nthe following are excellent resources (with examples):\nofficial python docs for urllib2\nurllib2 - the missing manual\nurllib2 cookbook\nPMOTW - urllib2 \n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"urllib2"
] |
stackoverflow_0002096484_python_urllib2.txt
|
Q:
A few questions regarding Pythons 'import' feature
I just downloaded Beautiful Soup and I've decided I'll make a small library (is that what they call them in Python?) that will return results of a movie given and IMDB movie search.
My question is, how exactly does this import thing work?
For example, I downloaded BeautifulSoup and all it is, is a .py file. Does that file have to be in the same folder as the my python application (my project that will use the library)?
A:
BeautifulSoup.py will need to be placed somewhere on the Python search path, which is available to you in the sys.path array. Note that the current directory is always included in this array (as the empty string).
>>> import sys
>>> sys.path
['', 'C:\\Windows\\system32\\python26.zip', 'c:\\python26\\DLLs', 'c:\\python26\\lib', 'c:\\python26\\lib\\plat-win', 'c
:\\python26\\lib\\lib-tk', 'c:\\python26', 'c:\\python26\\lib\\site-packages', 'c:\\python26\\lib\\site-packages\\win32'
, 'c:\\python26\\lib\\site-packages\\win32\\lib', 'c:\\python26\\lib\\site-packages\\Pythonwin']
A:
See the module search path. For your case, placing the .py file in the same folder will work.
A:
Python modules are top level entities in python programs that can be imported (analogous to C files). There is a load path which contains a list of directories to search for modules when you're importing them. I'd recommend that you go through the modules section of the official tutorial for details (and through the whole tutorial as well).
A:
For Ubuntu, you can search for packages with the command
apt-cache search beautifulsoup
This should yield
python-beautifulsoup - error-tolerant HTML parser for Python
So the easiest way to install BeautifulSoup for ubuntu would be to run
sudo apt-get install python-beautifulsoup
Once you do this, you can put
import BeautifulSoup
in any of your scripts and your python installation will find the module.
A:
Have a look at the documentation on packages. When you import a package, python searches within sys.path, so you must place Beautiful Soup within the path, or append a new directory to the path.
Example:
import sys
print "Before:\n", sys.path
sys.path.append('/some/directory')
print "After:\n", sys.path
|
A few questions regarding Pythons 'import' feature
|
I just downloaded Beautiful Soup and I've decided I'll make a small library (is that what they call them in Python?) that will return results of a movie given and IMDB movie search.
My question is, how exactly does this import thing work?
For example, I downloaded BeautifulSoup and all it is, is a .py file. Does that file have to be in the same folder as the my python application (my project that will use the library)?
|
[
"BeautifulSoup.py will need to be placed somewhere on the Python search path, which is available to you in the sys.path array. Note that the current directory is always included in this array (as the empty string).\n>>> import sys\n>>> sys.path\n['', 'C:\\\\Windows\\\\system32\\\\python26.zip', 'c:\\\\python26\\\\DLLs', 'c:\\\\python26\\\\lib', 'c:\\\\python26\\\\lib\\\\plat-win', 'c\n:\\\\python26\\\\lib\\\\lib-tk', 'c:\\\\python26', 'c:\\\\python26\\\\lib\\\\site-packages', 'c:\\\\python26\\\\lib\\\\site-packages\\\\win32'\n, 'c:\\\\python26\\\\lib\\\\site-packages\\\\win32\\\\lib', 'c:\\\\python26\\\\lib\\\\site-packages\\\\Pythonwin']\n\n",
"See the module search path. For your case, placing the .py file in the same folder will work.\n",
"Python modules are top level entities in python programs that can be imported (analogous to C files). There is a load path which contains a list of directories to search for modules when you're importing them. I'd recommend that you go through the modules section of the official tutorial for details (and through the whole tutorial as well).\n",
"For Ubuntu, you can search for packages with the command\napt-cache search beautifulsoup\n\nThis should yield \npython-beautifulsoup - error-tolerant HTML parser for Python\n\nSo the easiest way to install BeautifulSoup for ubuntu would be to run\nsudo apt-get install python-beautifulsoup\n\nOnce you do this, you can put\nimport BeautifulSoup \n\nin any of your scripts and your python installation will find the module. \n",
"Have a look at the documentation on packages. When you import a package, python searches within sys.path, so you must place Beautiful Soup within the path, or append a new directory to the path.\nExample:\nimport sys\nprint \"Before:\\n\", sys.path\nsys.path.append('/some/directory')\nprint \"After:\\n\", sys.path\n\n"
] |
[
3,
1,
1,
1,
0
] |
[
"Might not be relevant, but have you considered using imdbpy? Last time I used it it worked pretty well...\n"
] |
[
-1
] |
[
"import",
"python"
] |
stackoverflow_0002095505_import_python.txt
|
Q:
TypeError upon merely opening a file with csv.DictReader?
I've just uploaded this CSV file via a form, POSTing it to my Python CGI script. The upload seems to have completed successfully. Permissions on the folder are 777, on the file are 755.
>>> import csv
>>> csvHandle = open('files/TestData.csv', "rb")
>>> csvRawRecordDicts = csv.DictReader(csvHandle)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __init__() takes at least 3 arguments (2 given)
The values are as follows:
csvRawRecordDicts undefined,
csv = <module 'csv' from '/usr/lib/python2.3/csv.pyc'>,
csv.DictReader = <class csv.DictReader>,
csvHandle = <open file 'files/TestData.csv', mode 'rb'>
The code works fine on my local computer with Python 2.5. The error happens on 2.3.
What is the thought-process for debugging something like this? Where do I begin looking?
A:
There are a couple of things you could be doing:
read the relevant docs and see that DictReader requires two arguments at least, while you're passing one
try to do >>> help(csv.DictReader) and arrive to the same conclusion.
As reading of the docs might explain second of the arguments should be fieldnames (I presume list will suffice), importantly this information was conveyed in the error message!
A:
All of what Silent Ghost said, plus:
A change of emphasis: In my opinion, the most important point is to read the error message carefully. In this case, it is telling you simply and plainly that you need to supply another argument. Checking the help (or the docs for the Python version that you are running) follows ...
Another point: make sure that you understand what your code is doing. csv.DictReader() does NOT open a file. File system permissions are not relevant -- you have already opened the file and passed the handle to csv.DictReader().
|
TypeError upon merely opening a file with csv.DictReader?
|
I've just uploaded this CSV file via a form, POSTing it to my Python CGI script. The upload seems to have completed successfully. Permissions on the folder are 777, on the file are 755.
>>> import csv
>>> csvHandle = open('files/TestData.csv', "rb")
>>> csvRawRecordDicts = csv.DictReader(csvHandle)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __init__() takes at least 3 arguments (2 given)
The values are as follows:
csvRawRecordDicts undefined,
csv = <module 'csv' from '/usr/lib/python2.3/csv.pyc'>,
csv.DictReader = <class csv.DictReader>,
csvHandle = <open file 'files/TestData.csv', mode 'rb'>
The code works fine on my local computer with Python 2.5. The error happens on 2.3.
What is the thought-process for debugging something like this? Where do I begin looking?
|
[
"There are a couple of things you could be doing:\n\nread the relevant docs and see that DictReader requires two arguments at least, while you're passing one\ntry to do >>> help(csv.DictReader) and arrive to the same conclusion.\n\nAs reading of the docs might explain second of the arguments should be fieldnames (I presume list will suffice), importantly this information was conveyed in the error message!\n",
"All of what Silent Ghost said, plus:\nA change of emphasis: In my opinion, the most important point is to read the error message carefully. In this case, it is telling you simply and plainly that you need to supply another argument. Checking the help (or the docs for the Python version that you are running) follows ...\nAnother point: make sure that you understand what your code is doing. csv.DictReader() does NOT open a file. File system permissions are not relevant -- you have already opened the file and passed the handle to csv.DictReader(). \n"
] |
[
1,
1
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0002096466_csv_python.txt
|
Q:
Parsing name and address information with differing number of spaces
I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be:
"¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 12345-6789¬¬¬¬EOL¬"
I need to separate the name into parts and the city|state|zip into parts. However, the name may or may not have a middle initial so:
m = l[4].split("¬")
firstName, mi, lastName = m[2].split()
won't work if there is no middle initial. Also, the name of the city may or may not have spaces so:
city, state, zipCode = m[4].split()
won't work if the city is 'San Antonio' or 'Rio de Janeiro' for instance.
Bottom line, how do I parse sections of a field where the section is not always in the same format?
A:
In your examples it seems that you can in both cases solve the problem by getting the 'first fields', the 'last fields' and 'everything in between':
m = line.split("¬")[2].split()
firstname = m[0]
surname = m[-1]
initials = m[1:-1] # Maybe just keep this as a list?
And:
m = line.split("¬")[4].split()
city = ' '.join(m[:-2])
state = m[-2]
zipCode = m[-1]
In general you can handle a single field containing spaces by getting the 'fixed' fields from both the start and the end and whatever is left over is the field that can contain spaces.. As soon as you have two fields containing spaces in the same column, there's nothing you can do. It's ambiguously defined.
With the data format you have, you may have some problems if there are people with first or last names containing spaces such as Robert Van de Graff. This can be solved if you have an initial by looking for words containing only one letter such as: Robert J. Van de Graaff and using those to define where the first and last names start and end. But in general you may have problems.
Also there's an internationalization issue hidden here: not everyone writes their 'first name' first - sometimes they write their family name first.
A:
Basically what Anon suggests, you can implement it like this:
cityInfo = m[4].split()
city, state, zipCode = ' '.join(cityInfo[:-2]), cityInfo[-2], cityInfo[-1])
|
Parsing name and address information with differing number of spaces
|
I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be:
"¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 12345-6789¬¬¬¬EOL¬"
I need to separate the name into parts and the city|state|zip into parts. However, the name may or may not have a middle initial so:
m = l[4].split("¬")
firstName, mi, lastName = m[2].split()
won't work if there is no middle initial. Also, the name of the city may or may not have spaces so:
city, state, zipCode = m[4].split()
won't work if the city is 'San Antonio' or 'Rio de Janeiro' for instance.
Bottom line, how do I parse sections of a field where the section is not always in the same format?
|
[
"In your examples it seems that you can in both cases solve the problem by getting the 'first fields', the 'last fields' and 'everything in between':\nm = line.split(\"¬\")[2].split()\nfirstname = m[0]\nsurname = m[-1]\ninitials = m[1:-1] # Maybe just keep this as a list?\n\nAnd:\nm = line.split(\"¬\")[4].split()\ncity = ' '.join(m[:-2])\nstate = m[-2]\nzipCode = m[-1]\n\nIn general you can handle a single field containing spaces by getting the 'fixed' fields from both the start and the end and whatever is left over is the field that can contain spaces.. As soon as you have two fields containing spaces in the same column, there's nothing you can do. It's ambiguously defined. \nWith the data format you have, you may have some problems if there are people with first or last names containing spaces such as Robert Van de Graff. This can be solved if you have an initial by looking for words containing only one letter such as: Robert J. Van de Graaff and using those to define where the first and last names start and end. But in general you may have problems.\nAlso there's an internationalization issue hidden here: not everyone writes their 'first name' first - sometimes they write their family name first.\n",
"Basically what Anon suggests, you can implement it like this:\ncityInfo = m[4].split()\ncity, state, zipCode = ' '.join(cityInfo[:-2]), cityInfo[-2], cityInfo[-1])\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"parsing",
"python",
"street_address"
] |
stackoverflow_0002097191_parsing_python_street_address.txt
|
Q:
how to safely generate a SQL LIKE statement using python db-api
I am trying to assemble the following SQL statement using python's db-api:
SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%';
where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried
beginningOfString = 'abc'
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%', beginningOfString)
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%%', beginningOfString)
I am out of ideas; what is the correct way to do this?
A:
It's best to separate the parameters from the sql if you can.
Then you can let the db module take care of proper quoting of the parameters.
sql='SELECT x FROM myTable WHERE x LIKE %s'
args=[beginningOfString+'%']
cursor.execute(sql,args)
A:
EDIT:
As Brian and Thomas noted, the far better way to do this would be to use:
beginningOfString += '%'
cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) )
since the first method leaves you open to SQL injection attacks.
Left in for history:
Try:
cursor.execute("SELECT x FROM myTable WHERE x LIKE '%s%%'" % beginningOfString)
|
how to safely generate a SQL LIKE statement using python db-api
|
I am trying to assemble the following SQL statement using python's db-api:
SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%';
where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried
beginningOfString = 'abc'
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%', beginningOfString)
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%%', beginningOfString)
I am out of ideas; what is the correct way to do this?
|
[
"It's best to separate the parameters from the sql if you can.\nThen you can let the db module take care of proper quoting of the parameters.\nsql='SELECT x FROM myTable WHERE x LIKE %s'\nargs=[beginningOfString+'%']\ncursor.execute(sql,args)\n\n",
"EDIT:\nAs Brian and Thomas noted, the far better way to do this would be to use:\nbeginningOfString += '%'\ncursor.execute(\"SELECT x FROM myTable WHERE x LIKE ?\", (beginningOfString,) )\n\nsince the first method leaves you open to SQL injection attacks.\n\nLeft in for history:\nTry: \ncursor.execute(\"SELECT x FROM myTable WHERE x LIKE '%s%%'\" % beginningOfString)\n\n"
] |
[
26,
3
] |
[
"Take note of Sqlite3 documentation: \n\nUsually your SQL operations will need\n to use values from Python variables.\n You shouldn’t assemble your query\n using Python’s string operations\n because doing so is insecure; it makes\n your program vulnerable to an SQL\n injection attack.\nInstead, use the DB-API’s parameter\n substitution. Put ? as a placeholder\n wherever you want to use a value, and\n then provide a tuple of values as the\n second argument to the cursor’s\n execute() method. (Other database\n modules may use a different\n placeholder, such as %s or :1.) For\n example:\n# Never do this -- insecure!\nsymbol = 'IBM'\nc.execute(\"... where symbol = '%s'\" % symbol)\n\n# Do this instead\nt = (symbol,)\nc.execute('select * from stocks where symbol=?', t)\n\n# Larger example\nfor t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),\n ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n ]:\n c.execute('insert into stocks values (?,?,?,?,?)', t)\n\n\nI think you want this:\ncursor.execute('SELECT x FROM myTable WHERE x LIKE '%?%', (beginningOfString,) )\n\n"
] |
[
-1
] |
[
"python",
"python_db_api",
"sql",
"sql_like"
] |
stackoverflow_0002097475_python_python_db_api_sql_sql_like.txt
|
Q:
Error handling in the RequestHandler without embedding in URI
When a user sends a filled form, I want to print an error message in case there is an input error. One of the GAE sample codes does this by embedding the error message in the URI.
Inside the form handler (get):
self.redirect('/compose?error_message=%s' % message)
and in the handler (get) of redirected URI, gets the message from request:
values = {
'error_message': self.request.get('error_message'),
...
Is there a way to accomplish the same without embedding the message in the URI?
A:
Is the values dict being rendered by the template engine? If so, you can pass the error string directly like this:
values = {
'error_message': 'there is an error',
...
|
Error handling in the RequestHandler without embedding in URI
|
When a user sends a filled form, I want to print an error message in case there is an input error. One of the GAE sample codes does this by embedding the error message in the URI.
Inside the form handler (get):
self.redirect('/compose?error_message=%s' % message)
and in the handler (get) of redirected URI, gets the message from request:
values = {
'error_message': self.request.get('error_message'),
...
Is there a way to accomplish the same without embedding the message in the URI?
|
[
"Is the values dict being rendered by the template engine? If so, you can pass the error string directly like this:\nvalues = {\n 'error_message': 'there is an error',\n ...\n\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"web_applications"
] |
stackoverflow_0002092708_google_app_engine_python_web_applications.txt
|
Q:
Property XXXX is not multi-line exception in python GAE
I have a simple model object with
profilename = db.StringProperty()
and when I get a string with "Some More" and try to
put
it in model
it throws exception
Property profilename is not multi-line
Is space equivalent to newline or I have missed something here? It is
put ting
for single word strings without spaces.
A:
The check's being done at application level, specifically in StringProperty.validate -- the code in question (which you can find in your SDK's sources in ext/db/init.py) is:
if not self.multiline and value and value.find('\n') != -1:
raise BadValueError('Property %s is not multi-line' % self.name)
so there's no way it can be triggered unless a \n has indeed found its way into the value you're passing in. To help you debug the issue, use
logging.info('value is: %r', value)
just before the put that's giving you problems -- what do you see in the logs as a result? The %r format specifier shows the repr of your string, so you'll be able to observe where's the pesky \n that shouldn't ever be there, and, from that info, debug the issue.
|
Property XXXX is not multi-line exception in python GAE
|
I have a simple model object with
profilename = db.StringProperty()
and when I get a string with "Some More" and try to
put
it in model
it throws exception
Property profilename is not multi-line
Is space equivalent to newline or I have missed something here? It is
put ting
for single word strings without spaces.
|
[
"The check's being done at application level, specifically in StringProperty.validate -- the code in question (which you can find in your SDK's sources in ext/db/init.py) is:\nif not self.multiline and value and value.find('\\n') != -1:\n raise BadValueError('Property %s is not multi-line' % self.name)\n\nso there's no way it can be triggered unless a \\n has indeed found its way into the value you're passing in. To help you debug the issue, use\nlogging.info('value is: %r', value)\n\njust before the put that's giving you problems -- what do you see in the logs as a result? The %r format specifier shows the repr of your string, so you'll be able to observe where's the pesky \\n that shouldn't ever be there, and, from that info, debug the issue.\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002096471_google_app_engine_google_cloud_datastore_python.txt
|
Q:
How do I get a µ character out of sqlite and onto a web-page?
On a Python driven web app using a sqlite datastore I had this error:
Could not decode to UTF-8 column
'name' with text '300µL-10-10'
Reading here it looks like I need to switch my text-factory to str and get bytestrings but when I do this my html output looks like this:
300�L-10-10
I do have my content-type set as:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
A:
Unfortunately, the data in your datastore is not encoded as UTF-8; instead, it's probably either latin-1 or cp1252. To decode it automatically, try setting Connection.text_factory to your own function:
def convert_string(s):
try:
u = s.decode("utf-8")
except UnicodeDecodeError:
u = s.decode("cp1252")
return u
conn.text_factory = convert_string
|
How do I get a µ character out of sqlite and onto a web-page?
|
On a Python driven web app using a sqlite datastore I had this error:
Could not decode to UTF-8 column
'name' with text '300µL-10-10'
Reading here it looks like I need to switch my text-factory to str and get bytestrings but when I do this my html output looks like this:
300�L-10-10
I do have my content-type set as:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
|
[
"Unfortunately, the data in your datastore is not encoded as UTF-8; instead, it's probably either latin-1 or cp1252. To decode it automatically, try setting Connection.text_factory to your own function:\ndef convert_string(s):\n try:\n u = s.decode(\"utf-8\")\n except UnicodeDecodeError:\n u = s.decode(\"cp1252\")\n return u\n\nconn.text_factory = convert_string\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"sqlite",
"unicode",
"utf_8"
] |
stackoverflow_0002097256_python_sqlite_unicode_utf_8.txt
|
Q:
Python readline on a pipe that has been opened as non-blocking
I have a Linux fifo that has been opened in non-blocking mode. As expected, when I call read on the file object, it returns immediately. I use select to make sure there is no busy waiting, but that my program is still notified when there is any data available. Out of curiosity, I tried the readline function and was surprised to find that readline blocks until a newline character is found. I examined the processor usage via top and it seems like readline does not busy wait. Since my application is performance sensitive, I am wondering if there are any performance implications when using readline on a non-blocking socket.
A:
The core part of Python's readline is in fileobject.c:get_line and is
FILE_BEGIN_ALLOW_THREADS(f)
FLOCKFILE(fp);
while ((c = GETC(fp)) != EOF &&
(*buf++ = c) != '\n' &&
buf != end)
;
FUNLOCKFILE(fp);
FILE_END_ALLOW_THREADS(f)
where
#ifdef HAVE_GETC_UNLOCKED
#define GETC(f) getc_unlocked(f)
#define FLOCKFILE(f) flockfile(f)
#define FUNLOCKFILE(f) funlockfile(f)
#else
#define GETC(f) getc(f)
#define FLOCKFILE(f)
#define FUNLOCKFILE(f)
#endif
There's nothing special going on. Are you sure your observations are what you think they are?
|
Python readline on a pipe that has been opened as non-blocking
|
I have a Linux fifo that has been opened in non-blocking mode. As expected, when I call read on the file object, it returns immediately. I use select to make sure there is no busy waiting, but that my program is still notified when there is any data available. Out of curiosity, I tried the readline function and was surprised to find that readline blocks until a newline character is found. I examined the processor usage via top and it seems like readline does not busy wait. Since my application is performance sensitive, I am wondering if there are any performance implications when using readline on a non-blocking socket.
|
[
"The core part of Python's readline is in fileobject.c:get_line and is\nFILE_BEGIN_ALLOW_THREADS(f)\nFLOCKFILE(fp);\n\nwhile ((c = GETC(fp)) != EOF &&\n (*buf++ = c) != '\\n' &&\n buf != end)\n ;\nFUNLOCKFILE(fp);\nFILE_END_ALLOW_THREADS(f)\n\nwhere\n#ifdef HAVE_GETC_UNLOCKED\n#define GETC(f) getc_unlocked(f)\n#define FLOCKFILE(f) flockfile(f)\n#define FUNLOCKFILE(f) funlockfile(f)\n#else\n#define GETC(f) getc(f)\n#define FLOCKFILE(f)\n#define FUNLOCKFILE(f)\n#endif\n\nThere's nothing special going on. Are you sure your observations are what you think they are?\n"
] |
[
1
] |
[] |
[] |
[
"file",
"nonblocking",
"pipe",
"python",
"readline"
] |
stackoverflow_0002093788_file_nonblocking_pipe_python_readline.txt
|
Q:
can SimpleXMLRPCServer listen on multiple addresses?
I have two IPs mapping to the machine, and I was wondering how I can have one python xmlrpc server listening on both IPs (same port), like you could do with Apache.
Thank you,
A:
Use "" as the host:
s = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8000))
|
can SimpleXMLRPCServer listen on multiple addresses?
|
I have two IPs mapping to the machine, and I was wondering how I can have one python xmlrpc server listening on both IPs (same port), like you could do with Apache.
Thank you,
|
[
"Use \"\" as the host:\ns = SimpleXMLRPCServer.SimpleXMLRPCServer((\"\", 8000))\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"simplexmlrpcserver"
] |
stackoverflow_0002098045_python_simplexmlrpcserver.txt
|
Q:
Using a function to create a function in Python
I'm new to programming and I'm interested in if it's possible to use a function to create another function based in inputted information:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 5', 'Fun for 5 to 7', 'Fun for 7 to 10', 'Fun for over 10'))
method = getattr(PotatoHead, new_toy[0])
def method(self):
I don't think that I'm doing this right
Thankful for any help
---Edit---
Sorry for not making it clear:
I'm creating a virtual pet sort of game for my younger sister.
The 'PotatoHead' can 'play' with certain toys as dictated by functions such as this:
def play_Softball(self):
self.happiness_num = float(self.happiness)
if float(self.age) <= 3.0:
self.happiness_num = self.happiness_num + 0.3
elif float(self.age) > 3.0 and float(self.age) < 4.0:
self.happiness_num = self.happiness_num + 0.7
elif float(self.age) > 4.0 and float(self.age) < 7.0:
self.happiness_num = self.happiness_num + 1.0
elif float(self.age) > 7.0 and float(self.age) < 9.0:
self.happiness_num = self.happiness_num + 0.5
elif float(self.age) > 9.0:
self.happiness_num = self.happiness_num + 0.02
gui.msgbox(
msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',
title = 'WARNING!',
ok_button = 'Understood')
self.happiness = str(self.happiness_num)
I want there to be a function that allows the creation of a new 'toy' as a function that is similar to the one above.
Again, thanks for any help
---UPDATE---
Thanks again, but just wondering
Is it possible to work something such as this into it:
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
in this context:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 3', 'Fun for 3 to 4', 'Fun for 4 to 7', 'Fun for 7 to 9', 'Fun for over 9'))
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
self.toys.append(new_toy[0])
thanks again for any help
A:
Here is an example python function that returns a new function based on the parameter passed in. I'm not sure what you are trying to do but this might help point you in the right direction.
def add_to(amount):
def f(x):
return x + amount
return f
if __name__ == "__main__":
add_2 = add_to(2)
add_3 = add_to(3)
print add_2(42)
print add_3(42)
Given your toy example (which seems like a fun thing to do for you sister) you might try something like this (I haven't tested the code, but it should help out):
def create_toy(self, fun_0_3, fun_3_4, fun_4_7, fun_7_9, fun_9_plus):
def toy(self):
self.happiness_num = float(self.happiness)
if float(self.age) <= 3.0:
self.happiness_num = self.happiness_num + fun_0_3
elif float(self.age) > 3.0 and float(self.age) < 4.0:
self.happiness_num = self.happiness_num + fun_3_4
elif float(self.age) > 4.0 and float(self.age) < 7.0:
self.happiness_num = self.happiness_num + fun_4_7
elif float(self.age) > 7.0 and float(self.age) < 9.0:
self.happiness_num = self.happiness_num + fun_7_9
elif float(self.age) > 9.0:
self.happiness_num = self.happiness_num + fun_9_plus
gui.msgbox(
msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',
title = 'WARNING!',
ok_button = 'Understood')
self.happiness = str(self.happiness_num)
return toy
#somewhere else
play_Softball = create_toy(0.3, 0.7, 1.0, 0.5, 0.02)
|
Using a function to create a function in Python
|
I'm new to programming and I'm interested in if it's possible to use a function to create another function based in inputted information:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 5', 'Fun for 5 to 7', 'Fun for 7 to 10', 'Fun for over 10'))
method = getattr(PotatoHead, new_toy[0])
def method(self):
I don't think that I'm doing this right
Thankful for any help
---Edit---
Sorry for not making it clear:
I'm creating a virtual pet sort of game for my younger sister.
The 'PotatoHead' can 'play' with certain toys as dictated by functions such as this:
def play_Softball(self):
self.happiness_num = float(self.happiness)
if float(self.age) <= 3.0:
self.happiness_num = self.happiness_num + 0.3
elif float(self.age) > 3.0 and float(self.age) < 4.0:
self.happiness_num = self.happiness_num + 0.7
elif float(self.age) > 4.0 and float(self.age) < 7.0:
self.happiness_num = self.happiness_num + 1.0
elif float(self.age) > 7.0 and float(self.age) < 9.0:
self.happiness_num = self.happiness_num + 0.5
elif float(self.age) > 9.0:
self.happiness_num = self.happiness_num + 0.02
gui.msgbox(
msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',
title = 'WARNING!',
ok_button = 'Understood')
self.happiness = str(self.happiness_num)
I want there to be a function that allows the creation of a new 'toy' as a function that is similar to the one above.
Again, thanks for any help
---UPDATE---
Thanks again, but just wondering
Is it possible to work something such as this into it:
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
in this context:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 3', 'Fun for 3 to 4', 'Fun for 4 to 7', 'Fun for 7 to 9', 'Fun for over 9'))
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
self.toys.append(new_toy[0])
thanks again for any help
|
[
"Here is an example python function that returns a new function based on the parameter passed in. I'm not sure what you are trying to do but this might help point you in the right direction.\ndef add_to(amount):\n def f(x):\n return x + amount\n return f\n\nif __name__ == \"__main__\":\n add_2 = add_to(2)\n add_3 = add_to(3)\n\n print add_2(42)\n print add_3(42)\n\nGiven your toy example (which seems like a fun thing to do for you sister) you might try something like this (I haven't tested the code, but it should help out):\ndef create_toy(self, fun_0_3, fun_3_4, fun_4_7, fun_7_9, fun_9_plus):\n def toy(self):\n self.happiness_num = float(self.happiness)\n if float(self.age) <= 3.0:\n self.happiness_num = self.happiness_num + fun_0_3\n elif float(self.age) > 3.0 and float(self.age) < 4.0:\n self.happiness_num = self.happiness_num + fun_3_4\n elif float(self.age) > 4.0 and float(self.age) < 7.0:\n self.happiness_num = self.happiness_num + fun_4_7\n elif float(self.age) > 7.0 and float(self.age) < 9.0:\n self.happiness_num = self.happiness_num + fun_7_9\n elif float(self.age) > 9.0:\n self.happiness_num = self.happiness_num + fun_9_plus\n gui.msgbox(\n msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',\n title = 'WARNING!',\n ok_button = 'Understood')\n self.happiness = str(self.happiness_num)\n return toy\n\n#somewhere else\nplay_Softball = create_toy(0.3, 0.7, 1.0, 0.5, 0.02)\n\n"
] |
[
2
] |
[] |
[] |
[
"function",
"python"
] |
stackoverflow_0002098181_function_python.txt
|
Q:
Python optparse not seeing argument
I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. Any ideas? I imagine its something simple that I am overlooking. Any and all help is great, thanks, Justin.
[justin87@el-beasto-loco python]$ python openall.py -f chords.tar
Usage: openall.py [options] arg
openall.py: error: incorrect number of arguments
[justin87@el-beasto-loco python]$
#!/usr/bin/python
import tarfile
import os
import zipfile
from optparse import OptionParser
def check_tar(file):
if tarfile.is_tarfile(file):
return True
def open_tar(file):
try:
tar = tarfile.open(file)
tar.extractall()
tar.close()
except tarfile.ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except tarfile.CompressionError:
print "Compression method is not supported or data cannot be decoded"
except tarfile.StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except tarfile.ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
def check_zip(file):
if zipfile.is_zipfile(file):
return True
def open_zip(file):
try:
zip = zipfile.ZipFile(file)
zip.extractall()
zip.close()
#open the zip
print "GOT TO OPENING"
except zipfile.BadZipfile:
print "The error raised for bad ZIP files (old name: zipfile.error)."
except zipfile.LargeZipFile:
print "The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled."
rules = ((check_tar, open_tar),
(check_zip, open_zip)
)
def checkall(file):
for checks, extracts in rules:
if checks(file):
return extracts(file)
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = options.filename
checkall(file)
if __name__ == '__main__':
main()
A:
Your problem is probably the if len(args) != 1:. That is looking for an additional argument (i.e. not an option). If you remove that check and look at your options dictionary you should see {'filename': 'blah'}.
A:
After parsing the options out of the argument list, you check that you were passed an argument. This is independent of the argument to -f. It sounds like you're just not passing this argument. Since you also don't actually use this argument, you should probably just remove the check on len(args).
A:
Your input filename isn't an option to the program, it's an argument:
def main():
usage = "Usage: %prog [options] FILE"
description = "Read data from FILE."
parser = OptionParser(usage, description=description)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = args[0]
checkall(file)
You can usually tell the difference because options generally have sensible defaults while arguments don't.
A:
You should set the 'action' attribute in the 'add_option()' method to 'store', this tells the optparse object to store the argument immediately following the option flag, though this is the default behavior. The value following the flag will then be stored in 'options.filename' and not in args. I also think that the
if len(args) != 1:
is also an issue, you will get the same message if len(args) is greater than or less than 1.
|
Python optparse not seeing argument
|
I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. Any ideas? I imagine its something simple that I am overlooking. Any and all help is great, thanks, Justin.
[justin87@el-beasto-loco python]$ python openall.py -f chords.tar
Usage: openall.py [options] arg
openall.py: error: incorrect number of arguments
[justin87@el-beasto-loco python]$
#!/usr/bin/python
import tarfile
import os
import zipfile
from optparse import OptionParser
def check_tar(file):
if tarfile.is_tarfile(file):
return True
def open_tar(file):
try:
tar = tarfile.open(file)
tar.extractall()
tar.close()
except tarfile.ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except tarfile.CompressionError:
print "Compression method is not supported or data cannot be decoded"
except tarfile.StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except tarfile.ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
def check_zip(file):
if zipfile.is_zipfile(file):
return True
def open_zip(file):
try:
zip = zipfile.ZipFile(file)
zip.extractall()
zip.close()
#open the zip
print "GOT TO OPENING"
except zipfile.BadZipfile:
print "The error raised for bad ZIP files (old name: zipfile.error)."
except zipfile.LargeZipFile:
print "The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled."
rules = ((check_tar, open_tar),
(check_zip, open_zip)
)
def checkall(file):
for checks, extracts in rules:
if checks(file):
return extracts(file)
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = options.filename
checkall(file)
if __name__ == '__main__':
main()
|
[
"Your problem is probably the if len(args) != 1:. That is looking for an additional argument (i.e. not an option). If you remove that check and look at your options dictionary you should see {'filename': 'blah'}.\n",
"After parsing the options out of the argument list, you check that you were passed an argument. This is independent of the argument to -f. It sounds like you're just not passing this argument. Since you also don't actually use this argument, you should probably just remove the check on len(args).\n",
"Your input filename isn't an option to the program, it's an argument:\ndef main():\n usage = \"Usage: %prog [options] FILE\"\n description = \"Read data from FILE.\"\n parser = OptionParser(usage, description=description)\n\n (options, args) = parser.parse_args()\n if len(args) != 1:\n parser.error(\"incorrect number of arguments\")\n\n file = args[0]\n checkall(file)\n\nYou can usually tell the difference because options generally have sensible defaults while arguments don't.\n",
"You should set the 'action' attribute in the 'add_option()' method to 'store', this tells the optparse object to store the argument immediately following the option flag, though this is the default behavior. The value following the flag will then be stored in 'options.filename' and not in args. I also think that the \nif len(args) != 1:\n\nis also an issue, you will get the same message if len(args) is greater than or less than 1. \n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"optparse",
"python"
] |
stackoverflow_0002098211_optparse_python.txt
|
Q:
Mod_Python + Django library import issue
I recently had a site that was running perfect for months, all of a sudden it decided to dump itself for no approximate reason.
I am running django + mod_python + apache, and the system decided it was time to start ignoring the import of the pycurl library, my intial first thought was that somehow the library had become corrupted, or the paths were uncached by apache or mod_python.
After checking the paths, symbolic links, permissions and reinstalling the exact build of pycurl I am still recieving the same error. The strange thing is, is that I can load the library within python itself and run tests with no issues, but not within mod_python. I know for a fact that the paths are correctly pointed as I have checked them numerous times and updated the system cache accordingly.
Django now will not load or throw any errors, nor will apache log anything if I try and import the library it will just silently fail... I have been exploring this issue for 2 days now and have not come up with anything.
Any help would be greatly appreciated.
Just to add some here, the server has not been touched in any way since the final revision and launch.
I have checked every log that would indicate some type of attack against the server and there is nothing, the only thing that exists is request from my hosting provider which is where the error in question first started to appear.
Also the similar issue: stackoverflow.com/questions/1099981/… - does not work in this case.
Incase anyone is wondering the versions are as follows
Python 2.4.3
Mod_Python 3.2.8
Apache 2.2.3
Redhat Red Hat Enterprise Linux Server release 5.4
Linux Kernal 2.6.18-128.7.1.el5 x86_64
A:
If the problem is a failing import when running under Apache but the import works when running from your login shell, double-check that there isn't a directory/file permission problem with the failing module(s). They must be read-accessible and in some cases also execute-accessible from the user id that Apache is running under.
A:
The httpd process could be running into the open file limit; see help ulimit in bash for the relevant option to change.
A:
Well now ... I have debugged this issue ... and the answer is quite surprising.
R**kspace decided to do a few updates to the box, updating the dependent library in question and it caused the issues ... after reinstalling the library it would try to load the c module and it was not a comp version with the current pycurl ... and they couldn't figure this out themselves for 2 days.
|
Mod_Python + Django library import issue
|
I recently had a site that was running perfect for months, all of a sudden it decided to dump itself for no approximate reason.
I am running django + mod_python + apache, and the system decided it was time to start ignoring the import of the pycurl library, my intial first thought was that somehow the library had become corrupted, or the paths were uncached by apache or mod_python.
After checking the paths, symbolic links, permissions and reinstalling the exact build of pycurl I am still recieving the same error. The strange thing is, is that I can load the library within python itself and run tests with no issues, but not within mod_python. I know for a fact that the paths are correctly pointed as I have checked them numerous times and updated the system cache accordingly.
Django now will not load or throw any errors, nor will apache log anything if I try and import the library it will just silently fail... I have been exploring this issue for 2 days now and have not come up with anything.
Any help would be greatly appreciated.
Just to add some here, the server has not been touched in any way since the final revision and launch.
I have checked every log that would indicate some type of attack against the server and there is nothing, the only thing that exists is request from my hosting provider which is where the error in question first started to appear.
Also the similar issue: stackoverflow.com/questions/1099981/… - does not work in this case.
Incase anyone is wondering the versions are as follows
Python 2.4.3
Mod_Python 3.2.8
Apache 2.2.3
Redhat Red Hat Enterprise Linux Server release 5.4
Linux Kernal 2.6.18-128.7.1.el5 x86_64
|
[
"If the problem is a failing import when running under Apache but the import works when running from your login shell, double-check that there isn't a directory/file permission problem with the failing module(s). They must be read-accessible and in some cases also execute-accessible from the user id that Apache is running under.\n",
"The httpd process could be running into the open file limit; see help ulimit in bash for the relevant option to change.\n",
"Well now ... I have debugged this issue ... and the answer is quite surprising.\nR**kspace decided to do a few updates to the box, updating the dependent library in question and it caused the issues ... after reinstalling the library it would try to load the c module and it was not a comp version with the current pycurl ... and they couldn't figure this out themselves for 2 days.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"apache",
"django",
"mod_python",
"pycurl",
"python"
] |
stackoverflow_0002094783_apache_django_mod_python_pycurl_python.txt
|
Q:
Python re.sub question
Greetings all,
I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables.
a = 'foo'
b = 'bar'
text = 'find a replacement for me [[:a:]] and [[:b:]]'
desired_output = 'find a replacement for me foo and bar'
re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid
re.sub('\[\[:(.+):\]\]','\1',text) #replaces the value with 'a' or 'b', not var value
thoughts?
A:
You can specify a callback when using re.sub, which has access to the groups:
http://docs.python.org/library/re.html#text-munging
a = 'foo'
b = 'bar'
text = 'find a replacement for me [[:a:]] and [[:b:]]'
desired_output = 'find a replacement for me foo and bar'
def repl(m):
contents = m.group(1)
if contents == 'a':
return a
if contents == 'b':
return b
print re.sub('\[\[:(.+?):\]\]', repl, text)
Also notice the extra ? in the regular expression. You want non-greedy matching here.
I understand this is just sample code to illustrate a concept, but for the example you gave, simple string formatting is better.
A:
Sounds like overkill. Why not just do something like
text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')
?
A:
>>> d={}
>>> d['a'] = 'foo'
>>> d['b'] = 'bar'
>>> text = 'find a replacement for me [[:a:]] and [[:b:]]'
>>> t=text.split(":]]")
>>> for n,item in enumerate(t):
... if "[[:" in item:
... t[n]=item[: item.rindex("[[:") +3 ] + d[ item.split("[[:")[-1]]
...
>>> print ':]]'.join( t )
'find a replacement for me [[:foo:]] and [[:bar:]]'
|
Python re.sub question
|
Greetings all,
I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables.
a = 'foo'
b = 'bar'
text = 'find a replacement for me [[:a:]] and [[:b:]]'
desired_output = 'find a replacement for me foo and bar'
re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid
re.sub('\[\[:(.+):\]\]','\1',text) #replaces the value with 'a' or 'b', not var value
thoughts?
|
[
"You can specify a callback when using re.sub, which has access to the groups:\nhttp://docs.python.org/library/re.html#text-munging\na = 'foo'\nb = 'bar'\n\ntext = 'find a replacement for me [[:a:]] and [[:b:]]'\n\ndesired_output = 'find a replacement for me foo and bar'\n\ndef repl(m):\n contents = m.group(1)\n if contents == 'a':\n return a\n if contents == 'b':\n return b\n\nprint re.sub('\\[\\[:(.+?):\\]\\]', repl, text)\n\nAlso notice the extra ? in the regular expression. You want non-greedy matching here.\nI understand this is just sample code to illustrate a concept, but for the example you gave, simple string formatting is better.\n",
"Sounds like overkill. Why not just do something like\ntext = \"find a replacement for me %(a)s and %(b)s\"%dict(a='foo', b='bar')\n\n?\n",
">>> d={} \n>>> d['a'] = 'foo' \n>>> d['b'] = 'bar' \n>>> text = 'find a replacement for me [[:a:]] and [[:b:]]'\n>>> t=text.split(\":]]\")\n>>> for n,item in enumerate(t):\n... if \"[[:\" in item:\n... t[n]=item[: item.rindex(\"[[:\") +3 ] + d[ item.split(\"[[:\")[-1]]\n...\n>>> print ':]]'.join( t )\n'find a replacement for me [[:foo:]] and [[:bar:]]'\n\n"
] |
[
32,
8,
2
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002094975_python_regex.txt
|
Q:
Python Detect Keystrokes Sent to Another Application
I have a Python program that sends keystrokes to another application using SendKeys. Some of the keystrokes, however, must be sent to the application after it does some processing (which takes an unknown amount of time). So far I have had to let the Python application know the processing was finished by Alt+Tabbing back to the DOS window and hitting Enter. I'd like to have a key combination (Shift+F1 or something like that) that I can hit in the receiving application that signals the Python program to continue without me having to switch back to the DOS window. How would I make it so I can detect keystrokes in Python even though the focus is on another window?
A:
Have a look at pyHook.
It allows Keyboard hooking:
import pythoncom, pyHook
def OnKeyboardEvent(event):
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Ascii:', event.Ascii, chr(event.Ascii)
print 'Key:', event.Key
print 'KeyID:', event.KeyID
print 'ScanCode:', event.ScanCode
print 'Extended:', event.Extended
print 'Injected:', event.Injected
print 'Alt', event.Alt
print 'Transition', event.Transition
print '---'
# return True to pass the event to other handlers
return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
|
Python Detect Keystrokes Sent to Another Application
|
I have a Python program that sends keystrokes to another application using SendKeys. Some of the keystrokes, however, must be sent to the application after it does some processing (which takes an unknown amount of time). So far I have had to let the Python application know the processing was finished by Alt+Tabbing back to the DOS window and hitting Enter. I'd like to have a key combination (Shift+F1 or something like that) that I can hit in the receiving application that signals the Python program to continue without me having to switch back to the DOS window. How would I make it so I can detect keystrokes in Python even though the focus is on another window?
|
[
"Have a look at pyHook.\nIt allows Keyboard hooking:\nimport pythoncom, pyHook \n\ndef OnKeyboardEvent(event):\n print 'MessageName:',event.MessageName\n print 'Message:',event.Message\n print 'Time:',event.Time\n print 'Window:',event.Window\n print 'WindowName:',event.WindowName\n print 'Ascii:', event.Ascii, chr(event.Ascii)\n print 'Key:', event.Key\n print 'KeyID:', event.KeyID\n print 'ScanCode:', event.ScanCode\n print 'Extended:', event.Extended\n print 'Injected:', event.Injected\n print 'Alt', event.Alt\n print 'Transition', event.Transition\n print '---'\n\n# return True to pass the event to other handlers\n return True\n\n# create a hook manager\nhm = pyHook.HookManager()\n# watch for all mouse events\nhm.KeyDown = OnKeyboardEvent\n# set the hook\nhm.HookKeyboard()\n# wait forever\npythoncom.PumpMessages()\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"sendkeys"
] |
stackoverflow_0002098388_python_sendkeys.txt
|
Q:
Best JSON library to get JSON data for Django?
What is the best JSON library to get JSON data for Django, 'simplejson' or otherwise?
thanks very much
A:
Django itself integrates simplejson and has the ability to use your own version from the system if you have it installed.
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
As Alex notes, the json module is bundled with Python 2.6 and above -- that's actually simplejson source pulled into Python core. This might demonstrate to you that it has wide acceptance in the Python community.
The reason that you may want to use your own version is that simplejson when compiled with C extensions and cjson, a different module, are substantially more performant than the versions bundled with Django or Python.
A:
Python 2.6 comes with a json module in the standard library -- so that would be best if you're on Python 2.6; for older Python versions, simplejson may be roughly equivalent.
|
Best JSON library to get JSON data for Django?
|
What is the best JSON library to get JSON data for Django, 'simplejson' or otherwise?
thanks very much
|
[
"Django itself integrates simplejson and has the ability to use your own version from the system if you have it installed.\nfrom django.core import serializers\njson_serializer = serializers.get_serializer(\"json\")()\n\nAs Alex notes, the json module is bundled with Python 2.6 and above -- that's actually simplejson source pulled into Python core. This might demonstrate to you that it has wide acceptance in the Python community.\nThe reason that you may want to use your own version is that simplejson when compiled with C extensions and cjson, a different module, are substantially more performant than the versions bundled with Django or Python.\n",
"Python 2.6 comes with a json module in the standard library -- so that would be best if you're on Python 2.6; for older Python versions, simplejson may be roughly equivalent.\n"
] |
[
9,
8
] |
[] |
[] |
[
"django",
"json",
"python"
] |
stackoverflow_0002098611_django_json_python.txt
|
Q:
POSTing forms in Django's admin interface
I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows:
def email_selected(self,request,queryset):
rep_list = []
for each in queryset:
reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name))
contact_reps = reps.filter(is_contact=True)
for rep in contact_reps:
rep_list.append(rep)
return email_form(request,queryset,rep_list)
email_form exists as a view and fills a template with this code:
def email_form(request,queryset,rep_list):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email','noreply@localboast'),['redacted@email.com'],
)
return HttpResponseRedirect('thanks')
else:
form = EmailForm()
return render_to_response('corpware/admin/email-form.html',{'form':form,})
and the template exists as follows:
<body>
<form action="/process_mail/" method="post">
<table>
{{ form.as_table }}
</table>
<input type = "submit" value = "Submit">
</form>
</body>
/process_mail/ is hardlinked to another view in urls.py - which is a problem. I'd really like it so that I don't have to use <form action="/process_mail/" method="post"> but unfortunately I can't seem to POST the user inputs to the view handler without the admin interface for the model being reloaded in it's place (When I hit the submit button with , the administration interface appears, which I don't want.)
Is there a way that I could make the form POST to itself (<form action="" method="post">) so that I can handle inputs received in email_form? Trying to handle inputs with extraneous URLs and unneeded functions bothers me, as I'm hardcoding URLs to work with the code.
A:
You can use django's inbuilt url tag to avoid hardcoding links. see...
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url
Chances are you'd be better off setting up a mass mailer to be triggered off by a cron job rather than on the post.
Check out the answer I posted here
Django scheduled jobs
Also if you insist on triggering the email_send function on a view update perhaps look at
http://docs.djangoproject.com/en/dev/topics/signals/
|
POSTing forms in Django's admin interface
|
I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows:
def email_selected(self,request,queryset):
rep_list = []
for each in queryset:
reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name))
contact_reps = reps.filter(is_contact=True)
for rep in contact_reps:
rep_list.append(rep)
return email_form(request,queryset,rep_list)
email_form exists as a view and fills a template with this code:
def email_form(request,queryset,rep_list):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email','noreply@localboast'),['redacted@email.com'],
)
return HttpResponseRedirect('thanks')
else:
form = EmailForm()
return render_to_response('corpware/admin/email-form.html',{'form':form,})
and the template exists as follows:
<body>
<form action="/process_mail/" method="post">
<table>
{{ form.as_table }}
</table>
<input type = "submit" value = "Submit">
</form>
</body>
/process_mail/ is hardlinked to another view in urls.py - which is a problem. I'd really like it so that I don't have to use <form action="/process_mail/" method="post"> but unfortunately I can't seem to POST the user inputs to the view handler without the admin interface for the model being reloaded in it's place (When I hit the submit button with , the administration interface appears, which I don't want.)
Is there a way that I could make the form POST to itself (<form action="" method="post">) so that I can handle inputs received in email_form? Trying to handle inputs with extraneous URLs and unneeded functions bothers me, as I'm hardcoding URLs to work with the code.
|
[
"You can use django's inbuilt url tag to avoid hardcoding links. see... \nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#url\nChances are you'd be better off setting up a mass mailer to be triggered off by a cron job rather than on the post.\nCheck out the answer I posted here\nDjango scheduled jobs\nAlso if you insist on triggering the email_send function on a view update perhaps look at \nhttp://docs.djangoproject.com/en/dev/topics/signals/\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_admin",
"django_templates",
"django_urls",
"python"
] |
stackoverflow_0002098527_django_django_admin_django_templates_django_urls_python.txt
|
Q:
GAE datastore eager loading in python api
I have two models in relation one-to-many:
class Question(db.Model):
questionText = db.StringProperty(multiline=False)
class Answer(db.Model):
answerText = db.StringProperty(multiline=False)
question = db.ReferenceProperty(Question, collection_name='answers')
I have front-end implemented in Flex and use pyamf to load data.
When i try to load all answers with related questions all works as desired and I can access
field
answer.question
however in case of loading questions (e.g. by Questions.all() ), 'question.answers' remains empty/null
(though on server/python side I can revise question.answers without problem - probably after lazy-loading).
So is it possible to load all questions along with answers ?
(I know this is possible in JPA Java api but what about python ?)
Shoud I use additional setting, GQL query or django framework to make it work ?
A:
By default PyAMF will not encode ReferenceProperty fields unless they have already been specifically loaded by the service method. This is on purpose so you don't end up encoding more than you have to.
PyAMF looks for a special class attribute __amf__ which it uses to customise the encoding and decoding process for instances of that type. More information can be found in the docs.
So, to force the encoding of all answers for all questions you should be able to do:
class Question(db.Model):
class __amf__:
static = ('answers',)
questionText = db.StringProperty(multiline=False)
class Answer(db.Model):
answertText = db.StringProperty(multiline=False)
question = db.ReferenceProperty(Question, collection_name='answers')
Setting the static attribute will ensure that every Question instance has the answers attribute set (via getattr) which will in turn to the datastore lookup that you require.
It is important to not that this setting is application wide, so any question will have an answers attribute as it appears on the instance.
|
GAE datastore eager loading in python api
|
I have two models in relation one-to-many:
class Question(db.Model):
questionText = db.StringProperty(multiline=False)
class Answer(db.Model):
answerText = db.StringProperty(multiline=False)
question = db.ReferenceProperty(Question, collection_name='answers')
I have front-end implemented in Flex and use pyamf to load data.
When i try to load all answers with related questions all works as desired and I can access
field
answer.question
however in case of loading questions (e.g. by Questions.all() ), 'question.answers' remains empty/null
(though on server/python side I can revise question.answers without problem - probably after lazy-loading).
So is it possible to load all questions along with answers ?
(I know this is possible in JPA Java api but what about python ?)
Shoud I use additional setting, GQL query or django framework to make it work ?
|
[
"By default PyAMF will not encode ReferenceProperty fields unless they have already been specifically loaded by the service method. This is on purpose so you don't end up encoding more than you have to.\nPyAMF looks for a special class attribute __amf__ which it uses to customise the encoding and decoding process for instances of that type. More information can be found in the docs.\nSo, to force the encoding of all answers for all questions you should be able to do:\nclass Question(db.Model):\n class __amf__:\n static = ('answers',)\n\n questionText = db.StringProperty(multiline=False)\n\nclass Answer(db.Model):\n answertText = db.StringProperty(multiline=False)\n question = db.ReferenceProperty(Question, collection_name='answers')\n\nSetting the static attribute will ensure that every Question instance has the answers attribute set (via getattr) which will in turn to the datastore lookup that you require.\nIt is important to not that this setting is application wide, so any question will have an answers attribute as it appears on the instance.\n"
] |
[
1
] |
[] |
[] |
[
"eager_loading",
"google_app_engine",
"google_cloud_datastore",
"pyamf",
"python"
] |
stackoverflow_0002098417_eager_loading_google_app_engine_google_cloud_datastore_pyamf_python.txt
|
Q:
Reverse ForeignKey lookup
I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps...
#article.models
from someapp.author.models import Author
class Article(model.Model):
...
author = models.ForeignKey(Author)
# author.models
class Author(model.Model):
...
From this schema I want to be able to get all the articles by an author. Something like:
author = Author(pk=1)
articles = author.articles
My first reaction was to write a method that did a simple look up in the article model based on the authors ID. What happened here was a never ending inclusion loop because of the separate files. Article needed Author imported to use for the ForeignKey and Author needed article included to use for the model look up. This felt hacky and wrong. I would much rather do it the right way... So, what is the Django way?
A:
I think this is what you're asking for...
class Article(model.Model):
...
author = models.ForeignKey(Author, related_name='articles')
On a side note, by default without changing anything you've got, I think this would work for you...
article.author_set
But to maintain the article.authors syntax you mention above, you can specify that yourself with related_name.
|
Reverse ForeignKey lookup
|
I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps...
#article.models
from someapp.author.models import Author
class Article(model.Model):
...
author = models.ForeignKey(Author)
# author.models
class Author(model.Model):
...
From this schema I want to be able to get all the articles by an author. Something like:
author = Author(pk=1)
articles = author.articles
My first reaction was to write a method that did a simple look up in the article model based on the authors ID. What happened here was a never ending inclusion loop because of the separate files. Article needed Author imported to use for the ForeignKey and Author needed article included to use for the model look up. This felt hacky and wrong. I would much rather do it the right way... So, what is the Django way?
|
[
"I think this is what you're asking for...\nclass Article(model.Model):\n ...\n author = models.ForeignKey(Author, related_name='articles')\n\nOn a side note, by default without changing anything you've got, I think this would work for you...\narticle.author_set\n\nBut to maintain the article.authors syntax you mention above, you can specify that yourself with related_name.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"models",
"python"
] |
stackoverflow_0002099037_django_models_python.txt
|
Q:
Parallel while Loops in Python
I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.
Is it possible to run 2 while loops parallel to each other in python?
eg:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Sleep', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
elif input_event_1 == 'Feed':
myPotatoHead.feed_potato_head()
elif input_event_1 == 'Exercise':
myPotatoHead.exercise_potato_head()
elif input_event_1 == 'Teach':
myPotatoHead.teach_potato_head(myPotatoHead)
elif input_event_1 == 'Play':
myPotatoHead.play_with_toy()
elif input_event_1 == 'Sleep':
myPotatoHead.put_p_h_asleep()
elif input_event_1 == 'Go to Doctor':
myPotatoHead.doctor_check_up()
elif input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 1:
sys.exit(0)
while 1:
time.sleep(20)
myPotatoHead.hunger = str(float(myPotatoHead.hunger) + 1.0)
myPotatoHead.happiness = str(float(myPotatoHead.happiness) - 1.0)
myPotatoHead.tiredness = str(float(myPotatoHead.tiredness) + 1.0)
If not, is there some way that I can turn this into one loop?
I want the stuff in the second loop to happen every 20 seconds, but the stuff in the first loop to by constantly happening.
Thanks for any help
A:
Have a look at Threading.Timer.
There is a code recipe here to schedule a function to run every 5 seconds.
import thread
import threading
class Operation(threading._Timer):
def __init__(self, *args, **kwargs):
threading._Timer.__init__(self, *args, **kwargs)
self.setDaemon(True)
def run(self):
while True:
self.finished.clear()
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
else:
return
self.finished.set()
class Manager(object):
ops = []
def add_operation(self, operation, interval, args=[], kwargs={}):
op = Operation(interval, operation, args, kwargs)
self.ops.append(op)
thread.start_new_thread(op.run, ())
def stop(self):
for op in self.ops:
op.cancel()
self._event.set()
if __name__ == '__main__':
# Print "Hello World!" every 5 seconds
import time
def hello():
print "Hello World!"
timer = Manager()
timer.add_operation(hello, 5)
while True:
time.sleep(.1)
A:
The only way to "have two while loops in parallel" would be to place them on different threads, but then you need to tackle the synchronization and coordination problems between them since they're reaching into the same object.
I suggest you instead put a time check in the first (and single) loop and perform the increases that you now have in the second loop proportionately to that time-check; not quite satisfactory since the buttonbox call might take an indefinite amount of time to return, but way simpler to arrange, esp. for a beginner, than proper threading coordination.
Once you do have the basic logic in place and working, then you can consider threads again (with a periodic timer for what you'd like in the 2nd loop in one thread, the blocking buttonbox call in the main thread [[I think in easygui it has to be]], both feeding events into a Queue.Queue [[intrinsically thread-safe]] with another thread getting them and operating accordingly, i.e. most of what you now have in the 1st loop). But that's quite an advanced architectural problem, which is why I recommend you don't try to deal w/it right now!-)
A:
put one of them into a function, the threading.Thread class supports a target attribute:
import threading
threading.Thread(target=yourFunc).start()
Will start yourFunc() running in the background.
A:
You should use State Machines for this (see the Apress pygame book - downloads here: http://apress.com/book/downloadfile/3765 ), see chapter 7.
A simplified state machine:
def do_play(pet, time_passed):
pet.happiness += time_pass*4.0
def do_feed(pet, time_passed):
pet.hunger -= time_passed*4.0
def do_sleep(pet, time_passed):
pet.tiredness += time_passed*4.0
if pet.tiredness <= 0:
return 'Waiting'
def do_waiting(pet, time_passed):
pass
def do_howl(pet, time_passed):
print 'Hoooowl'
def do_beg(pet, time_passed):
print "I'm bored!"
def do_dead(pet, time_passed):
print '...'
STATE_TO_FUNC = dict(Waiting=do_waiting,
Sleeping=do_sleep,
Feeding=do_feed,
Playing=do_play,
Howling=do_howl,
Begging=do_beg,
Dead=do_dead
)
class Pet:
def __init__(self):
self.state = 'Waiting'
self.hunger = 1.0
self.tiredness = 1.0
self.happiness = 1.0
def process(self, time_passed):
self.hunger +=1*time_passed
self.tiredness +=1*time_passed
self.happiness -= 1*time_passed
func = STATE_TO_FUNC[self.state]
new_state = func(self, time_passed)
if new_state is not None:
self.set_state(new_state)
if self.hunger >10:
self.set_state('Dead')
elif self.hunger > 5 and not (self.state == 'Feeding'):
self.set_state('Howling')
elif self.tiredness > 5:
self.set_state('Sleeping')
elif self.happiness < 0 and not (self.state == 'Playing'):
self.set_state('Begging')
def set_state(self,state):
if not self.state == 'Dead':
self.state = state
from msvcrt import getch
import time
pet = Pet()
while True:
time0 = time.time()
cmd = getch() # what command?
pet.process(time.time()-time0)
if cmd == 'a':
pet.set_state('Feeding')
if cmd == 's':
pet.set_state('Sleeping')
if cmd == 'd':
pet.set_state('Playing')
A:
Essentially to have processing to happen in parallel you have several solutions
1- Separate processes (ie: programs) running independently that speak to one another through a specific protocol (eg: Sockets)
2- Or you can have the one process spawn off multiple threads
3- Build an event queue internally and process them one by one
That is the general picture.
As for the specific answer to your question, you said "the stuff in the first loop to b[e] constantly happening". The reality is you never want this to happen all the time, because all that will do is use up 100% of the CPU and nothing else will ever get done
The simplest solution is probably number 3.
The way I would implement it is in my main loop have a thread that goes through an event queue and sets a timer for each event. Once all the timers have been sent the main loop then goes to sleep.
When a timer times out, an other function will then run the corresponding function for the event that triggered that timer.
In your case, you have two events. One for displaying the selection menu (first loop) and the second for changing myPotatoHead. The timer associated with the first one, I would set to 0.5sec, making it larger reduces CPU usage but slows down responsivness, increasing it usses up more CPU, for the second event I would set a 20 second timer.
Ofcourse when the timer expires, you would not do while 1 but you will just go through your while loop body once (ie get rid of while).
A:
There is also a package called SimPy that you could also look at. The threading and multiprocessing libraries may also help.
A:
i think they cannot be coupled in to one while loop.
maybe you need to check the threading or multiprocessing library.
|
Parallel while Loops in Python
|
I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.
Is it possible to run 2 while loops parallel to each other in python?
eg:
while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Sleep', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
elif input_event_1 == 'Feed':
myPotatoHead.feed_potato_head()
elif input_event_1 == 'Exercise':
myPotatoHead.exercise_potato_head()
elif input_event_1 == 'Teach':
myPotatoHead.teach_potato_head(myPotatoHead)
elif input_event_1 == 'Play':
myPotatoHead.play_with_toy()
elif input_event_1 == 'Sleep':
myPotatoHead.put_p_h_asleep()
elif input_event_1 == 'Go to Doctor':
myPotatoHead.doctor_check_up()
elif input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 1:
sys.exit(0)
while 1:
time.sleep(20)
myPotatoHead.hunger = str(float(myPotatoHead.hunger) + 1.0)
myPotatoHead.happiness = str(float(myPotatoHead.happiness) - 1.0)
myPotatoHead.tiredness = str(float(myPotatoHead.tiredness) + 1.0)
If not, is there some way that I can turn this into one loop?
I want the stuff in the second loop to happen every 20 seconds, but the stuff in the first loop to by constantly happening.
Thanks for any help
|
[
"Have a look at Threading.Timer. \nThere is a code recipe here to schedule a function to run every 5 seconds.\nimport thread\nimport threading\n\nclass Operation(threading._Timer):\n def __init__(self, *args, **kwargs):\n threading._Timer.__init__(self, *args, **kwargs)\n self.setDaemon(True)\n\n def run(self):\n while True:\n self.finished.clear()\n self.finished.wait(self.interval)\n if not self.finished.isSet():\n self.function(*self.args, **self.kwargs)\n else:\n return\n self.finished.set()\n\nclass Manager(object):\n\n ops = []\n\n def add_operation(self, operation, interval, args=[], kwargs={}):\n op = Operation(interval, operation, args, kwargs)\n self.ops.append(op)\n thread.start_new_thread(op.run, ())\n\n def stop(self):\n for op in self.ops:\n op.cancel()\n self._event.set()\n\nif __name__ == '__main__':\n # Print \"Hello World!\" every 5 seconds\n\n import time\n\n def hello():\n print \"Hello World!\"\n\n timer = Manager()\n timer.add_operation(hello, 5)\n\n while True:\n time.sleep(.1)\n\n",
"The only way to \"have two while loops in parallel\" would be to place them on different threads, but then you need to tackle the synchronization and coordination problems between them since they're reaching into the same object.\nI suggest you instead put a time check in the first (and single) loop and perform the increases that you now have in the second loop proportionately to that time-check; not quite satisfactory since the buttonbox call might take an indefinite amount of time to return, but way simpler to arrange, esp. for a beginner, than proper threading coordination.\nOnce you do have the basic logic in place and working, then you can consider threads again (with a periodic timer for what you'd like in the 2nd loop in one thread, the blocking buttonbox call in the main thread [[I think in easygui it has to be]], both feeding events into a Queue.Queue [[intrinsically thread-safe]] with another thread getting them and operating accordingly, i.e. most of what you now have in the 1st loop). But that's quite an advanced architectural problem, which is why I recommend you don't try to deal w/it right now!-)\n",
"put one of them into a function, the threading.Thread class supports a target attribute:\nimport threading\nthreading.Thread(target=yourFunc).start()\n\nWill start yourFunc() running in the background.\n",
"You should use State Machines for this (see the Apress pygame book - downloads here: http://apress.com/book/downloadfile/3765 ), see chapter 7.\nA simplified state machine:\ndef do_play(pet, time_passed):\n pet.happiness += time_pass*4.0\n\ndef do_feed(pet, time_passed):\n pet.hunger -= time_passed*4.0\n\ndef do_sleep(pet, time_passed):\n pet.tiredness += time_passed*4.0\n if pet.tiredness <= 0:\n return 'Waiting'\n\ndef do_waiting(pet, time_passed):\n pass\n\ndef do_howl(pet, time_passed):\n print 'Hoooowl'\n\ndef do_beg(pet, time_passed):\n print \"I'm bored!\"\n\ndef do_dead(pet, time_passed):\n print '...'\n\nSTATE_TO_FUNC = dict(Waiting=do_waiting,\n Sleeping=do_sleep,\n Feeding=do_feed,\n Playing=do_play,\n Howling=do_howl,\n Begging=do_beg,\n Dead=do_dead\n )\n\nclass Pet:\n def __init__(self):\n self.state = 'Waiting'\n self.hunger = 1.0\n self.tiredness = 1.0\n self.happiness = 1.0\n\n def process(self, time_passed):\n self.hunger +=1*time_passed\n self.tiredness +=1*time_passed\n self.happiness -= 1*time_passed\n\n func = STATE_TO_FUNC[self.state]\n new_state = func(self, time_passed)\n if new_state is not None:\n self.set_state(new_state)\n\n if self.hunger >10:\n self.set_state('Dead')\n elif self.hunger > 5 and not (self.state == 'Feeding'):\n self.set_state('Howling')\n elif self.tiredness > 5:\n self.set_state('Sleeping')\n elif self.happiness < 0 and not (self.state == 'Playing'):\n self.set_state('Begging')\n\n def set_state(self,state):\n if not self.state == 'Dead':\n self.state = state\n\nfrom msvcrt import getch\nimport time\npet = Pet()\nwhile True:\n time0 = time.time()\n cmd = getch() # what command?\n pet.process(time.time()-time0)\n if cmd == 'a':\n pet.set_state('Feeding')\n if cmd == 's':\n pet.set_state('Sleeping')\n if cmd == 'd':\n pet.set_state('Playing')\n\n",
"Essentially to have processing to happen in parallel you have several solutions\n1- Separate processes (ie: programs) running independently that speak to one another through a specific protocol (eg: Sockets)\n2- Or you can have the one process spawn off multiple threads\n3- Build an event queue internally and process them one by one\nThat is the general picture.\nAs for the specific answer to your question, you said \"the stuff in the first loop to b[e] constantly happening\". The reality is you never want this to happen all the time, because all that will do is use up 100% of the CPU and nothing else will ever get done\nThe simplest solution is probably number 3.\nThe way I would implement it is in my main loop have a thread that goes through an event queue and sets a timer for each event. Once all the timers have been sent the main loop then goes to sleep.\nWhen a timer times out, an other function will then run the corresponding function for the event that triggered that timer.\nIn your case, you have two events. One for displaying the selection menu (first loop) and the second for changing myPotatoHead. The timer associated with the first one, I would set to 0.5sec, making it larger reduces CPU usage but slows down responsivness, increasing it usses up more CPU, for the second event I would set a 20 second timer.\nOfcourse when the timer expires, you would not do while 1 but you will just go through your while loop body once (ie get rid of while).\n",
"There is also a package called SimPy that you could also look at. The threading and multiprocessing libraries may also help.\n",
"i think they cannot be coupled in to one while loop.\nmaybe you need to check the threading or multiprocessing library.\n"
] |
[
3,
3,
3,
3,
1,
1,
0
] |
[] |
[] |
[
"events",
"loops",
"parallel_processing",
"python",
"while_loop"
] |
stackoverflow_0002098495_events_loops_parallel_processing_python_while_loop.txt
|
Q:
Does IronPython and Jython have the same GIL issues as CPython?
I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2.
Do IronPython and Jython have this same problem?
Thanks
A:
No, neither have a GIL at all.
See previous answer about Jython and IronPython wiki page.
|
Does IronPython and Jython have the same GIL issues as CPython?
|
I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2.
Do IronPython and Jython have this same problem?
Thanks
|
[
"No, neither have a GIL at all.\nSee previous answer about Jython and IronPython wiki page.\n"
] |
[
8
] |
[] |
[] |
[
"ironpython",
"jython",
"python"
] |
stackoverflow_0002099405_ironpython_jython_python.txt
|
Q:
TCP connection reset occurs when WSGI app responds before consuming environ['wsgi.input']
For our webservice, I wrote some logic to prevent multipart/form-data POSTs larger than, say, 4mb.
It boils down to the following (I've stripped away all WebOb usage and just reduced it to plain vanilla WSGI code):
import paste.httpserver
form = """\
<html>
<body>
<form method="post" enctype="multipart/form-data" action="/">
<input type="file" name="photopicker" />
<input type="submit" />
</form>
</body>
</html>
"""
limit = 4 * 1024 * 1024
def upload_app(environ, start_response):
if environ['REQUEST_METHOD'] == 'POST':
if int(environ.get('CONTENT_LENGTH', '0')) > limit:
start_response('400 Ouch', [('content-type', 'text/plain')])
return ["Upload is too big!"]
# elided: consume the file appropriately
start_response('200 OK', [('content-type', 'text/html')])
return [form]
paste.httpserver.serve(upload_app, port=7007)
The logic shown works right when unit tested. But as soon as I tried sending actual files larger than 4mb to this endpoint, I got errors like these on the client side:
Error 101 (net::ERR_CONNECTION_RESET): Unknown error. from Google Chrome
The connection to the server was reset while the page was loading. from Firefox
Same error occurs when using Python built-in wsgiref HTTP server.
Fact: once I added environ['wsgi.input'].read() just before responding with HTTP 400, the connection reset problem went away. Of course, this is not a good fix. It just shows what happens when you fully consume the input.
I perused HTTP: The Definitive Guide and found some interesting guidelines on how it was important to mangage TCP connections carefully when implementing HTTP servers and clients. It went on about how, instead of close-ing socket, it was preferred to do shutdown, so that the client had chance to react and stop sending more data to server.
Perhaps I am missing some crucial implementation detail that prevents such connection resets. Insights anyone?
See the gist.
A:
This is happening because you are discarding the input stream without reading it, and this is forcing it closed. The browser has queued up a good portion of the file to be sent already and then it gets a write error because the server closes the connection forcefully.
There is no way around this that I know of without reading all the input.
I would recommend some Javascript to test the size of the file before it is sent. Then the only people who get the error are those who are ignoring the client-side check because they don't have Javascript or because they are purposefully trying to be malicious.
|
TCP connection reset occurs when WSGI app responds before consuming environ['wsgi.input']
|
For our webservice, I wrote some logic to prevent multipart/form-data POSTs larger than, say, 4mb.
It boils down to the following (I've stripped away all WebOb usage and just reduced it to plain vanilla WSGI code):
import paste.httpserver
form = """\
<html>
<body>
<form method="post" enctype="multipart/form-data" action="/">
<input type="file" name="photopicker" />
<input type="submit" />
</form>
</body>
</html>
"""
limit = 4 * 1024 * 1024
def upload_app(environ, start_response):
if environ['REQUEST_METHOD'] == 'POST':
if int(environ.get('CONTENT_LENGTH', '0')) > limit:
start_response('400 Ouch', [('content-type', 'text/plain')])
return ["Upload is too big!"]
# elided: consume the file appropriately
start_response('200 OK', [('content-type', 'text/html')])
return [form]
paste.httpserver.serve(upload_app, port=7007)
The logic shown works right when unit tested. But as soon as I tried sending actual files larger than 4mb to this endpoint, I got errors like these on the client side:
Error 101 (net::ERR_CONNECTION_RESET): Unknown error. from Google Chrome
The connection to the server was reset while the page was loading. from Firefox
Same error occurs when using Python built-in wsgiref HTTP server.
Fact: once I added environ['wsgi.input'].read() just before responding with HTTP 400, the connection reset problem went away. Of course, this is not a good fix. It just shows what happens when you fully consume the input.
I perused HTTP: The Definitive Guide and found some interesting guidelines on how it was important to mangage TCP connections carefully when implementing HTTP servers and clients. It went on about how, instead of close-ing socket, it was preferred to do shutdown, so that the client had chance to react and stop sending more data to server.
Perhaps I am missing some crucial implementation detail that prevents such connection resets. Insights anyone?
See the gist.
|
[
"This is happening because you are discarding the input stream without reading it, and this is forcing it closed. The browser has queued up a good portion of the file to be sent already and then it gets a write error because the server closes the connection forcefully.\nThere is no way around this that I know of without reading all the input.\nI would recommend some Javascript to test the size of the file before it is sent. Then the only people who get the error are those who are ignoring the client-side check because they don't have Javascript or because they are purposefully trying to be malicious.\n"
] |
[
2
] |
[] |
[] |
[
"http",
"paste",
"python",
"tcp",
"wsgiref"
] |
stackoverflow_0002099752_http_paste_python_tcp_wsgiref.txt
|
Q:
Where is the function 'real_ugettext' in django?
In django.utils.translations.__init__.py:
def ugettext(message):
return real_ugettext(message)
I can't find it.
A:
Read that file a little closer:
def delayed_loader(*args, **kwargs):
"""
Replace each real_* function with the corresponding function from either
trans_real or trans_null (e.g. real_gettext is replaced with
trans_real.gettext or trans_null.gettext). This function is run once, the
first time any i18n method is called. It replaces all the i18n methods at
once at that time.
"""
#...
A:
Django does some nasty global-munging magic in order to replace it with ugettext from either trans_real or trans_null found in the same package.
|
Where is the function 'real_ugettext' in django?
|
In django.utils.translations.__init__.py:
def ugettext(message):
return real_ugettext(message)
I can't find it.
|
[
"Read that file a little closer:\ndef delayed_loader(*args, **kwargs):\n \"\"\"\n Replace each real_* function with the corresponding function from either\n trans_real or trans_null (e.g. real_gettext is replaced with\n trans_real.gettext or trans_null.gettext). This function is run once, the\n first time any i18n method is called. It replaces all the i18n methods at\n once at that time.\n \"\"\"\n #...\n\n",
"Django does some nasty global-munging magic in order to replace it with ugettext from either trans_real or trans_null found in the same package.\n"
] |
[
4,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002100032_django_python.txt
|
Q:
Caching non-view returns
I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system (ie make sure they're in the right group, if they can edit their profile, if they're group administrators, etc).
A check might look like this:
from django.contrib.auth.decorators import user_passes_test
test_canvote = lambda u: u.has_perm('polls.can_vote')
@user_passes_test(test_canvote)
def my_view(request):
# ...
This is actually code from the Django tutorial (mine is a little uglier). Sometimes a check is very database intensive, firing off multiple queries. With lots of users hitting permission-checked pages, things can quickly get quite slow.
My question is, can I (with your help) build a wrapper (or replacement) for the user_passes_test decorator that searches the cache for a key 'TESTCACHE' + user.pk + 'testname' and if it doesn't exist, executes the test and saves its result.
I've never written a decorator before but I imagine it would look nearly identical to the user_passes_test one, just passing the test as a string:
@cached_user_passes_test('test_canvote')
def my_view(request):
# ...
And as ever, let me know if I'm mad or if Django already does this for me (so I've problems elsewhere).
Edit: The standard decorators can be found here: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py
I think it might be easier replacing user_passes_test than wrapping it so here's the starting point. Of course, if you feel I'm incorrect in that statement, let me know:
try:
from functools import update_wrapper, wraps
except ImportError:
from django.utils.functional import update_wrapper, wraps # Python 2.3, 2.4 fallback.
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from django.utils.decorators import auto_adapt_to_methods
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func)(_wrapped_view)
return auto_adapt_to_methods(decorator)
A:
You might need to serialize the function (which I'm not doing when I use it as the key to the cache), but something like this should work:
from django.core.cache import cache
def cached_user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
key = str(test_func) + str(request.user)
cached_test_result = cache.get(key)
if cached_test_result != None:
test_result = cached_test_result
else:
test_result = test_func(request.user)
cache.set(key, test_result, 60)
if test_result:
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func)(_wrapped_view)
return auto_adapt_to_methods(decorator)
A:
First you can simply write:
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):
# ...
Second, if the permissions don't change in time, you are free to store some info in the session (I found it more convenient, than storing in a cache of whatever type), when the user logs in.
But remember, that if you change the permissions, the user has to log out, and back in to work with the new permissions.
|
Caching non-view returns
|
I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system (ie make sure they're in the right group, if they can edit their profile, if they're group administrators, etc).
A check might look like this:
from django.contrib.auth.decorators import user_passes_test
test_canvote = lambda u: u.has_perm('polls.can_vote')
@user_passes_test(test_canvote)
def my_view(request):
# ...
This is actually code from the Django tutorial (mine is a little uglier). Sometimes a check is very database intensive, firing off multiple queries. With lots of users hitting permission-checked pages, things can quickly get quite slow.
My question is, can I (with your help) build a wrapper (or replacement) for the user_passes_test decorator that searches the cache for a key 'TESTCACHE' + user.pk + 'testname' and if it doesn't exist, executes the test and saves its result.
I've never written a decorator before but I imagine it would look nearly identical to the user_passes_test one, just passing the test as a string:
@cached_user_passes_test('test_canvote')
def my_view(request):
# ...
And as ever, let me know if I'm mad or if Django already does this for me (so I've problems elsewhere).
Edit: The standard decorators can be found here: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py
I think it might be easier replacing user_passes_test than wrapping it so here's the starting point. Of course, if you feel I'm incorrect in that statement, let me know:
try:
from functools import update_wrapper, wraps
except ImportError:
from django.utils.functional import update_wrapper, wraps # Python 2.3, 2.4 fallback.
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from django.utils.decorators import auto_adapt_to_methods
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func)(_wrapped_view)
return auto_adapt_to_methods(decorator)
|
[
"You might need to serialize the function (which I'm not doing when I use it as the key to the cache), but something like this should work:\nfrom django.core.cache import cache\n\ndef cached_user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):\n if not login_url:\n from django.conf import settings\n login_url = settings.LOGIN_URL\n\n def decorator(view_func):\n def _wrapped_view(request, *args, **kwargs):\n key = str(test_func) + str(request.user)\n cached_test_result = cache.get(key)\n if cached_test_result != None:\n test_result = cached_test_result\n else:\n test_result = test_func(request.user)\n cache.set(key, test_result, 60) \n\n if test_result:\n return view_func(request, *args, **kwargs)\n path = urlquote(request.get_full_path())\n tup = login_url, redirect_field_name, path\n return HttpResponseRedirect('%s?%s=%s' % tup)\n return wraps(view_func)(_wrapped_view)\n return auto_adapt_to_methods(decorator)\n\n",
"First you can simply write:\nfrom django.contrib.auth.decorators import permission_required\n\n@permission_required('polls.can_vote')\ndef my_view(request):\n # ...\n\nSecond, if the permissions don't change in time, you are free to store some info in the session (I found it more convenient, than storing in a cache of whatever type), when the user logs in.\nBut remember, that if you change the permissions, the user has to log out, and back in to work with the new permissions.\n"
] |
[
1,
0
] |
[] |
[] |
[
"decorator",
"django",
"django_cache",
"python"
] |
stackoverflow_0002086420_decorator_django_django_cache_python.txt
|
Q:
django error. about django.forms
from django import forms
class a(forms.Form):
name = forms.CharField(initial='Your name')
url = forms.URLField(initial='Your Web site')
comment = forms.CharField()
data = {'name': 'hahaha', 'url': '', 'comment': 'Foo'}
f = a(data,auto_id=False)
#print f.is_valid()
print f.errors
errors:
Traceback (most recent call last):
File "D:\zjm_code\register\registration\a.py", line 15, in <module>
print f.errors
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 32, in __str__
return self.__unicode__().encode('utf-8')
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 21, in __unicode__
return self.as_ul()
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 27, in as_ul
for k, v in self.items()]))
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 71, in force_unicode
s = unicode(s)
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 37, in __unicode__
return self.as_ul()
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 42, in as_ul
% ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self]))
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 71, in force_unicode
s = unicode(s)
File "D:\Python25.4\Lib\site-packages\django\utils\functional.py", line 201, in __unicode_cast
return self.__func(*self.__args, **self.__kw)
File "D:\Python25.4\Lib\site-packages\django\utils\translation\__init__.py", line 62, in ugettext
return real_ugettext(message)
File "D:\Python25.4\Lib\site-packages\django\utils\translation\__init__.py", line 32, in delayed_loader
if settings.USE_I18N:
File "D:\Python25.4\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25.4\Lib\site-packages\django\conf\__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
A:
That error shows up because you're not running the script as part of a Django app. There are a number of measures you can take to get it to work, but having a form separate from the app will probably not be terribly useful.
|
django error. about django.forms
|
from django import forms
class a(forms.Form):
name = forms.CharField(initial='Your name')
url = forms.URLField(initial='Your Web site')
comment = forms.CharField()
data = {'name': 'hahaha', 'url': '', 'comment': 'Foo'}
f = a(data,auto_id=False)
#print f.is_valid()
print f.errors
errors:
Traceback (most recent call last):
File "D:\zjm_code\register\registration\a.py", line 15, in <module>
print f.errors
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 32, in __str__
return self.__unicode__().encode('utf-8')
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 21, in __unicode__
return self.as_ul()
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 27, in as_ul
for k, v in self.items()]))
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 71, in force_unicode
s = unicode(s)
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 37, in __unicode__
return self.as_ul()
File "D:\Python25.4\Lib\site-packages\django\forms\util.py", line 42, in as_ul
% ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self]))
File "D:\Python25.4\Lib\site-packages\django\utils\encoding.py", line 71, in force_unicode
s = unicode(s)
File "D:\Python25.4\Lib\site-packages\django\utils\functional.py", line 201, in __unicode_cast
return self.__func(*self.__args, **self.__kw)
File "D:\Python25.4\Lib\site-packages\django\utils\translation\__init__.py", line 62, in ugettext
return real_ugettext(message)
File "D:\Python25.4\Lib\site-packages\django\utils\translation\__init__.py", line 32, in delayed_loader
if settings.USE_I18N:
File "D:\Python25.4\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25.4\Lib\site-packages\django\conf\__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
|
[
"That error shows up because you're not running the script as part of a Django app. There are a number of measures you can take to get it to work, but having a form separate from the app will probably not be terribly useful.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002100198_django_python.txt
|
Q:
How to make os.mkfifo and subprocess.Popen work together?
I'm trying to redirect a patch command output using a named pipe. I tried like this:
fifo = os.path.join(self.path, 'pipe')
os.mkfifo(fifo)
op = os.popen('cat '+ fifo)
proc = Popen(['patch', current_keyframe, '--input='+fpath, '--output='+fifo], stdin=PIPE, stdout=PIPE)
os.unlink(fifo)
print op.read()
But my script stops at Popen() call just like patch command didn't completed. How I can make it work properly?
A:
You aren't waiting for the patch command to finish before you read from the fifo. Replace the subprocess.Popen() call with subprocess.call(), and remove the stdin/stdout redirections you aren't using. Also, use open(fifo) to read from the fifo, not os.popen('cat ' + fifo).
You realize, I hope, that you can avoid the FIFO entirely? After p = Popen(['patch', '--input', fpath], stdout=PIPE), you can just read patch's output from p.stdout.
|
How to make os.mkfifo and subprocess.Popen work together?
|
I'm trying to redirect a patch command output using a named pipe. I tried like this:
fifo = os.path.join(self.path, 'pipe')
os.mkfifo(fifo)
op = os.popen('cat '+ fifo)
proc = Popen(['patch', current_keyframe, '--input='+fpath, '--output='+fifo], stdin=PIPE, stdout=PIPE)
os.unlink(fifo)
print op.read()
But my script stops at Popen() call just like patch command didn't completed. How I can make it work properly?
|
[
"You aren't waiting for the patch command to finish before you read from the fifo. Replace the subprocess.Popen() call with subprocess.call(), and remove the stdin/stdout redirections you aren't using. Also, use open(fifo) to read from the fifo, not os.popen('cat ' + fifo).\nYou realize, I hope, that you can avoid the FIFO entirely? After p = Popen(['patch', '--input', fpath], stdout=PIPE), you can just read patch's output from p.stdout.\n"
] |
[
1
] |
[] |
[] |
[
"fifo",
"patch",
"python",
"subprocess"
] |
stackoverflow_0002100581_fifo_patch_python_subprocess.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.