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: Fitting a line in 3D Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D. Thanks. A: If you are trying to predict one value from the other two, then you should...
Fitting a line in 3D
Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D. Thanks.
[ "If you are trying to predict one value from the other two, then you should use lstsq with the a argument as your independent variables (plus a column of 1's to estimate an intercept) and b as your dependent variable. \nIf, on the other hand, you just want to get the best fitting line to the data, i.e. the line whi...
[ 59, 5 ]
[]
[]
[ "curve_fitting", "linear_algebra", "numpy", "python" ]
stackoverflow_0002298390_curve_fitting_linear_algebra_numpy_python.txt
Q: Using Property Builtin with GAE Datastore's Model I want to make attributes of GAE Model properties. The reason is for cases like to turn the value into uppercase before storing it. For a plain Python class, I would do something like: Foo(db.Model): def get_attr(self): return self.something def set_...
Using Property Builtin with GAE Datastore's Model
I want to make attributes of GAE Model properties. The reason is for cases like to turn the value into uppercase before storing it. For a plain Python class, I would do something like: Foo(db.Model): def get_attr(self): return self.something def set_attr(self, value): self.something = value.upper(...
[ "Subclassing GAE's Property class is especially helpful if you want more than one \"field\" with similar behavior, in one or more models. Don't worry, get_value_for_datastore and make_value_from_datastore are going to get called, on any store and fetch respectively -- so if you need to do anything fancy (including...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002303090_google_app_engine_google_cloud_datastore_python.txt
Q: Python equivalents of the common Perl modules? I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability): DBI + DBD::mysql LWP::UserAgent WWW::Mechanize XML::LibXML HTML::TreeBuilder CGI::FormBuilder Template::T...
Python equivalents of the common Perl modules?
I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability): DBI + DBD::mysql LWP::UserAgent WWW::Mechanize XML::LibXML HTML::TreeBuilder CGI::FormBuilder Template::Toolkit What are the Python equivalents to these?
[ "DBI + DBD::mysql\n\nMySQLdb\n\nLWP::UserAgent\n\nurllib (Python STL)\nurllib2 (Python STL)\n\nWWW::Mechanize\n\nMechanize\n\nXML::LibXML\n\nlibxml2\nlxml\n\nHTML::TreeBuilder\n\nxml.etree.ElementTree (Python STL)\n\nCGI::FormBuilder\n\ncgi and cgitb (Python STL)\n\nTemplate::Toolkit\n\nTemplate-Python\n\nNote: Ite...
[ 15, 14 ]
[]
[]
[ "migration", "perl", "python" ]
stackoverflow_0002333851_migration_perl_python.txt
Q: How do I get my python object back from a QVariant in PyQt4? I am creating a subclass of QAbstractItemModel to be displayed in an QTreeView. My index() and parent() function creates the QModelIndex using the QAbstractItemModel inherited function createIndex and providing it the row, column, and data needed. Here, ...
How do I get my python object back from a QVariant in PyQt4?
I am creating a subclass of QAbstractItemModel to be displayed in an QTreeView. My index() and parent() function creates the QModelIndex using the QAbstractItemModel inherited function createIndex and providing it the row, column, and data needed. Here, for testing purposes, data is a Python string. class TestModel(QAb...
[ "Have you tried this?\nmy_python_object = my_qvariant.toPyObject()\n\nhttp://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject (just for completeness, but there isn't much to see there...)\n", "The key thing is to use internalPointer() directly on the QModelIndex, not dealing with the QVariant at all.\ncla...
[ 13, 5 ]
[]
[]
[ "pyqt4", "python", "qabstractitemmodel", "qvariant" ]
stackoverflow_0002333420_pyqt4_python_qabstractitemmodel_qvariant.txt
Q: Transforming nested Python loops into list comprehensions I've started working on some Project Euler problems, and have solved number 4 with a simple brute force solution: def mprods(a,b): c = range(a,b) f = [] for d in c: for e in c: f.append(d*e) return f max([z for z in mprods(100,1000) if str(z)==(''...
Transforming nested Python loops into list comprehensions
I've started working on some Project Euler problems, and have solved number 4 with a simple brute force solution: def mprods(a,b): c = range(a,b) f = [] for d in c: for e in c: f.append(d*e) return f max([z for z in mprods(100,1000) if str(z)==(''.join([str(z)[-i] for i in range(1,len(str(z))+1)]))]) After s...
[ "c = range(a, b)\nprint [d * e for d in c for e in c]\n\n", "from itertools import product\n\ndef palindrome(i):\n return str(i) == str(i)[::-1]\n\nx = xrange(900,1000)\n\nmax(a*b for (a,b) in (product(x,x)) if palindrome(a*b))\n\n\nxrange(900,1000) is like range(900,1000) but instead of returning a list it retu...
[ 7, 3, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002329165_list_comprehension_python.txt
Q: Jython 2.2.1, howto move a file? shutils.move is non-existant! '''use Jython''' import shutil print dir(shutil) There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython? A: os.rename() to move, and os.unlink() to delete -- just like Python pre-...
Jython 2.2.1, howto move a file? shutils.move is non-existant!
'''use Jython''' import shutil print dir(shutil) There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?
[ "os.rename() to move, and os.unlink() to delete -- just like Python pre-shutil.\n", "If you need support for moving across filesystems, consider just copying CPython's shutil.py into your project. The Python License is flexible enough to allow this (even for commercial projects), as long as licensing and attribut...
[ 4, 1, 0 ]
[]
[]
[ "file_handling", "java", "jython", "python", "shutil" ]
stackoverflow_0000249262_file_handling_java_jython_python_shutil.txt
Q: Django queries: how to make contains OR not_contains queries I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely? Seems something like: Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )...
Django queries: how to make contains OR not_contains queries
I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely? Seems something like: Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )
[ "From the django q object documentation:\n\nYou can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) que...
[ 15 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002334698_django_python.txt
Q: Can distutils use a custom .def to expose extra symbols when it compiles a Windows .dll? I'm abusing distutils to compile an extension module for Python, but rather than using the Python C API I'm using ctypes to talk to the resulting shared library. This works fine in Linux because it automatically exports all sy...
Can distutils use a custom .def to expose extra symbols when it compiles a Windows .dll?
I'm abusing distutils to compile an extension module for Python, but rather than using the Python C API I'm using ctypes to talk to the resulting shared library. This works fine in Linux because it automatically exports all symbols in a shared library, but in Windows distutils provides a .def to export only the Python ...
[ "You can pass ['-Wl,--export-all-symbols'] as extra_link_args if you're using Mingw's GCC. There's probably a similar setting for Visual, somewhere in the IDE.\nThis works only if distutils chooses to use \"gcc -mdll\" as a linker instead of \"dllwrap\". It does so if your ld version is later than 2.10.90, which sh...
[ 1 ]
[]
[]
[ "distutils", "dll", "dllexport", "python", "windows" ]
stackoverflow_0002334754_distutils_dll_dllexport_python_windows.txt
Q: How to quickly (easy to script) preview 3D vectors / lines? I am busy reading 3D building models from a tool and thus generating a bunch of Line(p1, p2) objects, each consisting of two Point(x, y, z) objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only...
How to quickly (easy to script) preview 3D vectors / lines?
I am busy reading 3D building models from a tool and thus generating a bunch of Line(p1, p2) objects, each consisting of two Point(x, y, z) objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D). The reading is done in Python, specifically IronPy...
[ "I'm not a 3D-programming expert but there is a simple trick you can do.\nIf you imagine that the z axis is vertical to your screen then you can project a 3D point (x, y, z) like this: (zoom_factor*(x/z), zoom_factor*(y/z))\n", "You might try the PyQwt3D package. If that doesn't work, here's a list of other pyth...
[ 1, 1, 1, 1 ]
[]
[]
[ ".net", "3d", "ironpython", "python" ]
stackoverflow_0001345485_.net_3d_ironpython_python.txt
Q: A decent SSL library for Python 2.5 I am tasked with migrating a server's networking from plain sockets to SSL in python 2.5, and I've run into a snag. It seems that just about no SSL library out there fully implements the socket interface, so the code we currently have can't be straight migrated. Specifically, I ...
A decent SSL library for Python 2.5
I am tasked with migrating a server's networking from plain sockets to SSL in python 2.5, and I've run into a snag. It seems that just about no SSL library out there fully implements the socket interface, so the code we currently have can't be straight migrated. Specifically, I can't seem to find a library that support...
[ "How about this backport of Python 2.6's ssl module to Python 2.3+? It provides the same functionality described here, which appears to mean that it takes a normal socket.socket and wraps it in an SSL context.\n", "pyOpenSSL seems to support setblocking().\n" ]
[ 2, 0 ]
[]
[]
[ "python", "ssl" ]
stackoverflow_0002334354_python_ssl.txt
Q: Post processing attendance data with Django I have a web app which tries to determine when people are attending events. class Attendee(models.Model): location = models.ForeignKey(Location) user = models.ForeignKey(User) checked_in = models.DateTimeField() checked_out = models.DateTimeField() la...
Post processing attendance data with Django
I have a web app which tries to determine when people are attending events. class Attendee(models.Model): location = models.ForeignKey(Location) user = models.ForeignKey(User) checked_in = models.DateTimeField() checked_out = models.DateTimeField() last_active = models.DateTimeField() An Attendee i...
[ "You don't need a 'Django equivalent to a cron job', you just need a cron job. \nThe cron should run a standalone Django script - you can do this in several different ways, but the easiest way is to create a standalone ./manage.pycommand.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002335239_django_python.txt
Q: What is the scope of a defaulted parameter in Python? When you define a function in Python with an array parameter, what is the scope of that parameter? This example is taken from the Python tutorial: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) Prints: [1] [1, 2] [1, 2, 3] I'm ...
What is the scope of a defaulted parameter in Python?
When you define a function in Python with an array parameter, what is the scope of that parameter? This example is taken from the Python tutorial: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) Prints: [1] [1, 2] [1, 2, 3] I'm not quite sure if I understand what's happening here. Does ...
[ "The scope is as you would expect.\nThe perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].\nThe list is stored in f.__defaults__ (or f.func_defaults in Python 2.)\ndef f(a, L=[]):\n L.a...
[ 25, 7, 3, 2, 1, 0 ]
[ "You have to keep in mind that python is an interpreted language. What is happening here is when the function \"f\" is defined, it creates the list and assigns it to the default parameter \"L\" of function \"f\". Later, when you call this function, the same list is used as the default parameter. In short, the co...
[ -1 ]
[ "default_value", "function_calls", "parameters", "python", "scope" ]
stackoverflow_0002335160_default_value_function_calls_parameters_python_scope.txt
Q: How can I get the window focused on Windows and re-size it? I want to get the focused window so I can resize it... how can I do it? A: Use the GetForegroundWindow Win32 API to get the window handle. Then use the MoveWindow (or SetWindowPos if you prefer) win32 API to resize the window. Working with the Win32 API...
How can I get the window focused on Windows and re-size it?
I want to get the focused window so I can resize it... how can I do it?
[ "Use the GetForegroundWindow Win32 API to get the window handle.\nThen use the MoveWindow (or SetWindowPos if you prefer) win32 API to resize the window.\nWorking with the Win32 API can be done directly with ctypes and working with the dlls or by using the pywin32 project.\nEdit: Sure here is an example (Make sure ...
[ 17 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002335721_python_windows.txt
Q: How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I. Corrupted, to me, is the imag...
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted?
Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I. Corrupted, to me, is the image is loaded into Firefox and it says The image “such and such image” cannot be displaye...
[ "An easy way would be to try loading and verifying the files with PIL (Python Imaging Library).\nfrom PIL import Image\n\nv_image = Image.open(file)\nv_image.verify()\n\nCatch the exceptions...\nFrom the documentation:\nim.verify()\nAttempts to determine if the file is broken, without actually decoding the image da...
[ 27, 7, 5, 3, 0 ]
[]
[]
[ "image", "php", "python" ]
stackoverflow_0001401527_image_php_python.txt
Q: Convert dbus.String to normal string I am using dbus to get the current playing song from Songbird Media Player & Metadata is also taken from dbus object. The line where error comes is:- audio_file = MP3(current_playing_track['location'], ID3=ID3) The error is:- Traceback (most recent call last): File "./last....
Convert dbus.String to normal string
I am using dbus to get the current playing song from Songbird Media Player & Metadata is also taken from dbus object. The line where error comes is:- audio_file = MP3(current_playing_track['location'], ID3=ID3) The error is:- Traceback (most recent call last): File "./last.py", line 42, in <module> audio_file =...
[ "Just do str( your_dbus_string )\n" ]
[ 7 ]
[]
[]
[ "dbus", "python", "string" ]
stackoverflow_0002336127_dbus_python_string.txt
Q: pylint seems to not handle "from . import foo" style imports If I do: from . import foo In a script and run pylint over it, I get: F: 1: Unable to import %r Is there a way a work around for getting pylint to understand this syntax? A: Update to at least pylint 0.18.1 / logilab-astng 0.19.1? A: Note that th...
pylint seems to not handle "from . import foo" style imports
If I do: from . import foo In a script and run pylint over it, I get: F: 1: Unable to import %r Is there a way a work around for getting pylint to understand this syntax?
[ "Update to at least pylint 0.18.1 / logilab-astng 0.19.1?\n", "Note that the \"from . import smthg\" is only allowed in a Python package. \nI've tested this with \npylint --version\nNo config file found, using default configuration\npylint 0.19.0, \nastng 0.19.1, common 0.46.0\nPython 2.5.5 (r255:77872, Feb 1 20...
[ 0, 0 ]
[]
[]
[ "import", "pylint", "python" ]
stackoverflow_0002142810_import_pylint_python.txt
Q: How does pylint quit the Windows command box it is running in? Pylint is doing something odd on my Windows box - something that shouldn't be possible. This isn't a question about fixing pylint, so much as fixing my understanding. I have a typical install of the latest version of pylint, Python 2.6 and Windows Vist...
How does pylint quit the Windows command box it is running in?
Pylint is doing something odd on my Windows box - something that shouldn't be possible. This isn't a question about fixing pylint, so much as fixing my understanding. I have a typical install of the latest version of pylint, Python 2.6 and Windows Vista. If I open a Command Prompt, and run pylint from the command line,...
[ "I just tried this on XP:\nt.bat:\n\nexit\n\nRunning this closes the window!\nMaybe the command line for pylint uses a batch file which contains an exit?\n", "This is a very easy fix. Go into your python scripts folder and locate pylint.bat and open it in notepad.\nIt will read the following\n@echo off\nrem = \"...
[ 2, 1, 1 ]
[]
[]
[ "command_line", "errorlevel", "pylint", "python", "windows_vista" ]
stackoverflow_0001719898_command_line_errorlevel_pylint_python_windows_vista.txt
Q: Parse timezone abbreviation to UTC How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch? Currently my best approach is to use time.strptime() is this: def to_unixepoch(s): # ignore the time zone in strptime a = s.split() b = time.strptime(" ".join(a[:-1]) + " UTC...
Parse timezone abbreviation to UTC
How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch? Currently my best approach is to use time.strptime() is this: def to_unixepoch(s): # ignore the time zone in strptime a = s.split() b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z") # this p...
[ "The Python standard library does not really implement time zones. You should use python-dateutil. It provides useful extensions to the standard datetime module including a time zones implementation and a parser.\nYou can convert time zone aware datetime objects to UTC with .astimezone(dateutil.tz.tzutc()). For the...
[ 7 ]
[]
[]
[ "datetime", "python", "pytz", "time", "timezone" ]
stackoverflow_0002335405_datetime_python_pytz_time_timezone.txt
Q: Tcl/Tk Tkinter version 8.4 and 8.5 conflict on Mac Os X 10.4.11 with python 2.6.4 I am having trouble getting Tkinter up and runnning in order to install matplot lib. I am running Mac OS X 10.4.11, and just installed Python 2.6.4 . After several other fights, one remaining battle for me to get matlotlib installed...
Tcl/Tk Tkinter version 8.4 and 8.5 conflict on Mac Os X 10.4.11 with python 2.6.4
I am having trouble getting Tkinter up and runnning in order to install matplot lib. I am running Mac OS X 10.4.11, and just installed Python 2.6.4 . After several other fights, one remaining battle for me to get matlotlib installed is to have a working version of Tkinter, although there are several in my Mac from Xco...
[ "I think the important point from previous solutions proposed was that Python, upon install, detects the correct version and location of Tk. I assume you installed Tk after installing Python. This problem was solved on my machine when I reinstalled Python2.6 using the .dmg installer. I didn't need to rebuild or any...
[ 2 ]
[]
[]
[ "macos", "python", "tk_toolkit", "tkinter" ]
stackoverflow_0002247971_macos_python_tk_toolkit_tkinter.txt
Q: How do I make a command line program that takes arguments? How can I make a command line, so I can execute my program on Windows with some parameters... For example: C:/Program/App.exe -safemode A: have a look at the getopt and optparse modules from the standard lib, many good things could be also said about mor...
How do I make a command line program that takes arguments?
How can I make a command line, so I can execute my program on Windows with some parameters... For example: C:/Program/App.exe -safemode
[ "have a look at the getopt and optparse modules from the standard lib, many good things could be also said about more advanced argparse module.\nGenerally you just need to access sys.argv.\n", "I sense that you also want to generate an 'executable' that you can run standalone.... For that you use py2exe\nHere is ...
[ 9, 7, 3, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "command_line", "python", "windows" ]
stackoverflow_0002335989_command_line_python_windows.txt
Q: Customizing the language-guessing algorithm in Django I'm developing a multilingual Django website. It has two languages, English and Hebrew. I want the default language for every first-time visitor to be Hebrew, regardless of what his browser's Accept-Language is. Of course, if he changes language to English (and...
Customizing the language-guessing algorithm in Django
I'm developing a multilingual Django website. It has two languages, English and Hebrew. I want the default language for every first-time visitor to be Hebrew, regardless of what his browser's Accept-Language is. Of course, if he changes language to English (and thus gets the language cookie or the key in the session), ...
[ "Start by reading this: http://docs.djangoproject.com/en/1.1/topics/i18n/#topics-i18n\nThen read this: http://docs.djangoproject.com/en/1.1/topics/i18n/internationalization/#topics-i18n-internationalization\n\nEach RequestContext has access to\n three translation-specific variables:\nLANGUAGES is a list of tuples ...
[ 0, 0 ]
[]
[]
[ "django", "django_multilingual", "python" ]
stackoverflow_0002334402_django_django_multilingual_python.txt
Q: How to parse a single line csv string without the csv.reader iterator in python? I have a CSV file that i need to rearrange and renecode. I'd like to run line = line.decode('windows-1250').encode('utf-8') on each line before it's parsed and split by the CSV reader. Or I'd like iterate over lines myself run the re...
How to parse a single line csv string without the csv.reader iterator in python?
I have a CSV file that i need to rearrange and renecode. I'd like to run line = line.decode('windows-1250').encode('utf-8') on each line before it's parsed and split by the CSV reader. Or I'd like iterate over lines myself run the re-encoding and use just single line parsing form CSV library but with the same reader i...
[ "Loop over lines on file can be done this way:\nwith open('path/to/my/file.csv', 'r') as f:\n for line in f:\n puts line # here You can convert encoding and save lines\n\nBut if You want to convert encoding of a whole file You can also call:\n$ iconv -f Windows-1250 -t UTF8 < file.csv > file.csv\n\nEdit: ...
[ 2, 2, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002334436_csv_python.txt
Q: What's the best module to access SimpleDB in python? I'm writing a python script to select, insert, update, and delete data in SimpleDB. I've been using the simpledb module written by sixapart so far, and it's working pretty well. I've found one potential bug/feature that is problematic for me when running select ...
What's the best module to access SimpleDB in python?
I'm writing a python script to select, insert, update, and delete data in SimpleDB. I've been using the simpledb module written by sixapart so far, and it's working pretty well. I've found one potential bug/feature that is problematic for me when running select queries with "limit", and I'm thinking of trying it with t...
[ "I've found boto to be effective and straight forward and I've never had any trouble with queries with limits. Although I've never used the sixapart module. \n" ]
[ 3 ]
[]
[]
[ "amazon_simpledb", "python" ]
stackoverflow_0002336822_amazon_simpledb_python.txt
Q: Is it possible to read Fortran formatted data in Python? I get output files from very old Fortran programs, which look like: 0.81667E+00 -0.12650E+01 -0.69389E-03 0.94381E+00 -0.11985E+01 -0.11502E+00 0.96064E+00 -0.11333E+01 -0.17616E+00 0.10202E+01 -0.12435E+01 -0.93917E-01 0.10026E+01 -0.10904E+01...
Is it possible to read Fortran formatted data in Python?
I get output files from very old Fortran programs, which look like: 0.81667E+00 -0.12650E+01 -0.69389E-03 0.94381E+00 -0.11985E+01 -0.11502E+00 0.96064E+00 -0.11333E+01 -0.17616E+00 0.10202E+01 -0.12435E+01 -0.93917E-01 0.10026E+01 -0.10904E+01 -0.15108E+00 0.90516E+00 -0.11030E+01 -0.19139E+00 0.986...
[ "Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> float('-0.69389E-03')\n-0.00069388999999999996\n\n", ">>> line=\"0.81667E+00 -0.12650E+01 -0.69389E-03\"\n>>> map(float,line.spli...
[ 4, 2 ]
[]
[]
[ "floating_point", "format", "fortran", "python" ]
stackoverflow_0002336301_floating_point_format_fortran_python.txt
Q: Python code optimization (20x slower than C) I've written this very badly optimized C code that does a simple math calculation: #include <stdio.h> #include <math.h> #include <stdlib.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) unsigned long long int p(int); float full...
Python code optimization (20x slower than C)
I've written this very badly optimized C code that does a simple math calculation: #include <stdio.h> #include <math.h> #include <stdlib.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) unsigned long long int p(int); float fullCheck(int); int main(int argc, char **argv){ i...
[ "Since quickCheck is being called close to 25,000,000 times, you might want to use memoization to cache the answers.\nYou can do memoization in C as well as Python. Things will be much faster in C, also.\nYou're computing 1/6 in each iteration of quickCheck. I'm not sure if this will be optimized out by Python, b...
[ 17, 10, 5, 4, 2, 1 ]
[]
[]
[ "math", "optimization", "performance", "python" ]
stackoverflow_0002328495_math_optimization_performance_python.txt
Q: How can I figure out in my module if the main program uses a specific variable? I know this does not sound Pythonic, but bear with me for a second. I am writing a module that depends on some external closed-source module. That module needs to get instantiated to be used (using module.create()). My module attempts ...
How can I figure out in my module if the main program uses a specific variable?
I know this does not sound Pythonic, but bear with me for a second. I am writing a module that depends on some external closed-source module. That module needs to get instantiated to be used (using module.create()). My module attempts to figure out if my user already loaded that module (easy to do), but then needs to f...
[ "Looks like your code assumes that the .create() function was called, if at all, by the immediate/direct caller of your function (which you show only partially, making it pretty hard to be sure about what's going on) and the results placed in a global variable (of the module where the caller of your function reside...
[ 1, 0 ]
[]
[]
[ "global_variables", "python", "python_module" ]
stackoverflow_0002336868_global_variables_python_python_module.txt
Q: Convert SQL query to Django friendly format for application I have an SQL query thats runs on the Postgres database of my Django based webapp. The query runs against the data stored by Django-Notifications (a reusable app) and returns a list of email addresses that have not opted out of a specific notice type. Wh...
Convert SQL query to Django friendly format for application
I have an SQL query thats runs on the Postgres database of my Django based webapp. The query runs against the data stored by Django-Notifications (a reusable app) and returns a list of email addresses that have not opted out of a specific notice type. What I would really like to be able to do is to build an applicatio...
[ "You might have to make appropriate adjustments as far as model names go, since you didn't show them in your question:\nusers_to_exclude = Noticesetting.objects.filter(send=False, notice_type__label='announcement').values('user')\nemails = Emailaddress.objects.exclude(user__in=users_to_exclude)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python", "sql" ]
stackoverflow_0002337333_django_django_models_python_sql.txt
Q: django-tinymce: Using different options for different instances I have a model with an HTMLField which can be edited with a TinyMCE control in the admin. However, I would like to be able to give different options to TinyMCE depending on which instance of the model is being edited. How can I do this? (For example, ...
django-tinymce: Using different options for different instances
I have a model with an HTMLField which can be edited with a TinyMCE control in the admin. However, I would like to be able to give different options to TinyMCE depending on which instance of the model is being edited. How can I do this? (For example, if the user is editing the SimplePage instance whose slug is technolo...
[ "I guess you have a Media class in your ModelAdmin with additional JavaScript and CSS for the admin (like here). Your JavaScript doesn't know the slug of the current object, let's change that.\nFirst create one of the following directory structures in your templates directory: \"admin/your-app\" for an app or \"adm...
[ 1 ]
[]
[]
[ "django", "django_tinymce", "python", "tinymce" ]
stackoverflow_0002310835_django_django_tinymce_python_tinymce.txt
Q: Output of python scripts displayed only at termination when using SSH? I'm running a script to manage processes on a remote (SSH) machine. Let's call it five.py #!/usr/bin/python import time, subprocess subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) print(i) If i now run ssh user@...
Output of python scripts displayed only at termination when using SSH?
I'm running a script to manage processes on a remote (SSH) machine. Let's call it five.py #!/usr/bin/python import time, subprocess subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) print(i) If i now run ssh user@host five.py I would like to see the output 0 1 2 3 4 appear on my standa...
[ "You can add the -u on the shebang line as interjay hinted\n#!/usr/bin/python -u\n\nYou could also reopen stdout with buffering turned off or set to line buffering\nimport os,sys\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering...
[ 7, 0, 0 ]
[]
[]
[ "python", "ssh", "stdout" ]
stackoverflow_0002336270_python_ssh_stdout.txt
Q: Is it a bad idea to change the app_label assignment on existing Django models? I have the hair-brained idea of grouping models from different existing apps into one big new shiny app. There's not a super important reason I need to do this, but it would be nice to consolidate all of the code in one subdirectory and...
Is it a bad idea to change the app_label assignment on existing Django models?
I have the hair-brained idea of grouping models from different existing apps into one big new shiny app. There's not a super important reason I need to do this, but it would be nice to consolidate all of the code in one subdirectory and it would improve the site to group all the models together in the admin_index under...
[ "You're correct that moving models around would render existing ContentType entries useless. Without knowing the specifics of your project it's hard to say what might be a \"good idea\". You might just try branching your code, making the changes, and updating the content types and permissions tables to reflect. Alt...
[ 0 ]
[]
[]
[ "admin", "django", "models", "python", "templates" ]
stackoverflow_0002337259_admin_django_models_python_templates.txt
Q: Exceeding the size of lists in python I'm trying to implement the sieve of eratosthenes in python, however when trying to find all primes up to the sqare root of for instance 779695003923747564589111193840021 I get an error saying result of range() has too many items. My question is, how do I avoid this problem, i...
Exceeding the size of lists in python
I'm trying to implement the sieve of eratosthenes in python, however when trying to find all primes up to the sqare root of for instance 779695003923747564589111193840021 I get an error saying result of range() has too many items. My question is, how do I avoid this problem, if I instantiate the list with a while loop ...
[ "I would say, \"use xrange() instead\", but you are actually using the list of ints as the sieve result..... So an integer generator is not a correct solution.\nI think it will be difficult to materialize a list with 39312312323123123 elements in it, no matter what function you use to do so.... That is, after all,...
[ 6, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "memory", "prime_factoring", "python", "sieve_of_eratosthenes" ]
stackoverflow_0002337700_memory_prime_factoring_python_sieve_of_eratosthenes.txt
Q: Requesting advice on persisting objects from a dynamic language to a document database Do you have any insights into the most elegant way of persisting objects from a dynamic language in a document database? I have a solid background in C# and have just started programming in Python. At the same time I am trying t...
Requesting advice on persisting objects from a dynamic language to a document database
Do you have any insights into the most elegant way of persisting objects from a dynamic language in a document database? I have a solid background in C# and have just started programming in Python. At the same time I am trying to learn the ropes of MongoDB. Now I am wondering: what is the most elegant way to persist m...
[ "Python defines several special methods such as getstate and many others to allow your classes to define exactly how best to serialize and de-serialize their instances. They're all used internally by the pickle module (which then uses this information to produce a \"blob\", i.e. a string of bytes, and restore obje...
[ 1 ]
[]
[]
[ "dynamic_languages", "mongodb", "nosql", "orm", "python" ]
stackoverflow_0002337819_dynamic_languages_mongodb_nosql_orm_python.txt
Q: Pickling array.array in 2.4 using cPickle I am working on a project built on python 2.4 (It is an embedded python project, so I don't have a choice on the version of python used). Throughout the application, we use array.array to store data. Support for pickling array.array objects was added to pickle (and cPickl...
Pickling array.array in 2.4 using cPickle
I am working on a project built on python 2.4 (It is an embedded python project, so I don't have a choice on the version of python used). Throughout the application, we use array.array to store data. Support for pickling array.array objects was added to pickle (and cPickle) in 2.5. We have a viable workaround in 2.4 ...
[ "You can use the standard library module copy_reg to register functions to deal with pickling instances of types that don't natively support pickling; cPickle will use your registered functions where needed. I'd apply exactly this \"hook\" approach to your requirement of pickling instances of array.array.\n", "I...
[ 2, 1, 1 ]
[]
[]
[ "monkeypatching", "pickle", "python", "python_2.4" ]
stackoverflow_0002338001_monkeypatching_pickle_python_python_2.4.txt
Q: Keeping ORM with stored procedures I am developing a Python web app using sqlalchemy to communicate with mysql database. So far I have mostly been using sqlalchemy's ORM layer to speak with the database. The greatest benefit to me of ORM has been the speed of development, not having to write all these sql queries ...
Keeping ORM with stored procedures
I am developing a Python web app using sqlalchemy to communicate with mysql database. So far I have mostly been using sqlalchemy's ORM layer to speak with the database. The greatest benefit to me of ORM has been the speed of development, not having to write all these sql queries and then map them to models. Recently, h...
[ "SQLAlchemy doesn't have any good way to convert inserts, updates and deletes to stored procedure calls. It probably wouldn't be that hard to add the capability to have instead_{update,insert,delete} extensions on mappers, but no one has bothered yet. I consider the requirement to have simple DML statements go thro...
[ 3 ]
[]
[]
[ "database", "mysql", "python", "sqlalchemy", "stored_procedures" ]
stackoverflow_0002330278_database_mysql_python_sqlalchemy_stored_procedures.txt
Q: python, hash function selection Using Python and Django, I will let my users to give pdf based gifts to their friends, which the said friend will be able to claim pdf by entering to my site from the emailed link. Here is the plan User gives a gives to his friend, enters friends email In the background, a gift mod...
python, hash function selection
Using Python and Django, I will let my users to give pdf based gifts to their friends, which the said friend will be able to claim pdf by entering to my site from the emailed link. Here is the plan User gives a gives to his friend, enters friends email In the background, a gift model is saved which will contain a uniq...
[ "There is no need to use a hash, you just need a random token.\n\nCreate a string of random characters \nIf it is already used ( unlikely ) repeat step 1\n\nMake the string of characters long enough that you are happy it will be hard to guess \nan easy way to generate a random string is\n>>> import os\n>>> os.uran...
[ 6, 1, 0 ]
[]
[]
[ "django", "hash", "hashcode", "python" ]
stackoverflow_0002337825_django_hash_hashcode_python.txt
Q: In SciPy, using ix_() with sparse matrices doesn't seem to work so what else can I use? In Numpy, ix_() is used to grab rows and columns of a matrix, but it doesn't seem to work with sparse matrices. For instance, this code works because it uses a dense matrix: >>> import numpy as np >>> x = np.mat([[1,0,3],[0,4,5...
In SciPy, using ix_() with sparse matrices doesn't seem to work so what else can I use?
In Numpy, ix_() is used to grab rows and columns of a matrix, but it doesn't seem to work with sparse matrices. For instance, this code works because it uses a dense matrix: >>> import numpy as np >>> x = np.mat([[1,0,3],[0,4,5],[7,8,0]]) >>> print x [[1 0 3] [0 4 5] [7 8 0]] >>> print x[np.ix_([0,2],[0,2])] [[1 3] ...
[ "Try this instead:\n>>> print xspar\n (0, 0) 1\n (0, 2) 3\n (1, 1) 4\n (1, 2) 5\n (2, 0) 7\n (2, 1) 8\n>>> print xspar[[[0],[2]],[0,2]]\n (0, 0) 1\n (0, 2) 3\n (2, 0) 7\n\nNote the difference with this:\n>>> print xspar[[0,2],[0,2]]\n [[1 0]]\n\n" ]
[ 2 ]
[]
[]
[ "indexing", "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0002338260_indexing_numpy_python_scipy_sparse_matrix.txt
Q: parse xhtml in python 2.6 xml.etree.ElementTree.parse is choking on my xhtml file. I saw somewhere that lxml can handle html. Can someone tell me the documented way to parse, and then alter, xhtml? I want to add some javascript to xhtml on the fly. A: Have you tried BeautifulSoup? It handles documents that aren'...
parse xhtml in python 2.6
xml.etree.ElementTree.parse is choking on my xhtml file. I saw somewhere that lxml can handle html. Can someone tell me the documented way to parse, and then alter, xhtml? I want to add some javascript to xhtml on the fly.
[ "Have you tried BeautifulSoup? It handles documents that aren't well formed and I've found it pretty good.\n" ]
[ 3 ]
[]
[]
[ "python", "xhtml" ]
stackoverflow_0002338533_python_xhtml.txt
Q: Grabbing a random frame from a webcam with GStreamer in Python I'm trying to write a program to control a robot by interpreting frames from a webcam and happened upon GStreamer. I've been able to stream video in Python from the webcam with GStreamer with help from this page: http://www.ndeschildre.net/2008/04/04/p...
Grabbing a random frame from a webcam with GStreamer in Python
I'm trying to write a program to control a robot by interpreting frames from a webcam and happened upon GStreamer. I've been able to stream video in Python from the webcam with GStreamer with help from this page: http://www.ndeschildre.net/2008/04/04/python-power/ However, I don't know how to ask for a single RGB-encod...
[ "Look at the source code for cheese, the Gnome photobooth application.\nYou could also try the usersink.\n", "I've heard of some success with OpenCV's Python bindings. Here is one of those successes: http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/\n" ]
[ 1, 1 ]
[]
[]
[ "gstreamer", "python", "snapshot", "webcam" ]
stackoverflow_0002337147_gstreamer_python_snapshot_webcam.txt
Q: Why can't a Deferred be passed to a callback in Python Twisted? d = Deferred() d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed Why is this? I looked through the code and commit messages / Trac and see no reason why this should be the case. The most obvious way to bypass this is...
Why can't a Deferred be passed to a callback in Python Twisted?
d = Deferred() d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed Why is this? I looked through the code and commit messages / Trac and see no reason why this should be the case. The most obvious way to bypass this is to put the Deferred in a tuple, but why is this restriction here in ...
[ "There are two related reasons for this.\nFirst, it helps catch what is likely a mistake early - near the place where the mistake is being made. A Deferred is called back with a result which is then passed to all of its callbacks. If you make the result itself a Deferred, then there's not much these callbacks can...
[ 5 ]
[]
[]
[ "deferred_execution", "python", "twisted" ]
stackoverflow_0002321577_deferred_execution_python_twisted.txt
Q: QSqlTableModel, data function overload I'm trying to inherit QSqlTableModel to make data im my table display in way i need. class TableViewModel(QSqlTableModel): def __init__(self): super(TableViewModel, self).__init__() def flags(self, modelIndex): if not modelIndex.isValid(): ...
QSqlTableModel, data function overload
I'm trying to inherit QSqlTableModel to make data im my table display in way i need. class TableViewModel(QSqlTableModel): def __init__(self): super(TableViewModel, self).__init__() def flags(self, modelIndex): if not modelIndex.isValid(): return if modelIndex.column() != ...
[ "I'm not sure what that record.value is supposed to be (no indication in your code of where that record variable lives or how or when it's set). Anyway, for \"getting data from QSqlTableModel\" (whereby I assume you mean the base class you're subclassing), use\nwhatever = QSqlTableModel.data(self, modelIndex, role...
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0002338276_pyqt_python.txt
Q: How can I order elements in this case? - Django So I have a list of models, don't think the structure of these models is important. In this case Articles. So these Articles are ordered by popularity between a rank of 1 to 100, all the other articles have no ranks. Whenever I update the rank of a model the model w...
How can I order elements in this case? - Django
So I have a list of models, don't think the structure of these models is important. In this case Articles. So these Articles are ordered by popularity between a rank of 1 to 100, all the other articles have no ranks. Whenever I update the rank of a model the model with equivalent rank must loose its rank. Any ideas?
[ "Do you mean something like this?\ndef update_rank(rank, article):\n old = Article.object.get(rank=rank)\n old.rank = None\n old.save()\n article.rank = rank\n article.save()\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002339203_django_django_models_python.txt
Q: How can I run a py2exe program in windows without the terminal? Could someone explain to me how can I run my py2exe program, a console program, without the terminal on Windows? I'm trying to make a program that re-sizes windows and it supposed to start with windows, so I want it hide out but still running... A: ...
How can I run a py2exe program in windows without the terminal?
Could someone explain to me how can I run my py2exe program, a console program, without the terminal on Windows? I'm trying to make a program that re-sizes windows and it supposed to start with windows, so I want it hide out but still running...
[ "Use the setup() function like this:\nsetup(windows=['myfile.py'])\nSee the list of options for setup().\n", "Not really understand your requirement, but you can try start /MIN. type start /? on the command line to see its help page.\n", "Would you consider compiling it into an EXE (using py2exe or some such) a...
[ 4, 0, 0, 0 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0002338951_py2exe_python_windows.txt
Q: Any way of achieving the same thing as python -mpdb from inside the script? Besides wrapping all your code in try except, is there any way of achieving the same thing as running your script like python -mpdb script? I'd like to be able to see what went wrong when an exception gets raised. A: If you do not want t...
Any way of achieving the same thing as python -mpdb from inside the script?
Besides wrapping all your code in try except, is there any way of achieving the same thing as running your script like python -mpdb script? I'd like to be able to see what went wrong when an exception gets raised.
[ "If you do not want to modify the source then yOu could run it from ipython - an enhanced interactive python shell.\ne.g. run ipython then execute %pdb on to enable post-mortem debugging. %run scriptname will then run the script and automatically enter the debugger on any uncaught exceptions.\nAlternatively %run -...
[ 3, 1 ]
[ "import pdb; pdb.set_trace()\nSource: http://docs.python.org/library/pdb.html\n" ]
[ -1 ]
[ "debugging", "pdb", "python" ]
stackoverflow_0002337216_debugging_pdb_python.txt
Q: RGB to VIBGYOR in python After downloading an image and getting the rgb color code is there any algorithm to find in which range of VIBGYOR that particular rgb color code match? regards Arun A: The color range for VIBGYOR (or spectral colors) isn't the same as RGB. Check out wikipedia on color: http://en.wiki...
RGB to VIBGYOR in python
After downloading an image and getting the rgb color code is there any algorithm to find in which range of VIBGYOR that particular rgb color code match? regards Arun
[ "The color range for VIBGYOR (or spectral colors) isn't the same as RGB. \nCheck out wikipedia on color:\nhttp://en.wikipedia.org/wiki/Color\nPay special attention to \"Spectral colors and color reproduction\"\nAn example of the issue is that pink and magenta are nonspectral colors. In addition, the spectral color ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002339554_python.txt
Q: Workaround for python 2.4's yield not allowed in try block with finally clause I'm stuck on python2.4, so I can't use a finally clause with generators or yield. Is there any way to work around this? I can't find any mentions of how to work around this limitation in python 2.4, and I'm not a big fan of the workaro...
Workaround for python 2.4's yield not allowed in try block with finally clause
I'm stuck on python2.4, so I can't use a finally clause with generators or yield. Is there any way to work around this? I can't find any mentions of how to work around this limitation in python 2.4, and I'm not a big fan of the workarounds I've thought of (mainly involving __del__ and trying to make sure it runs withi...
[ "You can duplicate code to avoid the finally block:\ntry:\n yield 42\nfinally:\n do_something()\n\nBecomes:\ntry:\n yield 42\nexcept: # bare except, catches *anything*\n do_something()\n raise # re-raise same exception\ndo_something()\n\n(I've not tried this on Python 2.4, you may have to look at sys.exc_inf...
[ 7, 3 ]
[]
[]
[ "python", "python_2.4", "try_finally", "yield" ]
stackoverflow_0002339358_python_python_2.4_try_finally_yield.txt
Q: Transaction within transaction I want to know if open a transaction inside another is safe and encouraged? I have a method: def foo(): session.begin try: stuffs except Exception, e: session.rollback() raise e session.commit() and a method that calls the first one, insid...
Transaction within transaction
I want to know if open a transaction inside another is safe and encouraged? I have a method: def foo(): session.begin try: stuffs except Exception, e: session.rollback() raise e session.commit() and a method that calls the first one, inside a transaction: def bar(): stuf...
[ "There are two ways to nest transactions in SQLAlchemy. One is virtual transactions, where SQLAlchemy keeps track of how many begin's you have issued and issues the commit only when the outermost transaction commits. The rollback however is issued immediately. Because the transaction is virtual - i.e. the database ...
[ 19, 0, 0 ]
[]
[]
[ "database", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0002336950_database_postgresql_python_sqlalchemy.txt
Q: Better way to represent Many to many relationship in django admin I have a unique problem the way it should be handled in django admin. I have following models structure... class Product(models.Model): name = models.CharField(max_length = 100) base_price = models.DecimalField(max_digits = 5, decimal_pla...
Better way to represent Many to many relationship in django admin
I have a unique problem the way it should be handled in django admin. I have following models structure... class Product(models.Model): name = models.CharField(max_length = 100) base_price = models.DecimalField(max_digits = 5, decimal_places = 2) def __unicode__(self): return self.name class ...
[ "I got the solution, here is my answer to my question... Let me share it with you... I changed the model in following way....\nclass Product(models.Model):\n name = models.CharField(max_length = 100)\n base_price = models.DecimalField(max_digits = 5, decimal_places = 2)\n\n\n def __unicode__(self):\n ...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002332238_django_django_admin_django_models_python.txt
Q: Why copy post data in Django instead of working with it directly? Django code samples involving post data often shows code similar to this: if request.method == "POST": post = request.POST.copy() #do stuff with post data Is there a reason for copying the post data instead of working with it directly? A: I...
Why copy post data in Django instead of working with it directly?
Django code samples involving post data often shows code similar to this: if request.method == "POST": post = request.POST.copy() #do stuff with post data Is there a reason for copying the post data instead of working with it directly?
[ "I think it is because request.POST itself is defined immutable. If you want a version you can actually change (mutability), you need a copy of the data to work with.\nSee this link (request.POST is a QueryDict instance).\n\n\nclass QueryDict\nQueryDict instances are immutable, unless you create a copy() of them. T...
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002339857_django_python.txt
Q: Django slugified urls - how to handle collisions? I'm currently working on a toy project in Django. Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url. So, if a user writes a review called "The best thing ever!", the url would be something like: ...
Django slugified urls - how to handle collisions?
I'm currently working on a toy project in Django. Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url. So, if a user writes a review called "The best thing ever!", the url would be something like: www.example.com/reviews/the-best-thing-ever. That's a...
[ "I would recommend something like AutoSlugField. It has a few options available with respect to configuring uniqueness (unique and unique_with), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.\n", "One thing I never liked about the u...
[ 6, 6, 2, 0 ]
[]
[]
[ "collision", "django", "python", "slug", "url" ]
stackoverflow_0001490559_collision_django_python_slug_url.txt
Q: Why isn't Python installed on Windows by default? Or any other normal scripting language for that matter. I know there is VBScript and JScript. But I don't really like those for any kind of computing. I would really love to have python or ruby (or perl) interpreter installed with windows by default so when I write...
Why isn't Python installed on Windows by default?
Or any other normal scripting language for that matter. I know there is VBScript and JScript. But I don't really like those for any kind of computing. I would really love to have python or ruby (or perl) interpreter installed with windows by default so when I write small console applications I wouldn't need to distribu...
[ "Microsoft makes it pretty obvious they want you to use their version of everything. So what is in it for them to have Python or any other language as part of their Windows operating system? \nThey want you to program for Microsoft Internet Explorer using Microsoft Active Server Pages with Microsoft Visual Basi...
[ 6, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "default", "python", "ruby", "windows" ]
stackoverflow_0002340150_default_python_ruby_windows.txt
Q: How can I make URLs in Django similar to stackoverflow? I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questi...
How can I make URLs in Django similar to stackoverflow?
I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questions/id is the only part of the url that matters. How can I do...
[ "Stack Overflow uses the form\nexample.com/watch/1/this-is-a-slug\n\nwhich is easier to handle. You're opening a can of worms if you want the ID to be at the end of the slug token, since then it'll (for example) restrict what kinds of slugs you can use, or just make it harder on yourself.\nYou can use a url handler...
[ 9, 0 ]
[ "With all due respect to Stackoverflow, this is the wrong way to do it. You shouldn't need to have two elements in the URL that identify the page. The ID is irrelevant - it's junk. You should be able to uniquely identify a page from the slug alone.\n" ]
[ -3 ]
[ "django", "friendly_url", "python", "slug", "url" ]
stackoverflow_0002339436_django_friendly_url_python_slug_url.txt
Q: Set a DTD using minidom in python I am trying to include a reference to a DTD in my XML doc using minidom. I am creating the document like: doc = Document() foo = doc.createElement('foo') doc.appendChild(foo) doc.toxml() This gives me: <?xml version="1.0" ?> <foo/> I need to get something like: <?xml version="1...
Set a DTD using minidom in python
I am trying to include a reference to a DTD in my XML doc using minidom. I am creating the document like: doc = Document() foo = doc.createElement('foo') doc.appendChild(foo) doc.toxml() This gives me: <?xml version="1.0" ?> <foo/> I need to get something like: <?xml version="1.0" ?> <!DOCTYPE something SYSTEM "http...
[ "The documentation is out of date. Use the source, Luke. I do it something like this.\nfrom xml.dom.minidom import DOMImplementation\n\nimp = DOMImplementation()\ndoctype = imp.createDocumentType(\n qualifiedName='foo',\n publicId='', \n systemId='http://www.path.to.my.dtd.com/my.dtd',\n)\ndoc = imp.create...
[ 9, 1 ]
[]
[]
[ "dtd", "minidom", "python", "xml" ]
stackoverflow_0002337285_dtd_minidom_python_xml.txt
Q: web2py, OAuth and LinkedIn I am new to Python and Web2py and I am developing an app that will use the LinkedIn API. I use this library http://code.google.com/p/python-linkedin/ (it includes OAuth). My problem is very strange and that's why I am writing to the list. When I try to connect to LinkedIn from the web2py...
web2py, OAuth and LinkedIn
I am new to Python and Web2py and I am developing an app that will use the LinkedIn API. I use this library http://code.google.com/p/python-linkedin/ (it includes OAuth). My problem is very strange and that's why I am writing to the list. When I try to connect to LinkedIn from the web2py console I get a request Token. ...
[ "I just tried and it works but:\n1) make sure you run this on the same hostname that you registered with linkedin\n2) pass a full RETURN_URL, not a relative URL as returned by URL\ndef index():\n import linkedin\n from linkedin import linkedin\n RETURN_URL = \"http://web2py.com/linkedin/default/hello\"\n api = ...
[ 1, 0 ]
[]
[]
[ "linkedin", "oauth", "python", "web2py" ]
stackoverflow_0002312464_linkedin_oauth_python_web2py.txt
Q: SVN pre-commit hook to reject Python files with inconsistent tab usage The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage. I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file bei...
SVN pre-commit hook to reject Python files with inconsistent tab usage
The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage. I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file being committed to python -tt but my problem is that the file is also executed,...
[ "You can do this using the py_compile module:\n$ python -tt -c \"import py_compile; py_compile.compile('test.py', doraise=True)\"\n\nThe doraise=True will raise an exception and return with a nonzero exit code that you can easily test in your pre-commit hook.\n", "The preferred tab usage in Python is no tab usage...
[ 6, 2 ]
[]
[]
[ "pre_commit_hook", "python", "svn" ]
stackoverflow_0002341011_pre_commit_hook_python_svn.txt
Q: Logout functionality in django All In django project if 2 template windows are opened and if logout is triggered in 1 window the other window cookies are not cleared.How to delete the cookies also so that the logout will be triggered. def logout(request): //request = redirect('webbie.home.views.loginpage') ...
Logout functionality in django
All In django project if 2 template windows are opened and if logout is triggered in 1 window the other window cookies are not cleared.How to delete the cookies also so that the logout will be triggered. def logout(request): //request = redirect('webbie.home.views.loginpage') //request.delete_cookie('user_loca...
[ "In the cookie you should only store a session key. The server then needs to keep track of all session keys and associate expire date/time and user-account with them. For every user that logs in they should be given a new session key, though you may allow multiple logins/user-account. So when you check if the cooki...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002339941_django_python.txt
Q: As a Java programmer learning Python, what should I look out for? Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. ...
As a Java programmer learning Python, what should I look out for?
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I sho...
[ "\nDon't put everything into classes. Python's built-in list and dictionaries will take you far.\nDon't worry about keeping one class per module. Divide modules by purpose, not by class.\nUse inheritance for behavior, not interfaces. Don't create an \"Animal\" class for \"Dog\" and \"Cat\" to inherit from, just so ...
[ 25, 23, 14, 10, 7, 6, 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002339371_java_python.txt
Q: unladen-swallow with numpy/scipy has anyone used unladen-swallow with numpy/scipy for numeric/scientific applications? Is it significantly faster in your experience? Any opinions would be great. A: Nobody has extensive experience with Unladen Swallow yet (except the developers), so it's going to be difficult t...
unladen-swallow with numpy/scipy
has anyone used unladen-swallow with numpy/scipy for numeric/scientific applications? Is it significantly faster in your experience? Any opinions would be great.
[ "Nobody has extensive experience with Unladen Swallow yet (except the developers), so it's going to be difficult to find many people who can discuss it. Also, with the talk of merging Unladen Swallow (which is built using LLVM) with the CPython runtime, things are going to be something of a moving target until eve...
[ 5, 1, 1 ]
[]
[]
[ "numpy", "optimization", "python", "scipy", "unladen_swallow" ]
stackoverflow_0002328267_numpy_optimization_python_scipy_unladen_swallow.txt
Q: How do I get started with zc.buildout and Distribute? I want to use buildout for dependency management, and I hear distribute is the new good way to manage installation of your project. However, easy tutorials to get started seem to be thin on the ground. The most straight forward I've seen is Jacob Kaplan-Moss's ...
How do I get started with zc.buildout and Distribute?
I want to use buildout for dependency management, and I hear distribute is the new good way to manage installation of your project. However, easy tutorials to get started seem to be thin on the ground. The most straight forward I've seen is Jacob Kaplan-Moss's Developing Django apps with zc.buildout (my use case is a w...
[ "I've just started documenting the whole toolchain at http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html (2010-02-25: still got to write the buildout and the pastescript article).\nBasic toolchain idea: use setuptools to package your python code. Like the \"developing django apps\" article you ment...
[ 6, 0 ]
[]
[]
[ "buildout", "distribute", "python" ]
stackoverflow_0002305723_buildout_distribute_python.txt
Q: how are pgp keys formatted? i want to write a program in python to simply read pgp keys. however, i cant seem to find any documentation describing how pgp keys are formatted. i dont want to be searching through the source code of open pgp to look for source code that i wont be able to understand. say i open a pub...
how are pgp keys formatted?
i want to write a program in python to simply read pgp keys. however, i cant seem to find any documentation describing how pgp keys are formatted. i dont want to be searching through the source code of open pgp to look for source code that i wont be able to understand. say i open a public key, remove the top "-----BEG...
[ "You can read the PGP RFCs (looks like the latest is RFC 4880). But why not use pyme instead?\n" ]
[ 3 ]
[]
[]
[ "encryption", "gnupg", "pgp", "python" ]
stackoverflow_0002341486_encryption_gnupg_pgp_python.txt
Q: Python composite pattern exception handling & pylint I'm implementig a Composite pattern in this way: 1) the "abstract" component is: class Component(object): """Basic Component Abstraction""" def __init__(self, *args, **kw): raise NotImplementedError("must be subclassed") def status(self): ...
Python composite pattern exception handling & pylint
I'm implementig a Composite pattern in this way: 1) the "abstract" component is: class Component(object): """Basic Component Abstraction""" def __init__(self, *args, **kw): raise NotImplementedError("must be subclassed") def status(self): """Base Abstract method""" raise NotImplemen...
[ "Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.\nIf you don't want any instances of the Com...
[ 5, 2, 2, 1, 1 ]
[]
[]
[ "composite", "pylint", "python" ]
stackoverflow_0001091337_composite_pylint_python.txt
Q: customize the django admin panel? I want to change the django bydefault admin panel title bar where wirte the django administration. Actually I want to replace the django administration with the my site name. A: I found out the solution: Make the file in notpad {% extends "admin/base.html" %} {% load i18n %} {...
customize the django admin panel?
I want to change the django bydefault admin panel title bar where wirte the django administration. Actually I want to replace the django administration with the my site name.
[ "I found out the solution:\nMake the file in notpad \n{% extends \"admin/base.html\" %}\n{% load i18n %}\n\n{% block title %}{{ title }} | {% trans 'Your Customize name' %}{% endblock %}\n\n{% block branding %}\n<h1 id=\"site-name\">{% trans 'Your Customize name administration' %}</h1>\n{% endblock %}\n\n{% block n...
[ 6, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002333360_django_django_admin_python.txt
Q: Can't modify value returned by time.time() in Python code embedded in C++ I'm facing a very strange problem. The following code: import time target_time = time.time() + 30.0 doesn't work in Python code called from C++ (embedding)! target_time has the same value as time.time() and any attempt to modify it leaves t...
Can't modify value returned by time.time() in Python code embedded in C++
I'm facing a very strange problem. The following code: import time target_time = time.time() + 30.0 doesn't work in Python code called from C++ (embedding)! target_time has the same value as time.time() and any attempt to modify it leaves the value unchanged in a pdb console... alt text http://dl.dropbox.com/u/3545118...
[ "Found the answer in that thread:\nhttp://www.ogre3d.org/forums/viewtopic.php?f=1&t=55013&p=373940&hilit=D3DCREATE_FPU_PRESERVE#p373940\nhttp://msdn.microsoft.com/en-us/library/ee416457%28VS.85%29.aspx\nD3DCREATE_FPU_PRESERVE Set the precision for Direct3D floating-point calculations to the precision used by the c...
[ 0 ]
[]
[]
[ "c++", "direct3d", "embedding", "ogre3d", "python" ]
stackoverflow_0002333848_c++_direct3d_embedding_ogre3d_python.txt
Q: Django 1.1.1 chokes on multipart/form-data Initial story I'm trying to implement file upload using a simple form (I'm pasting stripped version, but all important parts are included): <form method="POST" action="" enctype="multipart/form-data"> <input type="file" name="up_file" size="50"> <input type=...
Django 1.1.1 chokes on multipart/form-data
Initial story I'm trying to implement file upload using a simple form (I'm pasting stripped version, but all important parts are included): <form method="POST" action="" enctype="multipart/form-data"> <input type="file" name="up_file" size="50"> <input type="hidden" name="cpk" value="{{c.pk}}"> <inp...
[ "You may need to provide your view and form code as we use form uploads with enctype=\"multipart/form-data\" in Django 1.1.1 with great success.\nThe following dummy app, for example, works perfectly in the dev server.\nviews.py\nfrom django import forms\nfrom django.shortcuts import render_to_response\n\nclass Upl...
[ 4 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0002341314_django_file_upload_python.txt
Q: wxPython Application.DoEvents() equivalent? Is there an Application.DoEvents() equivalent in wxPython? I am creating a form, then doing a slow I/O event, and the form is only partially drawn until the event finishes. I'd like to have the form fully drawn before the I/O starts. I've tried self.Refresh(), but it has...
wxPython Application.DoEvents() equivalent?
Is there an Application.DoEvents() equivalent in wxPython? I am creating a form, then doing a slow I/O event, and the form is only partially drawn until the event finishes. I'd like to have the form fully drawn before the I/O starts. I've tried self.Refresh(), but it has no effect.
[ "wx.Yield or wx.SafeYield\nAlthough you should really use a separate thread to do the I/O and use wx.CallAfter to post updates to the GUI thread.\nI usually use a pattern like this:\ndef start_work(self):\n thread = threading.Thread(target=self.do_work, args=(args, go, here))\n thread.setDaemon(True)\n thr...
[ 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002342183_python_wxpython_wxwidgets.txt
Q: capture using v4l2 and display preview using gstreamer How to pass the buffer/userpointer to gstreamer after Q_BUF, STREAM_ON, DQ_BUF. I tried using PIL's method frombuffer, but with no success. so I want to use gst sink now. Should I use gst.parse_launch() and how? Have anybody done it? A: The source code to Ch...
capture using v4l2 and display preview using gstreamer
How to pass the buffer/userpointer to gstreamer after Q_BUF, STREAM_ON, DQ_BUF. I tried using PIL's method frombuffer, but with no success. so I want to use gst sink now. Should I use gst.parse_launch() and how? Have anybody done it?
[ "The source code to Cheese tells all. http://projects.gnome.org/cheese/\n" ]
[ 0 ]
[]
[]
[ "gstreamer", "python", "v4l2" ]
stackoverflow_0002133822_gstreamer_python_v4l2.txt
Q: Python's c api and __add__ calls I am writing a binding system that exposes classes and functions to python in a slightly unusual way. Normally one would create a python type and provide a list of functions that represent the methods of that type, and then allow python to use its generic tp_getattro function to s...
Python's c api and __add__ calls
I am writing a binding system that exposes classes and functions to python in a slightly unusual way. Normally one would create a python type and provide a list of functions that represent the methods of that type, and then allow python to use its generic tp_getattro function to select the right one. For reasons I wo...
[ "Do you have an nb_add in your type's number methods structure (pointed by field tp_as_number of your type object)?\n" ]
[ 4 ]
[]
[]
[ "api", "python" ]
stackoverflow_0002342416_api_python.txt
Q: In a MVC patterned framework where would a screen-scraping module be located? In a MVC patterned framework where would a screen-scraping module most logically be located? In the model or the controller? Or is it completely outside of this pattern? A: You can call it as you might a model if you design it to behav...
In a MVC patterned framework where would a screen-scraping module be located?
In a MVC patterned framework where would a screen-scraping module most logically be located? In the model or the controller? Or is it completely outside of this pattern?
[ "You can call it as you might a model if you design it to behave like one. Then it can be easily used within a controller:\ndef update\n @company = Company.find(params[:id])\n\n @scraper = Scraper.find(:page => some_url, :method => :rip)\n\n @scraper.product_details.each do |params|\n @company.products.create...
[ 2, 0, 0, 0 ]
[]
[]
[ "model_view_controller", "python", "ruby_on_rails" ]
stackoverflow_0002342033_model_view_controller_python_ruby_on_rails.txt
Q: Create new class object I have 2 class in python cl1 in f1.py file and cl2 in f2.py file. I wrote import f2 import f2 class cl1: a = f2.cl2() But i see error in a = f2.cl2(): module object has no attribute 'cl2' Why? Thank you. A: sorry, i was wrong: your problem is probably that you have a circular import: ...
Create new class object
I have 2 class in python cl1 in f1.py file and cl2 in f2.py file. I wrote import f2 import f2 class cl1: a = f2.cl2() But i see error in a = f2.cl2(): module object has no attribute 'cl2' Why? Thank you.
[ "sorry, i was wrong:\nyour problem is probably that you have a circular import: f1 imports f2 and vice versa.\ncheck your design, as it usually should be possible to design your software without a circular import.\nsee: this\n", "The following code works just fine (if you're using Python 3 you can omit the (objec...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002340915_python.txt
Q: User location information mapping with lastfm music track history in python I have two separate python scripts. One is for getting user location information (which I get from web based geofeed provider.User Gsm is registerd with that services).Another is for retrieving lastfm user track history.I have already abl...
User location information mapping with lastfm music track history in python
I have two separate python scripts. One is for getting user location information (which I get from web based geofeed provider.User Gsm is registerd with that services).Another is for retrieving lastfm user track history.I have already able to get user location data and user music track information. Goal is to map thos...
[ "Write a third script that import both of the other as modules, and make sure each module's functionality is embodied in a function (as is Python's best practice), not just \"floating\" as module-level code -- a module's top-level statements should usually be limited to import, from, def, class, and simple assignme...
[ 1 ]
[]
[]
[ "last.fm", "location", "python" ]
stackoverflow_0002340589_last.fm_location_python.txt
Q: Ordering of Django models I set up an ordering='ordering_number' Meta attribute to my Django model, thinking that Django will use it when comparing instances. (ordering_number is an IntegerField in my model.) For example, if I have an instance a with ordering_number = 4 and an instance b with ordering_number = 7, ...
Ordering of Django models
I set up an ordering='ordering_number' Meta attribute to my Django model, thinking that Django will use it when comparing instances. (ordering_number is an IntegerField in my model.) For example, if I have an instance a with ordering_number = 4 and an instance b with ordering_number = 7, I'd expect that a < b would be ...
[ "From the documentation:\n\nThe default ordering for the object, for use when obtaining lists of objects\n\nSo the reason your comparisons aren't working is because they're not designed that way. Define __lt__() et alia to define ordering of instances.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002342913_django_python.txt
Q: How to pass data from Google App Engine(Python) to Flex 4 application I am using python and webapp framework in app engine for backend and flex 4 for front end. I would like to pass a string form backend to front end, so i write the following code in the main.py: class MainPage(webapp.RequestHandler): def get(se...
How to pass data from Google App Engine(Python) to Flex 4 application
I am using python and webapp framework in app engine for backend and flex 4 for front end. I would like to pass a string form backend to front end, so i write the following code in the main.py: class MainPage(webapp.RequestHandler): def get(self): userVO = "test" template_values = { 'url': self.request.uri, ...
[ "The best way to talk from Flex to GAE is using AMF. Here is how:\napp.yaml\napplication: flexandthecloud\nversion: 3\nruntime: python\napi_version: 1\n\nhandlers:\n- url: /services/.*\n script: main.py\n\nmain.py\n#!/usr/bin/env python\nimport wsgiref.handlers\n\nfrom pyamf.remoting.gateway.wsgi import WSGIGatew...
[ 2, 1, 1 ]
[]
[]
[ "apache_flex", "google_app_engine", "python", "swfobject" ]
stackoverflow_0002311796_apache_flex_google_app_engine_python_swfobject.txt
Q: django admin.site.name in template Hallo, is there any chance to access the "name" value of the current admin.site object in a admin template? I have 3 different admin.site-objects and want a template tag to generate generic content,depending on the current admin.site.name. thanks in advance A: You could provide...
django admin.site.name in template
Hallo, is there any chance to access the "name" value of the current admin.site object in a admin template? I have 3 different admin.site-objects and want a template tag to generate generic content,depending on the current admin.site.name. thanks in advance
[ "You could provide the name of the current site to all of your templates by writing a custom template context processor that would set a variable (e.g., SITE_NAME) in the context for every template.\n" ]
[ 3 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0002343286_admin_django_python.txt
Q: Python sub-package references I am about at wits end with what should be an extremely simple issue. Here is the format of a simple example that I wrote to try to fix my problem. I have a folder top with __all__ = ["p1","p2"] in __init__.py . I then have sub-folders p1 and p2 with __init__.py in both of them with _...
Python sub-package references
I am about at wits end with what should be an extremely simple issue. Here is the format of a simple example that I wrote to try to fix my problem. I have a folder top with __all__ = ["p1","p2"] in __init__.py . I then have sub-folders p1 and p2 with __init__.py in both of them with __all__ again defined with the names...
[ "Your problem is that your top package is not in your sys.path.\n", "All you describe is just fine and does not reproduce the error -- here's the simplest version I can think of:\n$ mkdir /tmp/path\n$ mkdir /tmp/path/top /tmp/path/top/p1 /tmp/path/top/p2\n$ touch /tmp/path/top/__init__.py /tmp/path/top/p1/__init_...
[ 3, 2 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0002343311_import_package_python.txt
Q: Open a file in the proper encoding automatically I'm dealing with some problems in a few files about the encoding. We receive files from other company and have to read them (the files are in csv format) Strangely, the files appear to be encoded in UTF-16. I am managing to do that, but I have to open them using the...
Open a file in the proper encoding automatically
I'm dealing with some problems in a few files about the encoding. We receive files from other company and have to read them (the files are in csv format) Strangely, the files appear to be encoded in UTF-16. I am managing to do that, but I have to open them using the codecs module and specifying the encoding, this way. ...
[ "chardet can help you.\n\nCharacter encoding auto-detection in\n Python 2 and 3. As smart as your\n browser. Open source.\n\n", "It won't be \"fixed\" in python 3, as it's not a fixable problem. Many documents are valid in several encodings, so the only way to determine the proper encoding is to know something...
[ 13, 6, 0 ]
[ "If it will be fixed in Python 3, it should also be fixed by using\nfrom __future__ import unicode_literals\n\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0002342284_python.txt
Q: how to make python to return floating point? I want python to return 0.5 if I write 1/2 (and not 1.0/2.0). how do I make python to return the floating point? (I tried using getcontext().prec form decimal module) thanks Ariel A: Use this, or switch to Python 3.0+ from __future__ import division A: from __futur...
how to make python to return floating point?
I want python to return 0.5 if I write 1/2 (and not 1.0/2.0). how do I make python to return the floating point? (I tried using getcontext().prec form decimal module) thanks Ariel
[ "Use this, or switch to Python 3.0+\nfrom __future__ import division\n\n", "from __future__ import division\n\n", "Python 3.x works the way you want by default.\nPython 2.2 and greater support from __future__ import division, which makes / return floating point. There is also the // operator that still perform...
[ 8, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002341771_python.txt
Q: Writing to file doesn't flush content automatically and cause out of memory in Python I made simple python program to generate big text file: import sys import random f = open('data.txt', 'w') for i in range(100000000): f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n") f.close() When I launch i...
Writing to file doesn't flush content automatically and cause out of memory in Python
I made simple python program to generate big text file: import sys import random f = open('data.txt', 'w') for i in range(100000000): f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n") f.close() When I launch it using CPython it eat all available OS memory and write nothing to the file. When I launch...
[ "Buffering is not the problem. The problem is calling the range() function with a giant argument, which will attempt to allocate an array with lots of elements. You will get the same error if you just say\nr = range(100000000)\n\n" ]
[ 9 ]
[ "Have you tried passing in a buffer size to the open function?\nf = open('data.txt', 'w', 5000)\n\n" ]
[ -1 ]
[ "buffer", "file", "flush", "python" ]
stackoverflow_0002343600_buffer_file_flush_python.txt
Q: How to add an Admin class to a model after syncdb? I added some models in my models.py and I want to add an admin class to use a wysiwyg-editor in text-fields. Well, I know that Django itself doesn't support migrations and I've used South, but it doesn't work either. South doesn't "see" the change. ...
How to add an Admin class to a model after syncdb?
I added some models in my models.py and I want to add an admin class to use a wysiwyg-editor in text-fields. Well, I know that Django itself doesn't support migrations and I've used South, but it doesn't work either. South doesn't "see" the change. ...
[ "syncdb and South are only concerned with descendants of Model in apps listed in INSTALLED_APPS. Everything else is handled by Django directly.\n", "I'm fairly sure that if you follow the steps as outlined in the tutorial to create an admin app it'll just work. Migration isn't an issue as the admin app creates ne...
[ 2, 1, 1 ]
[]
[]
[ "django", "django_models", "django_south", "python" ]
stackoverflow_0002343053_django_django_models_django_south_python.txt
Q: How to build an image object in PIL/Python I have a list of 3-item tuples that is the result of list(PIL.Image.getdata()). How do I do the opposite: build a PIL.Image object from this list? A: The output of getdata() does not include the image format or the size, so you'll need to preserve those (or get the info...
How to build an image object in PIL/Python
I have a list of 3-item tuples that is the result of list(PIL.Image.getdata()). How do I do the opposite: build a PIL.Image object from this list?
[ "The output of getdata() does not include the image format or the size, so you'll need to preserve those (or get the information some other way). Then do this, using the putdata() method:\n# get data from old image (as you already did)\ndata = list(oldimg.getdata())\n\n# create empty new image of appropriate forma...
[ 9 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0002343115_image_python_python_imaging_library.txt
Q: clicking "cancel" in tkColorChooser dialog leads to Error I use python 2.6 under linux (SUSE Linux Enterprise Desktop 11 (x86_64)). I tested some very simple code : import tkColorChooser tkColorChooser.askcolor() then if I click on cancel, I always get error like: Traceback (most recent call last): File "<stdin...
clicking "cancel" in tkColorChooser dialog leads to Error
I use python 2.6 under linux (SUSE Linux Enterprise Desktop 11 (x86_64)). I tested some very simple code : import tkColorChooser tkColorChooser.askcolor() then if I click on cancel, I always get error like: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/lib-tk/tkC...
[ "Looking at the version of tkColorChooser.py I have (Python 2.6.4, Win32), it should support the user pressing cancel (as do and should the other predefined dialogs): it is indeed supposed to return None when the results evals to False in a boolean context.\nTherefore, something strange is happening.\nedit: as I no...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002317680_python_tkinter.txt
Q: pylint: Using possibly undefined loop variable 'n' Pylint says W: 6: Using possibly undefined loop variable 'n' ... with this code: iterator = (i*i for i in range(100) if i % 3 == 0) for n, i in enumerate(iterator): do_something(i) print n because if the iterator is empty (for example []) n is undefined, ...
pylint: Using possibly undefined loop variable 'n'
Pylint says W: 6: Using possibly undefined loop variable 'n' ... with this code: iterator = (i*i for i in range(100) if i % 3 == 0) for n, i in enumerate(iterator): do_something(i) print n because if the iterator is empty (for example []) n is undefined, ok. But I like this trick. How to use it in a safe way? ...
[ "Have you considered merely initializing n to None before running the loop?\n", "Define a default value for n before the for statement:\niterator = (i*i for i in range(100) if i % 3 == 0)\n\nn=None\nfor n, i in enumerate(iterator):\n do_something(i)\n\nprint n\n\n" ]
[ 14, 4 ]
[]
[]
[ "enumerate", "python" ]
stackoverflow_0002344315_enumerate_python.txt
Q: Creating a Cron Job - Linux / Python Hi I have a Django script that I need to run, I think the commands could be called through bash. Thing is the script causes memory leaks after a long a period of time, so I would like to create an external cron job which calls the Python script. So the script would terminate an...
Creating a Cron Job - Linux / Python
Hi I have a Django script that I need to run, I think the commands could be called through bash. Thing is the script causes memory leaks after a long a period of time, so I would like to create an external cron job which calls the Python script. So the script would terminate and restart while retaking the lost memory. ...
[ "If you have an executable, say /home/bin/foobar, that restarts the script, and want to run it (say) every 10 minutes, the crontab entry needs to be:\n*/10 * * * * /home/bin/foobar\n\nwhich says to run it at every minute divisible by 10, every hour, every day.\nIf you save this (and any other periodic jobs you wan...
[ 7, 2, 1, 1 ]
[]
[]
[ "django", "linux", "python", "ubuntu" ]
stackoverflow_0002339725_django_linux_python_ubuntu.txt
Q: Python Regex to match a file in a list of files (getting error) I'm trying to use a regex in Python to match a file (saved as a string, ie "/volumes/footage/foo/bar.mov") to a log file I create that contains a list of files. But when I run the script, it gives me this error: sre_constants.error: unbalanced parenth...
Python Regex to match a file in a list of files (getting error)
I'm trying to use a regex in Python to match a file (saved as a string, ie "/volumes/footage/foo/bar.mov") to a log file I create that contains a list of files. But when I run the script, it gives me this error: sre_constants.error: unbalanced parenthesis. The code I'm using is this: To read the file: theLogFile = The_...
[ "Where is the regular expression pattern? Are you trying to use filenames contained in one file as patterns to search the other file? If so, you will want to step through the_file with someting like \nfor the_pattern in the_file:\n p = re.compile(the_pattern, re.IGNORECASE)\n m = p.search(the_log)\n ...\...
[ 3, 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002344193_python_regex.txt
Q: Python: group results by time intervals I have a large data loaded from a pickled file. The data is a sorted list of tuples containing a datetime and an int like this [ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L), (datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L), (datetime.datetime(2010, 2, 2...
Python: group results by time intervals
I have a large data loaded from a pickled file. The data is a sorted list of tuples containing a datetime and an int like this [ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L), (datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L), (datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L), etc ] I want to ...
[ "Check out itertools.groupby. You can pass a function that calculates the proper bucket as the key. Then, you can run your aggregations (counts, averages, what-have-you) on the groups in the resulting iterable.\n", "bisect.bisect is another way to solve this problem:\nimport datetime\nimport bisect\nimport collec...
[ 6, 6 ]
[]
[]
[ "python" ]
stackoverflow_0002344639_python.txt
Q: PyUnit tearDown and setUp vs __init__ and __del__ Is there a difference between using tearDown and setUp versus __init__ and __del__ when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use? A: setUp is called before every test, and tearDown is called after ever...
PyUnit tearDown and setUp vs __init__ and __del__
Is there a difference between using tearDown and setUp versus __init__ and __del__ when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?
[ "setUp is called before every test, and tearDown is called after every test.\n__init__ is called once when the class is instantiated -- but since a new\nTestCase instance is created for each individual test method, __init__ is\nalso called once per test.\nYou generally do not need to define __init__ or __del__ when...
[ 38 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002344772_python_unit_testing.txt
Q: Python script is running. I have a method name as a string. How do I call this method? everyone. Please see example below. I'd like to supply a string to 'schedule_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea h...
Python script is running. I have a method name as a string. How do I call this method?
everyone. Please see example below. I'd like to supply a string to 'schedule_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help class Bot: def work(self): pass def fight(self): ...
[ "Use getattr:\nclass Bot:\n def fight(self):\n print \"fighting is fun!\"\n\nclass Scheduler: \n def schedule_action(self,action):\n bot = Bot()\n getattr(bot,action)()\n\nscheduler = Scheduler()\nscheduler.schedule_action('fight')\n\nNote that getattr also takes an optional argument t...
[ 12, 7, 6, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002344212_python.txt
Q: Extra parameter for Django models With Django models, I want to achieve this: class Foo(models.Model): name = models.CharField(max_length=50) #wrapping the save function, including extra tasks def save(self, *args, **kwargs): super(Foo, self).save(*args, **kwargs) if extra_param: ...
Extra parameter for Django models
With Django models, I want to achieve this: class Foo(models.Model): name = models.CharField(max_length=50) #wrapping the save function, including extra tasks def save(self, *args, **kwargs): super(Foo, self).save(*args, **kwargs) if extra_param: ...do task 1 else: ...
[ "You can define non-persistent fields in your model.\nclass Foo(models.Model):\n name = models.CharField(max_length=50)\n extra_param = False\n\ndef save(self, *args, **kwargs):\n ... \n print self.extra_param\n\nAlternatively, you can do:\nFoo(name=\"Bill Gates\").save(extra_param=True)\n\ndef save(sel...
[ 9 ]
[]
[]
[ "django", "django_forms", "python", "wrapper" ]
stackoverflow_0002344994_django_django_forms_python_wrapper.txt
Q: Minimize python distribution size The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux. A: If all you want is to get the minimum subset you need (rathe...
Minimize python distribution size
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
[ "If all you want is to get the minimum subset you need (rather than build an exe which would constrain you to Windows systems), use the standard library module modulefinder to list all modules your program requires (you'll get all dependencies, direct and indirect). Then you can zip all the relevant .pyo or .pyc f...
[ 9, 4, 1 ]
[]
[]
[ "minimize", "python", "size" ]
stackoverflow_0002344712_minimize_python_size.txt
Q: Python: Why is comparison between lists and tuples not supported? When comparing a tuple with a list like ... >>> [1,2,3] == (1,2,3) False >>> [1,2,3].__eq__((1,2,3)) NotImplemented >>> (1,2,3).__eq__([1,2,3]) NotImplemented ... Python does not deep-compare them as done with (1,2,3) == (1,2,3). So what is the rea...
Python: Why is comparison between lists and tuples not supported?
When comparing a tuple with a list like ... >>> [1,2,3] == (1,2,3) False >>> [1,2,3].__eq__((1,2,3)) NotImplemented >>> (1,2,3).__eq__([1,2,3]) NotImplemented ... Python does not deep-compare them as done with (1,2,3) == (1,2,3). So what is the reason for this? Is it because the mutable list can be changed at any time...
[ "You can always \"cast\" it\n>>> tuple([1, 2]) == (1, 2)\nTrue\n\nKeep in mind that Python, unlike for example Javascript, is strongly typed, and some (most?) of us prefer it that way.\n", "There's no technical reason for lists not being able to compare to tuples; it's entirely a design decision driven by semanti...
[ 35, 14 ]
[]
[]
[ "comparison", "list", "python", "tuples" ]
stackoverflow_0002345092_comparison_list_python_tuples.txt
Q: How can I capture and print packets from the internet on Windows? How can I capture them? Is there any module/lib to do it? Please if it do, post an example A: If you can install Wireshark, you can use it programaticaly from Python. (This isn't yet supported on Windows, as per bug 3500.) You also have PyCap, a...
How can I capture and print packets from the internet on Windows?
How can I capture them? Is there any module/lib to do it? Please if it do, post an example
[ "If you can install Wireshark, you can use it programaticaly from Python. (This isn't yet supported on Windows, as per bug 3500.)\n\nYou also have PyCap, a Python Packet Capture and Injection Library that seems to be platform independent.\n\nYet another packet sniffing module is Scapy, that I though didn't work on ...
[ 1 ]
[]
[]
[ "packets", "python", "windows" ]
stackoverflow_0002345217_packets_python_windows.txt
Q: What is the Python code to split up a string so that it prints out normally in an 80-character window without wrapping? When I run my program (which decrypts a paragraph from a certain document), I have: W E T H E P E O P L E O F T H E U N I T E D S T A T E S I N O R D E R T O F O R M A M O R E P E R F E C T U N I...
What is the Python code to split up a string so that it prints out normally in an 80-character window without wrapping?
When I run my program (which decrypts a paragraph from a certain document), I have: W E T H E P E O P L E O F T H E U N I T E D S T A T E S I N O R D E R T O F O R M A M O R E P E R F E C T U N I O N E S T A B L I S H J U S T I C E I N S U R E D O M E S T I C T R A N Q U I L I T Y P R O V I D E F O R T H E C O M M O N ...
[ "I don't know what that one-character-a-line is about because you didn't tell us the reason, but the textwrap module will give you what you want:\ns=\"WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION, ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE, PROMOTE TH...
[ 6, 1, 0 ]
[]
[]
[ "character", "python", "string", "word_wrap" ]
stackoverflow_0002345384_character_python_string_word_wrap.txt
Q: Pyunit: "Import Site" Using pyUnit to do what is currently a very small and simple unit test I am getting the message: 'import site' failed; use -v for traceback ... ____________________________________________ Ran 3 tests in 0.094S When I rerun the unit test with the -v parameter, it returns verbose information ...
Pyunit: "Import Site"
Using pyUnit to do what is currently a very small and simple unit test I am getting the message: 'import site' failed; use -v for traceback ... ____________________________________________ Ran 3 tests in 0.094S When I rerun the unit test with the -v parameter, it returns verbose information about each of the 3 tests a...
[ "The first thing to know is that the message you're seeing is from the Python interpreter, and has nothing to do with pyUnit. The -v in the message refers to \"python -v\".\nAs to why you can't import site, and why running pyUnit with -v makes the error go away, I don't know. Do you have your own site.py?\n" ]
[ 1 ]
[]
[]
[ "python", "python_unittest", "unit_testing" ]
stackoverflow_0002345331_python_python_unittest_unit_testing.txt
Q: using a key to rearrange string Using Python I want to randomly rearrange sections of a string based on a given key. I also want to restore the original string with the same key: def rearrange(key, data): pass def restore(key, rearranged_data): pass Efficiency is not important. Any ideas? Edit: can assu...
using a key to rearrange string
Using Python I want to randomly rearrange sections of a string based on a given key. I also want to restore the original string with the same key: def rearrange(key, data): pass def restore(key, rearranged_data): pass Efficiency is not important. Any ideas? Edit: can assume key is hashable, but may be multip...
[ "Use random.shuffle with the key as a seed:\nimport random\n\ndef rearrange(key, data):\n random.seed(key)\n d = list(data)\n random.shuffle(d)\n return ''.join(d)\n\ndef restore(key, rearranged_data):\n l = len(rearranged_data)\n random.seed(key)\n d = range(l)\n random.shuffle(d)\n s = ...
[ 4, 3, 1 ]
[]
[]
[ "algorithm", "encryption", "python", "string" ]
stackoverflow_0002345628_algorithm_encryption_python_string.txt
Q: pygresql - insert and return serial I'm using PyGreSQL to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field: create table job_runners ( id SERIAL PRIMARY KEY, hostname ...
pygresql - insert and return serial
I'm using PyGreSQL to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field: create table job_runners ( id SERIAL PRIMARY KEY, hostname varchar(100) not null, is_availab...
[ "INSERT INTO job_runners\n (hostname,is_available) VALUES ('localhost',true)\n RETURNING id\n\nThat said, I have no idea about pygresql, but by what you've already written, I guess it's db.query() that you want to use here.\n", "The documentation in PyGreSQL says that if you call dbconn.query() with and ins...
[ 2, 1, 0 ]
[]
[]
[ "postgresql", "pygresql", "python" ]
stackoverflow_0001438430_postgresql_pygresql_python.txt
Q: Does turning a list into a set, then back again, cause problems in Python? I'm turning a list into a set in Python, like so: request.session['vote_set'] = set(request.session['vote_set']) So I can easily do a if x in set lookup and eliminate duplicates. Then, when I'm done, I reconvert it: request.session['vote_s...
Does turning a list into a set, then back again, cause problems in Python?
I'm turning a list into a set in Python, like so: request.session['vote_set'] = set(request.session['vote_set']) So I can easily do a if x in set lookup and eliminate duplicates. Then, when I'm done, I reconvert it: request.session['vote_set'] = list(request.session['vote_set']) Is there a better way to do this? Am I...
[ "You'll lose duplicates if you actually wanted them. If this is actually a list of \"votes\" as your naming suggests, you'd 'lose' some :)\nwhy not just:\nif x in set(request.session['vote_set'])\n\nif you're worried.\nAlthough I have to wonder if that would be slower than just plain:\nif x in request.session['vote...
[ 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002345862_python.txt
Q: Why is post_save being raised twice during the save of a Django model? I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified. The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't ...
Why is post_save being raised twice during the save of a Django model?
I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified. The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it c...
[ "Apparently, Python is sensitive to the way you import modules. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to do an initial import.\nInside my blog application I was using imports such as:\nfr...
[ 13, 9, 1 ]
[]
[]
[ "django", "django_models", "python", "signals" ]
stackoverflow_0002345400_django_django_models_python_signals.txt
Q: In python, I need to store one element of the source of an html page as a string. How can I do this? So far I have managed to write some code that should print the source of the page. The problem is, it doesn't. I tried it with another web site, and it printed it out fine, so I used wget on the page "http://www.wh...
In python, I need to store one element of the source of an html page as a string. How can I do this?
So far I have managed to write some code that should print the source of the page. The problem is, it doesn't. I tried it with another web site, and it printed it out fine, so I used wget on the page "http://www.whitepages.com/carrier_lookup?carrier=other&number_0=2165138899&response=1" which should download the page f...
[ "For an explanation of what a 403 result from HTTP means, and how to deal with it, see here.\nI have no idea what \"I need to save as a different string the carrier that the search found\" can possibly mean -- I can't even parse it as an English sentence, nor do I know what \"the line under the line\" means either....
[ 1 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0002346154_html_parsing_python.txt
Q: How can I remove part of an string on the re.search result? text = urllib.urlopen('www.text.com').read() frase = re.search("your text here(.*)", text).group() With these code, I get the result as "your text here mister"... How can I remove the your text here from the result, staying only with the "mister" part? ...
How can I remove part of an string on the re.search result?
text = urllib.urlopen('www.text.com').read() frase = re.search("your text here(.*)", text).group() With these code, I get the result as "your text here mister"... How can I remove the your text here from the result, staying only with the "mister" part?
[ "Specify the number of the group (= thing between parenthesis in the regex) you want to receive in the call to group():\nfrase = re.search(...).group(1)\n\n", "don't need regex\ntext = urllib.urlopen('www.text.com').read()\nprint ''.join( text.split(\"your text here\")[1:] )\n\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002346215_python.txt
Q: How can you draw a bezier curve given four points with wxPython? It appears to me that the DC's only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline? A: Given 4 control points, the formula for the ass...
How can you draw a bezier curve given four points with wxPython?
It appears to me that the DC's only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline?
[ "Given 4 control points, the formula for the associated cubic Bezier curve is not hard to compute. Once you calculate a set of points on the curve, you could use DC.DrawLines to draw it.\nThere is a python implementation for calculating points on generalized Bezier curves (shameless plug) here. It's generalized in ...
[ 2, 1 ]
[]
[]
[ "bezier", "python", "spline", "wxpython" ]
stackoverflow_0002346054_bezier_python_spline_wxpython.txt
Q: Is it OK to do 302s for architecture in my web applciation? For example, in my index(request): def index(request): if logged_in: return HttpResponseRedirect("/home_profile") else: return HttpResponseRedirect("/login") This way, when the user hits my home page...he is redirected appropriate...
Is it OK to do 302s for architecture in my web applciation?
For example, in my index(request): def index(request): if logged_in: return HttpResponseRedirect("/home_profile") else: return HttpResponseRedirect("/login") This way, when the user hits my home page...he is redirected appropriately. Is this a good architecture? Or will this cause caching probl...
[ "Redirection is ok(302 shouldn't cause any caching problem, as 302's are temporary), but why you need to have redirection in both if and else. Better way is to redirect to login page if not logged-in, view should otherwise return the response, instead of unnecessarily redirecting e.g.\ndef home(request):\n if no...
[ 3 ]
[]
[]
[ "django", "python", "redirect" ]
stackoverflow_0002347074_django_python_redirect.txt
Q: Regular expression to ignore a certain number of character repetitions I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string. Given a string like: This | is || token || some...
Regular expression to ignore a certain number of character repetitions
I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string. Given a string like: This | is || token || some ||| text I would like to end up with: This \| is || token || some \|\|\| t...
[ "No need regex. You are using Python after all. :)\n>>> s=\"This | is || token || some ||| text\"\n>>> items=s.split()\n>>> items\n['This', '|', 'is', '||', 'token', '||', 'some', '|||', 'text']\n>>> for n,i in enumerate(items):\n... if \"|\" in i and i.count(\"|\")!=2:\n... items[n]=i.replace(\"|\",\"...
[ 2, 1, 0 ]
[]
[]
[ "python", "regex", "regex_negation" ]
stackoverflow_0002346917_python_regex_regex_negation.txt