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:
wxPython: Threading GUI --> Using Custom Event Handler
I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: http://wiki.wxpython.org/LongRunningTasks which provides several ... | wxPython: Threading GUI --> Using Custom Event Handler | I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: http://wiki.wxpython.org/LongRunningTasks which provides several examples. I have settled on learning the first example, invo... | [
"That's the old style of defining custom events. See the migration guide for more information.\nTaken from the migration guide:\n\nIf you create your own custom event\n types and EVT_* functions, and you\n want to be able to use them with the\n Bind method above then you should\n change your EVT_* to be an ins... | [
4,
2,
0
] | [] | [] | [
"custom_events",
"multithreading",
"python",
"wxpython"
] | stackoverflow_0002345608_custom_events_multithreading_python_wxpython.txt |
Q:
Python's subprocessing with pipes and large files
I'm trying to use python + ffmpeg + oggenc to convert any audiofile to ogg. The program works, almost. But for big files (i think > ~6mb) the ffmpeg process starts to sleep at pipe_wait. I don't know which pipe it waits for.
If I kill the ffmpeg process, the oggenc... | Python's subprocessing with pipes and large files | I'm trying to use python + ffmpeg + oggenc to convert any audiofile to ogg. The program works, almost. But for big files (i think > ~6mb) the ffmpeg process starts to sleep at pipe_wait. I don't know which pipe it waits for.
If I kill the ffmpeg process, the oggenc process continues and I get a resulting ogg-file with ... | [
"What exactly do you do with the stderr channels of the two pipes?\nEncoders/decoders typically produce lots of stderr output, as status updates; this output is piped to your process, and buffers will become full. Perhaps you should add some dummy ffmpeg.stderr.read() call before the (useless, I think) .communicate... | [
5,
0
] | [] | [] | [
"ffmpeg",
"python",
"subprocess"
] | stackoverflow_0002358936_ffmpeg_python_subprocess.txt |
Q:
positioning sound with pygame?
Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.
A:
http://pysonic.sourceforge.net/
Try this out, it's a wrapper over the FMOD sound library, it won't disappoint :)
A:
... | positioning sound with pygame? | Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.
| [
"http://pysonic.sourceforge.net/\nTry this out, it's a wrapper over the FMOD sound library, it won't disappoint :)\n",
"You are correct - Pygame itself doesn't have any high-level way to position sound other than manually adjusting channel volumes (and it looks like it only supports stereo).\nThe best way, to do ... | [
1,
1,
0
] | [] | [] | [
"audio",
"pygame",
"python"
] | stackoverflow_0001583284_audio_pygame_python.txt |
Q:
OpenID or Auth in Django?
What are the pros and cons of using open id vs auth? Shoud I do both?
A:
That depends whether you want to support Open ID. As to the reasons behind Open ID, in my view the most compelling one is that it avoids requiring your users to have an account just for your site, with all the has... | OpenID or Auth in Django? | What are the pros and cons of using open id vs auth? Shoud I do both?
| [
"That depends whether you want to support Open ID. As to the reasons behind Open ID, in my view the most compelling one is that it avoids requiring your users to have an account just for your site, with all the hassle that involves (yet another username and password to remember).\nIf you decide you want to use Open... | [
5,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002359272_django_python.txt |
Q:
Compatibility with IIS and Apache -- PHP, Python, etc?
I'm currently planning out a web app that I want to host for people and allow them to host themselves on either Linux/Apache of IIS6 or IIS7 (for the benefits of bandwidth, directory services [login, etc.]).
I see that PHP is supported on both platforms. I've... | Compatibility with IIS and Apache -- PHP, Python, etc? | I'm currently planning out a web app that I want to host for people and allow them to host themselves on either Linux/Apache of IIS6 or IIS7 (for the benefits of bandwidth, directory services [login, etc.]).
I see that PHP is supported on both platforms. I've heard people serving Django and Python in IIS using PyISAPI... | [
"I have several production php5/6 applications that run on either windows/iis and apache/linux. switching between platforms has not been an issue for me. i test on a windows server talking to a mysql db on a linux machine. i deploy to a linux web server without issue. i cannot speak for rails or pytong as i'm not a... | [
0,
0
] | [] | [] | [
"apache",
"iis",
"php",
"python"
] | stackoverflow_0002359314_apache_iis_php_python.txt |
Q:
Python - lexical analysis and tokenization
I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem:
I've got very large properties files (in the order of 1,000 properties), w... | Python - lexical analysis and tokenization | I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem:
I've got very large properties files (in the order of 1,000 properties), which when distilled, are really just about 15 im... | [
"There's an excellent article on Using Regular Expressions for Lexical Analysis at effbot.org.\nAdapting the tokenizer to your problem:\nimport re\n\ntoken_pattern = r\"\"\"\n(?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*)\n|(?P<integer>[0-9]+)\n|(?P<dot>\\.)\n|(?P<open_variable>[$][{])\n|(?P<open_curly>[{])\n|(?P<close_cur... | [
14,
4,
2,
1,
1
] | [] | [] | [
"lexical_analysis",
"python",
"transform"
] | stackoverflow_0002358890_lexical_analysis_python_transform.txt |
Q:
If I'm only planning to use MySQL, and if speed is a priority, is there any convincing reason to use SQLAlchemy?
SQLAlchemy seems really heavyweight if all I use is MySQL.
Why are convincing reasons for/against the use of SQLAlchemy in an application that only uses MySQL.
A:
ORM means that your OO application ac... | If I'm only planning to use MySQL, and if speed is a priority, is there any convincing reason to use SQLAlchemy? | SQLAlchemy seems really heavyweight if all I use is MySQL.
Why are convincing reasons for/against the use of SQLAlchemy in an application that only uses MySQL.
| [
"ORM means that your OO application actually makes sense when interpreted as the interaction of objects.\nNo ORM means that you must wallow in the impedance mismatch between SQL and Objects. Working without an ORM means lots of redundant code to map between SQL query result sets, individual SQL statements and obje... | [
7,
4,
0
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002358822_mysql_pylons_python_sqlalchemy.txt |
Q:
Correctness about variable scope
I'm currently developing some things in Python and I have a question about variables scope.
This is the code:
a = None
anything = False
if anything:
a = 1
else:
a = 2
print a # prints 2
If I remove the first line (a = None) the code still works as before. However in this ... | Correctness about variable scope | I'm currently developing some things in Python and I have a question about variables scope.
This is the code:
a = None
anything = False
if anything:
a = 1
else:
a = 2
print a # prints 2
If I remove the first line (a = None) the code still works as before. However in this case I'd be declaring the variable ins... | [
"As a rule of thumb, scopes are created in three places:\n\nFile-scope - otherwise known as module scope\nClass-scope - created inside class blocks\nFunction-scope - created inside def blocks\n\n(There are a few exceptions to these.)\nAssigning to a name reserves it in the scope namespace, marked as unbound until r... | [
8,
2,
1,
0,
0
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0002359726_python_scope.txt |
Q:
Python try/except ... function always returns false
I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns false.
def add(self):
#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been complet... | Python try/except ... function always returns false | I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns false.
def add(self):
#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been completed
try:
#Validate if e-mail address is in cor... | [
"You haven't included a return statement for the positive case... Also, when a function doesn't include a return statement, the caller receives None instead... \ndef add(self):\n\n #1 -- VALIDATE EMAIL ADDRESS\n #Check that e-mail has been completed\n try:\n #Validate if e-mail address is in correc... | [
5,
1,
1,
0,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002356573_pylons_python.txt |
Q:
Tips on how to parse custom file format
Sorry about the vague title, but I really don't know how to describe this problem concisely.
I've created a (more or less) simple domain-specific language that I will to use to specify what validation rules to apply to different entities (generally forms submitted from a web... | Tips on how to parse custom file format | Sorry about the vague title, but I really don't know how to describe this problem concisely.
I've created a (more or less) simple domain-specific language that I will to use to specify what validation rules to apply to different entities (generally forms submitted from a web page). I've included a sample at the bottom ... | [
"First off, if you want to learn about parsing, then write your own recursive descent parser. The language you've defined only requires a handful of productions. I suggest using Python's tokenize library to spare yourself the boring task of converting a stream of bytes into a stream of tokens.\nFor practical parsin... | [
9,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"file_format",
"parsing",
"python"
] | stackoverflow_0002036236_file_format_parsing_python.txt |
Q:
Bash while loop calling a Python script
I would like to call a Python script from within a Bash while loop. However, I do not understand very well how to use appropriately the while loop (and maybe variable) syntax of the Bash. The behaviour I am looking for is that, while a file still contains lines (DNA sequence... | Bash while loop calling a Python script | I would like to call a Python script from within a Bash while loop. However, I do not understand very well how to use appropriately the while loop (and maybe variable) syntax of the Bash. The behaviour I am looking for is that, while a file still contains lines (DNA sequences), I am calling a Python script to extract g... | [
"No idea why you want to do this.\nc=1\nwhile [[ -s file.txt ]] ; # Stop when file.txt has no more lines\ndo\n echo \"Python script called $c times\"\n python script.py # Uses file.txt and removes lines from it\n c=$(($c + 1))\ndone\n\n",
"try -gt to eliminate the shell metacharacter >\nwhile [ `wc -l f... | [
3,
1,
0,
0
] | [] | [] | [
"bash",
"python",
"while_loop"
] | stackoverflow_0002359896_bash_python_while_loop.txt |
Q:
How to import constants from .h file into python module
What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this impor... | How to import constants from .h file into python module | What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this importing by using h2xs utility to generate .pm module.
Constants... | [
"I recently used the pyparsing library to scan for enum constants. Here it is, along with a sample string and the resulting output. Notice it also handles comments and commented out sections. With a little modification it could stuff the constants in a dictionary.\nfrom pyparsing import *\n\nsample = '''\n st... | [
6,
1,
0,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0001942020_c_python.txt |
Q:
Dealing with UTF-8 numbers in Python
Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then:
with open(file) as f:
a,b,c=map(int,f.readline... | Dealing with UTF-8 numbers in Python | Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then:
with open(file) as f:
a,b,c=map(int,f.readline().split(','))
would throw this:
invalid ... | [
"import codecs\n\nwith codecs.open(file, \"r\", \"utf-8-sig\") as f:\n a, b, c= map(int, f.readline().split(\",\"))\n\nThis works in Python 2.6.4. The codecs.open call opens the file and returns data as unicode, decoding from UTF-8 and ignoring the initial BOM.\n",
"What you're seeing is a UTF-8 encoded BOM, o... | [
17,
13
] | [] | [] | [
"byte_order_mark",
"character_encoding",
"python",
"utf_8"
] | stackoverflow_0002359832_byte_order_mark_character_encoding_python_utf_8.txt |
Q:
how to read an excel file on google app engine
Generally I work with CSV files but for this project I need to support XLS too. Does anyone have experience reading XLS files on GAE with Python?
2 possible alternatives I am considering:
xlrd
Google Docs API
A:
xlrd saves you the network round-trip implied by the ... | how to read an excel file on google app engine | Generally I work with CSV files but for this project I need to support XLS too. Does anyone have experience reading XLS files on GAE with Python?
2 possible alternatives I am considering:
xlrd
Google Docs API
| [
"xlrd saves you the network round-trip implied by the use of Google Docs; if you don't need to keep the document stored (which would be a substantial plus for Google Docs), this might incline you towards xlrd. I believe they're both high-quality.\nHowever, for both speed and accuracy of \"translation\", there's re... | [
3
] | [] | [] | [
"csv",
"excel",
"google_app_engine",
"python"
] | stackoverflow_0002360010_csv_excel_google_app_engine_python.txt |
Q:
Python directory list returned to Django template
Total Python newb here. I have a images directory and I need to return the names and urls of those files to a django template that I can loop through for links. I know it will be the server path, but I can modify it via JS. I've tried os.walk, but I keep getting... | Python directory list returned to Django template | Total Python newb here. I have a images directory and I need to return the names and urls of those files to a django template that I can loop through for links. I know it will be the server path, but I can modify it via JS. I've tried os.walk, but I keep getting empty results.
| [
"If your images are in one directory\nimport os\nroot=\"/my\"\nPath=os.path.join(root,\"path\",\"images\")\nos.chdir(Path)\nfor files in os.listdir(\".\"):\n if files[-3:].lower() in [\"gif\",\"png\",\"jpg\",\"bmp\"] :\n print \"image file: \",files\n\n",
"If it's a single directory, os.listdir('thedir... | [
2,
1
] | [] | [] | [
"directory_structure",
"list",
"python"
] | stackoverflow_0002360205_directory_structure_list_python.txt |
Q:
wxPython change field on tab
I apologize for a simple question, but I did not see this in the tutorials.
I have a very simple gui, but I would like the user to be able to press the TAB key and have it move from one input field to another. I am using wxPython with Python 2.6.
A:
It should just work in the genera... | wxPython change field on tab | I apologize for a simple question, but I did not see this in the tutorials.
I have a very simple gui, but I would like the user to be able to press the TAB key and have it move from one input field to another. I am using wxPython with Python 2.6.
| [
"It should just work in the general case; what specific controls are you having issues with? You may need to pass wx.TAB_TRAVERSAL as a style, or if you need to manipulate the order, you can use the Move(After|Before)InTabOrder(otherControl) methods on the control.\nSee http://wiki.wxpython.org/Getting%20Started#Ho... | [
6
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002359300_python_wxpython.txt |
Q:
Google App Engine with Eclipse?
I'm trying to use Google App Engine with Eclipse but it's not working.
I downloaded PyDev, and made a Hello World Python app, so that's working fine.
Then I created a new project, with the "Google App Engine" template. I was following these instructions. I used the "Hello Webapp Wor... | Google App Engine with Eclipse? | I'm trying to use Google App Engine with Eclipse but it's not working.
I downloaded PyDev, and made a Hello World Python app, so that's working fine.
Then I created a new project, with the "Google App Engine" template. I was following these instructions. I used the "Hello Webapp World" as a template, and didn't change ... | [
"I've dealt with this same problem myself. \nThe Main Module needs to be set to the following:\n${GOOGLE_APP_ENGINE}/dev_appserver.py\n\nIt does cover it in the instructions, step 3 under Starting Your First Project. I must have glazed over it myself the first time as well. Hope this helps!\n"
] | [
6
] | [] | [] | [
"eclipse",
"google_app_engine",
"pydev",
"python"
] | stackoverflow_0002359550_eclipse_google_app_engine_pydev_python.txt |
Q:
Python: Misunderstanding about how imports work
Here is my loader class, ItemLoader.py:
from google.appengine.ext import db
from google.appengine.tools import bulkloader
import models
class ItemLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(self, 'Item', [('CSIN', int), # no... | Python: Misunderstanding about how imports work | Here is my loader class, ItemLoader.py:
from google.appengine.ext import db
from google.appengine.tools import bulkloader
import models
class ItemLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(self, 'Item', [('CSIN', int), # not too DRY...
... | [
"You must add models directory to the PYTHONPATH. From docs:\n(which is in your PYTHONPATH, such as the directory where you'll run the tool)\n\nIf you don't do that, python can't find your module.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"import",
"python"
] | stackoverflow_0002360399_google_app_engine_import_python.txt |
Q:
Python and Memory Consumption
I am searching for a way to be able to handle overloading the RAM and CPU using a high memory program... I would like to process a LARGE amount of data contained in files. I then read the files and process the data therein. The problem is there are many nested for loops and a root XML... | Python and Memory Consumption | I am searching for a way to be able to handle overloading the RAM and CPU using a high memory program... I would like to process a LARGE amount of data contained in files. I then read the files and process the data therein. The problem is there are many nested for loops and a root XML file is being created from all the... | [
"Do you really need to keep the whole data from the XML file on memory at once?\nMost (all?) XML libraries out there allow you to do iterative parsing, meaning that you keep in memory just a few nodes of the XML file, not the whole file. That is unless you are making a string containing the XML file yourself withou... | [
3
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0002360483_memory_management_python.txt |
Q:
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distr... | Recommended ways to split some functionality into functions, modules and packages? | There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).
... | [
"There's a classic paper by David Parnas called \"On the criteria to be used in decomposing systems into modules\". It's a classic (and has a certain age, so can be a little outdated).\nMaybe you can start from there, a PDF is available here\nhttp://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf\n",
... | [
7,
4,
2,
1,
1,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0001168565_module_package_python.txt |
Q:
Google App Engine: Give arguments to a script from URL handler?
Here is a portion of my app.yaml file:
handlers:
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
- url: /detail/(\d)+
script: Detail.py
- url: /.*
script: Index.py
I want that capture group (the ... | Google App Engine: Give arguments to a script from URL handler? | Here is a portion of my app.yaml file:
handlers:
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
- url: /detail/(\d)+
script: Detail.py
- url: /.*
script: Index.py
I want that capture group (the one signified by (\d)) to be available to the script Detail.py. How c... | [
"I see two questions, how to pass elements of the url path as variables in the handler, and how to get the catch-all to render properly.\nBoth of these have more to do with the main() method in the handler than the app.yaml\n1) to pass the id in the /detail/(\\d) url, you want something like this:\nclass DetailHand... | [
12
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002360638_google_app_engine_python.txt |
Q:
What should people new to Python know about its community and ecosystem?
I'm cobbling together some sort of an introduction to Python, but one that focuses on the community and the ecosystem around Python rather than just the language. With How to Think Like a Computer Scientist and other great tutorials, it's eas... | What should people new to Python know about its community and ecosystem? | I'm cobbling together some sort of an introduction to Python, but one that focuses on the community and the ecosystem around Python rather than just the language. With How to Think Like a Computer Scientist and other great tutorials, it's easy to get familiar with the language, but it took me a fair while before I knew... | [
"I think one of the most important thing a beginner need to know about Python ecosystem is that it's a general purpose language surrounded by specialized libs. Experienced pythonistas know them, but a newbie can't:\n\nDon't stop to tkinter : go wx, gtk or qt.\nDon't dev web code by hands : use TurboGears, Pylons, W... | [
18,
9,
7,
5,
4,
4,
1
] | [] | [] | [
"documentation",
"python"
] | stackoverflow_0002351793_documentation_python.txt |
Q:
Global function in __init__.py not accessible using Pylons + Python
I'm having trouble creating a global function accessible from within all classes. I receive an error from within user.py that says:
NameError: global name 'connectCentral' is not defined
Here is my current code.
project/model/__ init __.py:
... | Global function in __init__.py not accessible using Pylons + Python | I'm having trouble creating a global function accessible from within all classes. I receive an error from within user.py that says:
NameError: global name 'connectCentral' is not defined
Here is my current code.
project/model/__ init __.py:
"""The application's model objects"""
import sqlalchemy as sa
fro... | [
"You need to qualify the name with the module (or package) it's in, so:\n try:\n project.model.connectCentral()\n\netc.\n"
] | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002360846_pylons_python.txt |
Q:
Building an interleaved buffer for pyopengl and numpy
I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array.
... | Building an interleaved buffer for pyopengl and numpy | I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array.
Is there a better way to do this? I would have thought it ... | [
"The reason that create_array_1 is so much faster seems to be that the items in the (python) list all point to the same object. You can see this if you test:\nprint (ibuffer[0] is ibuffer[1])\n\ninside the subroutines. In create_array_1 this is true (before you create the numpy array), while in create_array_2 this ... | [
1,
1,
0
] | [] | [] | [
"2d",
"numpy",
"opengl",
"pyopengl",
"python"
] | stackoverflow_0002350110_2d_numpy_opengl_pyopengl_python.txt |
Q:
Solving Sparse Linear Problem With Some Known Boundary Values
I'm trying to solve a Poisson equation on a rectangular domain which ends up being a linear problem like
Ax=b
but since I know the boundary conditions, there are nodes where I have the solution values. I guess my question is...
How can I solve the... | Solving Sparse Linear Problem With Some Known Boundary Values | I'm trying to solve a Poisson equation on a rectangular domain which ends up being a linear problem like
Ax=b
but since I know the boundary conditions, there are nodes where I have the solution values. I guess my question is...
How can I solve the sparse system Ax=b if I know what some of the coordinates of x are... | [
"If I understand correctly, some elements of x are known, and some are not, and you want to solve Ax = b for the unknown values of x, correct?\nLet Ax = [A1 A2][x1; x2] = b, where the vector x = [x1; x2], the vector x1 has the unknown values of x, and vector x2 have the known values of x. Then, A1x1 = b - A2x2. The... | [
1
] | [] | [] | [
"numpy",
"poisson",
"python",
"sparse_matrix"
] | stackoverflow_0002361176_numpy_poisson_python_sparse_matrix.txt |
Q:
datetime rendering in the admin forms
I have the following Model and ModelAdmin classes. However when I view the posts in the admin list page, the created fields are rendered as 2010-03-01 22:15:18.494594. I've tried setting the DATETIME_FORMAT variable in settings.py, but that didn't help. Any ideas how to con... | datetime rendering in the admin forms | I have the following Model and ModelAdmin classes. However when I view the posts in the admin list page, the created fields are rendered as 2010-03-01 22:15:18.494594. I've tried setting the DATETIME_FORMAT variable in settings.py, but that didn't help. Any ideas how to control the formatting of datetime fields in t... | [
"I am not aware of a way to simply specify a date format for use in the admin interface. You do have other options though. Take a look here. According to the documentation the list of columns on the list page can include the name of a field (or simply property if I remember correctly), a callable (taking the mod... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002360699_django_python.txt |
Q:
using __init__.py
I am having difficulty understanding the usage scenarios or design goals of python's __init__.py files in my projects.
Assume that I have 'model' directory (refers as a package) which contains the following files
__init__.py
meta.py
solrmodel.py
mongomodel.py
samodel.py
I found two ways of usin... | using __init__.py | I am having difficulty understanding the usage scenarios or design goals of python's __init__.py files in my projects.
Assume that I have 'model' directory (refers as a package) which contains the following files
__init__.py
meta.py
solrmodel.py
mongomodel.py
samodel.py
I found two ways of using __init__.py:
I have ... | [
"The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize.\nOne example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer... | [
52,
23
] | [] | [] | [
"initialization",
"module",
"package",
"python"
] | stackoverflow_0002361124_initialization_module_package_python.txt |
Q:
django error :1146, "Table 'basic_project.topics_topic' doesn't exist"
TemplateSyntaxError at /tribes/
Caught an exception while rendering: (1146, "Table
'basic_project.topics_topic' doesn't exist")
Why?
A:
Because.
You have to run syncdb everytime you add a new app or model.
| django error :1146, "Table 'basic_project.topics_topic' doesn't exist" |
TemplateSyntaxError at /tribes/
Caught an exception while rendering: (1146, "Table
'basic_project.topics_topic' doesn't exist")
Why?
| [
"Because.\nYou have to run syncdb everytime you add a new app or model.\n"
] | [
2
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0002361451_django_pinax_python.txt |
Q:
Pure Python in Xcode?
Could anyone tell me how to use pure Python without Cocoa support in Xcode? I can only find the Cocoa-Python template on the Internet.
Thanks in advance.
A:
If you are just trying to write pure Python command line tools, using Xcode is like using a big sledge hammer to hit a tiny nail, in o... | Pure Python in Xcode? | Could anyone tell me how to use pure Python without Cocoa support in Xcode? I can only find the Cocoa-Python template on the Internet.
Thanks in advance.
| [
"If you are just trying to write pure Python command line tools, using Xcode is like using a big sledge hammer to hit a tiny nail, in other words, probably not the best tool for the job. There are some old posts out there about how to set up a pure Python Xcode project, like this one, but, in the end, you might be... | [
7,
0,
0,
0
] | [] | [] | [
"python",
"xcode"
] | stackoverflow_0002359994_python_xcode.txt |
Q:
Modifying the `clear` attribute of an image with TinyMCE
I'm using TinyMCE with the tinymce-django app in my Django website. I am using it in the admin interface to edit HTML fields. (Something like a flatpage.)
When adding images with TinyMCE, how can I change their clear style attribute?
A:
First go to the ima... | Modifying the `clear` attribute of an image with TinyMCE | I'm using TinyMCE with the tinymce-django app in my Django website. I am using it in the admin interface to edit HTML fields. (Something like a flatpage.)
When adding images with TinyMCE, how can I change their clear style attribute?
| [
"First go to the image popup. After selecting image, navigate to Appearance tab.\nIf you don't see this popup, make sure that the editor mode is advanced and the plugin advimage is included.\nNow, you have two options to do so:\n\nCSS class. You have to define, for example, .clear { clear: both; }\n in your CSS sty... | [
2,
0
] | [] | [] | [
"django",
"django_tinymce",
"python"
] | stackoverflow_0002309894_django_django_tinymce_python.txt |
Q:
RSS screen scraper
Can anyone point me towards a ready made RSS screen scraper, preferably in Python in order to get full text RSS feeds?
A:
There's a good list of them here, which mentions Feed Parser, which you use like this:
import feedparser
python_wiki_rss_url = "http://www.python.org/cgi-bin/moinmoin/" \
... | RSS screen scraper | Can anyone point me towards a ready made RSS screen scraper, preferably in Python in order to get full text RSS feeds?
| [
"There's a good list of them here, which mentions Feed Parser, which you use like this:\nimport feedparser\n\npython_wiki_rss_url = \"http://www.python.org/cgi-bin/moinmoin/\" \\\n \"RecentChanges?action=rss_rc\"\n\nfeed = feedparser.parse( python_wiki_rss_url )\n\nYou can then do things like:\... | [
3,
1,
0
] | [] | [] | [
"python",
"rss"
] | stackoverflow_0002362066_python_rss.txt |
Q:
Is Tkinter worth learning?
I generally make my desktop interfaces with Qt, but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally Tkinter comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
(source: kb-creative.net)
... | Is Tkinter worth learning? | I generally make my desktop interfaces with Qt, but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally Tkinter comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
(source: kb-creative.net)
| [
"The answer to your question is a resounding yes.\nQt is good, I have nothing against it. But Tk is better and far easier to use and quite well documented - not just on the Python webspace, but there are also many third-party tutorials out there. This particular one is where I learned it from and it has been quite ... | [
24,
4,
4,
2,
0
] | [] | [] | [
"python",
"qt",
"tk_toolkit",
"tkinter",
"user_interface"
] | stackoverflow_0002361328_python_qt_tk_toolkit_tkinter_user_interface.txt |
Q:
Database-Independent MAX() Function in SQLAlchemy
I'd like to calculate a MAX() value for a column. What's the proper way to do this in sqlalchemy while preserving database independence?
A:
You can find aggregate functions in:
from sqlalchemy import func
func.avg(...)
func.sum(...)
func.max(...)
In 0.5 y... | Database-Independent MAX() Function in SQLAlchemy | I'd like to calculate a MAX() value for a column. What's the proper way to do this in sqlalchemy while preserving database independence?
| [
"You can find aggregate functions in: \nfrom sqlalchemy import func \nfunc.avg(...) \nfunc.sum(...) \nfunc.max(...) \n\nIn 0.5 you can use an ORM query like a select:\nsession.query(func.max(Table.column)) \n\n"
] | [
6
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002358634_mysql_pylons_python_sqlalchemy.txt |
Q:
PyQt4: Adding QtMessageBox.information functionality to custom window
what I need is something very alike QtMessageBox.information method, but I need it form my custom window.
I need a one window with few labels, one QtTreeViewWidget, one QButtonGroup … This window will be called from main window. If we call class... | PyQt4: Adding QtMessageBox.information functionality to custom window | what I need is something very alike QtMessageBox.information method, but I need it form my custom window.
I need a one window with few labels, one QtTreeViewWidget, one QButtonGroup … This window will be called from main window. If we call class that implements called window as SelectionWindow, than what I need is:
cla... | [
"I would do something like this:\n\ndialog window with buttonbox ->\nevents connected to accept() and\nreject() slots of the dialog itself\nset the dialog modality to something like application modal\ncall the exec_() method of the dialog to keep it blocking until the user chooses ok/cancel\nafter the execution of ... | [
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0002335104_pyqt4_python.txt |
Q:
Python: Access Posix' locale database without setlocale()
The setup is a Django based website on an Ubuntu server system with lots of useful information in /usr/share/i18n/locales.
The question: Can I access this pool of wisdom without using Python's locale.setlocale() afore?
The reason: The docs say, that it is
... | Python: Access Posix' locale database without setlocale() | The setup is a Django based website on an Ubuntu server system with lots of useful information in /usr/share/i18n/locales.
The question: Can I access this pool of wisdom without using Python's locale.setlocale() afore?
The reason: The docs say, that it is
very expensive to call setlocale(), and
affects the whole appli... | [
"The magic library to achieve this is called Babel. Does what I want:\nBefore\nimport locale\nsetlocale(LC_ALL, 'de')\nx = locale.format('%.2f', 123)\nsetlocale(LC_ALL, '')\n\nAfter\nfrom babel.numbers import format_decimal\nx = format_decimal(123, format='#0.00', locale='de')\n\n...and has a good Djang integration... | [
3
] | [] | [] | [
"django",
"internationalization",
"locale",
"posix",
"python"
] | stackoverflow_0002361764_django_internationalization_locale_posix_python.txt |
Q:
At what point does importing become the correct solution?
This weekend I was working on a project and I needed to use a binomial distribution to test the probability of an event (the probability that x of y characters would be alphanumeric given random bytes). My first solution was to write the test myself since ... | At what point does importing become the correct solution? | This weekend I was working on a project and I needed to use a binomial distribution to test the probability of an event (the probability that x of y characters would be alphanumeric given random bytes). My first solution was to write the test myself since it is rather simple.
def factorial(n):
if n == 0:
r... | [
"\"when should I use code already written at the cost of including far more than I need\"\nAlways.\nWhen should I just write my own implementation?\nNever.\nThe \"including far more than I need\" question is generally quite silly. What do you care how much is \"included\"?\nThe only time this can ever matter is wh... | [
5,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002356036_import_python.txt |
Q:
How can i capture the UDP packet and find the TTL Values from the packet using python
HI
I want to capture the UDP packets by joining to the Multicast group. after the receving the packet i want to check for the TTL value from that UDP packet. How can i achieve this by using python ?
The Sammple code as mentioned... | How can i capture the UDP packet and find the TTL Values from the packet using python | HI
I want to capture the UDP packets by joining to the Multicast group. after the receving the packet i want to check for the TTL value from that UDP packet. How can i achieve this by using python ?
The Sammple code as mentioned below:
here
rec_port is any port which i had used to bind; eg: 9180
rec_hostname is any m... | [
"You probably want to use this python wrapper. If it doesn't satisfy you can wrap libpcap yourself.\nIn response to unwind: You don't have to act \"promiscious\" with libpcap, you can inject and snoop valid traffic -- i.e., meant for your NIC.\nEdit: Read this tutorial on pcap to figure out how to isolate the ttl f... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002362541_python.txt |
Q:
Delete() views and template code
Template:
<form method="POST" action="/customer/delete/">
<div style="float: right;
margin: 0px; padding: 05px; ">
Name:<select name="customer">
{% for customer in customer %}
<option value="{{ customer.name|escape }}" ></option><br />
{% endfor %}
</select>
<input t... | Delete() views and template code | Template:
<form method="POST" action="/customer/delete/">
<div style="float: right;
margin: 0px; padding: 05px; ">
Name:<select name="customer">
{% for customer in customer %}
<option value="{{ customer.name|escape }}" ></option><br />
{% endfor %}
</select>
<input type=submit value="delete">
</div>
</... | [
"Your URLConf isn't catching any data to pass on to the variable name. You need to either catch it as a part of the URL, or leave it to catch in a POSTed argument.\nAs part of the URL:\n(r'^customer/(?P<name>[a-z]*)/delete/', 'quote.excel.views.delete')\n\ndef delete(request, name):\n if request.method == \"POS... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002361074_django_python.txt |
Q:
Match start and end of file in python with regex
I'm having a hard time finding the regex for the start and end of a file in python.
How would I accomplish this ?
A:
Read the whole file into a string, then \A matches only the beginning of a string, and \Z matches only the end of a string. With re.MULTILINE, '^'... | Match start and end of file in python with regex | I'm having a hard time finding the regex for the start and end of a file in python.
How would I accomplish this ?
| [
"Read the whole file into a string, then \\A matches only the beginning of a string, and \\Z matches only the end of a string. With re.MULTILINE, '^' matches the beginning of the string and the just after a newline, and '$' matches the end of the string and just before a newline. See the Python documentation for... | [
20,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002362471_python_regex.txt |
Q:
Nested functions scope in Python
I have the following function that walks a nested tree and prints the result
def walk_tree(tree):
def read_node(node):
print node
for n in node['subnodes']:
read_node(n)
read_node(tree)
If I want to return a txt with the data collected from w... | Nested functions scope in Python | I have the following function that walks a nested tree and prints the result
def walk_tree(tree):
def read_node(node):
print node
for n in node['subnodes']:
read_node(n)
read_node(tree)
If I want to return a txt with the data collected from walking the tree, thought that the foll... | [
"txt is accessible in read_node, I think it's just some problem with += and that txt is not in local scope in read_node.\n>>> def a():\n... x = \"\"\n... def b():\n... x += \"X\"\n... b()\n... print x\n... \n>>> a()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>... | [
6,
5,
0
] | [] | [] | [
"python",
"tree"
] | stackoverflow_0002363266_python_tree.txt |
Q:
python os.utime doesn't update the access time
I'm trying to modify the access timestamp and modify timestamp of a remote file
I'm using the following line:
os.utime(filePath, (1267533581,1267090862))
the modify timestamp get updated but the access timestamp doesn't
I have tried to use this on a local file on a ... | python os.utime doesn't update the access time | I'm trying to modify the access timestamp and modify timestamp of a remote file
I'm using the following line:
os.utime(filePath, (1267533581,1267090862))
the modify timestamp get updated but the access timestamp doesn't
I have tried to use this on a local file on a local file and everything is working well
I'm worki... | [
"Perhaps the last access time is disabled on your system. This could have been done for performance purposes. It's controlled by a registry setting. See:\nhttp://www.pctools.com/guides/registry/detail/50\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002363497_python.txt |
Q:
Splitting list in python
I have a list which I have obtained from a python script. the content of the list goes something like:
The content below is in a file but I loaded it into a list for comparing it to something else. But now I have to split this list such that each new list created contains the complex name ... | Splitting list in python | I have a list which I have obtained from a python script. the content of the list goes something like:
The content below is in a file but I loaded it into a list for comparing it to something else. But now I have to split this list such that each new list created contains the complex name with the corresponding number.... | [
"without more detailed info and assuming your \"list\" is in a file.\nf=0\nfor line in open(\"file\"):\n if \"d.complex.2\" in line: break # or exit\n if \"d.complex.1\" in line:\n f=1\n if f:\n print line.rstrip()\n\noutput\n$ ./python.py\nd.complex.1\n24\n25\n67\n123\n764\n\n",
">>> mylis... | [
0,
0
] | [] | [] | [
"list",
"python",
"split"
] | stackoverflow_0002363417_list_python_split.txt |
Q:
Embedding Python code as a preprocessor PHP style
I'm going back over an old project where I added preprocessor functionality to Essence' and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill.
Instead I just need to be able to embed dynamic language... | Embedding Python code as a preprocessor PHP style | I'm going back over an old project where I added preprocessor functionality to Essence' and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill.
Instead I just need to be able to embed dynamic language code into the file, isolate it at runtime, eval and in... | [
"Your best bet is to use one of the already made (and battle tested) Templating Engines. The two big ones that I've used are Mako, and Cheetah. They allow you to embed code right in the page, and are mostly used as the View in an MVC architecture.\nIf you feel that using one of those engines is overkill for your ... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0002363609_python.txt |
Q:
Teaching Python to a Law Student
Im trying to teach python to a Law student (happens to be my fiancee).She has been insisting on me teaching her about it. One problem: She doesn't know anything about programming.
I was thinking on starting with dive into python, but i'm worried most not about the python part, but... | Teaching Python to a Law Student | Im trying to teach python to a Law student (happens to be my fiancee).She has been insisting on me teaching her about it. One problem: She doesn't know anything about programming.
I was thinking on starting with dive into python, but i'm worried most not about the python part, but the "she does not know anything about... | [
"Nothing is better for learning to program than a real project (by real I mean of use for somebody besides the author), internet connection and an expert friend. As long as she is willing to learn.\nScreencasts are a great way to learn new stuff fast and not-so-boring. Try http://showmedo.com for example\n",
"Sco... | [
5,
3,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002363116_python.txt |
Q:
Python PIL: color index to RGB
following this link i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an int as value. What is it? I guess some sort of index, but how to convert it to a p... | Python PIL: color index to RGB | following this link i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an int as value. What is it? I guess some sort of index, but how to convert it to a proper rgb value? Thanks
[..]
img = I... | [
"img = Image.open(GIF_FILENAME)\nrgbimg = img.convert('RGB')\nfor i in range(5):\n print rgbimg.getpixel((i, 0))\n\n"
] | [
7
] | [] | [] | [
"image",
"python"
] | stackoverflow_0002363583_image_python.txt |
Q:
Comparing two lists items in python
I have two files which I loaded into lists. The content of the first file is something like this:
d.complex.1
23
34
56
58
68
76
.
.
.
etc
d.complex.179
43
34
59
69
76
.
.
.
etc
The content of the second file is also the same but with different numerical values. Please consider ... | Comparing two lists items in python | I have two files which I loaded into lists. The content of the first file is something like this:
d.complex.1
23
34
56
58
68
76
.
.
.
etc
d.complex.179
43
34
59
69
76
.
.
.
etc
The content of the second file is also the same but with different numerical values. Please consider from one d.complex.* to another d.complex... | [
"Open the file using Python's open function, then iterate over all its lines. Check whether the line contains a number, if so, increase its count in a defaultdict instance as described here.\nRepeat this for the other file and compare the resulting dicts.\n",
"First create a function which can load a given file, ... | [
2,
1
] | [] | [] | [
"compare",
"file",
"python"
] | stackoverflow_0002363954_compare_file_python.txt |
Q:
returning out of for-loop
I'm pretty new at python and I was wondering if this:
def func(self, foo):
for foo in self.list:
if foo.boolfunc(): return True
return False
is good practice.
Can I return out of a loop like the above or should i use a while-loop, like so?
def func(self, foo):
found... | returning out of for-loop | I'm pretty new at python and I was wondering if this:
def func(self, foo):
for foo in self.list:
if foo.boolfunc(): return True
return False
is good practice.
Can I return out of a loop like the above or should i use a while-loop, like so?
def func(self, foo):
found = false
while(not found & ... | [
"There's nothing wrong with your example, but it's better to write\ndef func(self, foo):\n return any(foo.boolfunc() for foo in self.list)\n\n",
"It should be mentioned that in Python, for loops can have an else clause. The else clause is only executed when the loop terminates through exhaustion of the list.\n... | [
14,
9,
6,
5,
2
] | [
"\"Breaking out of a loop\" can easily devolve to bad practice because it conceals the terminating condition of the loop.\nIf your if statement is of moderate complexity, then it can become unclear what post-condition the loop establishes.\nIf your exit condition is obvious, then an early exit is a common syntactic... | [
-2
] | [
"for_loop",
"python",
"while_loop"
] | stackoverflow_0002363602_for_loop_python_while_loop.txt |
Q:
print value of a column in django
How to print the test field in the following query in django
res=Resources.objects.filter(test=request.profile)
logging.debug(test) # won't work
I wanted to check what this value is compared with..
A:
You have to iterate through res and print each model's value of test in turn.... | print value of a column in django | How to print the test field in the following query in django
res=Resources.objects.filter(test=request.profile)
logging.debug(test) # won't work
I wanted to check what this value is compared with..
| [
"You have to iterate through res and print each model's value of test in turn.\n",
"You may also try the values_list method, eg:\nResource.objects.filter(test=request.profile).values_list(\"test\")\n\nIt returns a list of tuples with the value of \"test\" for each matched record.\n"
] | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002362729_django_python.txt |
Q:
Python: slicing a very large binary file
Say I have a binary file of 12GB and I want to slice 8GB out of the middle of it. I know the position indices I want to cut between.
How do I do this? Obviously 12GB won't fit into memory, that's fine, but 8GB won't either... Which I thought was fine, but it appears binary ... | Python: slicing a very large binary file | Say I have a binary file of 12GB and I want to slice 8GB out of the middle of it. I know the position indices I want to cut between.
How do I do this? Obviously 12GB won't fit into memory, that's fine, but 8GB won't either... Which I thought was fine, but it appears binary doesn't seem to like it if you do it in chunks... | [
"Here's a quick example. Adapt as needed:\ndef copypart(src,dest,start,length,bufsize=1024*1024):\n with open(src,'rb') as f1:\n f1.seek(start)\n with open(dest,'wb') as f2:\n while length:\n chunk = min(bufsize,length)\n data = f1.read(chunk)\n ... | [
8
] | [] | [] | [
"binary",
"large_files",
"python"
] | stackoverflow_0002363483_binary_large_files_python.txt |
Q:
Google App Engine: Trouble with Datastore Query
This query works:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0]
although if there are no results returned, it blows up in my face. (How can I get around this? A for loop seems dubious when I want at max one iteration.)
This query does not work:
item = ... | Google App Engine: Trouble with Datastore Query | This query works:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0]
although if there are no results returned, it blows up in my face. (How can I get around this? A for loop seems dubious when I want at max one iteration.)
This query does not work:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSI... | [
"You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following:\n>>> results = [] # an empty list\n>>> item = results[0] # Raises an IndexError, because there is nothing in the list\n\nWhat you need to do instead is:\nitem = db.GqlQuery(\"S... | [
9,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002364531_google_app_engine_google_cloud_datastore_python.txt |
Q:
Designing to easily migrate to Google App Engine
I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future.
Alternatively, I could desig... | Designing to easily migrate to Google App Engine | I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future.
Alternatively, I could design the app for GAE from the start, and so in that case,... | [
"Just out of top of my head:\n\nIt's really ONLY a key->value store, don't be fooled by things like GQL (which is just a subset of SQL SELECT)\nNo JOINs - often you have to denormalize or forget\nMore or less frequent timeouts\n(Very) slow access comparing to local SQL base.\nCOUNT very expensive\nOFFSET (in SELECT... | [
7
] | [] | [] | [
"google_app_engine",
"non_relational_database",
"python",
"relational_database",
"web2py"
] | stackoverflow_0002365647_google_app_engine_non_relational_database_python_relational_database_web2py.txt |
Q:
Python (Jython) Playing notes from pixels in picture
This is from a class assignment:
This program is about listening to colors. We will treat pictures as piano scores.
Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pi... | Python (Jython) Playing notes from pixels in picture | This is from a class assignment:
This program is about listening to colors. We will treat pictures as piano scores.
Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pixel in every 4th row and do the following. It will compute... | [
"Robbie is right for the width/height for loops.\nThe loop you are using to get the pixels and play the notes looks as if it is getting ALL the pixels and playing them all every time you get a unique x and y. What you should be doing is be getting the pixel at (x,y) then pulling out the rgb values and calling play ... | [
1,
1
] | [] | [] | [
"image_manipulation",
"jython",
"python"
] | stackoverflow_0002364966_image_manipulation_jython_python.txt |
Q:
haskell vs python typing
I am looking for example where things in python would be easier to program just because it is dynamically typed?
I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typin... | haskell vs python typing | I am looking for example where things in python would be easier to program just because it is dynamically typed?
I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance?
PS: I am... | [
"\nCan I program in Haskell as I can in python without static typing being a hindrance\n\nYes. \nTo elaborate, I would say the main gotcha will be the use of existential types in Haskell for heterogeneous data structures (regular data structures holding lists of variously typed elements). This often catches OO peop... | [
7,
5,
4
] | [] | [] | [
"dynamic",
"haskell",
"python",
"static",
"types"
] | stackoverflow_0002365783_dynamic_haskell_python_static_types.txt |
Q:
Python interface for outputting MIDI files or text that's readable by audio programs
I am looking for a python package or library that will allow me to programmatically output a file format (e.g. MIDI) that can be read by audio/sound processing programs, like LogicPro or iDrum. What are the best options for this?... | Python interface for outputting MIDI files or text that's readable by audio programs | I am looking for a python package or library that will allow me to programmatically output a file format (e.g. MIDI) that can be read by audio/sound processing programs, like LogicPro or iDrum. What are the best options for this?
| [
"A large number of possibilities are listed here, especially under the \"Midi Mania\" header. For your requirements, and the various packages' descriptions, it seems to me that pythonmidi might suit you best, but I have no first-hand experience with it.\n"
] | [
1
] | [] | [] | [
"audio",
"midi",
"python"
] | stackoverflow_0002365884_audio_midi_python.txt |
Q:
How to read and extract data from a binary data file with multiple variable-length records?
Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-len... | How to read and extract data from a binary data file with multiple variable-length records? | Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records.
I've got as far as ... | [
"You have to read in pieces. Not because of memory constraints, but because of the parsing requirements. 18MiB fits in memory easily. On a 4Gb machine it fits in memory 200 times over.\nHere's the usual design pattern.\n\nRead the first 4 bytes only. Use struct to unpack just those bytes.\nConfirm the sync byte... | [
6,
2,
2
] | [] | [] | [
"binary_data",
"gps",
"python"
] | stackoverflow_0002365998_binary_data_gps_python.txt |
Q:
Django + GAE (Google App Engine) : most convenient path for a beginner?
Some background info first:
Goal: a medium-level complexity web app that I will need to maintain and possibly extend for a few years.
Experience: good knowledge of python, some experience of MVC frameworks (in PHP).
Desiderata: using django a... | Django + GAE (Google App Engine) : most convenient path for a beginner? | Some background info first:
Goal: a medium-level complexity web app that I will need to maintain and possibly extend for a few years.
Experience: good knowledge of python, some experience of MVC frameworks (in PHP).
Desiderata: using django and google app engine.
I read extensively about the compatibility issues betw... | [
"I'm not sure if Django is a good fit for you. Django is a great framework for standalone applications because it provides a full stack solution: an ORM, authentication system and an admin interface, to name a few. You won't be able to use any of these on App Engine. Furthermore, many of the code samples are geared... | [
6
] | [] | [] | [
"django",
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0002364364_django_google_app_engine_python_web_applications.txt |
Q:
Where can i get exercises for 'Dive into Python'?
I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better.
A:
I used ProjectEuler.net when learni... | Where can i get exercises for 'Dive into Python'? | I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better.
| [
"I used ProjectEuler.net when learning Python. It also helped sharpen my math skills. \n",
"Consider using How to Think Like a Computer Scientist instead of Dive Into Python to learn Python. The former has exercises in every chapter, is targeted for a more appropriate version of Python (Python 3 does not have the... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002366056_python.txt |
Q:
Can you go to a line with the file operations in python?
I'm parsing a file and need to keep track of where I am in the file...
let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file wit... | Can you go to a line with the file operations in python? | I'm parsing a file and need to keep track of where I am in the file...
let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file with the tell() method of the file. Is there a way to mark the li... | [
"You may like this better: http://docs.python.org/library/linecache.html\n\"In case of a crash I'm marking my position in another file with the tell() method of the file.\"\nGood.\n\"Is there a way to mark the line and be able to go back to that line position\"\nThat's what you are doing. You're marking the line w... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002366448_python.txt |
Q:
Is there a way to specify a fixed (or variable) number of elements for lxml in Python
There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to in... | Is there a way to specify a fixed (or variable) number of elements for lxml in Python | There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list of ... | [
"lxml supports XPath:\nfrom lxml import etree\nroot = etree.fromstring(\"...your xml...\")\n\nel, = root.xpath(\"//div[text() = 'the string']/preceding-sibling::*[9]\")\n\n",
"Does this do the trick?\nfrom itertools import islice\nancestor = islice(theitem.iterancestors(), 4) # To get the fourth ancestor\n\nEDIT ... | [
3,
1,
0
] | [] | [] | [
"html",
"lxml",
"python",
"screen_scraping"
] | stackoverflow_0002367000_html_lxml_python_screen_scraping.txt |
Q:
on click event in wx.Panel?
how can I click on a wx.Panel and that changes its color?
What is the name of the event.
(I want to do a similar thing as Firefox Extras)
Thanks in advance! :)
A:
A quick google for wxpython mouse events turns up http://www.wxpython.org/docs/api/wx.MouseEvent-class.html
So using this,... | on click event in wx.Panel? | how can I click on a wx.Panel and that changes its color?
What is the name of the event.
(I want to do a similar thing as Firefox Extras)
Thanks in advance! :)
| [
"A quick google for wxpython mouse events turns up http://www.wxpython.org/docs/api/wx.MouseEvent-class.html\nSo using this, you could do something like:\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.panel = wx.Panel(self)\n self.panel.BackgroundColou... | [
9
] | [] | [] | [
"panel",
"python",
"wxpython"
] | stackoverflow_0002367076_panel_python_wxpython.txt |
Q:
In Django, how do I make my sessions persist through http://example.com and http://www.example.com?
If I set a session in example.com, it doesn't work on www.example.com. I'd like all subdomains, and all www, to be treated as one big thing.
example.com and all its subdomains should have all the session cookies of ... | In Django, how do I make my sessions persist through http://example.com and http://www.example.com? | If I set a session in example.com, it doesn't work on www.example.com. I'd like all subdomains, and all www, to be treated as one big thing.
example.com and all its subdomains should have all the session cookies of everything.
Do I change this in Apache2?
| [
"I found the solution:\nSESSION_COOKIE_DOMAIN = \".example.com\"\n\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"python",
"session"
] | stackoverflow_0002367448_apache_django_python_session.txt |
Q:
Why won't my Python scatter plot work?
I created a very simple scatter plot using pylab.
pylab.scatter(engineSize, fuelMile)
pylab.show()
The rest of the program isn't worth posting, because it's that line that's giving me the problem. When I change "scatter" to "plot" it graphs the data, but each point is part o... | Why won't my Python scatter plot work? | I created a very simple scatter plot using pylab.
pylab.scatter(engineSize, fuelMile)
pylab.show()
The rest of the program isn't worth posting, because it's that line that's giving me the problem. When I change "scatter" to "plot" it graphs the data, but each point is part of a line and that makes the whole things a s... | [
"I bet engineSize, fuelMile are stings, try printing them, if that is the case, you have to convert them to float before passing them as arguments to scatter\nfloatval = float(strval)\n\n",
"Okay, so since this works, something must be wrong with your inputs. Clearly you need to post more, unless this \"answer\"... | [
9,
2
] | [] | [] | [
"graph",
"matplotlib",
"python",
"scatter"
] | stackoverflow_0001746312_graph_matplotlib_python_scatter.txt |
Q:
How do I implement polymorphic arithmetic operators pythonicly?
I'm trying to create a class that will allow me to add/multiply/divide objects of the same class together or add/multiply numeric arguments to each member of the class
So my class is for coordinates (I am aware there are great packages out there that ... | How do I implement polymorphic arithmetic operators pythonicly? | I'm trying to create a class that will allow me to add/multiply/divide objects of the same class together or add/multiply numeric arguments to each member of the class
So my class is for coordinates (I am aware there are great packages out there that do everything I want better than I could ever hope to on my own, but ... | [
"The \"Pythonic\" way is to \"ask forgiveness rather than permission\" - that is, instead of checking the type beforehand, try to add and, if it fails, catch the exception and deal with it, like so:\nclass GpsPoint(object):\n \"\"\"A class for representing gps coordinates\"\"\"\n def __init__(self, x, y, z):\... | [
6,
2,
0
] | [] | [] | [
"polymorphism",
"python",
"type_conversion"
] | stackoverflow_0002367753_polymorphism_python_type_conversion.txt |
Q:
Sed script to edit csv file Or Python
In our project we need to import the csv file to postgres.
There are multiple types of files meaning the length of the file changes as some files are with fewer columns and some with all of them.
We need a fast way to import this file to postgres. I want to use COPY FROM of th... | Sed script to edit csv file Or Python | In our project we need to import the csv file to postgres.
There are multiple types of files meaning the length of the file changes as some files are with fewer columns and some with all of them.
We need a fast way to import this file to postgres. I want to use COPY FROM of the postgres since the speed requirement of t... | [
"Are you aware of the fact that COPY FROM lets you specify which columns (as well as in which order they) are to be imported?\nCOPY tablename ( column1, column2, ... ) FROM ...\n\nSpecifying directly, at the Postgres level, which columns to import and in what order, will typically be the fastest and most efficient ... | [
3,
2,
2,
0,
0,
0
] | [] | [] | [
"awk",
"python",
"sed",
"text_processing"
] | stackoverflow_0002367338_awk_python_sed_text_processing.txt |
Q:
Django url.py Different view functions with the same regex name pattern
I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that ... | Django url.py Different view functions with the same regex name pattern | I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that part out of the regex some how?
urlpatterns = patterns('catalog.category_view... | [
"I'd personally put this logic in the view rather than the urlspatterns.\nI would create a list of all the special categories so for this:\nspecial_cats = ['cat1','cat2','cat3']\n\nThen for you view you can do something like this:\ndef generic_cat_view(request, cat_slug):\n if cat_slug in special_cats:\n ... | [
4
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0002367918_django_django_urls_python.txt |
Q:
Passing JSON to Python script via AJAX
What's the ideal way to pass a large JSON data object from Javascript through AJAX to a Python script?
A:
Are you using some web framework? Django has pretty decent support for JSON decoding/encoding.
| Passing JSON to Python script via AJAX | What's the ideal way to pass a large JSON data object from Javascript through AJAX to a Python script?
| [
"Are you using some web framework? Django has pretty decent support for JSON decoding/encoding.\n"
] | [
1
] | [] | [] | [
"ajax",
"javascript",
"json",
"python"
] | stackoverflow_0002368001_ajax_javascript_json_python.txt |
Q:
In mako, how can I cycle through a list and display each value?
I have a Python list that I'm supplying to the template:
{'error_name':'Please enter a name',
'error_email':'Please enter an email'}
And would like to display:
<ul>
<li>Please enter a name</li>
<li>Please enter an email</li>
</ul>
A:
<ul>
% for pr... | In mako, how can I cycle through a list and display each value? | I have a Python list that I'm supplying to the template:
{'error_name':'Please enter a name',
'error_email':'Please enter an email'}
And would like to display:
<ul>
<li>Please enter a name</li>
<li>Please enter an email</li>
</ul>
| [
"<ul>\n% for prompt in whateveryoucalledit.values():\n <li>${prompt}</li>\n% endfor\n</ul>\n\nwhere whateveryoucalledit it is the name under which you chose to pass that container (which, as a comment noticed, is a dict, not a list). The nice thing about mako, after all, is precisely that it's wonderfully close t... | [
5
] | [] | [] | [
"mako",
"pylons",
"python",
"templates"
] | stackoverflow_0002367682_mako_pylons_python_templates.txt |
Q:
How to convert from unicode with python
In database I have saved string in which the problem word is: za\u0161\u010diten.
[ed.: the "problem word" seems to have changed]
When I want to present this string on my page (with req.write(string)). I get this error: UnicodeEncodeError: 'ascii' codec can't encode charact... | How to convert from unicode with python | In database I have saved string in which the problem word is: za\u0161\u010diten.
[ed.: the "problem word" seems to have changed]
When I want to present this string on my page (with req.write(string)). I get this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 686-687: ordinal not in range... | [
"req.write(string.encode(encoding))\n\nwhere encoding is the charset you declared in the Content-Type header.\n",
"If string refers to the string module, then yes that string doesn't have encode. If string is in fact a unicode object, then it does have an encode but perhaps string may in fact be an str object.\nB... | [
2,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002367744_python_unicode.txt |
Q:
Find text in gtk.TextView
I have a gtk.Textview. I want to find and select some of the text in this TextView programmatically.
I have this code but it's not working correctly.
search_str = self.text_to_find.get_text()
start_iter = textbuffer.get_start_iter()
match_start = textbuffer.get_start_iter()
match_end... | Find text in gtk.TextView | I have a gtk.Textview. I want to find and select some of the text in this TextView programmatically.
I have this code but it's not working correctly.
search_str = self.text_to_find.get_text()
start_iter = textbuffer.get_start_iter()
match_start = textbuffer.get_start_iter()
match_end = textbuffer.get_end_iter() ... | [
"start_iter.forward_search returns a tuple of the start and end matches so your found variable has both match_start and match_end in it\nthis should make it work:\nsearch_str = self.text_to_find.get_text()\nstart_iter = textbuffer.get_start_iter()\n# don't need these lines anymore\n#match_start = textbuffer.get_s... | [
6
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0002364014_gtk_pygtk_python.txt |
Q:
How do I use Flickzeug to get interactive tracebacks from a paste deploy WSGI pipeline?
I'd like to use Flickzeug to see interactive tracebacks by adding it to my paste deploy file's pipeline. The following doesn't work. What will?
[pipeline]
pipeline =
flickzeug
myapp
A:
Use the filter-with directive in... | How do I use Flickzeug to get interactive tracebacks from a paste deploy WSGI pipeline? | I'd like to use Flickzeug to see interactive tracebacks by adding it to my paste deploy file's pipeline. The following doesn't work. What will?
[pipeline]
pipeline =
flickzeug
myapp
| [
"Use the filter-with directive in your application declaration.\n[app:main]\nuse = ...\n...\n\nfilter-with = flickzeug\n\n\n[filter:flickzeug]\nuse = egg:...#...\n...\nFor more information, see the first example in the Filter Composition section of the Paste Deploy documentation.\n"
] | [
0
] | [] | [] | [
"paster",
"python",
"wsgi"
] | stackoverflow_0002299173_paster_python_wsgi.txt |
Q:
Apache/Django freezing after a few requests
I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04.
I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the brows... | Apache/Django freezing after a few requests | I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04.
I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the browser spinner would just keep spinning).
It works fo... | [
"It sounds a lot like there's something happening between django and your newly housed database.\nJust to eliminate apache from the mix, you should run it as the dev server (on some random port to stop people using it) and see if you still have issues. If you do, it's the database. If it behaves, it could be apache... | [
0,
0
] | [] | [] | [
"apache2",
"django",
"mod_wsgi",
"postgresql",
"python"
] | stackoverflow_0001300213_apache2_django_mod_wsgi_postgresql_python.txt |
Q:
Why does python + pylons "remember" previously specified class variables?
I have a simple form in python + pylons that submits to a controller. However, each page load doesn't seem to be a fresh instantiation of the class. Rather, class variables specified on the previous page load are still accessible.
What's... | Why does python + pylons "remember" previously specified class variables? | I have a simple form in python + pylons that submits to a controller. However, each page load doesn't seem to be a fresh instantiation of the class. Rather, class variables specified on the previous page load are still accessible.
What's going on here? And what's the solution?
| [
"Pylons uses a multi-threaded application server and variables are not cleared from request to request. This is a performance issue, as re-instantiating entire class trees would be expensive. Instead of storing the data returned by the user in a class, use a sessions system (Pylons comes with one or use something... | [
1,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002368482_pylons_python.txt |
Q:
Getting info from all related objects in django
I'm trying to do something pretty simple, but I'm new to Django. I have a quiz system set up for an experiment I'm running.
The relevant entries in models.py follow:
class Flavor(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
... | Getting info from all related objects in django | I'm trying to do something pretty simple, but I'm new to Django. I have a quiz system set up for an experiment I'm running.
The relevant entries in models.py follow:
class Flavor(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Passage(models.Model):
name... | [
"Well, since no one has helped you yet, here:\n# *snip* -- view:\ncontext = { 'test_subjects' : TestSubject.objects.all() }\nreturn render_to_response('Template', context)\n# *snip*\n\n# *snip* -- template:\n{% for test_subject in test_subjects %}\n{{ test_subject.ip }}\n{# ... snip ... #}\n{% empty %}\nThere are n... | [
0
] | [] | [] | [
"django",
"object",
"python",
"templates",
"views"
] | stackoverflow_0002368465_django_object_python_templates_views.txt |
Q:
Google App Engine: Basic Django Issue
I'm using Django templating with Google App Engine. I'm trying unsuccessfully to print out a menu.
The controller:
menu_items = {
'menu_items': [
{
'href': '/', 'name': 'Home'
},
{
'href': '/cart', 'name': 'Cart'
}
... | Google App Engine: Basic Django Issue | I'm using Django templating with Google App Engine. I'm trying unsuccessfully to print out a menu.
The controller:
menu_items = {
'menu_items': [
{
'href': '/', 'name': 'Home'
},
{
'href': '/cart', 'name': 'Cart'
}
],
}
render('Views/menu.html', self, {'m... | [
"menu_items = {'menu_items': [{'href': '/', 'name': 'Home'},\n {'href': '/cart', 'name': 'Cart'}],\n }\nrender('Views/menu.html', self, {'menu_items': menu_items})\n\nLook at these lines carefully. menu_items (dictionary) has a key menu_items with a value having a type list.... | [
5
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002368651_django_google_app_engine_python.txt |
Q:
I want my Python script to detect the version and quit gracefully in case of a mismatch
I'd like to make it as general as possible - e.g. handle as many versions as possible.
Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement.
Please let me know if ... | I want my Python script to detect the version and quit gracefully in case of a mismatch | I'd like to make it as general as possible - e.g. handle as many versions as possible.
Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement.
Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic b... | [
"The sys module also contains the version info (first available in version 2.0):\nimport sys\n\nif sys.version_info[0] == 2:\n print(\"You are using Python 2.x\")\nelif sys.version_info[0] == 3:\n print(\"You are using Python 3.x\")\n\n",
"In order to get around syntax errors you would have to use condition... | [
9,
8,
3,
3,
2,
2
] | [] | [] | [
"python",
"version"
] | stackoverflow_0002368574_python_version.txt |
Q:
python file manipulation
I have a file with entries such as:
26 1
33 2
.
.
.
and another file with sentences in english
I have to write a script to print the 1st word in sentence number 26
and the 2nd word in sentence 33.
How do I do it?
A:
The following code should do the task. With assumptions that files are ... | python file manipulation | I have a file with entries such as:
26 1
33 2
.
.
.
and another file with sentences in english
I have to write a script to print the 1st word in sentence number 26
and the 2nd word in sentence 33.
How do I do it?
| [
"The following code should do the task. With assumptions that files are not too large. You may have to do some modification to deal with edge cases (like double space, etc)\n# Get numers from file\nnum = []\nwith open('1.txt') as file:\n num = file.readlines()\n\n# Get text from file \ntext = []\nwith open('2... | [
2,
1,
0,
0
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0002368618_file_python_string.txt |
Q:
How do I drop a bash shell from within Python?
i'm working on a python tcp shell; I'd like to be able to telnet to a port, and have it prompt me with a shell: ex.
$ telnet localhost 5555
Connected to localhost.
Escape character is '^]'.
$
The answer below was quite helpful in getting me on my way. Here's the wor... | How do I drop a bash shell from within Python? | i'm working on a python tcp shell; I'd like to be able to telnet to a port, and have it prompt me with a shell: ex.
$ telnet localhost 5555
Connected to localhost.
Escape character is '^]'.
$
The answer below was quite helpful in getting me on my way. Here's the working code.
import SocketServer, os, subprocess
clas... | [
"import os\nos.system('sh') # or bash, tcsh, zsh, whatever. :-P\n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0002368872_python.txt |
Q:
Google visualization api on app engine not working... (python)
I'm trying to render the sortable table that's provided in Google visualization API in my app on app engine, but it's not working. The app is written in python and uses the django framework.
When I copy the generated HTML/Javascript and save it as a pl... | Google visualization api on app engine not working... (python) | I'm trying to render the sortable table that's provided in Google visualization API in my app on app engine, but it's not working. The app is written in python and uses the django framework.
When I copy the generated HTML/Javascript and save it as a plain html file locally, it works just fine. This leads me to believe ... | [
"Wait, where are you doing the rendering? The visapi stuff goes in the client-side. Is that where you have it? (Sorry if that's obvious; it's really not entirely clear from the way you wrote the question.)\nMore details would definitely help.\n",
"In case anyone else has this issue - I messed up headers of the... | [
0,
0
] | [] | [] | [
"google_app_engine",
"google_visualization",
"python"
] | stackoverflow_0002290827_google_app_engine_google_visualization_python.txt |
Q:
Bad file descriptor error
If I try executing the following code
f = file('test','rb')
fout = file('test.out','wb')
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
Where 'test' is any arbitrary file, I get:
Traceback (most recent call last):
File "testbad.p... | Bad file descriptor error | If I try executing the following code
f = file('test','rb')
fout = file('test.out','wb')
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
Where 'test' is any arbitrary file, I get:
Traceback (most recent call last):
File "testbad.py", line 12, in <module>
pr... | [
"you've only opened the file fout for writing, not reading. To open for both use\nfout = file('test.out','r+b')\n\n"
] | [
37
] | [] | [] | [
"file",
"python"
] | stackoverflow_0002368967_file_python.txt |
Q:
List fields present in a table
Is there any way to to list out the fields present in a table in django models
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.ForeignKey(School)
emp = models.ForeignKey(User, unique=True)
How to list out the filed names from the t... | List fields present in a table | Is there any way to to list out the fields present in a table in django models
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.ForeignKey(School)
emp = models.ForeignKey(User, unique=True)
How to list out the filed names from the table Profile,(just like desc Profile... | [
"Profile._meta.fields will get you a list of fields. The name property of the field object contains the name of the field. Profile._meta.get_fields_with_model() will return a list of 2-tuples of (field, model), with model being None if the field is in Profile.\n"
] | [
19
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002368948_django_python.txt |
Q:
How do I know if jobs have been/are performing? - Crontab
I have followed the suggestion in this question
as I am using Django, I have set the script to store date and time of each run of the script in the db, but no entry has been stored yet in the database.
Is there a way to figure out, other than typing "top" ... | How do I know if jobs have been/are performing? - Crontab | I have followed the suggestion in this question
as I am using Django, I have set the script to store date and time of each run of the script in the db, but no entry has been stored yet in the database.
Is there a way to figure out, other than typing "top" and searching through?
| [
"First, I would probably configure cron to mail yourself any output by using MAILTO:\nIn /etc/crontab:\nMAILTO=username\n\nSecond, I usually add something to my script that (almost) cannot possibly fail, like the following:\n#!/bin/sh\necho \"$0 ran on `date +%c`\" >> /tmp/crontab_test.log\n\n# ... rest of program\... | [
5,
2,
1
] | [] | [] | [
"crontab",
"django",
"linux",
"python"
] | stackoverflow_0002367892_crontab_django_linux_python.txt |
Q:
xhtml/rst to excel conversion
I am working on a reporting tool and need to generate reports in various formats including pdf, html and excel(.xls or any format which can be easily opened in excel)
I am thinking of generating basic report in xhtml or restructuredtext(rst) and then converting it to other formats, I ... | xhtml/rst to excel conversion | I am working on a reporting tool and need to generate reports in various formats including pdf, html and excel(.xls or any format which can be easily opened in excel)
I am thinking of generating basic report in xhtml or restructuredtext(rst) and then converting it to other formats, I can use xhtml2pdf or rst2pdf for pd... | [
"For converting a dataset in XML (or XHTML) to Excel -\nI haven't done this myself, but MSDN provides an example XSLT (plus some irrelevant .NET code) for converting a sample dataset to Excel. It should not be too difficult, as the output is the XML format accepted by Excel.\n"
] | [
1
] | [] | [] | [
"excel",
"python",
"restructuredtext",
"xhtml",
"xls"
] | stackoverflow_0002369230_excel_python_restructuredtext_xhtml_xls.txt |
Q:
how to geocode phone number
I have a list of phone numbers with area code prefixes that I want to find a latitude/longitude location for.
Is there a library (ideally Python) or service that can do this?
A:
You may be able to obtain limited free information (e.g. town) or, for a hefty fee, some relatively more de... | how to geocode phone number | I have a list of phone numbers with area code prefixes that I want to find a latitude/longitude location for.
Is there a library (ideally Python) or service that can do this?
| [
"You may be able to obtain limited free information (e.g. town) or, for a hefty fee, some relatively more detailed information (address), from various Whitepages-like providers. This should cover landlines as well as, to some degree, mobile (cell) lines. Be aware that in the case of mobile lines the information (... | [
1
] | [] | [] | [
"geocoding",
"phone_number",
"python"
] | stackoverflow_0002369340_geocoding_phone_number_python.txt |
Q:
Arguments in the middle of a string to be localized
I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters :
print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah')
This ac... | Arguments in the middle of a string to be localized | I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters :
print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah')
This actually does the job, but is not really what I would call ... | [
"I'd suggest \nprint 'Hello dear user, your name is %(first_name)s %(last_name)s' % params\n\n",
"Something like this should do the trick :\nprint _('Hello dear user, your name is %s %s and blah blah blah') % (params['first_name'], params['last_name'])\n\n",
"I would go with templates if I were you. That would ... | [
3,
1,
1,
0
] | [] | [] | [
"internationalization",
"python"
] | stackoverflow_0002370309_internationalization_python.txt |
Q:
How do I ensure I always get a list of matches from Python's Regular Expressions?
I'm trying to pull some information (no recursion necessary) from a jsp page (malformed xml) similar to this:
<td>
<html:button ...></html:button>
<html:submit ...></html:submit></td>
And a regex:
<html:(button|submit|cancel)[\s\S]*... | How do I ensure I always get a list of matches from Python's Regular Expressions? | I'm trying to pull some information (no recursion necessary) from a jsp page (malformed xml) similar to this:
<td>
<html:button ...></html:button>
<html:submit ...></html:submit></td>
And a regex:
<html:(button|submit|cancel)[\s\S]*?</html:(button|submit|cancel)>
re.findall() is giving me a list of tuples, like so:
[... | [
"Aside from the fact that a regex probably isn't what you want to do this with, you want to put the bit you want in groups using parentheses. If you want everything up to the closing </html:whatever> tag, then you want something like this:\n(<html:(button|submit|cancel)[\\s\\S]*?)</html:(button|submit|cancel)>\n\nI... | [
3,
1
] | [] | [] | [
"findall",
"python",
"regex",
"tuples"
] | stackoverflow_0002370369_findall_python_regex_tuples.txt |
Q:
best way to do this string conversion in Python
I need to convert a string to another which has removed anything before the second word
Example from this,
string = "xyz anything else"
string2 = "xyz anything else"
string3 = "xyz anything else"
to this,
string = "anything else"
string2 = "anything else"
string... | best way to do this string conversion in Python | I need to convert a string to another which has removed anything before the second word
Example from this,
string = "xyz anything else"
string2 = "xyz anything else"
string3 = "xyz anything else"
to this,
string = "anything else"
string2 = "anything else"
string3 = "anything else"
The way I've done it doesnt plea... | [
"s.split(None, 1)[-1]\n\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0002370974_python.txt |
Q:
How can I build a regular expression which has options part
How can I build a regular expression in python which can match all the following?
where it is a "string (a-zA-Z)" follow by a space follow by 1 or multiple 4 integers which separates by a comma:
Example:
someotherstring 42 1 48 17,
somestring 363 1 46 17,... | How can I build a regular expression which has options part | How can I build a regular expression in python which can match all the following?
where it is a "string (a-zA-Z)" follow by a space follow by 1 or multiple 4 integers which separates by a comma:
Example:
someotherstring 42 1 48 17,
somestring 363 1 46 17,363 1 34 17,401 3 8 14,
otherstring 42 1 48 17,363 1 34 17,
I ha... | [
">>> test = \"somestring 363 1 46 17,363 1 34 17,401 3 8 14,\"\n\nHere is a pyparsing processor for your input string:\n>>> from pyparsing import *\n>>> integer = Word(nums)\n>>> patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(',')))\n\nUsing patt.parseString returns a pyparsing ParseResults object, whic... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002369346_python_regex.txt |
Q:
Unable to get set intersection to work
Sorry for the double post, I will update this question if I can't get things to work :)
I am trying to compare two files. I will list the two file content:
File 1 File 2
"d.complex.1" "d.complex.1"
1 ... | Unable to get set intersection to work | Sorry for the double post, I will update this question if I can't get things to work :)
I am trying to compare two files. I will list the two file content:
File 1 File 2
"d.complex.1" "d.complex.1"
1 4
5 ... | [
"The problem is that you are using the intersection instead of the difference :)\nIf you use target_set.difference(target_set_1) you will have the results you're looking for.\nI'm not sure if I'm completely getting what you want, but is this what you are looking for?\ndef complex_file_to_dict(filename):\n out = ... | [
2,
1
] | [] | [] | [
"compare",
"loops",
"python",
"set"
] | stackoverflow_0002371405_compare_loops_python_set.txt |
Q:
How to append EOF to file using Perl or Python?
I’m trying to bulk insert data to SQL server express database. When doing bcp from Windows XP command prompt, I get the following error:
C:\temp>bcp in -T -f -S
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Native Client]Unexpected E... | How to append EOF to file using Perl or Python? | I’m trying to bulk insert data to SQL server express database. When doing bcp from Windows XP command prompt, I get the following error:
C:\temp>bcp in -T -f -S
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Native Client]Unexpected EOF encountered in BCP data-file
0 rows copied.
Netwo... | [
"EOF is End Of File. What probably occurred is that the file is not complete; the software expects data, but there is none to be had anymore.\nThese kinds of things happen when:\n\nthe export is interrupted (quit dump software while dumping)\nwhile copying the dumpfile aborting the copy\ndisk full during dump\n\nth... | [
3,
3,
1
] | [] | [] | [
"bcp",
"perl",
"python",
"sql_server"
] | stackoverflow_0002371645_bcp_perl_python_sql_server.txt |
Q:
Python: Get system calendar format
Is it possible to return the current system calendar format using Python? For example non-Gregorian calendar formats such as the Thai Buddhist calendar.
A:
Under windows?...for this approach you'll need to get the win32api package from here, here's a quick script to read the re... | Python: Get system calendar format | Is it possible to return the current system calendar format using Python? For example non-Gregorian calendar formats such as the Thai Buddhist calendar.
| [
"Under windows?...for this approach you'll need to get the win32api package from here, here's a quick script to read the registry key that holds the default calendar type for the system, but each user has their own key as well, so you may have to dynamically check. \nThis gets the iCalendarType key value which you ... | [
1
] | [] | [] | [
"calendar",
"internationalization",
"python"
] | stackoverflow_0002369332_calendar_internationalization_python.txt |
Q:
Open a second window in PyQt
I'm trying to use pyqt to show a custom QDialog window when a button on a QMainWindow is clicked. I keep getting the following error:
$ python main.py
DEBUG: Launch edit window
Traceback (most recent call last):
File "/home/james/Dropbox/Database/qt/ui_med.py", line 23, in launchEd... | Open a second window in PyQt | I'm trying to use pyqt to show a custom QDialog window when a button on a QMainWindow is clicked. I keep getting the following error:
$ python main.py
DEBUG: Launch edit window
Traceback (most recent call last):
File "/home/james/Dropbox/Database/qt/ui_med.py", line 23, in launchEditWindow
dialog = Ui_Dialog(c)... | [
"I've done like this in the past, and i can tell it works.\nassuming your button is called \"Button\"\nclass Main(QtGui.QMainWindow):\n ''' some stuff '''\n def on_Button_clicked(self, checked=None):\n if checked==None: return\n dialog = QDialog()\n dialog.ui = Ui_MyDialog()\n dial... | [
19,
3,
1
] | [] | [] | [
"dialog",
"pyqt",
"python"
] | stackoverflow_0001807299_dialog_pyqt_python.txt |
Q:
function not defined but really is defined
I am writing a script and in my script I have this function:
def insert_image(cursor, object_id, sku):
product_obj = core.Object.get(object_id)
string_sku = str(sku)
folder = string_sku[0] + string_sku[1] + string_sku[2]
found_url = False
# KLUDGE This... | function not defined but really is defined | I am writing a script and in my script I have this function:
def insert_image(cursor, object_id, sku):
product_obj = core.Object.get(object_id)
string_sku = str(sku)
folder = string_sku[0] + string_sku[1] + string_sku[2]
found_url = False
# KLUDGE This is ugly and redundant, however putting this in ... | [
"You have syntax errors in your function:\ntry urllib.urlopen(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku)):\n urllib.URLopener().retrieve(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku), \"%sPR-IT,PM.jpg\" % (sku))\n found_url = True\n except:\n found_url = Fa... | [
3,
0
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0002371981_nameerror_python.txt |
Q:
Python - functional "find"?
I need a function, which is capable of iterating over the collection, calling a supplied function with element of the collection as a parameter and returning the parameter or it's index when received "True" from supplied function.
It is somethong like this:
def find(f, seq, index_only=T... | Python - functional "find"? | I need a function, which is capable of iterating over the collection, calling a supplied function with element of the collection as a parameter and returning the parameter or it's index when received "True" from supplied function.
It is somethong like this:
def find(f, seq, index_only=True, item_only=False):
"""Re... | [
"Try itertools and for example ifilter.\n",
"I don't think there is any such function with such exact semantics, and anyway your function is short , good enough and you can easily improve it for later use, so use it.\nbecause simple is better than complex.\n",
"You can use itertools.dropwhile to skip over the i... | [
3,
3,
2
] | [] | [] | [
"functional_programming",
"lambda",
"python"
] | stackoverflow_0002371979_functional_programming_lambda_python.txt |
Q:
Importing bytea field into PostgreSQL database via psycopg2
I have a list of values as such:
row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']
I would like to insert these into a bytea field in my PostgreSQL database, using psycopg2, but I am unfamiliar with byte strings in python.
What is the best way to achi... | Importing bytea field into PostgreSQL database via psycopg2 | I have a list of values as such:
row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']
I would like to insert these into a bytea field in my PostgreSQL database, using psycopg2, but I am unfamiliar with byte strings in python.
What is the best way to achieve this?
| [
"I am not sure if this is the correct way, but the following appears to work: \n row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']\n as_hex = ''.join(byte[2:].zfill(2) for byte in row)\n # as_hex = '14b6a100a100'\n bytes = buffer(as_hex.decode('hex'))\n\n cur.execute(\"INSERT INTO mylog (binaryfie... | [
2
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0002371779_postgresql_psycopg2_python.txt |
Q:
Python XML to dictionary to iterate over items
I have the following XML example
<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>
I need to iterate over each tag in a for loop in python. If tried many things but I just can't get it..
thanks for ... | Python XML to dictionary to iterate over items | I have the following XML example
<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>
I need to iterate over each tag in a for loop in python. If tried many things but I just can't get it..
thanks for the help
| [
"I personally use xml.etree.cElementTree, as I've found it works really well, it's fast, easy to use, and works well with big (>2GB) files.\nimport xml.etree.cElementTree as etree\n\nwith open(xml_file_path) as xml_file:\n tree = etree.iterparse(xml_file)\n for items in tree:\n for item in items:\n ... | [
7,
1,
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002372217_python_xml.txt |
Q:
Is there a Python version of CPAN?
So I've been using Perl for several years now and I'm starting to dabble a little in Python. Is there a sort of CPAN but for Python? What's the normal way to manage modules in Python? Any direction would be greatly appreciated. FWIW I use Linux so Windows-only solutions aren't re... | Is there a Python version of CPAN? | So I've been using Perl for several years now and I'm starting to dabble a little in Python. Is there a sort of CPAN but for Python? What's the normal way to manage modules in Python? Any direction would be greatly appreciated. FWIW I use Linux so Windows-only solutions aren't really useful to me.
| [
"The repository formerly known as Cheese Shop.\n\nPyPI\nThe Python Package Index is a repository of software for the Python programming language. There are currently 9140 packages here. To contact the PyPI admins, please use the Get help or Bug reports links.\n\nAlso, take a look at\n\nSIG for Python Resource Catal... | [
12,
1
] | [] | [] | [
"python"
] | stackoverflow_0002372445_python.txt |
Q:
More efficient solution to loop nesting required
I am trying to compare two files. I will list the two file content:
File 1 File 2
"d.complex.1" "d.complex.1"
1 4
5 5
48 ... | More efficient solution to loop nesting required | I am trying to compare two files. I will list the two file content:
File 1 File 2
"d.complex.1" "d.complex.1"
1 4
5 5
48 47
65 21
d.comp... | [
"Pointers:\n\nUse list comprehensions or generator expressions to simplify data processing. More readable\nJust generate the sets once.\nUse functions to not repeat yourself, especially doing the same task twice.\n\nI've made a few assumptions about your input data, you might want to try something like this.\ndef p... | [
1,
1
] | [] | [] | [
"for_loop",
"loops",
"nested",
"python"
] | stackoverflow_0002371956_for_loop_loops_nested_python.txt |
Q:
Flickr API automated login using Python library flickrapi
I have a web application that I want to sync with Flickr. I don't want the users to have to log into Flickr so I plan to use a single login. I believe I'll need to do something like this:
import flickrapi
flickr = flickrapi.FlickrAPI(myKey, mySecret)
(token... | Flickr API automated login using Python library flickrapi | I have a web application that I want to sync with Flickr. I don't want the users to have to log into Flickr so I plan to use a single login. I believe I'll need to do something like this:
import flickrapi
flickr = flickrapi.FlickrAPI(myKey, mySecret)
(token, frob) = flickr.get_token_part_one(perms='write', my_auth_call... | [
"If you don't want your users to authenticate with Flickr, you don't need to use the token-getting code at all. Just get a token for yourself once and include it with your code.\nNote that \"syncing\" other users' photos with your own account probably breaks Flickr's TOS.\n"
] | [
1
] | [] | [] | [
"django",
"flickr",
"python"
] | stackoverflow_0002373194_django_flickr_python.txt |
Q:
any python socket server framework?
I'm looking for a python socket server framework - not to handle http, but to handle tcp sockets. I've done it myself, but adding all the features is tedious. This framework would handle thread pooling, socket setup, signal handling, etc.
A big feature is code-reloading. If I u... | any python socket server framework? | I'm looking for a python socket server framework - not to handle http, but to handle tcp sockets. I've done it myself, but adding all the features is tedious. This framework would handle thread pooling, socket setup, signal handling, etc.
A big feature is code-reloading. If I use apache/mod_python, or django, or whate... | [
"Twisted is the usual suspect. Reloading in the case of mod_wsgi is easy since only the WSGI server needs to be restarted, not the whole web server (not that restarting the web server is all that hard, mind you...).\n",
"Use Apache, mod_wsgi in daemon mode and follow these guidelines.\nUpdate: I mentioned Apache ... | [
4,
2
] | [] | [] | [
"frameworks",
"python",
"tcp"
] | stackoverflow_0002373430_frameworks_python_tcp.txt |
Q:
fast java/python/C++ ipc
I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language.
I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to av... | fast java/python/C++ ipc | I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language.
I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to avoid the HTTP overhead. And XML... | [
"For the C++ backend you can use xmlrpc++ (LGPL'ed) - I'm planning to use it myself. It has very clean code so you can modify it easily if you need to.\nAs for the frontends in Java/Python, you could make use of Apache XML-RPC (don't know anything about it) or Python's xmlrpclib (very easy to use).\nXML-RPC should ... | [
2
] | [] | [] | [
"c++",
"ipc",
"java",
"python",
"rpc"
] | stackoverflow_0002373540_c++_ipc_java_python_rpc.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.