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:
Paramiko connection issue
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...
#connect.py
import user, db
import paramiko, time, os
paramiko.util.log_to_file('paramiko-log.tx... | Paramiko connection issue | I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...
#connect.py
import user, db
import paramiko, time, os
paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
def _... | [
"I tried the code and it ran fine. I made only a few changes.\nFirst, I didn't know what \"user\" and \"db\" are, so I commented out\nimport user, db\n\nand \ndatabase = db.Database()\n\nand used my own data for username, password, etc. \nSecond, the PySide module isn't available via my package manager, so I used ... | [
1,
0
] | [] | [] | [
"desktop_application",
"paramiko",
"python"
] | stackoverflow_0004762822_desktop_application_paramiko_python.txt |
Q:
Is it possible to align a menu to the right of the menu bar using wxPython?
I'm trying to create a menu bar in wxPython 2.8.11.0 and Python 2.7 where most of the menus are left aligned (as normal) but one is - ideally - right aligned, or at least separated in some way from the rest.
Is this possible?
EDIT: This ne... | Is it possible to align a menu to the right of the menu bar using wxPython? | I'm trying to create a menu bar in wxPython 2.8.11.0 and Python 2.7 where most of the menus are left aligned (as normal) but one is - ideally - right aligned, or at least separated in some way from the rest.
Is this possible?
EDIT: This needs to be a cross-platform solution.
| [
"If the native menubar doesn't support it, then wxPython probably won't either. There is a pure Python implementation of the menubar though. It's called FlatMenu. I would try that. If it doesn't work, at least you can hack it or submit a patch in Python code rather than trying to figure out the C++ for fixing wxWid... | [
1
] | [] | [] | [
"cross_platform",
"menu",
"menubar",
"python",
"wxpython"
] | stackoverflow_0004730785_cross_platform_menu_menubar_python_wxpython.txt |
Q:
Python Remote Procedure Call (Without the Remote Part)
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.
Obviously I do not want to run the main server as roo... | Python Remote Procedure Call (Without the Remote Part) | I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.
Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or comma... | [
"Following my comment, I was interested to see if it was possible, so I had a go at putting this together: https://github.com/takowl/ZeroRPC\nBear in mind that this is thrown together in an hour or so, so it's almost certainly inferior to any serious solution (e.g. any errors on the server side will crash it...). B... | [
2,
2,
0
] | [] | [] | [
"daemon",
"ipc",
"python",
"rpc"
] | stackoverflow_0004761617_daemon_ipc_python_rpc.txt |
Q:
l[:] performance problem
Recently I was debugging a code like following
def getList():
#query db and return a list
total_list = Model.objects.all()
result = list()
for item in total_list:
if item.attr1:
result.append(item)
return result
# in main code
org_list = getList... | l[:] performance problem | Recently I was debugging a code like following
def getList():
#query db and return a list
total_list = Model.objects.all()
result = list()
for item in total_list:
if item.attr1:
result.append(item)
return result
# in main code
org_list = getList()
list = orgList[:]#this lin... | [
"The code that you are showing would run in the 0.1 microseconds that it would take to raise an exception:\norg_list = getList()\nlist = orgList[:]#this line cause cpu problems.\n\norgList should be org_list. Show the minimal code that actually reproduces the problem. \nAlso, that kills the list built-in function. ... | [
2,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004763708_django_python.txt |
Q:
Modifying a variable in a module imported using from ... import *
Consider the following code:
#main.py
From toolsmodule import *
database = "foo"
#toolsmodule
database = "mydatabase"
As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule fr... | Modifying a variable in a module imported using from ... import * | Consider the following code:
#main.py
From toolsmodule import *
database = "foo"
#toolsmodule
database = "mydatabase"
As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule from main? The following does not work:
toolsmodule.database = "foo"
| [
"Sounds like yet another of the multitude of good reasons not to use from toolsmodule import *.\nIf you just do import toolsmodule, then you can do toolsmodule.database = 'foo', and everything is wonderful.\n",
"Pythons variable names are just labels on variables. When you import * all those labels are local and ... | [
19,
6,
2
] | [] | [] | [
"python",
"python_3.x",
"python_import"
] | stackoverflow_0004758562_python_python_3.x_python_import.txt |
Q:
Creating dictionary from space separated key=value string in Python
I have string as follows:
s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
I want to convert in to a dictionary as follows:
key | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace
How do I ... | Creating dictionary from space separated key=value string in Python | I have string as follows:
s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
I want to convert in to a dictionary as follows:
key | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace
How do I do this in Python?
| [
"\nThe shlex class makes it easy to write\n lexical analyzers for simple syntaxes\n resembling that of the Unix shell.\n This will often be useful for writing\n minilanguages, (for example, in run\n control files for Python applications)\n or for parsing quoted strings.\n\nimport shlex\n\ns = 'key1=1234 key2=... | [
29,
20
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004764547_dictionary_python.txt |
Q:
How do I automatically resize text to fit a fixed-size PyGTK label?
I have a fixed-size gtk.Label. I would like to automatically resize the text so that it fits within the Label. Is there an elegant way to do this with fonts that are not fixed width?
my_label = gtk.Label()
# Short text segment
my_label.set_text( ... | How do I automatically resize text to fit a fixed-size PyGTK label? | I have a fixed-size gtk.Label. I would like to automatically resize the text so that it fits within the Label. Is there an elegant way to do this with fonts that are not fixed width?
my_label = gtk.Label()
# Short text segment
my_label.set_text( "Short text segment." )
# Long text segment
### Determine required text ... | [
"I didn't have time to test this, but something along these lines ought to do what you want:\nsize = 12000 # thousandths of a point\ntemp_label = gtk.Label(my_label.get_text())\nwhile temp_label.get_width() > my_label.get_width():\n size -= 100\n temp_label.set_attributes(pango.Attrlist().insert(pango.AttrSiz... | [
0
] | [] | [] | [
"autoresize",
"gtk",
"label",
"pygtk",
"python"
] | stackoverflow_0004709819_autoresize_gtk_label_pygtk_python.txt |
Q:
Error in the python script
I have this simple python script where myvar1 is accessible in generate() function but not in copy() function. Need help figuring out the error:
#!/usr/bin/python
import os, time
def Test(tcid,descr,iterations,filsz):
def setup():
print "entering set up\n"
... | Error in the python script | I have this simple python script where myvar1 is accessible in generate() function but not in copy() function. Need help figuring out the error:
#!/usr/bin/python
import os, time
def Test(tcid,descr,iterations,filsz):
def setup():
print "entering set up\n"
global myvar1, myvar... | [
"In the copy() function, myvar1 is not declared as global, but assigned to in the statement myvar1 += 5.0. This implicitly makes the myvar1 a local variable. The print statement in the first line of the function also tries to access a local variable with the name myvar1, but such a local variable does not exist y... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004765062_python.txt |
Q:
Django TemplateDoesNotExist
Ok so I have a project called tvlistings and an app called progguide.
In my tvlistings directory I have the following in these files
settings.py
TEMPLATE_DIRS = (
'/home/paul/tvlistings/progguide/templates',
)
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns(... | Django TemplateDoesNotExist | Ok so I have a project called tvlistings and an app called progguide.
In my tvlistings directory I have the following in these files
settings.py
TEMPLATE_DIRS = (
'/home/paul/tvlistings/progguide/templates',
)
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^progguide/', include(... | [
"You were close though it's actually supposed to be\nreturn render_to_response('index.html', {'chan_prog_list': chan_prog_list})\n\n",
"Are you missing the templates folder?\nYou can use:\nreturn render_to_response('progguide/templates/index.html', {'chan_prog_list': chan_prog_list})\n\n",
"The string you pass ... | [
2,
1,
1
] | [] | [] | [
"django",
"model",
"python",
"url",
"views"
] | stackoverflow_0004765003_django_model_python_url_views.txt |
Q:
PyGTK TextView that only accepts single lines
I feel rather silly to ask this, but how does one create a TextView that only accepts single lines? Most other gui toolkits have a method such as "setMultiline" etc, but PyGTK seems to really enjoy multiple lines. Some other languages have "TextFields" for these simple... | PyGTK TextView that only accepts single lines | I feel rather silly to ask this, but how does one create a TextView that only accepts single lines? Most other gui toolkits have a method such as "setMultiline" etc, but PyGTK seems to really enjoy multiple lines. Some other languages have "TextFields" for these simpler text boxes.
http://www.pygtk.org/docs/pygtk/class... | [
"use gtk.Entry?\nhttp://www.pygtk.org/docs/pygtk/class-gtkentry.html\n",
"Oh I found it. I suppose the name makes sense...\nhttp://www.pygtk.org/docs/pygtk/class-gtkentry.html\n"
] | [
5,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004765147_gtk_pygtk_python.txt |
Q:
Help with rotating xy-pixel coordinates, unsure about my function
Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.
Is this the right way to do it?:
Each pixels distance from the middlepoint is its radius.... | Help with rotating xy-pixel coordinates, unsure about my function | Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.
Is this the right way to do it?:
Each pixels distance from the middlepoint is its radius.
Then in python code
new_x = avg_pos_x+(math.cos(math.radians(105))*rad... | [
"Rather than figuring out where each pixel in the original image goes, you should figure out where each pixel in the new image came from. You can do this just by rotating negative 105 degrees.\nold_x = avg_pos_x+(math.cos(math.radians(-105))*radius)\nold_y = avg_pos_y-(math.sin(math.radians(-105))*radius)\n\nThen ... | [
1,
0
] | [] | [] | [
"python",
"rotation"
] | stackoverflow_0004764516_python_rotation.txt |
Q:
Python DDL abstraction
Are there any Python libraries that provide an abstraction of SQL DDL?
I have an application that needs to dynamically add/adjust database columns, and I don't want to have to model CREATE TABLE and all the datatypes.
I am looking for something relatively lightweight; full ORMs like SQLAlche... | Python DDL abstraction | Are there any Python libraries that provide an abstraction of SQL DDL?
I have an application that needs to dynamically add/adjust database columns, and I don't want to have to model CREATE TABLE and all the datatypes.
I am looking for something relatively lightweight; full ORMs like SQLAlchemy will unfortunately not be... | [
"Have you looked at SQLAlchemy?\nIt's an object-relational mapper (abstraction layer) that sits between your python code and the (relational) database.\nIt does DDL such as create table.\n"
] | [
2
] | [] | [] | [
"ddl",
"python"
] | stackoverflow_0004765011_ddl_python.txt |
Q:
python and javascript with html generation
On a website that I manage, we have JSON files which contain page data. We then create the page using this JSON.
The data looks roughly like this (except a lot more complex).
[
{"title": "Hello world", "content": "World, hello to you!"},
{"title": "Hello world Part II... | python and javascript with html generation | On a website that I manage, we have JSON files which contain page data. We then create the page using this JSON.
The data looks roughly like this (except a lot more complex).
[
{"title": "Hello world", "content": "World, hello to you!"},
{"title": "Hello world Part II", "content": "The sequel to hello world."},
.... | [
"You can use the server to render the page and grab that with an AJAX response. While this avoids code duplication, it might be less efficient since you have to query the server to render each page, rather than making the client do it themselves (this might not be too much of an issue, though). It shouldn't take up... | [
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0004765298_javascript_python.txt |
Q:
Buildbot parsing Python Unit test results
I have a test suite that outputs test results in the Python Unit Test format: http://docs.python.org/library/unittest.html
Is there an existing Buildbot module/plugin that can parse this form?
Example:
DigitalReadWrite_02 ... ok
Dig... | Buildbot parsing Python Unit test results | I have a test suite that outputs test results in the Python Unit Test format: http://docs.python.org/library/unittest.html
Is there an existing Buildbot module/plugin that can parse this form?
Example:
DigitalReadWrite_02 ... ok
DigitalReadWrite_03 ... | [
"No, it makes no sense to develop a parser. You can obtain the equivalent information from classes in runner.py module.\nConsider extending both classes TextTestRunner and TextTestResult with your custom logic (python 2.7). The output you have listed is produced by TextTestResult. \nAlternatively you can extend onl... | [
3
] | [] | [] | [
"buildbot",
"parsing",
"python",
"unit_testing"
] | stackoverflow_0003943590_buildbot_parsing_python_unit_testing.txt |
Q:
how to make package for my python project
I have a python project, which uses qt(UI) for user input and then creates the pdf using latex.
I want to make full package of my whole projects in some form of exe.
I came to know about pyinstaller, pyexe and cx_frezer.
So which one should I pick up first.
My exe should r... | how to make package for my python project | I have a python project, which uses qt(UI) for user input and then creates the pdf using latex.
I want to make full package of my whole projects in some form of exe.
I came to know about pyinstaller, pyexe and cx_frezer.
So which one should I pick up first.
My exe should run in windows 98, xp, vista and linux.
So how ... | [
"This might be a viable alternative to freeze and py2exe. Python allows compilation into bytecode. You will have to do this on all of your target platforms for specific python versions. Run in root of your project folder\n\npython -m compileall\n\nSee http://docs.python.org/library/compileall.html for details.\nAft... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004042278_python.txt |
Q:
DB-API SQLite INSERT statement throws InterfaceError in Python 2.7
Given a SQLite table I've created, with the field in question being type TEXT, the following fails:
hsh = hashlib.sha1("".join(some_list)).hexdigest()
db_setup(hsh)
I receive the error:
InterfaceError: Error binding parameter 2 - probably unsupport... | DB-API SQLite INSERT statement throws InterfaceError in Python 2.7 | Given a SQLite table I've created, with the field in question being type TEXT, the following fails:
hsh = hashlib.sha1("".join(some_list)).hexdigest()
db_setup(hsh)
I receive the error:
InterfaceError: Error binding parameter 2 - probably unsupported type.
def db_setup(my_hash, oavals)
to_insert = (my_hash,)
('... | [
"It is failing because to_insert is a tuple, not the value you wish to insert.\nTry changing that first line to:\nto_insert = my_hash\n\nOr better yet, just put my_hash into your parameter list.\nHere's an example:\n>>> hsh = '49cb6536afc7e4a4b3a94eb493aae4d52b8f6a60'\n>>> conn = sqlite3.connect(':memory:')\n>>> c ... | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004765614_python_sqlite.txt |
Q:
Java or Python for math?
I'm trying to write a pretty heavy duty math-based project, which will parse through about 100MB+ data several times a day, so, I need a fast language that's pretty easy to use. I would have gone with C, but, getting a large project done in C is very difficult, especially with the low leve... | Java or Python for math? | I'm trying to write a pretty heavy duty math-based project, which will parse through about 100MB+ data several times a day, so, I need a fast language that's pretty easy to use. I would have gone with C, but, getting a large project done in C is very difficult, especially with the low level programming getting in your ... | [
"Java will usually be quicker to run (don't take this as an absolute truth), but slower to write.\nPython is the opposite. Since libraries such as SciPy and NumPy already exist, which are built upon fast C code, I'd suggest going with Python if you prefer to go the \"speedier\" way in terms of code writing. Unless ... | [
19,
11,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"java",
"math",
"python",
"stocks"
] | stackoverflow_0004759485_java_math_python_stocks.txt |
Q:
Queue.Queue vs semaphores, locks, etc. in multithreaded Python code
The principal challenge of
multi-threaded applications is
coordinating threads that share data
or other resources. To that end, the
threading module provides a number of
synchronization primitives including
locks, events, condition var... | Queue.Queue vs semaphores, locks, etc. in multithreaded Python code |
The principal challenge of
multi-threaded applications is
coordinating threads that share data
or other resources. To that end, the
threading module provides a number of
synchronization primitives including
locks, events, condition variables,
and semaphores.
While those tools are powerful, minor
design... | [
"I'm not sure I'd consider semaphores and locks \"more powerful methods\", as you suggest.\nQueues are generally a higher-order abstraction. In other words, you could use semaphores and locks to build thread-safe queues.\nWhich you'd use where depends on your application. Queues are good for passing \"work\" betw... | [
6,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004765785_multithreading_python.txt |
Q:
Using Mako Templates in Pyramid with Google App Engine
With Pyramid and mod_wsgi, to use mako templates you just add this line to development.ini:
mako.directories = house:templates
Unfortunately, Pyramid in the Google App Engine doesn't have an development.ini file, and I get the following error:
File "appengine... | Using Mako Templates in Pyramid with Google App Engine | With Pyramid and mod_wsgi, to use mako templates you just add this line to development.ini:
mako.directories = house:templates
Unfortunately, Pyramid in the Google App Engine doesn't have an development.ini file, and I get the following error:
File "appengine-monkey/pyramidapp/app/lib/python/pyramid-1.0a9-py2.5.egg/py... | [
"I found out from the pylons-devel mailing list. Figured I would post the answer here.\nThe way to do this is pass it to the Configurator as a setting. So in the __init__.py file make the following change:\nconfig = Configurator(settings={'mako.directories':['house:templates']}) \n\n"
] | [
9
] | [] | [] | [
"pyramid",
"python"
] | stackoverflow_0004740644_pyramid_python.txt |
Q:
Installing Numpy and Scipy - Can't find system python 2.6
I"m trying to install numpy and scipy for a data analysis class I have this semester. I'm trying to install it from the package on sourceforge.net, but as I follow the wizard I can't select my HD. There is a message saying numpy.1.5.1 requires System Python... | Installing Numpy and Scipy - Can't find system python 2.6 | I"m trying to install numpy and scipy for a data analysis class I have this semester. I'm trying to install it from the package on sourceforge.net, but as I follow the wizard I can't select my HD. There is a message saying numpy.1.5.1 requires System Python 2.6. I know it is there as when I type $ python version 2.6.1 ... | [
"The official Numpy 1.5.1 installer for Python 2.6 for OS X appear to require the python.org Python 2.6, not the Apple-supplied Python 2.6.\n"
] | [
7
] | [] | [] | [
"macos",
"numpy",
"python",
"python_2.6",
"scipy"
] | stackoverflow_0004765226_macos_numpy_python_python_2.6_scipy.txt |
Q:
Restart exception handling if one part fails
I have the following snippet:
def check1(n):
if len(n) != 4:
return raw_input("Enter 4 digits only")
else:
return True
def check2(n):
if n.isdigit() != True:
return raw_input("Enter digits only")
else:
return True
def ch... | Restart exception handling if one part fails | I have the following snippet:
def check1(n):
if len(n) != 4:
return raw_input("Enter 4 digits only")
else:
return True
def check2(n):
if n.isdigit() != True:
return raw_input("Enter digits only")
else:
return True
def check3(n):
if len(set(str(n))) != 4:
ret... | [
"Your question, as it stands, has nothing to do with exceptions. Try the following:\nchecks = [\n lambda n: (len(n)==4, \"Enter 4 digits only.\"),\n lambda n: (n.isdigit(), \"Enter digits only.\"),\n lambda n: (len(set(str(n)))==4, \"Enter non duplicate numbers only.\")\n]\n\na = raw_input(\"Enter the 4 nu... | [
3,
1,
1
] | [] | [] | [
"error_handling",
"loops",
"python"
] | stackoverflow_0004765320_error_handling_loops_python.txt |
Q:
How to limit file size when writing one?
I am using the output streams from the io module and writing to files. I want to be able to detect when I have written 1G of data to a file and then start writing to a second file. I can't seem to figure out how to determine how much data I have written to the file.
Is ther... | How to limit file size when writing one? | I am using the output streams from the io module and writing to files. I want to be able to detect when I have written 1G of data to a file and then start writing to a second file. I can't seem to figure out how to determine how much data I have written to the file.
Is there something easy built in to io? Or might I ha... | [
"if you are using this file for a logging purpose i suggest using the RotatingFileHandler in logging module like this:\nimport logging\nimport logging.handlers\n\nfile_name = 'test.log'\n\ntest_logger = logging.getLogger('Test')\nhandler = logging.handlers.RotatingFileHandler(file_name, maxBytes=10**9)\ntest_logger... | [
16,
9,
3,
2,
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003999007_file_io_python.txt |
Q:
How to retrieve BlobStore file name from BlobReferenceProperty?
I'm having a hard time understanding how to do something that should be straightforward.
class Spam(db.Model):
egg = blobstore.BlobReferenceProperty(blobstore.BlobKey, required=False)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler)... | How to retrieve BlobStore file name from BlobReferenceProperty? | I'm having a hard time understanding how to do something that should be straightforward.
class Spam(db.Model):
egg = blobstore.BlobReferenceProperty(blobstore.BlobKey, required=False)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file'... | [
"No, I think egg_blob (aka spam.egg) is a BlobInfo. Once you have spam.egg I don't think you need to go back to the blobstore for it, do you? Have you tried just using the spam.egg reference? i.e. do\nself.redirect('/serve/%s' % spam.egg.key())\n\n"
] | [
2
] | [] | [] | [
"blobstore",
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0004765751_blobstore_datastore_google_app_engine_python.txt |
Q:
Online compilers/runtime for Java, C++, Python and ObjC?
Does anyone know of a good online compiler/runtime (for C++, Java, Python, ObjC etc.) that I can access on the web?
What I'm looking for is something that would allow me to type in a program in a web form and to run the program and see the results online.
(... | Online compilers/runtime for Java, C++, Python and ObjC? | Does anyone know of a good online compiler/runtime (for C++, Java, Python, ObjC etc.) that I can access on the web?
What I'm looking for is something that would allow me to type in a program in a web form and to run the program and see the results online.
(Let's not get into the why for now. Suffice it to say for the ... | [
"ideone is something better but what particular advence do you need? \n",
"http://codepad.org/\n\ncodepad.org is an online\n compiler/interpreter, and a simple\n collaboration tool. Paste your code\n below, and codepad will run it and\n give you a short URL you can use to\n share it in chat or email.\n\nLang... | [
40,
21,
3,
3,
2,
2,
2,
1,
1
] | [] | [] | [
"c++",
"compiler_construction",
"java",
"python",
"runtime"
] | stackoverflow_0000567682_c++_compiler_construction_java_python_runtime.txt |
Q:
Modifying specific array elements in Python 3.1
I have two arrays: array and least_common (filter array)
The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.
for i in range (len(array)):
for j in range(len(leas... | Modifying specific array elements in Python 3.1 | I have two arrays: array and least_common (filter array)
The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.
for i in range (len(array)):
for j in range(len(least_common)):
if array[i] is least_common[j... | [
"In Python, what you are trying to do is done using lists. There is another separate data type called arrays, but that is for totally different purpose. Please don't confuse and use the proper terminology, list.\nLists can be iterated through. You need to not index the elements out of the list and then access them ... | [
3,
3,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004767078_list_python.txt |
Q:
Parameterising an import statement
I maintain a Python module that wraps and exposes the functionality of a DLL (also maintained by me). The interfacing with the DLL uses ctypes.
This all works wonderfully thanks to the wonders of ctypes. However, as I am by no means a Python expert, there are some parts of the ... | Parameterising an import statement | I maintain a Python module that wraps and exposes the functionality of a DLL (also maintained by me). The interfacing with the DLL uses ctypes.
This all works wonderfully thanks to the wonders of ctypes. However, as I am by no means a Python expert, there are some parts of the Python that I feel are not idiomatic.
In... | [
"You should defer loading the DLL to the point where it's actually used for the first time, and offer an optional function initialize:\n_initialized=False\ndef initialize(path=None):\n if _initialized:\n if path:\n raise ValueError, \"initialize called after first use\"\n return\n if path is None:\n ... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004767160_python.txt |
Q:
How can I rotate a 3D array?
Currently, if I want to compare pressure under each of the paws of a dog, I only compare the pressure underneath each of the toes. But I want to try and compare the pressures underneath the entire paw.
But to do so I have to rotate them, so the toes overlap (better). Because most of t... | How can I rotate a 3D array? | Currently, if I want to compare pressure under each of the paws of a dog, I only compare the pressure underneath each of the toes. But I want to try and compare the pressures underneath the entire paw.
But to do so I have to rotate them, so the toes overlap (better). Because most of the times the left and right paws a... | [
"Why would you do it that way? Why not simply integrate the whole region and compare? In this case you'll get a magnitude of the force and you can simply compare scalars which would be much easier.\nIf you need to somehow compare regions(and hence that's why you need to align them) then maybe attempt a feature extr... | [
3,
2
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0004765341_image_processing_python.txt |
Q:
Generating unique number sequence for use as entity key for app engine datastore
Has anyone got any example code for creating a unique number sequence to be used as keys for an entity in a Google app engine datastore?
Would like to use sequential order numbers as the key.
A:
Use db.allocate_ids() as described he... | Generating unique number sequence for use as entity key for app engine datastore | Has anyone got any example code for creating a unique number sequence to be used as keys for an entity in a Google app engine datastore?
Would like to use sequential order numbers as the key.
| [
"Use db.allocate_ids() as described here to generate unique IDs for your entities.\nHere's a quick example derived from the example at the above link:\nfrom google.appengine.ext import db\n\n# get unique ID number - I just get 1 here, but you could get many ...\nnew_ids = db.allocate_ids(handmade_key, 1)\n\n# db.al... | [
6,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002825934_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to transfer basic objects between Ruby and Python?
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:
IO.popen('./convert.py', 'w') do |w|
w.write({ :height => height, :width => width, :id => job_id, :data =>... | How to transfer basic objects between Ruby and Python? | Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:
IO.popen('./convert.py', 'w') do |w|
w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json)
w.write "\n"
w.close_write
end
In t... | [
"Maybe MessagePack is the way to go then. Bindings for several languages exist, including Ruby and Python.\n",
"It certainly appears generating and (especially) parsing the JSON could be improved, as a simple custom format led to a huge difference, without resorting to a non-text format. I had to change your use... | [
9,
2
] | [] | [] | [
"python",
"ruby",
"serialization"
] | stackoverflow_0004767514_python_ruby_serialization.txt |
Q:
operator.setitem problem in python 3
I have a problem when using operator.setitem in python 3.
When I use the code below and run it in python 3.1.
people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)
>>> {}
That just prin... | operator.setitem problem in python 3 | I have a problem when using operator.setitem in python 3.
When I use the code below and run it in python 3.1.
people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)
>>> {}
That just prints out a empty dictionary {}.
But I use th... | [
"That's a very unpythonesque way to do it. This is much better (and more efficient):\npeople = (('fred','sam','jane','betty'), (1,2,3,4))\np_dict = dict(zip(*people))\n\nWorks on 2.x and 3.x.\n",
"The problem is that the map() is never 'executed'. In Python 3, map just returns an iterator - the individual element... | [
3,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004767729_python_python_3.x.txt |
Q:
dividing and conquering etree.iterparse using multiprocessing
so let's imagine a large xml document (filesize > 100 mb) that we want to iterparse using cElementTree.iterparse.
but all those cores Intel promised us would be worthwhile, how do we put them to use? here's what I want:
from itertools import islice
fro... | dividing and conquering etree.iterparse using multiprocessing | so let's imagine a large xml document (filesize > 100 mb) that we want to iterparse using cElementTree.iterparse.
but all those cores Intel promised us would be worthwhile, how do we put them to use? here's what I want:
from itertools import islice
from xml.etree import ElementTree as etree
tree_iter = etree.iterpars... | [
"I think you need a good threadpool with a task queue for this. I found (and use) this very good one (it's in python3, but shouldn't be too hard to convert to 2.x):\n# http://code.activestate.com/recipes/577187-python-thread-pool/\n\nfrom queue import Queue\nfrom threading import Thread\n\nclass Worker(Thread):\n ... | [
0
] | [] | [] | [
"elementtree",
"multiprocessing",
"python",
"xml"
] | stackoverflow_0004767741_elementtree_multiprocessing_python_xml.txt |
Q:
adding a class via python
Having a such html
somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"
Via python I want to add class "foo" to those <pre> tags which contains a child <code> thus my output will be :
somehtml = "<p>Here is my solution: </p><pre... | adding a class via python | Having a such html
somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"
Via python I want to add class "foo" to those <pre> tags which contains a child <code> thus my output will be :
somehtml = "<p>Here is my solution: </p><pre class="foo"><code> some code h... | [
"Using lxml, it could be done like this:\nimport lxml.html as lh\nimport io\n\nsomehtml = \"<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>\"\n\ndoc=lh.parse(io.BytesIO(somehtml))\nroot=doc.getroot() \npres=root.xpath('//pre/code/..')\n\nfor pre in pres:\n pre.... | [
4
] | [] | [] | [
"html",
"python"
] | stackoverflow_0004767815_html_python.txt |
Q:
Tipfy: How to display blob in template?
Given is on gae using tipfy (python) the following model:
greeting.avatar = db.Blob(avatar)
What is the template-tag to display a blob (here image)?
A:
In this case the blob is an an image, which is great. Just use images.get_serving_url(blob_key) and you're happy. I've u... | Tipfy: How to display blob in template? | Given is on gae using tipfy (python) the following model:
greeting.avatar = db.Blob(avatar)
What is the template-tag to display a blob (here image)?
| [
"In this case the blob is an an image, which is great. Just use images.get_serving_url(blob_key) and you're happy. I've used this function, and trust me, it is awesome for serving images. Just append =sxx to the url where xx is the pixel size you want. It automatically resizes the image and serves it. \nIf the blob... | [
2,
1
] | [] | [] | [
"blob",
"google_app_engine",
"python",
"tipfy"
] | stackoverflow_0004763715_blob_google_app_engine_python_tipfy.txt |
Q:
Fluid flow, heat transfer and Python
full EDIT:
I will give some more information about the whole problem. The project is in early stage and my question is actually only about a narrow portion of the thing.
the final goal:
I am currently trying to simulate the flow of hot air around a rigid obstacle in Python. I h... | Fluid flow, heat transfer and Python | full EDIT:
I will give some more information about the whole problem. The project is in early stage and my question is actually only about a narrow portion of the thing.
the final goal:
I am currently trying to simulate the flow of hot air around a rigid obstacle in Python. I have a steady inflow of air, the flow in th... | [
"Python would actually be a fine choice if you were writing it all from scratch. But you'll need a LOT of background to do it from scratch.\nA coupled solution is a difficult problem.\nIt's been pointed out to me that you're using a package - FEniCS (thank you, Sven). My original answer needs some amendment. I'l... | [
6
] | [] | [] | [
"pde",
"physics",
"python",
"scientific_computing"
] | stackoverflow_0004768045_pde_physics_python_scientific_computing.txt |
Q:
A charset problem about parsing HTML with lxml.html
I've being trying to parse an html page in Python using lxml.html.
I used the following code:
import lxml.html as H
page = open('page.html', 'r').read()
doc = H.fromstring(page)
print H.tostring(doc)
The page.html is a web page I downloaded with a proxy program ... | A charset problem about parsing HTML with lxml.html | I've being trying to parse an html page in Python using lxml.html.
I used the following code:
import lxml.html as H
page = open('page.html', 'r').read()
doc = H.fromstring(page)
print H.tostring(doc)
The page.html is a web page I downloaded with a proxy program I wrote before which do some work about using proxy and e... | [
"http://lxml.de/parsing.html#python-unicode-strings says:\n\nYou should generally avoid converting\n XML/HTML data to unicode before\n passing it into the parsers. It is\n both slower and error prone.\n\n"
] | [
2
] | [] | [] | [
"character_encoding",
"html",
"lxml",
"parsing",
"python"
] | stackoverflow_0004768054_character_encoding_html_lxml_parsing_python.txt |
Q:
Downloading Files with Python Urllib, Urllib2
I am trying to download files from a website using urllib as described in this thread: link text
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
I am able to download the files (mostly pdf) but all I get is corrupted files that can... | Downloading Files with Python Urllib, Urllib2 | I am trying to download files from a website using urllib as described in this thread: link text
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
I am able to download the files (mostly pdf) but all I get is corrupted files that cannot open. I suspect it's because the website requir... | [
"First urllib2 actually supports cookies and cookie handling should be easy, second of all you can check what kind of file you have downloaded. E.g. AFAIK all mp3 starts with the bytes \"ID3\"\nimport cookielib, urllib2\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nr =... | [
1,
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0004768004_python_urllib_urllib2.txt |
Q:
How can I combine stdlib logging with py.test
I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.
The problem with this ... | How can I combine stdlib logging with py.test | I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.
The problem with this is that the logging module ends up trying to log me... | [
"Logging/capturing interactions are to better work with the upcoming 2.0.1 release, which you can install already as a development snapshot by:\npip install -i http://pypi.testrun.org pytest \n\nYou should get at least \"2.0.1.dev9\" when you type \"py.test --version\" afterwards. And the problem/error your posted ... | [
6,
3
] | [
"All you need to do is to pass the -s option to py.test, so that it won't capture the stdout.\n"
] | [
-1
] | [
"logging",
"pytest",
"python",
"unit_testing"
] | stackoverflow_0004724122_logging_pytest_python_unit_testing.txt |
Q:
Python login to website via twitter
A website use 'login via twitter'. Just like this site use facebook. How do I log in and get login cookies for the website (using python), if I know twitter username and password?
A:
In general , Twitter doesn't support 'username' and 'password' Authentication. Now, Twitter us... | Python login to website via twitter | A website use 'login via twitter'. Just like this site use facebook. How do I log in and get login cookies for the website (using python), if I know twitter username and password?
| [
"In general , Twitter doesn't support 'username' and 'password' Authentication. Now, Twitter uses OAuth2 for authentication. There are python-twitter libraries available for this. such as : https://github.com/simplegeo/python-oauth2\nThis could be helpful to You: http://abhi74k.wordpress.com/2010/12/21/tweeting-fro... | [
5,
2
] | [] | [] | [
"authorization",
"python",
"twitter"
] | stackoverflow_0004768169_authorization_python_twitter.txt |
Q:
Rerendering a Pylons form with a querystring parameter after FormEncode validation fails
My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action
I have a simple form that tak... | Rerendering a Pylons form with a querystring parameter after FormEncode validation fails | My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action
I have a simple form that takes a required querystring (id) value, uses that as a hidden form field value, and validates th... | [
"If you are using an id arg in your newnode my preference would be to use the same arg in it's related createnode function. Adapt your post url to use an id, and you wont need to hidden the parent_id because it is now part of the url.\n<form method=\"post\" action=\"/node/createnode/${request.urlvars['id']}\">\n <... | [
1,
0
] | [] | [] | [
"formencode",
"pylons",
"python",
"validation"
] | stackoverflow_0004742842_formencode_pylons_python_validation.txt |
Q:
Different realizations with the same random seed
I have a project with different modules. Then I have a file called Main.py which has some code that calls these modules during the run. In the file Main.py I set random seed using:
random.seed(2)
The output that I get from different runs is not identical even if I ... | Different realizations with the same random seed | I have a project with different modules. Then I have a file called Main.py which has some code that calls these modules during the run. In the file Main.py I set random seed using:
random.seed(2)
The output that I get from different runs is not identical even if I use the same random seed. Could you tell me why this m... | [
"Thread safety deals with concurrent programming - or in other words, when you two different codepaths executing at the same time through means of threading. As something that might be a single line of code to you as a programmer are usually a multitude of seperate actions, a different thread might interfere with w... | [
1
] | [] | [] | [
"python",
"random",
"seed"
] | stackoverflow_0004767932_python_random_seed.txt |
Q:
boost python with threads
It seems boost::python and boost::thread don't really like each other for what I can tell.
Please refer to http://pastebin.com/Cy123mJK
This is a simplification of the problems I am having with my boost::python and boost::thread-based application.
If anyone can tell me why these problems ... | boost python with threads | It seems boost::python and boost::thread don't really like each other for what I can tell.
Please refer to http://pastebin.com/Cy123mJK
This is a simplification of the problems I am having with my boost::python and boost::thread-based application.
If anyone can tell me why these problems are occurring; I have no clue, ... | [
"You are running python in multiple threads at the same time in Producer::run() and Consumer::run().\nTo be exact, you run this before locking the mutex:\nboost::python::object writer = this->k->Get<boost::python::object>(\"write\");\n\nMaybe you didn't realize that Boost eventually calls PyObject_GetItem when you ... | [
7
] | [] | [] | [
"boost",
"crash",
"multithreading",
"python"
] | stackoverflow_0004685216_boost_crash_multithreading_python.txt |
Q:
How to perform double sort inside an array?
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo
class foo:
def __init__(self,a1,a2):
self.attrb1 = a1
self.attrb2 = a2
def sort(self):
return self.attrb1
An array "bar" contain obj... | How to perform double sort inside an array? | I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo
class foo:
def __init__(self,a1,a2):
self.attrb1 = a1
self.attrb2 = a2
def sort(self):
return self.attrb1
An array "bar" contain objects of type foo. I want to sort the array in des... | [
"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)\n\nAnd you don't need to define foo.sort\n",
"You're using classes already so just implement __lt__:\nclass foo:\n def __init__(self,a1,a2):\n self.attrb1 = a1\n self.attrb2 = a2\n\n # just for convenience in `__lt__`\n def default... | [
7,
2,
1,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004768151_python_sorting.txt |
Q:
Python Image Uploading with AjaxUpload
I'm trying to use AjaxUpload with Python:
http://valums.com/ajax-upload/
I would like to know how to access the uploaded file with Python. On the web site, it says:
* PHP: $_FILES['userfile']
* Rails: params[:userfile]
What is the Syntax for Python?
request.params['userfil... | Python Image Uploading with AjaxUpload | I'm trying to use AjaxUpload with Python:
http://valums.com/ajax-upload/
I would like to know how to access the uploaded file with Python. On the web site, it says:
* PHP: $_FILES['userfile']
* Rails: params[:userfile]
What is the Syntax for Python?
request.params['userfile'] doesn't seem to work.
Thanks in advance!... | [
"import cgi\n\n#This will give you the data of the file,\n# but won't give you the filename, unfortunately.\n# For that you have to do some other trick.\nfile_data = cgi.FieldStorage.getfirst('file')\n\n#<IGNORE if you're not using mod_python>\n\n#(If you're using mod_python you can also get the Request object\n# b... | [
1,
1,
0
] | [] | [] | [
"ajax_upload",
"image_uploading",
"pylons",
"python",
"python_imaging_library"
] | stackoverflow_0001517959_ajax_upload_image_uploading_pylons_python_python_imaging_library.txt |
Q:
Retrieving a set of model objects that are indirectly related
I have 4 models:
class TransitLine(models.Model):
name = models.CharField(max_length=32)
class Stop(models.Model):
line = models.ForeignKey(TransitLine, related_name='stops')
class ExitType(models.Model):
name = models.CharField(max_length... | Retrieving a set of model objects that are indirectly related | I have 4 models:
class TransitLine(models.Model):
name = models.CharField(max_length=32)
class Stop(models.Model):
line = models.ForeignKey(TransitLine, related_name='stops')
class ExitType(models.Model):
name = models.CharField(max_length=32)
people_limit = models.PositiveSmallIntegerField()
class E... | [
"I would try something like this:\nExitType.objects.filter(exits__stop__line=line).distinct()\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python",
"sql"
] | stackoverflow_0004769377_django_django_models_django_queryset_python_sql.txt |
Q:
Returning the argument from a list comprehension that's result satisfies
It's a horrible title, I know; the basic explanation of what I mean is:
y=min([func(x) for x in range(z)])
As is, y contains the value of the output of func(x_min). (x_min might not actually be the smaller value in the range).
Basically, I'... | Returning the argument from a list comprehension that's result satisfies | It's a horrible title, I know; the basic explanation of what I mean is:
y=min([func(x) for x in range(z)])
As is, y contains the value of the output of func(x_min). (x_min might not actually be the smaller value in the range).
Basically, I'm looking for a way to get x_min in this generic case in a more pythonic way. A... | [
"Use key argument:\nmin(iterable, key=func)\n\n"
] | [
4
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0004769664_functional_programming_python.txt |
Q:
Google Python gdata Library Installation Failing
[Note, I have removed some information, such as my username, and the
IDs to my spreadsheets]
Hi! I'm on a mac, and I'm trying my best to install gdata for google python.
Before I go on, I'm using this tutorial here:
http://code.google.com/apis/gdata/articles/pyt... | Google Python gdata Library Installation Failing | [Note, I have removed some information, such as my username, and the
IDs to my spreadsheets]
Hi! I'm on a mac, and I'm trying my best to install gdata for google python.
Before I go on, I'm using this tutorial here:
http://code.google.com/apis/gdata/articles/python_client_lib.html
I have python version: 2.6.1, so ... | [
"sudo mv /usr/local/lib/python2.6/dist-packages/* /usr/lib/python2.6/dist-packages\n\n"
] | [
3
] | [] | [] | [
"failed_installation",
"gdata_python_client",
"python"
] | stackoverflow_0004673610_failed_installation_gdata_python_client_python.txt |
Q:
Django - importing dynamically
I'm trying to do a dynamic import of a python module in django. I have two different apps that I want to import from, and I want to replace these import statements:
from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
I am dynamically able to create the str... | Django - importing dynamically | I'm trying to do a dynamic import of a python module in django. I have two different apps that I want to import from, and I want to replace these import statements:
from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
I am dynamically able to create the strings App1ProfileForm and App2Profile... | [
"You don't want to do this. Imports are done when the relevant code is first executed - in the case of module-level imports, it's when the module itself is imported. If you're depending on something in the request, or some other run-time element, to determine what class you want, then this will not work.\nInstead, ... | [
4,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004769398_django_python.txt |
Q:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?
I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simp... | Learning Python from Ruby; Differences and Similarities | I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?
I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs... | [
"Here are some key differences to me:\n\nRuby has blocks; Python does not.\nPython has functions; Ruby does not. In Python, you can take any function or method and pass it to another function. In Ruby, everything is a method, and methods can't be directly passed. Instead, you have to wrap them in Proc's to pass ... | [
155,
27,
11,
8,
6
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0004769004_python_ruby.txt |
Q:
Learning Ruby from Python; Differences and Similarities
Inspired by Learning Python from Ruby; Differences and Similarities.
I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic). The question I'm linking to addresses t... | Learning Ruby from Python; Differences and Similarities | Inspired by Learning Python from Ruby; Differences and Similarities.
I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic). The question I'm linking to addresses this a bit, but are there any other resources out there that t... | [
"While not targeted at Python programmers, you might find this idomatic Ruby talk useful.\n(Related, but for Python: Code Like a Pythonista: Idiomatic Python)\n",
"The Ruby website has a page exactly on this topic. It's a summary list, so other answers with more best-practice style comments are surely a good idea... | [
11,
7
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0004769478_python_ruby.txt |
Q:
How do I pass url parameter to form value?
The form has this hidden field
<input type="hidden" name="dir_type" value="tshirt">
url parameters are
/dir?type=tshirt
/dir?type=books
/dir?type=posters
and so on.
Now I hard coded value="tshirts" but how do I get parameter for the relevant page?
I found several pages ... | How do I pass url parameter to form value? | The form has this hidden field
<input type="hidden" name="dir_type" value="tshirt">
url parameters are
/dir?type=tshirt
/dir?type=books
/dir?type=posters
and so on.
Now I hard coded value="tshirts" but how do I get parameter for the relevant page?
I found several pages like this dealing with similar topics but I did ... | [
"a. pass the type value to the view:\nclass Directory(webapp.RequestHandler):\n def get(self):\n ....\n merchandise_type = self.request.get(\"type\", \"\")\n items = Item.all()\n items.filter(\"type =\", merchandise_type)\n path = os.path.join(os.path.dirname(__file__), 'dir_details... | [
2
] | [] | [] | [
"forms",
"google_app_engine",
"html",
"python"
] | stackoverflow_0004769063_forms_google_app_engine_html_python.txt |
Q:
What is the best way in python to get a denormalized array from this ordered array?
I have this array:
>>> print raw_data
['LEVEL 1',
'SUBJECT A',
'GROUP X',
'COMMENT i',
'COMMENT ii',
'COMMENT iii',
'GROUP Y',
'COMMENT iv',
'COMMENT v',
'COMMENT vi',
'LEVEL 2',
'SUBJECT B',
'GROUP Z',
'COMMENT vii',
'COMMENT viii... | What is the best way in python to get a denormalized array from this ordered array? | I have this array:
>>> print raw_data
['LEVEL 1',
'SUBJECT A',
'GROUP X',
'COMMENT i',
'COMMENT ii',
'COMMENT iii',
'GROUP Y',
'COMMENT iv',
'COMMENT v',
'COMMENT vi',
'LEVEL 2',
'SUBJECT B',
'GROUP Z',
'COMMENT vii',
'COMMENT viii',
'COMMENT ix',
'SUBJECT C',
'GROUP X2',
'COMMENT x',
'COMMENT xi',
'COMMENT xii',
'COMM... | [
"Pseudocode, don't have a handy python interpreter right now:\nSet LEVEL, SUBJECT, GROUP to None, results to []\n\nLoop over the list\n if its a 'LEVEL', set LEVEL to it\n if its a 'SUBJECT', set SUBJECT to it\n if its a 'GROUP', set GROUP to it\n if its a \"COMMENT\", append [LEVEL SUBJECT GROUP and COMMENT] t... | [
5,
3
] | [] | [] | [
"arrays",
"python",
"roman_numerals"
] | stackoverflow_0004770289_arrays_python_roman_numerals.txt |
Q:
How do I create as assoc record with SQLAlchemy in Pylons?
I've got a User model and a Ledger model with a many-to-many relationship. SQLAlchemy has created my database tables correctly, so I'm pretty sure it's got the right mappings. I can create a new record in each table, but I can't figure out how to associa... | How do I create as assoc record with SQLAlchemy in Pylons? | I've got a User model and a Ledger model with a many-to-many relationship. SQLAlchemy has created my database tables correctly, so I'm pretty sure it's got the right mappings. I can create a new record in each table, but I can't figure out how to associate them. How do I do it?
My table definitions:
user_table = sa... | [
"I found my answer in this tutorial.\nledger = model.Ledger()\nledger.name = name\nledger.users.append(user)\nmeta.Session.add(ledger)\nmeta.Session.commit()\n\n"
] | [
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004770317_pylons_python_sqlalchemy.txt |
Q:
store a queryset in the session with django
I have problem storing a big queryset in the session. This queryset is from a search and I need to store it for paginate inside every result. This is the code in my view:
c = queryset.order_by('-order')
request.session['query_search'] = c
You can see an example in my s... | store a queryset in the session with django | I have problem storing a big queryset in the session. This queryset is from a search and I need to store it for paginate inside every result. This is the code in my view:
c = queryset.order_by('-order')
request.session['query_search'] = c
You can see an example in my site: http://www.lukmi.com/escorts/barcelona/
This... | [
"You could store only the list of PKs and then query through them when you need to.\n",
"I'm currently developing a very similar site to yours also in Django.\nI stored the queryset in cache, where cache key is an urlencoded string of search parameters- this way if someone performs identical search it doesn't hav... | [
4,
3,
0,
0
] | [] | [] | [
"django",
"django_queryset",
"pagination",
"python",
"session"
] | stackoverflow_0001975700_django_django_queryset_pagination_python_session.txt |
Q:
Functional Equivalent to Python Statement Logic
I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the operator module, but the behavior is remarkable different.
For example, the and statement does the behavior I want, whereas operator.and_ s... | Functional Equivalent to Python Statement Logic | I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the operator module, but the behavior is remarkable different.
For example, the and statement does the behavior I want, whereas operator.and_ seems to requir an explicit type comparison, or else i... | [
"The functions operator.and_ and operator.or_ are the equivalent of the bit-wise \"and\" function and \"or\" function, respectively. There are no functions representing the and and or operators in operator, but you can use the built-ins any() and all() instead. They will take a single sequence as argument, but yo... | [
9
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0004770727_python_scripting.txt |
Q:
Populating a PDF file - Python
I have a ready-made PDF document containing placeholder values in certain areas.
e.g. {{ first_name }}, {{ postcode }}, ...
I need to substitute these values using python.
Any suggestions?
A:
It's a somewhat strange way to go about things, as PDFs aren't really designed to be modi... | Populating a PDF file - Python | I have a ready-made PDF document containing placeholder values in certain areas.
e.g. {{ first_name }}, {{ postcode }}, ...
I need to substitute these values using python.
Any suggestions?
| [
"It's a somewhat strange way to go about things, as PDFs aren't really designed to be modified. Depending on how those PDFs you have were generated, it may be very hard to do any replacement. You cannot easily alter any formatting, including line breaks, so the only case this is really useful is if you have some so... | [
4,
3,
0
] | [] | [] | [
"pdf",
"python"
] | stackoverflow_0004750441_pdf_python.txt |
Q:
Proving the primality of strong probable primes
Using the probabilistic version of the Miller-Rabin test, I have generated a list of medium-large (200-300 digit) probable primes. But probable ain't good enough! I need to know these numbers are prime. Is there a library -- preferably wrapped or wrappable in Python ... | Proving the primality of strong probable primes | Using the probabilistic version of the Miller-Rabin test, I have generated a list of medium-large (200-300 digit) probable primes. But probable ain't good enough! I need to know these numbers are prime. Is there a library -- preferably wrapped or wrappable in Python -- that implements one of the more efficient primalit... | [
"As an algorithm that gives a reliable polynomial primality test, consider AKS. There is an older SO article referencing implementations and presentations of the algorithm.\n",
"I've found that the Pari/GP library and language use APR-CL to prove primality, which is actually the preferred algorithm for numbers in... | [
9,
7
] | [] | [] | [
"algorithm",
"primes",
"python"
] | stackoverflow_0004752190_algorithm_primes_python.txt |
Q:
Python- The Word Game "Ghost", File I/O, and List question
I want to create computer for the word-game Ghost. However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work):
import os, random, sys, math, string
def main():
... | Python- The Word Game "Ghost", File I/O, and List question | I want to create computer for the word-game Ghost. However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work):
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictio... | [
"I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).\nIt is better to just make a new list. One possible way to do this is to replace the lines\nfor line in wordlist:\n if not line.startswith(word):\n wordlist.remove(line)\n\nwith\... | [
2,
1,
0
] | [] | [] | [
"file",
"list",
"python",
"string"
] | stackoverflow_0004764553_file_list_python_string.txt |
Q:
repeating previous regex
I have a line (and a arbitrary number of them)
0 1 1 75 55
I can get it by doing
x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
if x != None:
print(x.group(1))
print(x.group(2))
print(x.group(3))
But there must be a neater way to write this... | repeating previous regex | I have a line (and a arbitrary number of them)
0 1 1 75 55
I can get it by doing
x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
if x != None:
print(x.group(1))
print(x.group(2))
print(x.group(3))
But there must be a neater way to write this. I was looking at the docs fo... | [
"Repetition of capturing groups does not work, and won't any time soon (in the sense of having the ability to individually actually access the matched parts) – you will just have to write the regex the long way or use a string method such as .split(), avoiding regex altogether.\n",
"Have you considered findall wh... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004771096_python_regex.txt |
Q:
How to keep imports neat in Django?
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY princip... | How to keep imports neat in Django? | This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it... | [
"You're right that it's easy to ignore DRY when working Django imports, or with python imports in general.\nIt's sometimes beneficial to separate common imports by domain, then create a module for managing those imports. The next step is one of the few exceptions I make to my personal rule of \"Don't use import *\... | [
4,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004763372_django_python.txt |
Q:
Python application for updating an embedded device - is it feasible?
I am considering to write a tool for updating a WinCE based device. The update procedure consists of following steps:
get several files from two different zip-archives
start target and while it is booting send a command over serial interface RS2... | Python application for updating an embedded device - is it feasible? | I am considering to write a tool for updating a WinCE based device. The update procedure consists of following steps:
get several files from two different zip-archives
start target and while it is booting send a command over serial interface RS232 (switch in bootstrap mode)
transfer WinCE-OS image and a flash-tool ove... | [
"You can use pyserial or python for windows extensions to send the serial command, telnetlib to send telnet commands and and ftplib for the FTP part. Eventually, you even can install Python on the WinCE device, but should should not need it.\n"
] | [
1
] | [] | [] | [
"python",
"windows_ce"
] | stackoverflow_0004769930_python_windows_ce.txt |
Q:
Basic Python imports question
If I have a src directory setup like this:
main.py
pkg1:
__init__.py
util.py
pkg2:
__init__.py
test.py
Can you tell me the best way to import pkg1.util from main.py and from test.py?
Thanks! (If I need to have another __init__.py file in the root directory, let me kno... | Basic Python imports question | If I have a src directory setup like this:
main.py
pkg1:
__init__.py
util.py
pkg2:
__init__.py
test.py
Can you tell me the best way to import pkg1.util from main.py and from test.py?
Thanks! (If I need to have another __init__.py file in the root directory, let me know?)
| [
"Since you mention that this is Python 3, you do not have to add the following to your .py files. I would still though because it helps backwards portability if some poor sod who's stuck on Python 2 needs to use your code:\nfrom __future__ import absolute_import\n\nGiven that you are using Python 3, or that you're... | [
5,
1
] | [] | [] | [
"import",
"python",
"python_3.x"
] | stackoverflow_0004771475_import_python_python_3.x.txt |
Q:
Python defining methods
I have been reading some python code out there and I see some variations on how one write method.
Some write (example 1):
def A() :
*method A implementation*
def B():
*method B implementation*
Others write (example 2):
def A() :
*method A implementation*
def B():
*method B implemen... | Python defining methods | I have been reading some python code out there and I see some variations on how one write method.
Some write (example 1):
def A() :
*method A implementation*
def B():
*method B implementation*
Others write (example 2):
def A() :
*method A implementation*
def B():
*method B implementation*
Does anyone know the... | [
"As far as I understand in the second example function B() will be accessible only from the function A(). And in the first one both functions will be globally accessible.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004772023_python.txt |
Q:
I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined
Defining __setattr__ overrides all setter methods / properties I define in a class. I want to use the defined setter methods in the property, if a property exists for a ... | I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined | Defining __setattr__ overrides all setter methods / properties I define in a class. I want to use the defined setter methods in the property, if a property exists for a field and use self.__dict__[name] = value otherwise.
Help! I found one solution that used __setitem__, but this does not work for me
Where are prope... | [
"You need to rewrite your __setattr__ function. As per the docs, new style classes should use baseclass.__setattr__(self, attr, value) instead of self.__dict__[attr] = value. The former will lookup any descriptors whereas the latter will assign directly to the dict.\nSo rewrite your method as\ndef __setattr__(self,... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0004772095_python.txt |
Q:
Distinguishing between same exception by where it was called
I have an unavoidable situation that looks like this (simplified):
FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
FUNCTION_TO_CALL(args, kargs)
def y(foo, bar=None):
if foo == bar: # actually not this stupid
raise TypeError()... | Distinguishing between same exception by where it was called | I have an unavoidable situation that looks like this (simplified):
FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
FUNCTION_TO_CALL(args, kargs)
def y(foo, bar=None):
if foo == bar: # actually not this stupid
raise TypeError()
else:
pass
def z(foo, bar, baz=None):
pass
Horribly ugl... | [
"You could always make your own exceptions subclassing TypeError, and use them individually.\nclass TooManyArgumentsError(TypeError):\n pass\nclass EqualityError(TypeError):\n pass\n\n",
"Matt Billenstein's comment on Keith Morrow's answer is the right way to do this. But alternatively, if for some bizarre ... | [
3,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004772233_python_python_3.x.txt |
Q:
Anybody know a valid mechanism to detect the degree of similarity between two strings
I need to know how far the two strings are similar in terms of some measuring index
A:
Probably the most commonly used metric is something called Levenshtein Distance, sometimes called "Edit Distance". In simple terms, it measu... | Anybody know a valid mechanism to detect the degree of similarity between two strings | I need to know how far the two strings are similar in terms of some measuring index
| [
"Probably the most commonly used metric is something called Levenshtein Distance, sometimes called \"Edit Distance\". In simple terms, it measures the number of edits (additions, deletions, or in a generalized method, also transpositions) that you need to make the strings in the comparison identical.\nThe algorithm... | [
6,
5
] | [] | [] | [
"python"
] | stackoverflow_0004772438_python.txt |
Q:
Input LOG file information into MySQL using Python
I need to take a linux log file and enter the data into a mysql table, and separate each field into columns. I have been trying to use the LOAD DATA INFILE command. Only problem is, the data is not delimited and I cannot TERMINATE FIELDS BY '' because the file in... | Input LOG file information into MySQL using Python | I need to take a linux log file and enter the data into a mysql table, and separate each field into columns. I have been trying to use the LOAD DATA INFILE command. Only problem is, the data is not delimited and I cannot TERMINATE FIELDS BY '' because the file includes spaces in the log message. If anyone has any ide... | [
"Pre-format this file. I'm assuming the blank lines in your file are not there (otherwise you can remove them using the commented code). Let's say you're using python:\nparsed = open(\"parsed.txt\", 'a') ... | [
1
] | [] | [] | [
"file_io",
"load",
"mysql",
"python"
] | stackoverflow_0004748400_file_io_load_mysql_python.txt |
Q:
Easy_install or pip with NTLM auth
In my working environment, internet access is managed by NTLM authentication and is associated with Windows user account, and easy_install or pip doesn't work:
C:\>easy_install django
install_dir D:\Python26\Lib\site-packages\
Searching for django
Reading http://pypi.python.org/s... | Easy_install or pip with NTLM auth | In my working environment, internet access is managed by NTLM authentication and is associated with Windows user account, and easy_install or pip doesn't work:
C:\>easy_install django
install_dir D:\Python26\Lib\site-packages\
Searching for django
Reading http://pypi.python.org/simple/django/
Download error: timed out ... | [
"Use NTLMAPS, and point pip to the local proxy.\n"
] | [
4
] | [] | [] | [
"easy_install",
"ntlm",
"pip",
"python"
] | stackoverflow_0004772649_easy_install_ntlm_pip_python.txt |
Q:
Django with huge mysql database
What would be the best way to import multi-million record csv files into django.
Currently using python csv module, it takes 2-4 days for it process 1 million record file. It does some checking if the record already exists, and few others.
Can this process be achieved to execute in ... | Django with huge mysql database | What would be the best way to import multi-million record csv files into django.
Currently using python csv module, it takes 2-4 days for it process 1 million record file. It does some checking if the record already exists, and few others.
Can this process be achieved to execute in few hours.
Can memcache be used some... | [
"I'm not sure about your case, but we had similar scenario with Django where ~30 million records took more than one day to import.\nSince our customer was totally unsatisfied (with the danger of losing the project), after several failed optimization attempts with Python, we took a radical strategy change and did th... | [
3,
1,
0,
0,
0
] | [] | [] | [
"csv",
"django",
"python"
] | stackoverflow_0003385400_csv_django_python.txt |
Q:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.
Example: Say I want 3
s = [1,2,3,4,5,3,9,8] => s[2] appears first
A:
def first_dup( seq ):
# keep track of the position... | Find the position of a specific number that appear first in the list [python] | So I want to find a number that appears more than once in the list. I want the position of the first one.
Example: Say I want 3
s = [1,2,3,4,5,3,9,8] => s[2] appears first
| [
"def first_dup( seq ):\n # keep track of the positions\n seen = {}\n for pos,item in enumerate(seq):\n if item in seen:\n # saw it before, so its a duplicate\n return seen[item]\n else:\n # first time we see it, store the pos\n seen[item] = pos\n\n"... | [
5,
3,
1,
0,
0,
0
] | [
"s.index(3)\n\nwill return 2, as you desire.\nindex will raise ValueError if the specified item is not in the list.\n"
] | [
-1
] | [
"duplicates",
"list",
"position",
"python"
] | stackoverflow_0004772374_duplicates_list_position_python.txt |
Q:
How are Python in-place operator functions different than the standard operator functions?
From the docs:
Many operations have an “in-place”
version. The following functions
provide a more primitive access to
in-place operators than the usual
syntax does; for example, the
statement x += y is equivalent to x =
ope... | How are Python in-place operator functions different than the standard operator functions? | From the docs:
Many operations have an “in-place”
version. The following functions
provide a more primitive access to
in-place operators than the usual
syntax does; for example, the
statement x += y is equivalent to x =
operator.iadd(x, y). Another way to
put it is to say that z =
operator.iadd(x, y) is equivalent to
... | [
"First, you need to understand the difference between __add__ and __iadd__.\nAn object's __add__ method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.\nAn object's __iadd__ method also takes two parameters, but makes the change in-place, modifying the contents ... | [
31,
0
] | [] | [] | [
"function",
"operator_keyword",
"python"
] | stackoverflow_0004772987_function_operator_keyword_python.txt |
Q:
Need help with While Loop
I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.
I need to create a script in Python using a while loop that does this:
zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza
Keep in mind that the script should be able... | Need help with While Loop | I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.
I need to create a script in Python using a while loop that does this:
zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza
Keep in mind that the script should be able to do this with any word. For... | [
"for (initialization_expression;loop_condition;increment_expression){\n // statements\n}\n\nis basically just a nice way of writing\ninitialize_expression;\nwhile(loop_condition){\n // statements\n increment_expression\n}\n\nDeconstruct your for loops into this format and you should have your solution.\n",
... | [
7,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0004771812_loops_python.txt |
Q:
How can I move file into Recycle Bin / trash on different platforms using PyQt4?
I would like to add the next feature to my cross-platform PyQt4 application: when user selects some file and select "remove" action on it that file will be moved to Recycle Bin folder instead of being permantly removed. I think I can ... | How can I move file into Recycle Bin / trash on different platforms using PyQt4? | I would like to add the next feature to my cross-platform PyQt4 application: when user selects some file and select "remove" action on it that file will be moved to Recycle Bin folder instead of being permantly removed. I think I can find Windows-specific solution using Win32 API or something similar, but I'd like to k... | [
"It's a good thing you're using Python, I created a library to do just that a while ago:\nhttp://www.hardcoded.net/articles/send-files-to-trash-on-all-platforms.htm\nOn PyPI: Send2Trash\nInstallation\nUsing conda:\nconda install Send2Trash\n\nUsing pip:\npip install Send2Trash\n\nUsage\nDelete file or folders\nfrom... | [
76,
2,
1
] | [] | [] | [
"cross_platform",
"pyqt4",
"python",
"qt4",
"recycle_bin"
] | stackoverflow_0003628517_cross_platform_pyqt4_python_qt4_recycle_bin.txt |
Q:
Detecting password encryption type --can I import them into Django?
I have a legacy system with passwords that look like this 115c28e0578f262bde08e3de39ee9066. Im not quite sure if they were created with md5 or crypt or... It was a java application that created them.
My new system is in Python (Django) and I tried... | Detecting password encryption type --can I import them into Django? | I have a legacy system with passwords that look like this 115c28e0578f262bde08e3de39ee9066. Im not quite sure if they were created with md5 or crypt or... It was a java application that created them.
My new system is in Python (Django) and I tried to run a comparison check on a known password using md5(), sha1() and cr... | [
"In general, you will need to know the exact algorithm used by the Java program. Then you would be able to recreate the same results in Python. (You cannot get the plain-text password from the hash, without using brute-force, but you should be able to recreate the same hashing algorithm, so you can verify a user's ... | [
4
] | [] | [] | [
"java",
"md5",
"passwords",
"python",
"sha1"
] | stackoverflow_0004773381_java_md5_passwords_python_sha1.txt |
Q:
Log user in using django
I would like to scrape web app with authentication. I am planning on using django/python to build the app. The app should log a user in the backend, and pick list of tables and store those in Django.
BeautifulSoup will be most likely used to get list of tables.
What would be best approach ... | Log user in using django | I would like to scrape web app with authentication. I am planning on using django/python to build the app. The app should log a user in the backend, and pick list of tables and store those in Django.
BeautifulSoup will be most likely used to get list of tables.
What would be best approach to log a user with username an... | [
"There's also Scrapy with this django-related feature :\nhttp://doc.scrapy.org/experimental/djangoitems.html\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004773338_django_python.txt |
Q:
Creating a CLI (Shell?) in Python
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.
I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:
def... | Creating a CLI (Shell?) in Python | I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.
I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:
def delete(loc):
if os.path.exists(loc... | [
"Or if you want a cmd shell, you could use the cmd lib. It offers python interfaces to making command lines.\nhttp://docs.python.org/library/cmd.html\n",
"I think you should now to use simple argparse module to get command line arguments\n\n\nimport argparse\n\nfrom functions import delete\n\nparser = argparse.Ar... | [
9,
4,
1
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0004772847_command_line_interface_python.txt |
Q:
Choosing tags based upon thumbnails, update to Sqlite
I have a SQLite database with 7000 rows with:
Images / ID / Tag
Images = array of urls of images (from the same "family")
ID = Unique id so I can identify the images
Tag = What are the images about (right now this is empty)
What's the easiest way to make a pr... | Choosing tags based upon thumbnails, update to Sqlite | I have a SQLite database with 7000 rows with:
Images / ID / Tag
Images = array of urls of images (from the same "family")
ID = Unique id so I can identify the images
Tag = What are the images about (right now this is empty)
What's the easiest way to make a program so that the user can choose the tags (based on the im... | [
"I'll try to use Django framework.\nIf you are already familiar with Python, it's very easy to create web based application like you want and manage sqlite database !\nYou should read django tutorial.\nTo create django model from your existing sqlite database, you could take a look at this page\n",
"As to the tag... | [
2,
0,
0
] | [] | [] | [
"html",
"image",
"python",
"user_interface"
] | stackoverflow_0004646946_html_image_python_user_interface.txt |
Q:
C and Python code to Java help
I'm trying to read in some bytes from a file in Java and then create bitmasks from some of the data and lengths and offsets from others.
I'm so close to getting my program working but I keep getting garbled data coming out the other end.
I'm 90% sure my problem is something to do wit... | C and Python code to Java help | I'm trying to read in some bytes from a file in Java and then create bitmasks from some of the data and lengths and offsets from others.
I'm so close to getting my program working but I keep getting garbled data coming out the other end.
I'm 90% sure my problem is something to do with the way that Java is reading the b... | [
"you can set ByteBuffer's byteOrder to littleEndian and just use getInt\n"
] | [
1
] | [] | [] | [
"c",
"endianness",
"java",
"python"
] | stackoverflow_0004774133_c_endianness_java_python.txt |
Q:
How to use startproject (django-admin.py) if there is already a django project?
I am trying to start a new django project (using django-admin.py) but unfortunately I'm always getting the following error:
C:\Users\NAME\dev\django>django-admin.py startproject foo
Usage: django-admin.py subcommand [options] [args]
[.... | How to use startproject (django-admin.py) if there is already a django project? | I am trying to start a new django project (using django-admin.py) but unfortunately I'm always getting the following error:
C:\Users\NAME\dev\django>django-admin.py startproject foo
Usage: django-admin.py subcommand [options] [args]
[...]
The same applies to any other command of django-admin.py - every command does no... | [
"DJANGO_SETTINGS_MODULE is only needed when you want to use django-admin.py with an existing Django project.\nYour issue seems to be different, it seems like django-admin.py does not honor the command line parameters for some reason. Never tried it on Windows, but have you tried doing something like:\npython django... | [
4
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004774128_django_django_admin_python.txt |
Q:
High precision arithmetric in Python and/or C/C++?
Abstract: Which Python package or C-Library is the best option for very high precision arithmetic operations?
I have some functions which convert fractional days (0.0-0.99999..) to a human-readible format (hours, minutes, seconds; but more importantly: millisecond... | High precision arithmetric in Python and/or C/C++? | Abstract: Which Python package or C-Library is the best option for very high precision arithmetic operations?
I have some functions which convert fractional days (0.0-0.99999..) to a human-readible format (hours, minutes, seconds; but more importantly: milliseconds, microsecond, nanoseconds).
Conversion is done by thes... | [
"The difference is due to a bug in your code, not due to any accuracy issue. The line\noutput += self.nanosecond * (d(8.64) * d(10)**d(-9))\n\nshould be something like\noutput += self.nanosecond / d(86400000000000)\n\nFurthermore, it is a Bad Idea to use floating point literals in your code and convert them to Dec... | [
4,
2
] | [] | [] | [
"c",
"c++",
"math",
"precision",
"python"
] | stackoverflow_0004773603_c_c++_math_precision_python.txt |
Q:
Specification for Tally SOAP API
Where can I find specifications for Tally's SOAP API?
And does anyone know of any python libraries for the same?
A:
I do not think Tally supports a SOAP based interface, rather it does support a decent XML/HTTP interface. I tried to play around with it, using Java. Maybe this hel... | Specification for Tally SOAP API | Where can I find specifications for Tally's SOAP API?
And does anyone know of any python libraries for the same?
| [
"I do not think Tally supports a SOAP based interface, rather it does support a decent XML/HTTP interface. I tried to play around with it, using Java. Maybe this helps: http://subbaraman.wordpress.com/2010/07/01/playing-with-tally-software/\n"
] | [
1
] | [] | [] | [
"erp",
"financial",
"python"
] | stackoverflow_0004468833_erp_financial_python.txt |
Q:
Making my for loop executable
I've created this working for loop in Python:
a = 'word'
for i in range(len(a)):
print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
and I need to make it executable from the command line and also have it be able to take in new arguments.
I'm a little hazy on how to do this. I know that ... | Making my for loop executable | I've created this working for loop in Python:
a = 'word'
for i in range(len(a)):
print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
and I need to make it executable from the command line and also have it be able to take in new arguments.
I'm a little hazy on how to do this. I know that you need to use
if __name__ == '__... | [
"You can just simply write\nimport sys\na = sys.argv[1]\netc..\n\nAnd then run:\npython yourcode.py argument\n\nThe\nif __name__=='__main__':\n\nis not required, but you can also put your whole code under that. It's purpose is to specify code which gets executed only if you run your program like \"python yourcode.p... | [
2,
2,
0
] | [] | [] | [
"command_line_arguments",
"executable",
"for_loop",
"python"
] | stackoverflow_0004774813_command_line_arguments_executable_for_loop_python.txt |
Q:
python: representing square grid that wraps on itself (cylinder)
I am modeling something that occurs on a square grid that wraps on itself (i.e., if you walk up past the highest point, you end up at the lowest point, like a cylinder; if you walk to the right, you just hit the boundary). I need to keep track of the... | python: representing square grid that wraps on itself (cylinder) | I am modeling something that occurs on a square grid that wraps on itself (i.e., if you walk up past the highest point, you end up at the lowest point, like a cylinder; if you walk to the right, you just hit the boundary). I need to keep track of the location of various agents, the amount of resources at different poin... | [
"If you want a hashable Point class without too much work, subclass tuple and add your own neighbor methods. \nclass Point(tuple):\n def r_neighbor(self):\n return Point((self[0] + 1, self[1]))\n def l_neighbor(self): \n [...]\n\nx = Point((10, 11))\nprint x\nprint x.r_neighbor()\n\nThe tuple co... | [
2,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004773934_oop_python.txt |
Q:
View with data from many databases
I'm building site in django, which lists items of many suppliers. Each supplier has own big database and make changes quite often. I have to be aware of all changes in no more than 60 minutes. There are about 10m items to display. How to implement all that in a efficient way?
A... | View with data from many databases | I'm building site in django, which lists items of many suppliers. Each supplier has own big database and make changes quite often. I have to be aware of all changes in no more than 60 minutes. There are about 10m items to display. How to implement all that in a efficient way?
| [
"It seems to me that your application has a pretty ugly architecture. Try to refactor it or you will have troubles.\nAnyway, you can try to cache your suppliers' data to your own database (single) and save some resources.\n"
] | [
1
] | [] | [] | [
"database",
"distributed",
"django",
"python"
] | stackoverflow_0004775375_database_distributed_django_python.txt |
Q:
What is the best Google App Engine blobstore workflow?
What is the best workflow for uploading file to the blobstore while saving information about the blob and other fields to a model record?
For example, should I submit the form to the blobstore upload url (blobstore.create_upload_url), clean the form, redirect... | What is the best Google App Engine blobstore workflow? | What is the best workflow for uploading file to the blobstore while saving information about the blob and other fields to a model record?
For example, should I submit the form to the blobstore upload url (blobstore.create_upload_url), clean the form, redirect if errors and save and redirect if not?
What is the best w... | [
"The solution I've come up with for this is not the prettiest but it gets the job done. On the upload view (view that is specified in the create_upload_url function) I'm passing the post variables to the same form class from the first page. If the form is valid I'm saving the variables along with the BlobInfo.key t... | [
0
] | [] | [] | [
"blobstore",
"file_upload",
"forms",
"google_app_engine",
"python"
] | stackoverflow_0004764129_blobstore_file_upload_forms_google_app_engine_python.txt |
Q:
ImportError from modular django settings file
I am trying to create a modular settings file.
Why is it that this works:
project/
settings.py
other.py
With this line in settings.py
config_module = __import__('other', globals(), locals())
While the following raises an ImportError:
project/
settings.py
conf... | ImportError from modular django settings file | I am trying to create a modular settings file.
Why is it that this works:
project/
settings.py
other.py
With this line in settings.py
config_module = __import__('other', globals(), locals())
While the following raises an ImportError:
project/
settings.py
config/
other.py
With this line in settings.py:
co... | [
"Looks like your config dir is missing an __init__.py file to make it clear you want it treated as a module. The __init__.py file can be empty, but it needs to exist.\n"
] | [
2
] | [] | [] | [
"django",
"django_settings",
"python"
] | stackoverflow_0004775875_django_django_settings_python.txt |
Q:
Python Interactive Cmd Question (3 parameters problem)
I did figure out how to use the Cmd module offered in Python lib, but I am with a trouble now...
Here is the code:
def do_addtext(self, file, text = ""):
"Add text to the end of a file"
if os.path.exists(file) == True:
f = open(file... | Python Interactive Cmd Question (3 parameters problem) | I did figure out how to use the Cmd module offered in Python lib, but I am with a trouble now...
Here is the code:
def do_addtext(self, file, text = ""):
"Add text to the end of a file"
if os.path.exists(file) == True:
f = open(file, 'a')
f.write("\n" + text)
print "\... | [
"When the Cmd object parses the input, it takes the first word and uses that as the function name. The remainder of the text is passed in as a single parameter. The do_* functions take only 2 parameters: self and the remainder of the string from the input. So, if you type:\n> foo This is my text\n\nAt the prompt... | [
4
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0004775843_command_line_interface_python.txt |
Q:
Access in-memory unzipped file with codecs.open()
I'm trying to open in-memory unzipped files with codecs.open(). I've figured out how to unzip a file in memory, but I don't know how to create a file object and open it with codecs. I've experimented with different ZipFile properties, but no luck.
So, here how I op... | Access in-memory unzipped file with codecs.open() | I'm trying to open in-memory unzipped files with codecs.open(). I've figured out how to unzip a file in memory, but I don't know how to create a file object and open it with codecs. I've experimented with different ZipFile properties, but no luck.
So, here how I opened the zip in memory:
import zipfile, io
f = 'somezi... | [
"You don't need codecs.open() to access data in memory -- it is meant for loading files from disk. You can extract the file contents from your zipfile obbject using its extract() method and decode the resulting string using decode(). If you insist on using the codecs module, you can also get a file-like object by... | [
2
] | [] | [] | [
"codec",
"memory",
"python",
"zip"
] | stackoverflow_0004775904_codec_memory_python_zip.txt |
Q:
Building graph structure from GIS data in Python
I want to implement a driving direction in Python using something like Djikstra's shortest path. The algorithm requires the data to be represents in graph structure. Raw GIS data (e.g. shape files or OpenStreetMap data, however, represent their data differently. The... | Building graph structure from GIS data in Python | I want to implement a driving direction in Python using something like Djikstra's shortest path. The algorithm requires the data to be represents in graph structure. Raw GIS data (e.g. shape files or OpenStreetMap data, however, represent their data differently. Therefore, I was wondering is there any Python library th... | [
"Haven't used it yet, but there's a function that generates directed graphs from shapefiles in Networkx: http://networkx.lanl.gov/reference/readwrite.nx_shp.html. If it doesn't do exactly what you need, it might suggest a solution. Uses OGR's Python bindings to read data.\nSee also Graphserver http://bmander.github... | [
2
] | [] | [] | [
"gis",
"graph",
"python",
"shortest_path"
] | stackoverflow_0004774704_gis_graph_python_shortest_path.txt |
Q:
Selecting objects from form (HTML)
I am learning how to use Google App Engine / Python. (webapp)
I am coming from Java (could be my problem!), where if I put objects in a Swing list box, it would invoke their toString() method for display purposes. When I selected one of them it would return the object and not ju... | Selecting objects from form (HTML) | I am learning how to use Google App Engine / Python. (webapp)
I am coming from Java (could be my problem!), where if I put objects in a Swing list box, it would invoke their toString() method for display purposes. When I selected one of them it would return the object and not just the representation of it generated by ... | [
"According to the documentation:\n\nEvery model instance that has been stored in the datastore has a unique key that represents the object. The key() method of a model instance returns the Key object for the instance.\n\nSo you have to pass client’s key, not full name. Fix your template code:\n<select size=\"5\" na... | [
5
] | [] | [] | [
"google_app_engine",
"html",
"object",
"python",
"select"
] | stackoverflow_0004776197_google_app_engine_html_object_python_select.txt |
Q:
Plugins for Eclipse/PyDev
I started learning python recently, it seems fun and interesting. After comparing some IDEs, i concluded with Eclipse+PyDev, because i am already familiar with it from Java.
1) Can i use my favorite plugins(FindBugs, Log4E, Metrics) within the PyDev Perspective?
2) Which plugins do yo... | Plugins for Eclipse/PyDev | I started learning python recently, it seems fun and interesting. After comparing some IDEs, i concluded with Eclipse+PyDev, because i am already familiar with it from Java.
1) Can i use my favorite plugins(FindBugs, Log4E, Metrics) within the PyDev Perspective?
2) Which plugins do you use for python development in... | [
"\nCan i use my favorite\n plugins(FindBugs, Log4E, Metrics)\n within the PyDev Perspective?\n\nYou cannot use any Java-centric plugins from within the PyDev perspective. You will be able to use non-language specific plugins (VCS, etc..) in harmony with PyDev.\nIf you want a more \"first class\" editing solution ... | [
1,
0,
0
] | [] | [] | [
"eclipse",
"plugins",
"pydev",
"python"
] | stackoverflow_0004771412_eclipse_plugins_pydev_python.txt |
Q:
Changing Fast CGI to run a different version of python
i have a shared web server through Hostmonster. I am trying to install and run Django using python 2.6, however while they have 2.6 installed it is not the default python version. The default version is python 2.4.3, I have installed all the dependencies and D... | Changing Fast CGI to run a different version of python | i have a shared web server through Hostmonster. I am trying to install and run Django using python 2.6, however while they have 2.6 installed it is not the default python version. The default version is python 2.4.3, I have installed all the dependencies and Django, however the fcgi script still runs through python 2.4... | [
"On my system which is hosted on tigertech.net (a pretty vanilla hosting service), I configured using excellent advice from\nhttp://www.codekoala.com/blog/2008/installing-django-shared-hosting-site5/\nYou just need to make sure that the \"she-bang\" (first line in the .fcgi file) correctly identifies the version of... | [
0
] | [] | [] | [
"django",
"fastcgi",
"hostmonster",
"python"
] | stackoverflow_0004769994_django_fastcgi_hostmonster_python.txt |
Q:
Best way to redirect to referring page
I have a question similar to my previous question.
In the same app I have the VoteHandler that adds +1 when users click on the up arrow and then redirects to the same page.
Now that I added the url parameters to the pages and urls look like this
/dir?type=tshirt
I need to be... | Best way to redirect to referring page | I have a question similar to my previous question.
In the same app I have the VoteHandler that adds +1 when users click on the up arrow and then redirects to the same page.
Now that I added the url parameters to the pages and urls look like this
/dir?type=tshirt
I need to be able to redirect to the correct page.
And a... | [
"I would use the type parameter in this way:\nclass VoteHandler(webapp.RequestHandler):\n def get(self, id):\n id = int(id)\n item = Item.get_by_id(id)\n merchandise_type = self.request.get(\"type\", \"\")\n ..\n self.redirect('/%s' % merchandise_type)\n\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"redirect",
"referrer"
] | stackoverflow_0004775906_google_app_engine_python_redirect_referrer.txt |
Q:
Django: Populating data into a model based on an identifier
In my Django project, let's say I have the following model:
class City(models.Model):
name = models.CharField(max_length=255)
freebase_id = models.CharField(max_length=255)
latitude = models.DecimalField()
longitude = models.DecimalField()... | Django: Populating data into a model based on an identifier | In my Django project, let's say I have the following model:
class City(models.Model):
name = models.CharField(max_length=255)
freebase_id = models.CharField(max_length=255)
latitude = models.DecimalField()
longitude = models.DecimalField()
area = models.IntegerField()
(I've omitted the required par... | [
"I am doing something similar in my UserProfile model. I have a zip code field that, if it gets filled in by the user, is used to do a geo lookup to get city/state and lat/lng and store them in their respective fields in the model:\nclass UserProfile(models.Model):\n user = models.ForeignKey(User, unique=True)\... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"freebase",
"model",
"python"
] | stackoverflow_0004776335_django_django_models_freebase_model_python.txt |
Q:
Automatically nested for loops in python
I am aware that two collections can be accessed simultaneously using
for i,j in zip([1,2,3],[4,5,6]):
print i,j
1 4
2 5
3 6
What I would like to do is something like this:
for i,j in [[1,2,3],[4,5,6]]:
print i,j
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
I want python ... | Automatically nested for loops in python | I am aware that two collections can be accessed simultaneously using
for i,j in zip([1,2,3],[4,5,6]):
print i,j
1 4
2 5
3 6
What I would like to do is something like this:
for i,j in [[1,2,3],[4,5,6]]:
print i,j
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
I want python to automatically create the nested for loop fo... | [
"Try\nfor i, j in itertools.product([1, 2, 3], [4, 5, 6]):\n print i, j\n\n",
">>> [[x,y] for x in [1,2,3] for y in [4,5,6]]\n[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]\n\nIt should be pretty easy to get what you want out of the resulting list.\n",
"I've had some cases where the... | [
12,
1,
0
] | [] | [] | [
"for_loop",
"nested_loops",
"python"
] | stackoverflow_0004776791_for_loop_nested_loops_python.txt |
Q:
What does Python optimization (-O or PYTHONOPTIMIZE) do?
The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it... | What does Python optimization (-O or PYTHONOPTIMIZE) do? | The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it could generate?
Is there any downside to using -O?
The only t... | [
"In Python 2.7, -O has the following effect:\n\nthe byte code extension changes to .pyo\nsys.flags.optimize gets set to 1\n__debug__ is False\nasserts don't get executed\n\nIn addition -OO has the following effect:\n\nsys.flags.optimize gets set to 2\ndoc strings are not available\n\nTo verify the effect for a diff... | [
59
] | [] | [] | [
"optimization",
"python",
"python_3.x"
] | stackoverflow_0004777113_optimization_python_python_3.x.txt |
Q:
Issues using Queues in python when getting objects to skip the queue
Right now I am implementing a thread that will basically act as a consumer. There will be a FIFO queue that will get filled by other threads. The problem is that I want to add a special condition that will cause an item to skip the queue entirely... | Issues using Queues in python when getting objects to skip the queue | Right now I am implementing a thread that will basically act as a consumer. There will be a FIFO queue that will get filled by other threads. The problem is that I want to add a special condition that will cause an item to skip the queue entirely.
def EventThread (threading.Thread):
def __init__ (self, counter_obj... | [
"Have you looked at PriorityQueue?\n"
] | [
2
] | [] | [] | [
"blocking",
"multithreading",
"python",
"queue"
] | stackoverflow_0004777151_blocking_multithreading_python_queue.txt |
Q:
Converting Perl Regular Expressions to Python Regular Expressions
I'm having trouble converting a Perl regex to Python. The text I'm trying to match has the following pattern:
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastn... | Converting Perl Regular Expressions to Python Regular Expressions | I'm having trouble converting a Perl regex to Python. The text I'm trying to match has the following pattern:
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
In perl I was able to match this and extract the authors with
/Aut... | [
"You can do this:\n# find lines with authors\nimport re\n\n# multiline string to simulate possible input\ntext = '''\nStuff before\nThis won't be matched...\nAuthor(s) : Firstname Lastname \n Firstname Lastname \n Firstname Lastname \n Firstname Lastname\nOther(s) ... | [
3,
2,
1
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0004777072_perl_python_regex.txt |
Q:
Django - template inheritance with includes
I have a web app where users can have profiles (somewhat like facebook) and they can view their own profile as well as other peoples profiles. What you would see in your own profile would be everything, but someone else viewing your profile might not be able to see ever... | Django - template inheritance with includes | I have a web app where users can have profiles (somewhat like facebook) and they can view their own profile as well as other peoples profiles. What you would see in your own profile would be everything, but someone else viewing your profile might not be able to see everything on it.
In order to accomplish this, I have... | [
"What about instead of using an include, you made profile.html extend common-profile.html? Then just have an empty block in the common profile template that the non-common-profile template can add stuff to. Something like this:\ncommon-profile.html:\n{% extends 'base.html' %}\n\n{% block content %}\n <!-- Normal... | [
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004777317_django_python.txt |
Q:
PermanentTaskFailure: 'module' object has no attribute 'Migrate'
I'm using Nick Johnson's Bulk Update library on google appengine (http://blog.notdot.net/2010/03/Announcing-a-robust-datastore-bulk-update-utility-for-App-Engine). It works wonderfully for other tasks, but for some reason with the following code:
f... | PermanentTaskFailure: 'module' object has no attribute 'Migrate' | I'm using Nick Johnson's Bulk Update library on google appengine (http://blog.notdot.net/2010/03/Announcing-a-robust-datastore-bulk-update-utility-for-App-Engine). It works wonderfully for other tasks, but for some reason with the following code:
from google.appengine.ext import db
from myapp.main.models import Stor... | [
"It seems likely that your declaration of the 'Migrate' class is in the handler script (Eg, the one directly invoked by app.yaml). A limitation of deferred is that you can't use it to call functions defined in the handler module.\nIncidentally, my bulk update library is deprecated in favor of App Engine's mapreduce... | [
7
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004770669_google_app_engine_google_cloud_datastore_python.txt |
Q:
Matplotlib axis labels
How do I reduce the number of ticks on the axes with matplotlib (without using pyplot)?
self.figure = Figure((2.0, 2.0))
self.canvas = FigureCanvas(self.figure)
self.canvas.setParent(self)
self.axes = self.figure.add_subplot(111)
self.figure.subplots_adjust(left=0.18)
... | Matplotlib axis labels | How do I reduce the number of ticks on the axes with matplotlib (without using pyplot)?
self.figure = Figure((2.0, 2.0))
self.canvas = FigureCanvas(self.figure)
self.canvas.setParent(self)
self.axes = self.figure.add_subplot(111)
self.figure.subplots_adjust(left=0.18)
self.axes.fill(x, y, 'b')
... | [
"In pyplot it was xticks(...), but I couldn't find that in matplotlib.\nIt turns out, you have to use set_xticks\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004777314_matplotlib_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.