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: Dropdown menus in forms containing database primary keys In a framework like Django or Pylons you can set up function to handle form submissions. If your form involves a dropdown menu (i.e. a select tag) populated with objects from a database you can set the values equal to the primary key for the record like: <s...
Dropdown menus in forms containing database primary keys
In a framework like Django or Pylons you can set up function to handle form submissions. If your form involves a dropdown menu (i.e. a select tag) populated with objects from a database you can set the values equal to the primary key for the record like: <select> <option value="1">Volvo</option> <option value="2">...
[ "Using the primary key is fine. What exactly are you concerned with? This is an implementation detail that won't show up to the user in the actual rendered page.\n" ]
[ 3 ]
[]
[]
[ "django", "pylons", "python" ]
stackoverflow_0001091668_django_pylons_python.txt
Q: Are multiple classes in a single file recommended? Possible Duplicate: How many Python classes should I put in one file? Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file con...
Are multiple classes in a single file recommended?
Possible Duplicate: How many Python classes should I put in one file? Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file contains a single class I find the code more navigable. A...
[ "Here are some possible reasons:\n\nPython is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one mod...
[ 71, 21, 7, 5, 4, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001091756_class_python.txt
Q: What is the correct way to "pipe" Maven's output in Python to the screen when used in a Python shell script? My Python utility script contains UNIX system calls such as status, output = commands.getstatusoutput("ls -ltr") print "Output: ", output print "Status: ", status Which work fine and print the output to t...
What is the correct way to "pipe" Maven's output in Python to the screen when used in a Python shell script?
My Python utility script contains UNIX system calls such as status, output = commands.getstatusoutput("ls -ltr") print "Output: ", output print "Status: ", status Which work fine and print the output to the console but as soon as I run Maven from the same script, status, output = commands.getstatusoutput("mvn clean i...
[ "Are you sure that ${PWD} is properly expanded? If not, try:\nstatus, output = commands.getstatusoutput(\"mvn clean install -s./../../foo/bar/settings.xml -Dportal -Dmain.dir=%s/../.. -o\" % os.getcwd ())\n\n" ]
[ 0 ]
[]
[]
[ "maven_2", "python", "shell", "unix" ]
stackoverflow_0001092299_maven_2_python_shell_unix.txt
Q: Make your program USE a gui I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen. I used AutoIt to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck an...
Make your program USE a gui
I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen. I used AutoIt to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much wi...
[ "You can use WATSUP under Windows.\n", "I've had some luck with similar tasks using PyWinAuto.\n\npywinauto is a set of python modules\n to automate the Microsoft Windows GUI.\n At it's simplest it allows you to send\n mouse and keyboard actions to windows\n dialogs and controls.\n\nIt also has some support f...
[ 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "remote_control", "user_interface" ]
stackoverflow_0001084514_python_remote_control_user_interface.txt
Q: Where do I find the Python Crypto package when installing Paramiko on windows? I am trying to SFTP from Python running on windows and installed Paramiko as was recommended here. Unfortunately, it asks for Crypto.Util.randpool so I need to install the Crypto package. I found RPMS for Linux, but can't find anything ...
Where do I find the Python Crypto package when installing Paramiko on windows?
I am trying to SFTP from Python running on windows and installed Paramiko as was recommended here. Unfortunately, it asks for Crypto.Util.randpool so I need to install the Crypto package. I found RPMS for Linux, but can't find anything or source code for windows. The readme for Paramiko states: pycrypto compiled for Wi...
[ "See here for Win32 binaries for Python 2.2 through to 2.7\n" ]
[ 6 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0001092402_paramiko_python.txt
Q: want to get mac address of remote PC I have my web page in python, I am able to get the IP address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using Linux PC, we want to get it on Linux. A: I have a small, signed Java Applet, ...
want to get mac address of remote PC
I have my web page in python, I am able to get the IP address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using Linux PC, we want to get it on Linux.
[ "I have a small, signed Java Applet, which requires Java 6 runtime on the remote computer to do this. It uses the getHardwareAddress() method on NetworkInterface to obtain the MAC address. I use javascript to access a method in the applet that calls this and returns a JSON object containing the address. This ge...
[ 5, 3, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001092379_python_python_3.x.txt
Q: How do I set up a basic website with registration in Python on Dreamhost? I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them. Example: #!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" So now I am...
How do I set up a basic website with registration in Python on Dreamhost?
I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them. Example: #!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" So now I am looking for a basic framework, or a set of files that has already programmed t...
[ "Let me share my own experience with django. My prerequisits:\n\naverage knowledge of python\nvery weak idea of how web works (no js skills, just a bit of css)\nmy day job is filled with coding in C and I just wanted to try something different,\n so there certainly was a passion to learn (I think this is the most i...
[ 4, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "dreamhost", "python" ]
stackoverflow_0001026030_dreamhost_python.txt
Q: AppEngine server cannot import atom module I have gdata library install on my ArchLinux, and a simple application which imports atom library at the beginning, when I run gapp engine and access that web app, $ python2.5 ./dev_appserver.py ~/myapp It throws exception 'No module named atom'. But when I run 'import ...
AppEngine server cannot import atom module
I have gdata library install on my ArchLinux, and a simple application which imports atom library at the beginning, when I run gapp engine and access that web app, $ python2.5 ./dev_appserver.py ~/myapp It throws exception 'No module named atom'. But when I run 'import atom' in Python2.5 interactive mode, it works we...
[ "Add atom.py to the same directory you keep you GAE Python sources in, and make sure it's uploaded to the server when you upload your app. (The upload happens when you do appcfg.py update myapp/ unless you go out of your way to stop it; use the --verbose flag on the command to see exactly what's being uploaded or u...
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001092648_google_app_engine_python.txt
Q: BeanStalkd on Solaris doesnt return anything when called from the python library i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300". i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with...
BeanStalkd on Solaris doesnt return anything when called from the python library
i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300". i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with python my problem is when i try to write some code: import beanstalkc beanstalk = bea...
[ "It seems that the python-client listens to the server,\nbut the server has nothing to say.\nIs there something to read for the client?\nIs there a consumer AND a producer ?\nLook at this\n", "After looking in the code (beanstalkc):\nyour client has send his 'list-tubes' message, and is waiting for an answer.\n(u...
[ 1, 1, 1 ]
[]
[]
[ "beanstalkd", "python", "solaris", "yaml" ]
stackoverflow_0001044473_beanstalkd_python_solaris_yaml.txt
Q: Accidental overwrite of OSX Python system framework I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across http://wiki.python.org/moin/MacPython/Leopard stating...
Accidental overwrite of OSX Python system framework
I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across http://wiki.python.org/moin/MacPython/Leopard stating that you should do a partial install of the package to a...
[ "You may have overwritten the system framework but it is more likely that you just overwrote the symlinks in /usr/bin to point to the new version. Try going to /usr/bin and seeing (with something like ls -alsh) where the python symlink points to. It may be python2.6 or 3.0, which is in turn a ln to /System/Librar...
[ 5, 0 ]
[ "Restore from a recent Time Machine backup or somehow from DVD?\n" ]
[ -1 ]
[ "frameworks", "macos", "osx_leopard", "python" ]
stackoverflow_0000311621_frameworks_macos_osx_leopard_python.txt
Q: how can I not distribute my secret key (facebook api) while using python? I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so: import facebook fb...
how can I not distribute my secret key (facebook api) while using python?
I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so: import facebook fb = facebook.Facebook("my_api_key", "my_secret_key") and then logged in (fb.log...
[ "The relevant page on the FB developer wiki recommends a server component that just keeps your secret key and handles auth.getSession(), then gives your desktop app a session key. See that link for details.\n", "EDIT: cmb's session keys approach is better than the proxy described below. Config files and GAE are s...
[ 3, 1 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0001092942_facebook_python.txt
Q: What are some interesting features of the EveryBlock.com source code? The source code behind EveryBlock.com, a major Django-powered website founded by Adrian Holovaty, one of the co-Benevolent Dictators For Life of the Django framework, was recently open-sourced. The source is available as tarballs and on github. ...
What are some interesting features of the EveryBlock.com source code?
The source code behind EveryBlock.com, a major Django-powered website founded by Adrian Holovaty, one of the co-Benevolent Dictators For Life of the Django framework, was recently open-sourced. The source is available as tarballs and on github. This large body of code from an originator of Django should have some inter...
[ "Some of the things that I noticed:\n\nThe publishing system ebpub uses custom django Authentication and user system, hence cannot use django-admin.\nAltho' it uses Relational Database PostgreSQL, the data items for various data entries are stored in a single table, with types of fields defined in another table, fo...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "open_source", "python" ]
stackoverflow_0001067360_django_open_source_python.txt
Q: Objective-C string manipulation Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK. I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like...
Objective-C string manipulation
Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK. I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this: Objective-C string concatenati...
[ "For fixed size concatenation, you can use [NSString stringWithFormat:] like:\nNSString *str = [NSString stringWithFormat:@\"%@ %@ %@\",\n @\"Hello\", @\"World\", @\"Yay!\"];\n\n", "you can use join operation.\nNSArray *chunks = ... get an array, say by splitting it;\nstring = [c...
[ 9, 9, 4, 3, 2 ]
[]
[]
[ "objective_c", "objective_c++", "python", "ruby", "string" ]
stackoverflow_0001093805_objective_c_objective_c++_python_ruby_string.txt
Q: Python Error: TypeError: not all arguments converted during string formatting First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things ...
Python Error: TypeError: not all arguments converted during string formatting
First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options bu...
[ "Your tuple is misshaped\nf = open(\"%s/%s\" % (config['vsftp']['user_dir'], (vusername), 'wr'))\n\nShould be\nf = open(\"%s/%s\" % (config['vsftp']['user_dir'], (vusername)), 'wr')\n\n", "The error is here:\nopen(\"%s/%s\" % (config['vsftp']['user_dir'], (vusername), 'wr'))\n\nYou have three parameters, but only...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0001093884_python_typeerror.txt
Q: Windows XP - mute/unmute audio in programmatically in Python My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was mut...
Windows XP - mute/unmute audio in programmatically in Python
My machine has two audio inputs: a mic in that I use for gaming, and a line in that I use for guitar. When using one it's important that the other be muted to remove hiss/static, so I was hoping to write a small script that would toggle which one was muted (it's fairly inconvenient to click through the tray icon, switc...
[ "Disclaimer: I'm not a windows programming guru by any means...but here's my best guess\nPer the pywin32 FAQ:\n\nHow do I use the exposed Win32 functions to do xyz?\nIn general, the trick is to not\n consider it a Python/PyWin32 question\n at all, but to search for\n documentation or examples of your\n problem,...
[ 6, 3, 1, 0 ]
[]
[]
[ "audio", "python", "pywin32", "winapi", "windows" ]
stackoverflow_0001092466_audio_python_pywin32_winapi_windows.txt
Q: How to specify relations using SQLAlchemy declarative syntax? I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax? I am looking for a way to specify relations at a higher level, avoiding hav...
How to specify relations using SQLAlchemy declarative syntax?
I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax? I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addre...
[ "Assuming you are referring to the declarative plugin, where everything I am about to say is documented with examples:\nclass User(Base):\n __tablename__ = 'users'\n\n id = Column('id', Integer, primary_key=True)\n addresses = relation(\"Address\", backref=\"user\")\n\nclass Address(Base):\n __tablename...
[ 3, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000250398_python_sqlalchemy.txt
Q: Elegant way to abstract multiple function calls? Example: >>> def write_to_terminal(fmt, *args): ... print fmt % args >>> LOG = logging.getLogger(__name__) >>> info = multicall(write_to_terminal, LOG.info) >>> debug = multicall(write_debug_to_terminal, LOG.debug) >>> ... >>> info('Hello %s', 'guido') # display...
Elegant way to abstract multiple function calls?
Example: >>> def write_to_terminal(fmt, *args): ... print fmt % args >>> LOG = logging.getLogger(__name__) >>> info = multicall(write_to_terminal, LOG.info) >>> debug = multicall(write_debug_to_terminal, LOG.debug) >>> ... >>> info('Hello %s', 'guido') # display in terminal *and* log the message Is there an elegan...
[ "Something like this?\ndef multicall(*functions):\n def call_functions(*args, **kwds):\n for function in functions:\n function(*args, **kwds)\n return call_functions\n\nAnd if you want to aggregate the results:\ndef multicall(*functions):\n def call_functions(*args, **kwds):\n retu...
[ 5, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0001094611_function_python.txt
Q: Is there a Python language specification? Is there anything in Python akin to Java's JLS or C#'s spec? A: There's no specification per se. The closest thing is the Python Language Reference, which details the syntax and semantics of the language. A: You can check out the Python Reference A: No, python is de...
Is there a Python language specification?
Is there anything in Python akin to Java's JLS or C#'s spec?
[ "There's no specification per se. The closest thing is the Python Language Reference, which details the syntax and semantics of the language.\n", "You can check out the Python Reference\n", "No, python is defined by its implementation.\n" ]
[ 35, 2, 0 ]
[]
[]
[ "python", "specifications" ]
stackoverflow_0001094961_python_specifications.txt
Q: Python strings / match case I have a CSV file which has the following format: id,case1,case2,case3 Here is a sample: 123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitt...
Python strings / match case
I have a CSV file which has the following format: id,case1,case2,case3 Here is a sample: 123,null,X,Y 342,X,X,Y 456,null,null,null 789,null,null,X For each line I need to know which of the cases is not null. Is there an easy way to find out which case(s) are not null without splitting the string and going through ...
[ "You probably want to take a look at the CSV module, which has readers and writers that will enable you to create transforms.\n>>> from StringIO import StringIO\n>>> from csv import DictReader\n>>> fh = StringIO(\"\"\"\n... id,case1,case2,case3\n... \n... 123,null,X,Y\n... \n... 342,X,X,Y\n... \n... 456,null,null,n...
[ 2, 1, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001095026_csv_python.txt
Q: Can I send SIGINT to a Python subprocess on Windows? I've got a Python script managing a gdb process on Windows, and I need to be able to send a SIGINT to the spawned process in order to halt the target process (managed by gdb) It appears that there is only SIGTERM available in Win32, but clearly if I run gdb fr...
Can I send SIGINT to a Python subprocess on Windows?
I've got a Python script managing a gdb process on Windows, and I need to be able to send a SIGINT to the spawned process in order to halt the target process (managed by gdb) It appears that there is only SIGTERM available in Win32, but clearly if I run gdb from the console and Ctrl+C, it thinks it's receiving a SIGI...
[ "Windows doesn't have the unix signals IPC mechanism.\nI would look at sending a CTRL-C to the gdb process.\n" ]
[ 1 ]
[]
[]
[ "python", "sigint", "signal_handling", "subprocess", "windows" ]
stackoverflow_0001095549_python_sigint_signal_handling_subprocess_windows.txt
Q: Does get_or_create() have to save right away? (Django) I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently. I ...
Does get_or_create() have to save right away? (Django)
I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently. I can set the fields to null=True, but I don't want null field...
[ "You can just do:\ntry:\n obj = Model.objects.get(**kwargs)\nexcept Model.DoesNotExist:\n obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))\n\nwhich is pretty much what get_or_create does, sans commit.\n" ]
[ 39 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0001095663_django_django_models_django_orm_python.txt
Q: Alternative Python imaging libraries on Google App Engine? I am thinking about uploading images to Google App Engine, but I need to brighten parts of the image. I am not sure if the App Engine imagine API will be sufficient. I consider to try an overlay with a white image and partial opacity. However, if that doe...
Alternative Python imaging libraries on Google App Engine?
I am thinking about uploading images to Google App Engine, but I need to brighten parts of the image. I am not sure if the App Engine imagine API will be sufficient. I consider to try an overlay with a white image and partial opacity. However, if that does not yield the desired results, would there be another Python i...
[ "PNGcanvas might help, if PNG input and output is satisfactory -- it doesn't directly offer the \"brighten\" functionality you require, but it does let you load and save PNG files into memory and access them directly from Python, and it IS a single, simple Python source file.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python", "python_imaging_library" ]
stackoverflow_0001095325_google_app_engine_python_python_imaging_library.txt
Q: Finding partial strings in a list of strings - python I am trying to check if a user is a member of an Active Directory group, and I have this: ldap.set_option(ldap.OPT_REFERRALS, 0) try: con = ldap.initialize(LDAP_URL) con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password) ADUser = con.search_ext_s...
Finding partial strings in a list of strings - python
I am trying to check if a user is a member of an Active Directory group, and I have this: ldap.set_option(ldap.OPT_REFERRALS, 0) try: con = ldap.initialize(LDAP_URL) con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password) ADUser = con.search_ext_s(ad_settings.AD_SEARCH_DN, ldap.SCOPE_SUBTREE, \ ...
[ "If the format example you give is somewhat reliable, something like:\nimport re\ngrps = re.compile(r'CN=(\\w+)').findall\n\ndef anyof(short_group_list, adu):\n all_groups_of_user = set(g for gs in adu.get('memberOf',()) for g in grps(gs))\n return sorted(all_groups_of_user.intersection(short_group_list))\n\nwher...
[ 2, 1 ]
[]
[]
[ "list", "python", "regex" ]
stackoverflow_0001095270_list_python_regex.txt
Q: Comparing and updating array values in Python I'm developing a Sirius XM radio desktop player in Python, in which I want the ability to display a table of all the channels and what is currently playing on each of them. This channel data is obtained from their website as a JSON string. I'm looking for the best dat...
Comparing and updating array values in Python
I'm developing a Sirius XM radio desktop player in Python, in which I want the ability to display a table of all the channels and what is currently playing on each of them. This channel data is obtained from their website as a JSON string. I'm looking for the best data structure that would allow the cleanest way to co...
[ "Why not a dict, with channel number as the key and \"what's playing\" as the value? Easy to make from JSON, easy to sort (sorted(thedict) sorts by channel, sorted(thedict, key=thedict.get) sorts by value -- all operations are pretty easy (if you specify better exactly what operations you want to do I'll be happy ...
[ 4, 2 ]
[]
[]
[ "arrays", "data_structures", "list", "python" ]
stackoverflow_0001096003_arrays_data_structures_list_python.txt
Q: What is the easiest way to handle dates/times in Python? My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc. Should I use the datetime modu...
What is the easiest way to handle dates/times in Python?
My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc. Should I use the datetime module? Or just strftime? Or something fancier that isn't part of...
[ "Take a look at the dateutil module:\nhttp://labix.org/python-dateutil\nIt's good at doing the types of things you're looking for - see some of the examples in the documentation.\n", "You may have a look at Django's humanize module.\nIt is part of Django, but I think it would be quite easy to adapt it to your nee...
[ 2, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001096396_datetime_python.txt
Q: Can I view the doc string of a function in Python using VIM? Is there any way to view a function's doc string when writing Python in VIM? For instance: def MyFunction(spam): """A function that foobars the spam returns eggs""" return foobar(spam).eggs() I'd like to be able to type MyFunction(spam0) an...
Can I view the doc string of a function in Python using VIM?
Is there any way to view a function's doc string when writing Python in VIM? For instance: def MyFunction(spam): """A function that foobars the spam returns eggs""" return foobar(spam).eggs() I'd like to be able to type MyFunction(spam0) and see the doc string, either as a tooltip or in the status bar or ...
[ "The pythoncomplete script is probably what you are looking for.\n" ]
[ 2 ]
[]
[]
[ "docstring", "python", "vim" ]
stackoverflow_0001096912_docstring_python_vim.txt
Q: Incorporate custom template into the django admin interface and session I have made a custom formwizard and incorporated it into my admin interface. Basically I have taken the change_form.html and left it under the admin interface url: (r'^admin/compilation/evaluation/add/$', EvaluationWizard([EvaluationForm1,...
Incorporate custom template into the django admin interface and session
I have made a custom formwizard and incorporated it into my admin interface. Basically I have taken the change_form.html and left it under the admin interface url: (r'^admin/compilation/evaluation/add/$', EvaluationWizard([EvaluationForm1, EvaluationForm2])), It works, but the admin "session" is not kept. I can ac...
[ "If you need to make sure only authorised users access the page, you need to check for an admin user in your request handler. This will be the __call__ method in your EvaluationWizard class.\nBasically, the logic used by the admin is available for viewing here. Look for this in the AdminSite class:\nif not self.has...
[ 1 ]
[]
[]
[ "django", "django_admin", "django_templates", "python" ]
stackoverflow_0001096607_django_django_admin_django_templates_python.txt
Q: Issue with Facebook showAddSectionButton I am going absolutely batty trying to figure out how to get showAddSectionButton to work. The problem: I'm trying to get the 'add section button' to show up. There is nothing showing up right now. My code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.f...
Issue with Facebook showAddSectionButton
I am going absolutely batty trying to figure out how to get showAddSectionButton to work. The problem: I'm trying to get the 'add section button' to show up. There is nothing showing up right now. My code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" > <body> <div id=...
[ "I did finally figure out the problem.\nFacebook doesn't allow anything but FBML on the profile page (for some reason I thought I could use an iframe), which means you have to call setFBML with the profile_main property filled first.\nOnce I did that, the button popped right up.\n" ]
[ 0 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0001052613_facebook_google_app_engine_python.txt
Q: Override namespace in Python Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way t...
Override namespace in Python
Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'proje...
[ "Here's one way to do it, without touching sys.path, using the imp module in Python:\nimport imp\n\nf, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])\nproject = imp.load_module('a40bd22344', f, filename, desc)\n\nproject.some_func()\n\nHere is a link to some good documentation on the imp modul...
[ 25, 19, 17 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001096216_python_python_import.txt
Q: How do I upload pickled data to django FileField? I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is: #models.py from django.db import models class Data(models.Model): label = models.C...
How do I upload pickled data to django FileField?
I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is: #models.py from django.db import models class Data(models.Model): label = models.CharField(max_length=30) file = models.FileField(upl...
[ "Based on the answers to the questions I came up with the following solution:\nfrom django.core.files.base import ContentFile\nimport pickle\n\ncontent = pickle.dumps(somedata)\nfid = ContentFile(content)\ndata_entry.file.save(filename, fid)\nfid.close()\n\nAll of it is done on the server side and and users are NOT...
[ 10, 1, 0, 0, -3 ]
[]
[]
[ "django", "file", "pickle", "python", "upload" ]
stackoverflow_0000847904_django_file_pickle_python_upload.txt
Q: Programmatic control of python optimization? I've been playing with pyglet. It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual #!/usr/bin/env python by doing ./game.py then it's a bit clunky. But if I run it with python -O ./game.py or PYTHONO...
Programmatic control of python optimization?
I've been playing with pyglet. It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual #!/usr/bin/env python by doing ./game.py then it's a bit clunky. But if I run it with python -O ./game.py or PYTHONOPTIMIZE=1 ./game.py then its super-smooth. I'm do...
[ "\"On Linux I can easily provide a ./game script to run the file for end users:\"\nCorrect.\n\"but that's not very cross-platform.\"\nHalf-correct. There are exactly two shell languages that matter. Standard Linux \"sh\" and Non-standard Windows \"bat\" (a/k/a cmd.exe) and that's all there is nowadays. [When I...
[ 14, 2 ]
[]
[]
[ "multiplatform", "optimization", "pyglet", "python" ]
stackoverflow_0001092243_multiplatform_optimization_pyglet_python.txt
Q: Combining two JSON objects in to one I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. For eg: obj1 = ["a1", "a2", "a3"] obj2 = [{ "pk": "e1", ...
Combining two JSON objects in to one
I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. For eg: obj1 = ["a1", "a2", "a3"] obj2 = [{ "pk": "e1", "model": "AB.abc", "fields": { ...
[ "You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first:\ndata = { 'obj1' : obj1, 'obj2' : obj2 }\njson.dumps(data)\n\n", "Not sure if I'm missing something, but I think this works (tested in python 2.5) with the output you specify:\nimport simplejson\n\nfinalObj...
[ 22, 6, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0001096554_json_python.txt
Q: Display triangles in 3D using Python Disclaimer: The context is a project I'm working on as part of my Master's degree. I guess it qualifies as homework. Introduction (feel free to skip to the bottom line) Curved 3D surfaces are commonly displayed as a large set of very small triangles. Each triangle has the f...
Display triangles in 3D using Python
Disclaimer: The context is a project I'm working on as part of my Master's degree. I guess it qualifies as homework. Introduction (feel free to skip to the bottom line) Curved 3D surfaces are commonly displayed as a large set of very small triangles. Each triangle has the following properties: 3 corners uniform co...
[ "Well, that depends, very much, like which OS you are using, do you need to be portable, etc.\nBut a generic answer is probably to use something like OpenGL, which is a portable API, and has Python bindings. http://pyopengl.sourceforge.net/\nOn Windows you can use Direct3D, but that isn't particularily portable, an...
[ 7, 2, 0 ]
[]
[]
[ "3d", "geometry", "python" ]
stackoverflow_0001096476_3d_geometry_python.txt
Q: Pylons/Routes rewrite POST or GET to fancy URL The behavior I propose: A user loads up my "search" page, www.site.com/search, types their query into a form, clicks submit, and then ends up at www.site.com/search/the+query instead of www.site.com/search?q=the+query. I've gone through a lot of the Pylons documentati...
Pylons/Routes rewrite POST or GET to fancy URL
The behavior I propose: A user loads up my "search" page, www.site.com/search, types their query into a form, clicks submit, and then ends up at www.site.com/search/the+query instead of www.site.com/search?q=the+query. I've gone through a lot of the Pylons documentation already and just finished reading the Routes docu...
[ "HTML forms are designed to go to a specific URL with a query string (?q=) or an equivalent body in a POST -- either you write clever and subtle Javascript to intercept the form submission and rewrite it in your preferred weird way, or use redirect_to (and the latter will take some doing).\nBut why do you need such...
[ 2, 2 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0001096300_pylons_python_routes.txt
Q: Reallocating list in python Ok this is my problem. I am trying something like this: for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 point...
Reallocating list in python
Ok this is my problem. I am trying something like this: for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 points, glist[0] glist[1] glist[2] Th...
[ "Change del glist[:] to glist = []. You don't need to \"reuse\" or \"reallocate\" in Python, the garbagecollector will take care of that for you.\nAlso, you use 'i' as the loop variable in both loops. That's going to confuse you sooner or later. :)\n", "you can try \nglist=[]\n\n", "del glist[:] works fine for ...
[ 5, 1, 1 ]
[]
[]
[ "collections", "list", "memory_management", "python" ]
stackoverflow_0001098202_collections_list_memory_management_python.txt
Q: Looking for elegant glob-like DNA string expansion I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases. The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C. For example, say I have t...
Looking for elegant glob-like DNA string expansion
I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases. The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C. For example, say I have the string: ATMM I would like to take this string as inpu...
[ "Agree with other posters that it seems like a strange thing to want to do. Of course, if you really want to, there is (as always) an elegant way to do it in Python (2.6+):\nfrom itertools import product\nmap(\"\".join, product(*[['A', 'C'] if x == \"M\" else [x] for x in \"GMTTMCA\"]))\n\nFull solution with input ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "dna_sequence", "glob", "permutation", "python" ]
stackoverflow_0001098461_dna_sequence_glob_permutation_python.txt
Q: Extract only numbers from data in Jython Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance: [{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}] (where xxx are the floating point numbers). My question is how can I extract the numbers and put them in a more s...
Extract only numbers from data in Jython
Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance: [{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}] (where xxx are the floating point numbers). My question is how can I extract the numbers and put them in a more simple structure like a python list. Thank you...
[ "A PyJavaInstance is a Jython wrapper around a Java instance; how you extract numbers from it depends on what it is. If you need to get a bunch of stuff - some of which are strings and some of which are floats, then:\nfloat_list = []\nfor item in instance_properties:\n try:\n float_list.append(float(item)...
[ 2, 1, 0 ]
[]
[]
[ "extract", "jython", "list", "python" ]
stackoverflow_0001098613_extract_jython_list_python.txt
Q: Help me lambda-nize this To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map(). Im using a vector class but hopefully, the functions are...
Help me lambda-nize this
To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map(). Im using a vector class but hopefully, the functions are clear as to what they do. sel...
[ "You could use map, reduce, et al, but nowadays list comprehensions are the preferred way to do things in Python:\nrot_points = (i.rotated(self.orientation.get_angle()) for i in points)\nreal_points = [self.pos+i*self.scale for i in rot_points]\n\nNotice how I used (parentheses) instead of [brackets] in the first ...
[ 8, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0001098841_lambda_python.txt
Q: Replacing variable with function/class indicating dynamic value In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have: self.scale = 10 Making scale change according to sin would be nice. But adding f...
Replacing variable with function/class indicating dynamic value
In my program, I draw some quads. I want to add the functionality for them to scale up, then down, then go back to being static (to draw attention). In the quads I have: self.scale = 10 Making scale change according to sin would be nice. But adding frequency, amplitude and logic to my already bloated quad class is som...
[ "The distinction between\nquad.scale= 10\n\nand\nquad.scale= MySin()\n\nIs minor. Within the Quad class definition the \"scale\" attribute can be a property with proper getter and setter functions.\nclass Quad( object ):\n @property\n def scale( self ):\n return self._scale\n\n @scale.setter\n d...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001099328_python.txt
Q: for statement and i.find in list for a in ('90','52.6', '26.5'): if a == '90': z = (' 0',) elif a == '52.6': z = ('0', '5') else: z = ('25') for b in z: cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b) process = Popen(cmd, shell=True, stderr=STDOUT, stdou...
for statement and i.find in list
for a in ('90','52.6', '26.5'): if a == '90': z = (' 0',) elif a == '52.6': z = ('0', '5') else: z = ('25') for b in z: cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b) process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = proces...
[ "you are missing quotes around you first for statement try\nfor a in ('90','52.6', '26.5'):\n\n", "Once you've fixed the missing quote, you'll get weird behavior from this part:\nelse:\n z = ('25')\n\nfor b in z:\n\nthe parentheses here do nothing at all, and b in the loop will be '2' then '5'. You probably me...
[ 6, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001098970_python.txt
Q: How to properly do one-to-many joins on an (Python) Google App Engine datasource? I have some models set up like: class Apps(db.Model): name = db.StringProperty(multiline=False) description = db.TextProperty() class AppScreenshots(db.Model): image_file = db.StringProperty(multiline=False) ...
How to properly do one-to-many joins on an (Python) Google App Engine datasource?
I have some models set up like: class Apps(db.Model): name = db.StringProperty(multiline=False) description = db.TextProperty() class AppScreenshots(db.Model): image_file = db.StringProperty(multiline=False) description = db.StringProperty(multiline=False) app = db.Referenc...
[ "The problem I found when trying to run your code was that apparently you need to change the name of 'app' in AppScreenshots to something else such as 'apps'. The word 'app' must be reserved in this context.\nTry this Query instead. You could do .filter() too on this if you don't want the first entity.\nclass AppSc...
[ 5 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0001100472_google_app_engine_gql_python.txt
Q: Are there any class diagram generating tools for python source code? Are there any reverse-egineering UML tools for Python? A: This looks good: http://www.andypatterns.com/index.php?cID=65 How about this? http://www.greenteapress.com/thinkpython/swampy/lumpy.html A: pyUML may be what you are looking for. Altho...
Are there any class diagram generating tools for python source code?
Are there any reverse-egineering UML tools for Python?
[ "This looks good: http://www.andypatterns.com/index.php?cID=65\nHow about this? http://www.greenteapress.com/thinkpython/swampy/lumpy.html\n", "pyUML may be what you are looking for. Although it is an Eclipse plugin for PyDev.\n", "Sparx Enterprise Architect can reverse engineer Python code, at least according ...
[ 5, 2, 2 ]
[]
[]
[ "python", "uml" ]
stackoverflow_0001101301_python_uml.txt
Q: Why my Python test generator simply doesn't work? This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'... #!/usr/bin/python def testGen(): for a in [1,2,3,4,5,6,7,8,9,10]: yield a w = 0 while w < 10: print testGen().next() w += 1 A: You're crea...
Why my Python test generator simply doesn't work?
This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'... #!/usr/bin/python def testGen(): for a in [1,2,3,4,5,6,7,8,9,10]: yield a w = 0 while w < 10: print testGen().next() w += 1
[ "You're creating a new generator each time. You should only call testGen() once and then use the object returned. Try:\nw = 0\ng = testGen()\nwhile w < 10:\n print g.next()\n w += 1\n\nThen of course there's the normal, idiomatic generator usage:\nfor n in testGen():\n print n\n\nNote that this will only c...
[ 10 ]
[]
[]
[ "generator", "python", "testing", "yield" ]
stackoverflow_0001101550_generator_python_testing_yield.txt
Q: Help needed improving Python code using List Comprehensions I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how freq...
Help needed improving Python code using List Comprehensions
I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snip...
[ "Try this: \nassert len(oil_changes) >= 2\nsum_of_diffs = oil_changes[-1] - oil_changes[0]\nnumber_of_diffs = len(oil_changes) - 1\naverage_diff = sum_of_diffs / float(number_of_diffs)\n\n", "As other answers pointed out, you don't really need to worry unless your oil_changes list is extremely long. However, as a...
[ 9, 8, 3, 2, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001101611_list_comprehension_python.txt
Q: Create PyQt menu from a list of strings I have a list of strings and want to create a menu entry for each of those strings. When the user clicks on one of the entries, always the same function shall be called with the string as an argument. After some trying and research I came up with something like this: import ...
Create PyQt menu from a list of strings
I have a list of strings and want to create a menu entry for each of those strings. When the user clicks on one of the entries, always the same function shall be called with the string as an argument. After some trying and research I came up with something like this: import sys from PyQt4 import QtGui, QtCore class Ma...
[ "You're meeting what's been often referred to (maybe not entirely pedantically-correctly;-) as the \"scoping problem\" in Python -- the binding is late (lexical lookup at call-time) while you'd like it early (at def-time). So where you now have:\n for item in menuitems:\n entry = menu.addAction(item)\n ...
[ 25, 3 ]
[]
[]
[ "pyqt", "python", "qt", "signals_slots" ]
stackoverflow_0001100775_pyqt_python_qt_signals_slots.txt
Q: Unicode problem Django-Python-URLLIB-MySQL I am fetching a webpage (http://autoweek.com) and trying to process it but getting encoding error. Autoweek declares "iso-8859-1" encoding and has the word "Nürburgring" (u with umlaut) I do: # -*- encoding: utf-8 -*- import urllib webpage = urllib.urlopen(feed.crawl_ur...
Unicode problem Django-Python-URLLIB-MySQL
I am fetching a webpage (http://autoweek.com) and trying to process it but getting encoding error. Autoweek declares "iso-8859-1" encoding and has the word "Nürburgring" (u with umlaut) I do: # -*- encoding: utf-8 -*- import urllib webpage = urllib.urlopen(feed.crawl_url).read() webpage.decode("utf-8") it gives me t...
[ "If the webpage declares encoding iso-8859-1, can't you just do webpage.decode(\"iso-8859-1\")?\nAt that point, webpage is decoded for your app. When it is written into the database, the mapping there should handle the char-to-utf8 encoding.\nTo get the correct encoding, either tell the webserver that you only acce...
[ 3, 0 ]
[]
[]
[ "encoding", "python", "unicode", "urllib", "utf_8" ]
stackoverflow_0001101715_encoding_python_unicode_urllib_utf_8.txt
Q: Is there a way to plan and diagram an architecture for dynamic scripting languages like groovy or python? Say I want to write a large application in groovy, and take advantage of closures, categories and other concepts (that I regularly use to separate concerns). Is there a way to diagram or otherwise communicate...
Is there a way to plan and diagram an architecture for dynamic scripting languages like groovy or python?
Say I want to write a large application in groovy, and take advantage of closures, categories and other concepts (that I regularly use to separate concerns). Is there a way to diagram or otherwise communicate in a simple way the architecture of some of this stuff? How do you detail (without verbose documentation) the...
[ "UML isn't too well equipped to handle such things, but you can still use it to communicate your design if you are willing to do some mental mapping. You can find an isomorphism between most dynamic concepts and UMLs static object-model.\nFor example you can think of a closure as an object implementing a one method...
[ 3, 1 ]
[]
[]
[ "architecture", "dynamic_languages", "groovy", "python", "uml" ]
stackoverflow_0001102134_architecture_dynamic_languages_groovy_python_uml.txt
Q: Moving files under python I'm confused with file moving under python. Under windows commandline, if i have directory c:\a and a directory c:\b, i can do move c:\a c:\b which moves a to b result is directory structure c:\b\a If I try this with os.rename or shutil.move: os.rename("c:/a", "c:/b") I get WindowsErro...
Moving files under python
I'm confused with file moving under python. Under windows commandline, if i have directory c:\a and a directory c:\b, i can do move c:\a c:\b which moves a to b result is directory structure c:\b\a If I try this with os.rename or shutil.move: os.rename("c:/a", "c:/b") I get WindowsError: [Error 17] Cannot create a f...
[ "os.rename(\"c:/a\", \"c:/b/a\") \n\nis equivalent to \nmove c:\\a c:\\b\n\nunder windows commandline\n", "You can try using the Shutil module.\n", "os.rename(\"c:/a/\", \"c:/b\"/) --> Changes the name of folder a in folder b\nos.rename(\"c:/a/\", \"c:/b/a\") --> Put folder b into folder a\n", "When i need ma...
[ 16, 7, 1, 0 ]
[ "You will need to state the full path it's being moved to:\nsrc = 'C:\\a'\ndst_dir = 'C:\\b'\nlast_part = os.path.split(src)[1]\nos.rename(src, os.path.join(dst_dir, last_part))\n\nActually, it looks like shutil.move will do what you want by looking at its documentation:\n\nIf the destination is a directory or a sy...
[ -1, -1 ]
[ "move", "python", "windows" ]
stackoverflow_0001102825_move_python_windows.txt
Q: Python data/file Crc I am wanting to generate and store a CRC (or similar) value for a given list of files which can be used as a comparison at a later point. Writing a function to do this is simple enough, but is there a more standard way to do it within the Python libs? The value generated does not need to be of...
Python data/file Crc
I am wanting to generate and store a CRC (or similar) value for a given list of files which can be used as a comparison at a later point. Writing a function to do this is simple enough, but is there a more standard way to do it within the Python libs? The value generated does not need to be of any particular standard.
[ "recommend hashlib, it implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1 and MD5.\na demo code:\nimport hashlib\nm = hashlib.md5()\nfor line in open('data.txt', 'rb'):\n m.update(line)\nprint m.hexdigest()\n##ouput\n1ab8...
[ 6, 1 ]
[]
[]
[ "crc", "file", "hashlib", "md5", "python" ]
stackoverflow_0001103104_crc_file_hashlib_md5_python.txt
Q: python how to create different instances of the same class into an iteration My problem is: I would like to add to a Composite class Leaf objects created at runtime inside a Composite routine like this: def update(self, tp, msg, stt): """It updates composite objects """ d = Leaf() d.setDict(tp, ms...
python how to create different instances of the same class into an iteration
My problem is: I would like to add to a Composite class Leaf objects created at runtime inside a Composite routine like this: def update(self, tp, msg, stt): """It updates composite objects """ d = Leaf() d.setDict(tp, msg, stt) self.append_child(d) return self.status() Inside main: import li...
[ "\"But in this way I found always that my composite has just one leaf (\"d\") added even if update was called many times.\"\nNo, that code makes Composite having ten children.\n>>> c.children\n[<__main__.Leaf object at 0xb7da77ec>, <__main__.Leaf object at 0xb7da780c>,\n <__main__.Leaf object at 0xb7da788c>, <__mai...
[ 3, 1 ]
[]
[]
[ "composite", "design_patterns", "python" ]
stackoverflow_0001102822_composite_design_patterns_python.txt
Q: Starting and Controlling an External Process via STDIN/STDOUT with Python I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to. The ...
Starting and Controlling an External Process via STDIN/STDOUT with Python
I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to. The flow of what I'm trying to complete is to: Start the external process Iterate ...
[ "process.communicate(input='\\n') is wrong. If you will notice from the Python docs, it writes your string to the stdin of the child, then reads all output from the child until the child exits. From doc.python.org:\n\nPopen.communicate(input=None) Interact\n with process: Send data to stdin. Read\n data from std...
[ 9, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001087799_python_subprocess.txt
Q: Running both python 2.6 and 3.1 on the same machine I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some scripts that use python 2.6 and I can't convert them since they use some modules that aren't available for python 3.1 atm. So I'm considering installin...
Running both python 2.6 and 3.1 on the same machine
I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some scripts that use python 2.6 and I can't convert them since they use some modules that aren't available for python 3.1 atm. So I'm considering installing python 3.1 along with my python 2.6. I only found peopl...
[ "On my Linux system (Ubuntu Jaunty), I have Python 2.5, 2.6 and 3.0 installed, just by installing the binary (deb) packages 'python2.5', 'python2.6' and 'python3.0' using apt-get. Perhaps Fedora packages them and names them as RPMs in a similar way.\nI can run the one I need from the command line just by typing e.g...
[ 4, 2, 1, 0 ]
[]
[]
[ "linux", "python", "python_3.x" ]
stackoverflow_0001082692_linux_python_python_3.x.txt
Q: Is there any way to get python omnicomplete to work with non-system modules in vim? The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on. A: Once I generated ctags for one of my site-packages...
Is there any way to get python omnicomplete to work with non-system modules in vim?
The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.
[ "Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules.\nEDIT: Not true at all.\nHere's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most o...
[ 3, 2, 2, 2, 2, 0 ]
[]
[]
[ "omnicomplete", "python", "vim" ]
stackoverflow_0000199180_omnicomplete_python_vim.txt
Q: Run (remote) php script from (local) python script How do I make python (local) run php script on a remote server? I don't want to process its output with python script or anything, just execute it and meanwhile quit python (while php script will be already working and doing its job). edit: What I'm trying to ach...
Run (remote) php script from (local) python script
How do I make python (local) run php script on a remote server? I don't want to process its output with python script or anything, just execute it and meanwhile quit python (while php script will be already working and doing its job). edit: What I'm trying to achieve: python script connects to ftp server and uploads ...
[ "os.system(\"php yourscript.php\")\n\nAnother alternative would be:\n# will return new process' id\nos.spawnl(os.P_NOWAIT, \"php yourscript.php\")\n\nYou can check all os module documentation here.\n", "If python is on a different physical machine than the PHP script, I'd make sure the PHP script is web-accessibl...
[ 5, 4, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0001104064_php_python.txt
Q: Why would Django's cache work with locmem but fail with memcached? Using Django's cache with locmem (with simple Python classes as values stored in lists/tuples/maps) works perfectly but does not work with memcached. Only a fraction of the keys (despite ample memory allocated and large timeouts) make their way int...
Why would Django's cache work with locmem but fail with memcached?
Using Django's cache with locmem (with simple Python classes as values stored in lists/tuples/maps) works perfectly but does not work with memcached. Only a fraction of the keys (despite ample memory allocated and large timeouts) make their way into memcached, and none of them appear to have any associated value. When ...
[ "To find out what's going on, run memcached -vv 2>/tmp/mc_debug_log (I'm assuming you're on some sort of Unixy system) and run it for a short time -- you'll find detailed information in that logfile when you're done.\nDepending on what Python interface to memcached you're using, it may be that only strings are supp...
[ 3, 3 ]
[]
[]
[ "caching", "django", "memcached", "python" ]
stackoverflow_0001101049_caching_django_memcached_python.txt
Q: Pythonic way to get some rows of a matrix I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[...
Pythonic way to get some rows of a matrix
I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp Now that I've learnt a litt...
[ "It's the clean an obvious way. So, I'd say it doesn't get more Pythonic than that.\n", "It's worth looking at NumPy for its slicing syntax. Scroll down in the linked page until you get to \"Indexing, Slicing and Iterating\".\n", "As Curt said, it seems that Numpy is a good tool for this. Here's an example,\n...
[ 4, 4, 2 ]
[]
[]
[ "coding_style", "filtering", "list", "python" ]
stackoverflow_0001105101_coding_style_filtering_list_python.txt
Q: python - Problem storing Unicode character to MySQL with Django I have the string u"Played Mirror's Edge\u2122" Which should be shown as Played Mirror's Edge™ But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA: a = models.Achievement(...
python - Problem storing Unicode character to MySQL with Django
I have the string u"Played Mirror's Edge\u2122" Which should be shown as Played Mirror's Edge™ But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA: a = models.Achievement(name=u"Played Mirror's Edge\u2122") a.save() And I'm getting : 'asci...
[ "Thank you to everyone who was posting here. It really helps my unicode knowledge (and hoepfully other people learned something).\nWe seemed to be all barking up the wrong tree since I tried to simplify my problem and didn't give ALL information. It seems that I wasn't using \"REAL\" unicode strings, but rather Bea...
[ 12, 4, 3, 1, 0, 0 ]
[ "To me the apostrophe looks strange, should it not be escapded like so:\nu\"Played Mirror\\'s Edge\\u2122\"\n\n" ]
[ -1 ]
[ "django", "django_models", "mysql", "python", "unicode" ]
stackoverflow_0001102465_django_django_models_mysql_python_unicode.txt
Q: How are these type of python decorators written? I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax : @max_execs(5) def my_method(*a,**k): # do something here pass I think it's possible to write this type of decorator, but I d...
How are these type of python decorators written?
I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax : @max_execs(5) def my_method(*a,**k): # do something here pass I think it's possible to write this type of decorator, but I don't know how. I think a function won't be this decora...
[ "This is what I whipped up. It doesn't use a class, but it does use function attributes:\ndef max_execs(n=5):\n def decorator(fn):\n fn.max = n\n fn.called = 0\n def wrapped(*args, **kwargs):\n fn.called += 1\n if fn.called <= fn.max:\n return fn(*args, *...
[ 12, 4, 3, 2, 1, 0 ]
[]
[]
[ "decorator", "language_features", "python" ]
stackoverflow_0001106223_decorator_language_features_python.txt
Q: How does os.path map to posixpath.pyc and not os/path.py? What is the underlying mechanism in Python that handles such "aliases"? >>> import os.path >>> os.path.__file__ '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/posixpath.pyc' A: Taken from os.py on CPython 2.6: sys.modules['os.path'] = pa...
How does os.path map to posixpath.pyc and not os/path.py?
What is the underlying mechanism in Python that handles such "aliases"? >>> import os.path >>> os.path.__file__ '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/posixpath.pyc'
[ "Taken from os.py on CPython 2.6:\nsys.modules['os.path'] = path\nfrom os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,\n devnull)\n\npath is defined earlier as the platform-specific module:\nif 'posix' in _names:\n name = 'posix'\n linesep = '\\n'\n from posix import *\n try:\n...
[ 6, 0 ]
[]
[]
[ "alias", "import", "module", "path", "python" ]
stackoverflow_0001106455_alias_import_module_path_python.txt
Q: Python: better way to open lots of sockets I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion ...
Python: better way to open lots of sockets
I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize there a...
[ "I was puzzled why you would use recursion instead of a simple loop. My guess is that with a simple loop, you would have overwritten the variable sockname again and again, so that Python's garbage collection would actually close the previous socket after you created the next one. The solution is to store them all i...
[ 4, 2, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001106433_python_sockets.txt
Q: Is 'if element in aList' possible with Django templates? Does something like the python if "a" in ["a", "b", "c"]: pass exist in Django templates? If not, is there an easy way to implement it? A: This is something you usually do in your view functions. aList = ["a", "b", "c"] listAndFlags = [ (item,item in...
Is 'if element in aList' possible with Django templates?
Does something like the python if "a" in ["a", "b", "c"]: pass exist in Django templates? If not, is there an easy way to implement it?
[ "This is something you usually do in your view functions.\naList = [\"a\", \"b\", \"c\"]\nlistAndFlags = [ (item,item in aList) for item in someQuerySet ]\n\nNow you have a simple two-element list that you can display\n{% for item, flag in someList %}\n <tr><td class=\"{{flag}}\">{{item}}</td></tr>\n{% endfor %}...
[ 2, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001106849_django_django_templates_python.txt
Q: Find functions explicitly defined in a module (python) Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this: from datetime import date, datetime def test(): return "...
Find functions explicitly defined in a module (python)
Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this: from datetime import date, datetime def test(): return "This is a real method" Even if i use inspect() to filter ou...
[ "Are you looking for something like this?\nimport sys, inspect\n\ndef is_mod_function(mod, func):\n return inspect.isfunction(func) and inspect.getmodule(func) == mod\n\ndef list_functions(mod):\n return [func.__name__ for func in mod.__dict__.itervalues() \n if is_mod_function(mod, func)]\n\n\npri...
[ 30, 4, 2, 1, 0 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0001106840_introspection_python.txt
Q: What should I call this function composition? What should 'foo' be called, given the following? x.items is a set, y.values is a set. function a(key) returns an ordered list of x.items function b(x.item) returns a single y.value Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.val...
What should I call this function composition?
What should 'foo' be called, given the following? x.items is a set, y.values is a set. function a(key) returns an ordered list of x.items function b(x.item) returns a single y.value Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)). This feels like a f...
[ " function a(key) returns an ordered list of x.items\n function b(x.item) returns a single y.value\n\nExcept for the ordering, a() is in practice a filter, i.e. it \"filters\" or \"selects\" items from x.items according to a key. b() is a normal map, or function. Thus, I would choose for 'foo' the name \"composeFil...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "functional_programming", "math", "python" ]
stackoverflow_0001058273_functional_programming_math_python.txt
Q: How to exclude U+2028 from line separators in Python when reading file? I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (http://www.fileformat.info/info/unicode/char/2028/index.htm). I don't want it to be treated as a line break when I read lines from the file. Is there a way t...
How to exclude U+2028 from line separators in Python when reading file?
I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (http://www.fileformat.info/info/unicode/char/2028/index.htm). I don't want it to be treated as a line break when I read lines from the file. Is there a way to exclude it from separators when I iterate over the file or use readlines()?...
[ "I couldn't reproduce that behavior but here's a naive solution that just merges readline results until they don't end with U+2028.\n#!/usr/bin/env python\n\nfrom __future__ import with_statement\n\ndef my_readlines(f):\n buf = u\"\"\n for line in f.readlines():\n uline = line.decode('utf8')\n buf += uline\...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "readline", "separator", "utf_8" ]
stackoverflow_0001105106_python_readline_separator_utf_8.txt
Q: improving Boyer-Moore string search I've been playing around with the Boyer-Moore sting search algorithm and starting with a base code set from Shriphani Palakodety I created 2 additional versions (v2 and v3) - each making some modifications such as removing len() function from the loop and than refactoring the wh...
improving Boyer-Moore string search
I've been playing around with the Boyer-Moore sting search algorithm and starting with a base code set from Shriphani Palakodety I created 2 additional versions (v2 and v3) - each making some modifications such as removing len() function from the loop and than refactoring the while/if conditions. From v1 to v2 I see a...
[ "Using \"in bcs.keys()\" is creating a list and then doing an O(N) search of the list -- just use \"in bcs\". \nDo the goodSuffixShift(key) thing inside the search function. Two benefits: the caller has only one API to use, and you avoid having bcs as a global (horrid ** 2). \nYour indentation is incorrect in sev...
[ 4 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0001106112_performance_python.txt
Q: Python create function in a loop capturing the loop variable What's going on here? I'm trying to create a list of functions: def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) This isn't doing what I expect. I would expect the list to act like this: funcs[3](3) = 9 f...
Python create function in a loop capturing the loop variable
What's going on here? I'm trying to create a list of functions: def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) This isn't doing what I expect. I would expect the list to act like this: funcs[3](3) = 9 funcs[0](5) = 0 But all the functions in the list seem to be ident...
[ "lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished.\nThe behavior you're looking for can be achieved with functools.partial\nimport functools\n\ndef f(a,b):\n return a*b\n\nfun...
[ 20, 15, 10, 2, 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0001107210_lambda_python.txt
Q: hex to string formatting conversion in python I used to generate random string in the following way (now I've switched to this method). key = '%016x' % random.getrandbits(128) The key generated this way is most often a 32 character string, but once I've got 31 chars. This is what I don't get: why it's 32 chars, n...
hex to string formatting conversion in python
I used to generate random string in the following way (now I've switched to this method). key = '%016x' % random.getrandbits(128) The key generated this way is most often a 32 character string, but once I've got 31 chars. This is what I don't get: why it's 32 chars, not 16? Doesn't one hex digit take one character to ...
[ "Yes, but the format you're using doesn't truncate -- you generate 128 random bits, which require (usually) 32 hex digits to show, and the %016 means AT LEAST 16 hex digits, but doesn't just throw away the extra ones you need to show all of that 128-bit number. Why not generate just 64 random bits if that's what y...
[ 6, 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001107331_python_string.txt
Q: Assigning a Iron Python list to .NET array I have a list comprehension operating on elements of an .NET array like obj.arr = [f(x) for x in obj.arr] However the assignment back to obj.arr fails. Is it possible to convert a list to a .NET array in IronPython? A: Try this: obj.arr = Array[T]([f(x) for x in obj.ar...
Assigning a Iron Python list to .NET array
I have a list comprehension operating on elements of an .NET array like obj.arr = [f(x) for x in obj.arr] However the assignment back to obj.arr fails. Is it possible to convert a list to a .NET array in IronPython?
[ "Try this:\nobj.arr = Array[T]([f(x) for x in obj.arr])\n\nreplacing T with type of array elements.\nAlternatively:\nobj.arr = tuple([f(x) for x in obj.arr])\n\n", "Arrays have to be typed as far as I know. This works for me:\nnum_list = [n for n in range(10)]\n\nfrom System import Array\nnum_arr = Array[int](nu...
[ 10, 4 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0001107789_ironpython_python.txt
Q: Lengthy single line strings in Python without going over maximum line length How can I break a long one liner string in my code and keep the string indented with the rest of the code? PEP 8 doesn't have any example for this case. Correct ouptut but strangely indented: if True: print "long test long test long t...
Lengthy single line strings in Python without going over maximum line length
How can I break a long one liner string in my code and keep the string indented with the rest of the code? PEP 8 doesn't have any example for this case. Correct ouptut but strangely indented: if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> ...
[ "Adjacent strings are concatenated at compile time:\nif True:\n print (\"this is the first line of a very long string\"\n \" this is the second line\")\n\nOutput:\nthis is the first line of a very long string this is the second line\n\n", "if True:\n print \"long test long test long test long test...
[ 30, 7, 2, 0 ]
[ "if True:\n print \"long test long test long test \"+\n \"long test long test long test \"+\n \"long test long test long test \"\n\nAnd so on.\n" ]
[ -6 ]
[ "python", "string" ]
stackoverflow_0001104762_python_string.txt
Q: Noob components design question Updated question, see below I'm starting a new project and I would like to experiment with components based architecture (I chose PyProtocols). It's a little program to display and interract with realtime graphics. I started by designing the user input components: IInputDevice - e....
Noob components design question
Updated question, see below I'm starting a new project and I would like to experiment with components based architecture (I chose PyProtocols). It's a little program to display and interract with realtime graphics. I started by designing the user input components: IInputDevice - e.g. a mouse, keyboard, etc... An Input...
[ "I haven't used PyProtocols, only the Zope Component Architecture, but they are similar enough for these principles to be the same.\nYour error is that you have two adapters that can adapt the same thing. You both have an averaging filter and an inversion filter. When you then ask for the filter, both are found, an...
[ 1 ]
[]
[]
[ "interface", "protocols", "python" ]
stackoverflow_0001107368_interface_protocols_python.txt
Q: Do I have any obligations if I upload an egg to the CheeseShop? Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ? I haven't really released anything...
Do I have any obligations if I upload an egg to the CheeseShop?
Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ? I haven't really released anything as open source 'till now, and I'd like to know the process.
[ "\nYou have an obligation to register the package with a useful description. Nothing is more frustrating than finding a Package that may be good, but you don't know, because there is no description.\nTypical example of Lazy developer: http://pypi.python.org/pypi/gevent/0.9.1\nBetter: http://pypi.python.org/pypi/itt...
[ 9, 4, 3 ]
[]
[]
[ "egg", "pypi", "python" ]
stackoverflow_0001106759_egg_pypi_python.txt
Q: tools to aid in browsing/following (large) python projects' source code A specific example: becoming familiar with django's project source code (core, contrib, utils, etc.). Example of a useful tool: ctags - it allows you to "jump" to the file+location where a function/method is defined. Wondering about other to...
tools to aid in browsing/following (large) python projects' source code
A specific example: becoming familiar with django's project source code (core, contrib, utils, etc.). Example of a useful tool: ctags - it allows you to "jump" to the file+location where a function/method is defined. Wondering about other tools that developers use (example: is there a tool that given a function x(), ...
[ "The following is an aggregate of tools mentioned in other answers...\ncscope\nhttp://cscope.sourceforge.net/\nwikipedia entry: http://en.wikipedia.org/wiki/Cscope\ncscope is a console mode or text-based graphical interface ... It is often used on very large projects to find source code, functions, declarations, de...
[ 10, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "django", "ide", "python" ]
stackoverflow_0001077273_django_ide_python.txt
Q: Datastore access optimization I'm writing a small program to record reading progress, the data models are simple: class BookState(db.Model): isbn = db.StringProperty() title = db.StringProperty(required=True) pages = db.IntegerProperty(required=True) img = db.StringProperty() class UpdatePoint(...
Datastore access optimization
I'm writing a small program to record reading progress, the data models are simple: class BookState(db.Model): isbn = db.StringProperty() title = db.StringProperty(required=True) pages = db.IntegerProperty(required=True) img = db.StringProperty() class UpdatePoint(db.Model): book = db.ReferenceP...
[ "It seems I used Query class in a wrong way. I need to call ups.fetch() first to get the data. Now the code is a lot faster than before:\nbook = db.get(bookkey)\nq = book.updatepoint_set\nq.order('date')\nups = q.fetch(50)\n\n", "From the look of the code, it appears that your slow down is because its in the loop...
[ 3, 0 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0001108072_database_google_app_engine_python.txt
Q: How to include a python .egg library that is in a subdirectory (relative location)? How do you import python .egg files that are stored in a relative location to the .py code? For example, My Application/ My Application/library1.egg My Application/libs/library2.egg My Application/test.py How do you import and use...
How to include a python .egg library that is in a subdirectory (relative location)?
How do you import python .egg files that are stored in a relative location to the .py code? For example, My Application/ My Application/library1.egg My Application/libs/library2.egg My Application/test.py How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in-place?
[ "An .egg is just a .zip file that acts like a directory from which you can import stuff.\nYou can use the PYTHONPATH variable to add the .egg to your path, or append a directory to \nsys.path. Another option is to use a .pth file pointing to the eggs.\nFor more info see A Small Introduction to Python eggs, Python E...
[ 28, 2 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0001108384_egg_python.txt
Q: Looking for testing/QA idea for Python Web Application Project I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still pr...
Looking for testing/QA idea for Python Web Application Project
I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a f...
[ "Feather's great book is the first resource I always recommend to anybody in your situation (wish I had it in hand before I faced it my first four times or so!-) -- not Python specific but a lot of VERY useful general-purpose pieces of advice.\nAnother technique I've been happy with is fuzz testing -- low-effort, g...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "integration_testing", "python", "testing" ]
stackoverflow_0001107858_integration_testing_python_testing.txt
Q: python long running daemon job processor I want to write a long running process (linux daemon) that serves two purposes: responds to REST web requests executes jobs which can be scheduled I originally had it working as a simple program that would run through runs and do the updates which I then cron’d, but now ...
python long running daemon job processor
I want to write a long running process (linux daemon) that serves two purposes: responds to REST web requests executes jobs which can be scheduled I originally had it working as a simple program that would run through runs and do the updates which I then cron’d, but now I have the added REST requirement, and would a...
[ "\nIf the REST server and the scheduled jobs have nothing in common, do two separate implementations, the REST server and the jobs stuff, and run them as separate processes.\nAs mentioned previously, look into existing schedulers for the jobs stuff. I don't know if Twisted would be an alternative, but you might wan...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "long_running_processes", "python", "scheduling", "web_services" ]
stackoverflow_0001107826_long_running_processes_python_scheduling_web_services.txt
Q: Manually logging out a user, after a site update in Django I have a website, which will be frequently updated. Sometimes changes happen to User specific models and are linked to sessions. After I update my site, I want the user to log out and log back in. So I would log out the user right then. If he logs back in,...
Manually logging out a user, after a site update in Django
I have a website, which will be frequently updated. Sometimes changes happen to User specific models and are linked to sessions. After I update my site, I want the user to log out and log back in. So I would log out the user right then. If he logs back in, he will see the latest updates to the site. How do I do it?
[ "You could just reset your session table. This would logout every user. Of course, depending on what your doing with sessions, it could have other implications (like emptying a shopping cart, for example).\npython manage.py reset sessions\n\nOr in raw SQL:\nDELETE FROM django_sessions\n\n" ]
[ 10 ]
[ "See this: http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-out\nThat seems to cover it.\n" ]
[ -1 ]
[ "authentication", "django", "logout", "python" ]
stackoverflow_0001107598_authentication_django_logout_python.txt
Q: Twisted sometimes throws (seemingly incomplete) 'maximum recursion depth exceeded' RuntimeError Because the Twisted getPage function doesn't give me access to headers, I had to write my own getPageWithHeaders function. def getPageWithHeaders(contextFactory=None, *args, **kwargs): try: return _makeGette...
Twisted sometimes throws (seemingly incomplete) 'maximum recursion depth exceeded' RuntimeError
Because the Twisted getPage function doesn't give me access to headers, I had to write my own getPageWithHeaders function. def getPageWithHeaders(contextFactory=None, *args, **kwargs): try: return _makeGetterFactory(url, HTTPClientFactory, contextFactory=contextFactory, ...
[ "The specific traceback that you're looking at is a bit mystifying. You could try traceback.print_stack rather than traceback.print_exc to get a look at the entire stack above the problematic code, rather than just the stack going back to where the exception is caught.\nWithout seeing more of your traceback I can'...
[ 2, 1 ]
[ "The URL opener is likely following an un-ending series of 301 or 302 redirects.\n" ]
[ -1 ]
[ "python", "twisted" ]
stackoverflow_0001104587_python_twisted.txt
Q: What's a good way to render outlined fonts? I'm writing a game in python with pygame and need to render text onto the screen. I want to render this text in one colour with an outline, so that I don't have to worry about what sort of background the the text is being displayed over. pygame.font doesn't seem to offer...
What's a good way to render outlined fonts?
I'm writing a game in python with pygame and need to render text onto the screen. I want to render this text in one colour with an outline, so that I don't have to worry about what sort of background the the text is being displayed over. pygame.font doesn't seem to offer support for doing this sort of thing directly, a...
[ "A quick and dirty way would be to render your text multiple times with the outline color, shifted by small amounts on a circle around the text position:\n\n 1\n 8 | 2\n \\ | /\n \\|/\n 7----*----3\n /|\\\n / | \\ \n 6 | 4\n 5\n\nEdit: Doh you've b...
[ 4, 3 ]
[]
[]
[ "fonts", "pygame", "python" ]
stackoverflow_0001109498_fonts_pygame_python.txt
Q: How can I tell if my script is being run from a cronjob or from the command line? I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines: *** E0710091001.DAT *** [0.67%] *** E...
How can I tell if my script is being run from a cronjob or from the command line?
I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines: *** E0710091001.DAT *** [0.67%] *** E0710091001.DAT *** [1.33%] *** E0710091001.DAT *** [2.00%] *** E0710091001.DA...
[ "you could create a flag. Possibly undocumented that your cron job would pass to the utility to structure the output.\n", "I'd check sys.stderr.isatty() -- this way you avoid useless \"decoration\" output to stderr whenever it wouldn't be immediately perceptible by the user anyway.\n", "See code below. Replace...
[ 10, 9, 8, 6, 2 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0001110203_cron_python.txt
Q: Python clock function on FreeBSD While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156 The time.time() function works properly but I need a something with a slightly higher resolution. Does anyone the C function it's bound to and if there is an alternati...
Python clock function on FreeBSD
While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156 The time.time() function works properly but I need a something with a slightly higher resolution. Does anyone the C function it's bound to and if there is an alternative high resolution timer? I'm not prof...
[ "Python's time.clock calls C function clock(3) -- man clock should confirm that it's supposed to work on BSD, so I don't know why it's not working for you. Maybe you can try working around this apparent bug in your Python port by using ctypes to call the clock function from the system C library directly (if you hav...
[ 3, 1, 1, 0 ]
[]
[]
[ "bsd", "freebsd", "gettimeofday", "python", "timer" ]
stackoverflow_0001110063_bsd_freebsd_gettimeofday_python_timer.txt
Q: How can I check for a blank image in Qt or PyQt? I have generated a collection of images. Some of them are blank as in their background is white. I have access to the QImage object of each of the images. Is there a Qt way to check for blank images? If not, can someone recommend the best way to do it in Python? A:...
How can I check for a blank image in Qt or PyQt?
I have generated a collection of images. Some of them are blank as in their background is white. I have access to the QImage object of each of the images. Is there a Qt way to check for blank images? If not, can someone recommend the best way to do it in Python?
[ "I don't know about Qt, but there is an easy and efficient way to do it in PIL\nUsing the getextrema method, example:\nim = Image.open('image.png')\nbands = im.split()\nisBlank = all(band.getextrema() == (255, 255) for band in bands)\n\nFrom the documentation:\n\nim.getextrema() => 2-tuple\nReturns a 2-tuple contai...
[ 5, 1 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0001110403_pyqt4_python_qt4.txt
Q: python sqlalchemy performance? HI , I made a ICAPServer (similar with httpserver) for which the performance is very important. The DB module is sqlalchemy. I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`...
python sqlalchemy performance?
HI , I made a ICAPServer (similar with httpserver) for which the performance is very important. The DB module is sqlalchemy. I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`t know if the result is normal, or i...
[ "You should first measure where your bottleneck is, for example using the profile module.\nThen optimize, if you have the possibility to, the slowest part of the system.\n", "You can only push SQLAlchemy so far as a programmer. I would agree with you that the rest of the performance is up to your DBA, including c...
[ 5, 1, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001110805_python_sqlalchemy.txt
Q: @staticmethod gives SyntaxError: invalid syntax I have been using a python script for a long while and all of sudden it gives me: File "youtube-dl.py", line 103 @staticmethod ^ SyntaxError: invalid syntax If you want to see the script, its right here: http://bitbucket.org/rg3/youtube-dl/raw/2009.06.29/y...
@staticmethod gives SyntaxError: invalid syntax
I have been using a python script for a long while and all of sudden it gives me: File "youtube-dl.py", line 103 @staticmethod ^ SyntaxError: invalid syntax If you want to see the script, its right here: http://bitbucket.org/rg3/youtube-dl/raw/2009.06.29/youtube-dl What could be the reason? Update I am using...
[ "You might be using an old Python version that didn't support decorators yet.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001111227_python.txt
Q: Why does Django's signal handling use weak references for callbacks by default? The Django docs say this on the subject: Note also that Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To prevent this, pass weak=False when ...
Why does Django's signal handling use weak references for callbacks by default?
The Django docs say this on the subject: Note also that Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect(). I haven't been able to find any justification for w...
[ "Signals handlers are stored as weak references to avoid the object they reference from not being garbage collected (for example after explicit deletion of the signal handler), just because a signal is still flying around.\n", "Bound methods keep a reference to the object they belong to (otherwise, they cannot fi...
[ 14, 6 ]
[]
[]
[ "django", "django_signals", "garbage_collection", "python", "weak_references" ]
stackoverflow_0001110668_django_django_signals_garbage_collection_python_weak_references.txt
Q: Is there anything like HTTP::Recorder for Python? I really like Perl's HTTP::Recorder. Is there something like it for Python? A: I'm aware of Scotch and FunkLoad, but I don't know how they compare with HTTP::Recorder. See the following links for more details: http://darcs.idyll.org/~t/projects/scotch/doc/ als...
Is there anything like HTTP::Recorder for Python?
I really like Perl's HTTP::Recorder. Is there something like it for Python?
[ "I'm aware of Scotch and FunkLoad, but I don't know how they compare with HTTP::Recorder. See the following links for more details:\n\nhttp://darcs.idyll.org/~t/projects/scotch/doc/\n\nalso see the subsection \"Other Python Recorders and Proxies\"\n\nhttp://funkload.nuxeo.org/#test-recorder\n\n" ]
[ 4 ]
[]
[]
[ "http", "proxy", "python", "record" ]
stackoverflow_0001111356_http_proxy_python_record.txt
Q: How to build an Ecommerce Shopping Cart in Django? Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ? A: There's a book coming out that talks about just that. See here: http://www.apress.com/book/view/9781430225355 Edit: The above link is dead, so...
How to build an Ecommerce Shopping Cart in Django?
Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ?
[ "There's a book coming out that talks about just that. See here:\nhttp://www.apress.com/book/view/9781430225355\nEdit: The above link is dead, so here's a working link for the book: https://play.google.com/store/books/details?id=LwO1GzMN_QsC\nIt's called Beginning Django E-Commerce by James McGaw.\n", "Satchmo pr...
[ 7, 5, 3 ]
[]
[]
[ "django", "python", "shopping_cart" ]
stackoverflow_0001111173_django_python_shopping_cart.txt
Q: Separation of ORM and validation I use django and I wonder in what cases where model validation should go. There are at least two variants: Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated Validate data using forms and built-in clean_* facilities...
Separation of ORM and validation
I use django and I wonder in what cases where model validation should go. There are at least two variants: Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated Validate data using forms and built-in clean_* facilities From one point of view, answer is ob...
[ "I am not sure if this is best practise but what I do is that I tend to validate both client side and server side before pushing the data to the database. I know it requires a lot more effort but this can be done by setting some values before use and then maintaining them.\nYou could also try push in size contraint...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "architecture", "django", "django_models", "python", "validation" ]
stackoverflow_0001108967_architecture_django_django_models_python_validation.txt
Q: Performance of list(...).insert(...) I thought about the following question about computer's architecture. Suppose I do in Python from bisect import bisect index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?) x.insert(index, a) # O(1) + memcpy() which takes log n, plus, i...
Performance of list(...).insert(...)
I thought about the following question about computer's architecture. Suppose I do in Python from bisect import bisect index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?) x.insert(index, a) # O(1) + memcpy() which takes log n, plus, if I correctly understand it, a memory copy...
[ "Python is a language. Multiple implementations exist, and they may have different implementations for lists. So, without looking at the code of an actual implementation, you cannot know for sure how lists are implemented and how they behave under certain circumstances.\nMy bet would be that the references to the o...
[ 17, 12, 7 ]
[]
[]
[ "architecture", "list", "memcpy", "memory", "python" ]
stackoverflow_0001110332_architecture_list_memcpy_memory_python.txt
Q: Accessing Clipboard in Python version 3.1 I want to access the clipboard using Python 3.1. I've obviously come across win32clipboard, but it requires pywin32 and in its site I only found download versions for up to Python 2.13 or so. Bottom line: Is there a way to access the clipboard in Python 3.1 or do I have to...
Accessing Clipboard in Python version 3.1
I want to access the clipboard using Python 3.1. I've obviously come across win32clipboard, but it requires pywin32 and in its site I only found download versions for up to Python 2.13 or so. Bottom line: Is there a way to access the clipboard in Python 3.1 or do I have to revert to an old Python version?
[ "No you don't need to revert, it will be quite strange. Go to http://sourceforge.net/projects/pywin32/files/ and download package for Python 3.1 from there.\n" ]
[ 1 ]
[]
[]
[ "clipboard", "python" ]
stackoverflow_0001112057_clipboard_python.txt
Q: Returning Matplotlib image as string I am using matplotlib in a django app and would like to directly return the rendered image. So far I can go plt.savefig(...), then return the location of the image. What I want to do is: return HttpResponse(plt.renderfig(...), mimetype="image/png") Any ideas? A: Django's Htt...
Returning Matplotlib image as string
I am using matplotlib in a django app and would like to directly return the rendered image. So far I can go plt.savefig(...), then return the location of the image. What I want to do is: return HttpResponse(plt.renderfig(...), mimetype="image/png") Any ideas?
[ "Django's HttpResponse object supports file-like API and you can pass a file-object to savefig.\nresponse = HttpResponse(mimetype=\"image/png\")\n# create your image as usual, e.g. pylab.plot(...)\npylab.savefig(response, format=\"png\")\nreturn response\n\nHence, you can return the image directly in the HttpRespon...
[ 18, 6, 2, 0 ]
[]
[]
[ "django", "matplotlib", "python" ]
stackoverflow_0001108881_django_matplotlib_python.txt
Q: What are the different possible values for __name__ in a Python script, and what do they mean? Checking to see if __name__ == '__main__' is a common idiom to run some code when the file is being called directly, rather than through a module. In the process of writing a custom command for Django's manage.py, I foun...
What are the different possible values for __name__ in a Python script, and what do they mean?
Checking to see if __name__ == '__main__' is a common idiom to run some code when the file is being called directly, rather than through a module. In the process of writing a custom command for Django's manage.py, I found myself needing to use code.InteractiveConsole, which gives the effect to the user of a standard py...
[ "from the document of class code.InteractiveInterpreter([locals]):\nThe optional locals argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key '__name__' set to '__console__' and key '__doc__' set to None.\nmaybe u can turnning the locals argument, set _...
[ 9, 6 ]
[]
[]
[ "python" ]
stackoverflow_0001112198_python.txt
Q: file won't write in python I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks! edit...
file won't write in python
I'm trying to replace a string in all the files within the current directory. for some reason, my temp file ends up blank. It seems my .write isn't working because the secondfile was declared outside its scope maybe? I'm new to python, so still climbing the learning curve...thanks! edit: I'm aware my tempfile isn't be...
[ "Just glancing at the thing, it appears that your problem is with the 'w'.\nIt looks like you keep overwriting, not appending.\nSo you're basically looping through the file(s), \nand by the end you've only copied the last file to your temp file.\nYou'll may want to open the file with 'a' instead of 'w'.\n", "Your...
[ 5, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "file_io", "for_loop", "python" ]
stackoverflow_0000984216_file_io_for_loop_python.txt
Q: Replace URL with a link using regex in python how do I convert some text to a link? Back in PHP, I used this piece of code that worked well for my purpose: $text = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\3...
Replace URL with a link using regex in python
how do I convert some text to a link? Back in PHP, I used this piece of code that worked well for my purpose: $text = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\3</a>", $text); $text = preg_replace("#(...
[ "The code below is a simple translation to python. You should confirm that it actually does what you want. For more information, please see the Python Regular Expression HOWTO.\nimport re\n\npat1 = re.compile(r\"(^|[\\n ])(([\\w]+?://[\\w\\#$%&~.\\-;:=,?@\\[\\]+]*)(/[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)?)\", re.IGNORE...
[ 7 ]
[]
[]
[ "hyperlink", "python", "regex", "url" ]
stackoverflow_0001112012_hyperlink_python_regex_url.txt
Q: Why is BeautifulSoup throwing this HTMLParseError? I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed: Traceback (most recent call last): File "mx.py", line 7, in s = BeautifulSoup(content) File "build\bdist.win...
Why is BeautifulSoup throwing this HTMLParseError?
I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed: Traceback (most recent call last): File "mx.py", line 7, in s = BeautifulSoup(content) File "build\bdist.win32\egg\BeautifulSoup.py", line 1499, in __init__ File ...
[ "Worked fine for me using BeautifulSoup version 3.0.7. The latest is 3.1.0, but there's a note on the BeautifulSoup home page to try 3.0.7a if you're having trouble. I think I ran into a similar problem as yours some time ago and reverted, which fixed the problem; I'd try that. \nIf you want to stick with your c...
[ 5, 1, 1 ]
[]
[]
[ "beautifulsoup", "exception", "malformed", "parsing", "python" ]
stackoverflow_0001111656_beautifulsoup_exception_malformed_parsing_python.txt
Q: Python Win32 Extensions not Available? I am trying to get a post-commit.bat script running on a Windows Vista Ultimate machine for Trac. I have installed Trac and its working fine - but when I run this script I get the error: "The Python Win32 extensions for NT (service, event, logging) appear not to be Available...
Python Win32 Extensions not Available?
I am trying to get a post-commit.bat script running on a Windows Vista Ultimate machine for Trac. I have installed Trac and its working fine - but when I run this script I get the error: "The Python Win32 extensions for NT (service, event, logging) appear not to be Available." Anyone know why this would occur ?
[ "have u installed the Python Win32 module?\n" ]
[ 6 ]
[]
[]
[ "python", "trac" ]
stackoverflow_0001112784_python_trac.txt
Q: List of installed fonts OS X / C I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how? A: Python with PyObjC installed (which is the case for Mac OS X 10.5+, so this code will work without having to install anything): import Cocoa ...
List of installed fonts OS X / C
I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?
[ "Python with PyObjC installed (which is the case for Mac OS X 10.5+, so this code will work without having to install anything):\nimport Cocoa\nmanager = Cocoa.NSFontManager.sharedFontManager()\nfont_families = list(manager.availableFontFamilies())\n\n(based on htw's answer)\n", "Why not use the Terminal?\nSystem...
[ 14, 9, 4, 1, 0 ]
[]
[]
[ "c", "fonts", "macos", "python" ]
stackoverflow_0001113040_c_fonts_macos_python.txt
Q: Is it really OK to do object closeing/disposing in __del__? I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I sho...
Is it really OK to do object closeing/disposing in __del__?
I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I...
[ "Short answer : No.\nLong answer: Using __del__ is tricky, mainly because it's not guaranteed to be called. That means you can't do things there that absolutely has to be done. This in turn means that __del__ basically only can be used for cleanups that would happen sooner or later anyway, like cleaning up resource...
[ 15, 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001111505_python.txt
Q: Pure Python Tidy-like application/library I'm looking for a pure Python library which works like Tidy. Please kindly advise. Thank you. A: Use ElementTree Tidy HTML Tree Builder.
Pure Python Tidy-like application/library
I'm looking for a pure Python library which works like Tidy. Please kindly advise. Thank you.
[ "Use ElementTree Tidy HTML Tree Builder.\n" ]
[ 2 ]
[]
[]
[ "html", "python", "tidy", "xhtml", "xml" ]
stackoverflow_0001113421_html_python_tidy_xhtml_xml.txt
Q: Where to store secret keys and password in Python I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN. In the canonical PHP app you put secret keys, database passwords, and other app specific config in L...
Where to store secret keys and password in Python
I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN. In the canonical PHP app you put secret keys, database passwords, and other app specific config in LocalSettings.php. Is there a similar file/location whi...
[ "A user must configure their own secret key. A configuration file is the perfect place to keep this information.\nYou several choices for configuration files.\n\nUse ConfigParser to parse a config file.\nUse a simple Python module as the configuration file. You can simply execfile to load values from that file.\n...
[ 4, 3, 1 ]
[]
[]
[ "configuration", "google_maps", "python" ]
stackoverflow_0001113479_configuration_google_maps_python.txt