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:
Convert list to nested lists and dicts
I have a set of data that looks similar to this:
[ {"name":"item.key" , "value":"value"},
{"name":"item.key2" , "value":"value2"},
{"name":"item.list.0" , "value":"listValue1"},
{"name":"item.list.1" , "value":"listValue2"},
{"name":"item.list.2" , "value":"listV... | Convert list to nested lists and dicts | I have a set of data that looks similar to this:
[ {"name":"item.key" , "value":"value"},
{"name":"item.key2" , "value":"value2"},
{"name":"item.list.0" , "value":"listValue1"},
{"name":"item.list.1" , "value":"listValue2"},
{"name":"item.list.2" , "value":"listValue3"},·
{"name":"item.list2.0.key1" , "... | [
"This is probably not the most efficient way to do this, but...\nimport pprint\n\ndata = [{\"name\":\"item.key\" , \"value\":\"value\"},\n {\"name\":\"item.key2\" , \"value\":\"value2\"},\n {\"name\":\"item.list.0\" , \"value\":\"listValue1\"},\n {\"name\":\"item.list.1\" , \"value\":\"listValue2\"},\n {\"n... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007709092_python.txt |
Q:
using cmd or powershell, calling python file returns no output
I've just installed python 2.7.2 on this machine.
I'm attempting to run this code:
class Hello(object):
def main(self):
print "hello world"
if __name__ == "main":
h = Hello()
h.main()
When I call it with python ./foo.py, it... | using cmd or powershell, calling python file returns no output | I've just installed python 2.7.2 on this machine.
I'm attempting to run this code:
class Hello(object):
def main(self):
print "hello world"
if __name__ == "main":
h = Hello()
h.main()
When I call it with python ./foo.py, it does not return either a print statement or log statement, just wha... | [
"It's if __name__ == \"__main__\":. You forgot the underscores around main.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0007714198_python.txt |
Q:
With python sqlite3 module, how to deal with fields that contain double-quotes?
I was trying to access a database that has data that contains "" such as:
Tom "is" a cat.
When I use this code:
myData = 100; myKey = 'Tom "is" a cat.'
myCursor.execute('UPDATE MyTable SET MyField = %d WHERE MyTable.Key ==
"%s"' ... | With python sqlite3 module, how to deal with fields that contain double-quotes? | I was trying to access a database that has data that contains "" such as:
Tom "is" a cat.
When I use this code:
myData = 100; myKey = 'Tom "is" a cat.'
myCursor.execute('UPDATE MyTable SET MyField = %d WHERE MyTable.Key ==
"%s"' % (myData, myKey))
I got this error
sqlite3.OperationalError: near "is": syntax err... | [
"Use DB-API parameter substitution and leave the formatting to sqlite3 library:\nmyCursor.execute('UPDATE MyTable SET MyField = ? WHERE MyTable.Key == ?', (myData, myKey))\n\n"
] | [
4
] | [
"You should not use double quote for surrounding strings in sql statement, thus you should use single quote in the statement:\nmyData = 100 \nmyKey = 'Tom \"is\" a cat.'\nmyCursor.execute('''UPDATE MyTable SET MyField = %d WHERE MyTable.Key ='%s' ''' % (myData, myKey))\n\nTriple single quote allows you to use singl... | [
-2
] | [
"double_quotes",
"python",
"sqlite",
"string"
] | stackoverflow_0007714321_double_quotes_python_sqlite_string.txt |
Q:
Django count specific items of a many-to-one relationship
I have a Django app where users post messages and other users can vote the answers up or down, very similar to SO. I'm having an issue trying to get the "thumbs up" and "thumbs down" counts from within the template and I'm hoping someone can help me. The Po... | Django count specific items of a many-to-one relationship | I have a Django app where users post messages and other users can vote the answers up or down, very similar to SO. I'm having an issue trying to get the "thumbs up" and "thumbs down" counts from within the template and I'm hoping someone can help me. The PostVote is a many-to-one relationship with the Post class. Here ... | [
"You shouldn't really be doing logic in your templates. Add a couple count methods to your Post model:\nclass Post(models.Model):\n account = models.ForeignKey(Account)\n message = models.CharField(max_length=1024)\n timestamp = models.DateTimeField('post timestamp')\n\n def upvote_count(self):\n ... | [
2
] | [] | [] | [
"django",
"many_to_one",
"python"
] | stackoverflow_0007714290_django_many_to_one_python.txt |
Q:
Is there anything thing like pastescript without the paste part?
I am looking for a simple lib/tool like paster that I can easily create custom commands without having anything to do with paste itself. I am looking to create a helper tool like paster or manage.py to do various tasks like build (maybe using buildou... | Is there anything thing like pastescript without the paste part? | I am looking for a simple lib/tool like paster that I can easily create custom commands without having anything to do with paste itself. I am looking to create a helper tool like paster or manage.py to do various tasks like build (maybe using buildout), build documentation and run scripts/tests for a non-web/non-wsgi b... | [
"Often I use Fabric as my general purpose project janitor. Usually I automate the following tasks with Fabric:\n\ngenerate documentation\nrun tests\nmake releases\n\nInitially Fabric has been developed to ease the automation/scripting of commands to run on remote hosts using SSH. However, Fabric is also an excellen... | [
0
] | [] | [] | [
"automated_tests",
"build_automation",
"buildout",
"paste",
"python"
] | stackoverflow_0007562616_automated_tests_build_automation_buildout_paste_python.txt |
Q:
tkinter woes when porting 2.x code to 3.x, 'tkinter' module attribute doesn't exist
UPDATED: SEE BELOW
I've been porting the code for this assignment: http://www.stanford.edu/class/cs221/progAssignments/PA1/search.html (the entire source code is available as zip from there)
from Python 2.x to 3.x. Note, porting is... | tkinter woes when porting 2.x code to 3.x, 'tkinter' module attribute doesn't exist | UPDATED: SEE BELOW
I've been porting the code for this assignment: http://www.stanford.edu/class/cs221/progAssignments/PA1/search.html (the entire source code is available as zip from there)
from Python 2.x to 3.x. Note, porting is not the assignment, that's just me trying to keep the code up to date and avoiding insta... | [
"It appears Tkinter.tkinter was changed to tkinter._tkinter in Python 3. Compare these docs from Python 2 with these from Python 3. Also, dooneevent is no longer in tkinter._tkinter, but is still a member of the Tk (aka root) object.\nSo change your code to\ndef keys_pressed(d_o_e=lambda arg: _root_window.dooneev... | [
10
] | [] | [] | [
"porting",
"python",
"tkinter",
"version"
] | stackoverflow_0007714229_porting_python_tkinter_version.txt |
Q:
./manage.py Permission Denied
I'm trying to migrate my Django app using South and am getting permission denied warning. I'm logged in as root though (I know, risk risk, just trying to get things set-up). Why then does this get rejected?
root@Harold:~/OmniCloud/omnicloud: ./manage.py convert_to_south OmniCloud_App
... | ./manage.py Permission Denied | I'm trying to migrate my Django app using South and am getting permission denied warning. I'm logged in as root though (I know, risk risk, just trying to get things set-up). Why then does this get rejected?
root@Harold:~/OmniCloud/omnicloud: ./manage.py convert_to_south OmniCloud_App
-bash: ./manage.py: Permission deni... | [
"manage.py probably does not have its executable bit set, which is on purpose. Use python manage.py instead as per the Django docs.\n",
"You need to make sure that ./manage.py has the executable bit set:\nchmod a+x manage.py\n\n",
"If for any reason you NEED to execute manage.py just run:\nchmod +x manage.py\n\... | [
8,
2,
2,
0
] | [] | [] | [
"django",
"django_south",
"linux",
"python",
"unix"
] | stackoverflow_0007698425_django_django_south_linux_python_unix.txt |
Q:
Pad list in Python
How can I pad a list when printed in python?
For example, I have the following list:
mylist = ['foo', 'bar']
I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:
', '.join(mylist)
But how can I pad it to four ind... | Pad list in Python | How can I pad a list when printed in python?
For example, I have the following list:
mylist = ['foo', 'bar']
I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:
', '.join(mylist)
But how can I pad it to four indices with 'x's, so the o... | [
"In [1]: l = ['foo', 'bar']\n\nIn [2]: ', '.join(l + ['x'] * (4 - len(l)))\nOut[2]: 'foo, bar, x, x'\n\nThe ['x'] * (4 - len(l)) produces a list comprising the correct number of 'x'entries needed for the padding.\nedit There's been a question about what happens if len(l) > 4. In this case ['x'] * (4 - len(l)) resul... | [
11,
3,
0
] | [] | [] | [
"list",
"padding",
"python"
] | stackoverflow_0007714287_list_padding_python.txt |
Q:
Why isn't setup.py metadata being used on PyPI?
I had a beta-version of my package up on PyPi.
The meta-information (e.g. home page, categories, etc.) from setup.py appeared on the project's PyPi page.
Later, I updated the project. The only thing I changed in the setup.py was the version number.
Update: As always,... | Why isn't setup.py metadata being used on PyPI? | I had a beta-version of my package up on PyPi.
The meta-information (e.g. home page, categories, etc.) from setup.py appeared on the project's PyPi page.
Later, I updated the project. The only thing I changed in the setup.py was the version number.
Update: As always, never trust someone who says that. I changed from se... | [
"Running the following command on your setup.py should correct the issue:\n$ python setup.py register\n\nIdeally, you would want to run the register command alongside the upload. I usually use a minimum of three commands when releasing any package (sdist, register, upload). The following will make a typical releas... | [
4,
1
] | [] | [] | [
"cheeseshop",
"pypi",
"python",
"setuptools"
] | stackoverflow_0006252693_cheeseshop_pypi_python_setuptools.txt |
Q:
Interpolate large irregular grid onto another irregular grid in Python
I am trying to interpolate complex values from one irregular grid to another irregular grid using Python. The grids are in 2D and there are 103,113 data points. I am using Python 2.6.6, Scipy 0.7.2, Numpy 1.3.0, Matplotlib 0.99.3
In Matlab usin... | Interpolate large irregular grid onto another irregular grid in Python | I am trying to interpolate complex values from one irregular grid to another irregular grid using Python. The grids are in 2D and there are 103,113 data points. I am using Python 2.6.6, Scipy 0.7.2, Numpy 1.3.0, Matplotlib 0.99.3
In Matlab using griddata this is achieved in roughly 5 seconds.
BnGRID2 = griddata(R_GRID... | [
"Scipy's griddata seems to be able to deal with data sets of this size without problems:\n\nimport numpy as np\nimport scipy.interpolate\n\n# old grid\nx, y = np.mgrid[0:1:201j, 0:1:513j]\nz = np.sin(x*20) * (1j + np.cos(y*3))**2 # some data\n\n# new grid\nx2, y2 = np.mgrid[0.1:0.9:201j, 0.1:0.9:513j]\n\n# interp... | [
6
] | [] | [] | [
"interpolation",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0007701669_interpolation_matplotlib_numpy_python_scipy.txt |
Q:
access scope of variable in for loop
I have searched the SO before I post this question here and hopefully
this is not a duplicated one.
def print_me():
a_list = range(1, 10)
for idx, aa in enumerate(a_list):
pass
print(idx)
if __name__ == '__main__' : print_me()
Output is as follows:
8
I c... | access scope of variable in for loop | I have searched the SO before I post this question here and hopefully
this is not a duplicated one.
def print_me():
a_list = range(1, 10)
for idx, aa in enumerate(a_list):
pass
print(idx)
if __name__ == '__main__' : print_me()
Output is as follows:
8
I came from C++ world and could not figure ou... | [
"for loop doesn't create any scope. This is the reason.\nIn this particular code idx is a local variable of the print_me function.\nFrom the docs:\nThe following are blocks: \n\na module \na function body\na class definition\n\nUpdate\nGenerator expressions have their own scopes too.\nAs of Python 3.0 list comprehe... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0007715297_python.txt |
Q:
Old style python formatting issues
I looking to display numeric data right justified with a forced sign and spaces for the mantissa such that the decimals all align for each column. The new format specifier uses ">" to align, but I'm unable to get something working with the "c style" format.
For example I'm using:... | Old style python formatting issues | I looking to display numeric data right justified with a forced sign and spaces for the mantissa such that the decimals all align for each column. The new format specifier uses ">" to align, but I'm unable to get something working with the "c style" format.
For example I'm using:
'%+7.2f \n' % (data)
How do I get the ... | [
"That will work, you just have to remember that the first number (the 7 in your example) is the total width of the column including all digits before and after the decimal place and the decimal place and the leading +.\n>>> for n in (0.12345, 12345.6, 123):\n... print '%+9.2f' % (n)\n +0.12\n+12345.60\n +1... | [
1
] | [] | [] | [
"formatting",
"python"
] | stackoverflow_0007715310_formatting_python.txt |
Q:
How can I efficiently transform a numpy.int8 array in-place to a value-shifted numpy.uint8 array?
I have a large numpy array of signed bytes (dtype int8). It contains values in the full range -128 to +127. I'd like to convert the efficiently to an array of unsigned bytes (dtype uint8) by adding 128 to each elemen... | How can I efficiently transform a numpy.int8 array in-place to a value-shifted numpy.uint8 array? | I have a large numpy array of signed bytes (dtype int8). It contains values in the full range -128 to +127. I'd like to convert the efficiently to an array of unsigned bytes (dtype uint8) by adding 128 to each element, such that -128 → 0, 0 → 128, +127 → 255, etc. so of course the results still fit into an unsigned by... | [
"\nimport numpy as np\na = np.array([-128, -1, 0, 1, 127], dtype=np.int8)\na = a.view(np.uint8)\na += 128\nprint a\n# -> array([ 0, 127, 128, 129, 255], dtype=uint8)\n\nThis creates no copies, and all operations are in-place.\nEDIT: safer to cast first to uint --- unsigned wrap-around is defined.\nEDIT2: s/numpy/n... | [
16,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007715406_numpy_python.txt |
Q:
Python Distutils
I was unable to install cython due to strict version numbering class of Distutils. For example binutils-2.18.50-20080109-2.tar.gz cannot be used along with MinGW for installing cython. The source code documentation says that "The rationale for this version numbering system will be explained in the... | Python Distutils | I was unable to install cython due to strict version numbering class of Distutils. For example binutils-2.18.50-20080109-2.tar.gz cannot be used along with MinGW for installing cython. The source code documentation says that "The rationale for this version numbering system will be explained in the distutils documentati... | [
"That's just another stupidness of distutils. I personally remove this annoying check in my distutils installation on every windows machine I have to use.\nInstalling another mingw version would work as long as it passes the version check - but really, the whole idea of checking version of the tools does not make m... | [
1,
0,
0
] | [] | [] | [
"cython",
"distutils",
"mingw",
"python"
] | stackoverflow_0000298828_cython_distutils_mingw_python.txt |
Q:
What's the cleanest way to add arbitrary data to ModelForm?
Imagine we're developing a message system, and each Message has a foreign key for sender.
We're using ModelForms, and there is a MessageForm that infers its fields from Message.
Of course, we don't want the user to be able to spoof sender by posting a d... | What's the cleanest way to add arbitrary data to ModelForm? | Imagine we're developing a message system, and each Message has a foreign key for sender.
We're using ModelForms, and there is a MessageForm that infers its fields from Message.
Of course, we don't want the user to be able to spoof sender by posting a different sender ID.
Therefore, we must exclude sender from ModelF... | [
"Just exclude the sender field from the ModelForm and, when you instantiate the object in the view on the POST endpoint (just before saving), make sure you populate the sender field with the appropriate session or user ID.\nWhen you exclude the field, there is no way to add the field to the post data[1], so a user ... | [
1,
1
] | [] | [] | [
"django",
"django_1.3",
"django_forms",
"python"
] | stackoverflow_0007715263_django_django_1.3_django_forms_python.txt |
Q:
Python distutils not using correct version of gcc
I am trying to compile a package on Mac OSX 10.6.5. The package's install script relies on distutils. The problem is that the computer's default gcc is version 4.2 (I determined this by just running gcc --version in a terminal window) but when I run 'python setup... | Python distutils not using correct version of gcc | I am trying to compile a package on Mac OSX 10.6.5. The package's install script relies on distutils. The problem is that the computer's default gcc is version 4.2 (I determined this by just running gcc --version in a terminal window) but when I run 'python setup.py build', I see from the output that the distutils is... | [
"To force distutils to use a separate compiler, you can redefine a few variables via the environment. First, find out what distutils is using as defaults:\n>>> from distutils import sysconfig\n>>> sysconfig.get_config_var('LDSHARED')\n'gcc-4.0 -Wl,-F. -bundle -undefined dynamic_lookup'\n>>> sysconfig.get_config_va... | [
18,
5,
3,
1
] | [] | [] | [
"distutils",
"gcc",
"python"
] | stackoverflow_0005967065_distutils_gcc_python.txt |
Q:
How to install scripts to sbin with python's distutils?
Commonly on most unix systems there is a distinction between $PREFIX/bin and $PREFIX/sbin. When installing a piece of software the administrator decides about what $PREFIX is, but the author decides which programs are suitable for regular users and which are ... | How to install scripts to sbin with python's distutils? | Commonly on most unix systems there is a distinction between $PREFIX/bin and $PREFIX/sbin. When installing a piece of software the administrator decides about what $PREFIX is, but the author decides which programs are suitable for regular users and which are not. With Python's distutils a set of scripts can be defined ... | [
"You can specify where files should be installed in the data_files parameter. It should work putting '/sbin' in the directory specification:\nsetup(...,\n data_files=[('/sbin', ['rootfill']),\n ('/etc/init.d', ['init-script'])]\n )\n\n",
"For distutils, we are working on support to insta... | [
4,
1
] | [] | [] | [
"distutils",
"installation",
"python"
] | stackoverflow_0005028075_distutils_installation_python.txt |
Q:
where is the __enter__ and __exit__ defined for zipfile?
Based on the with statement
The context manager’s __exit__() is loaded for later use.
The context manager’s __enter__() method is invoked.
I have seen one of the with usage with zipfile
Question>
I have checked the source code of zipfile located here:
/us... | where is the __enter__ and __exit__ defined for zipfile? | Based on the with statement
The context manager’s __exit__() is loaded for later use.
The context manager’s __enter__() method is invoked.
I have seen one of the with usage with zipfile
Question>
I have checked the source code of zipfile located here:
/usr/lib/python2.6/zipfile.py
I don't know where the __enter__ an... | [
"zipfile.ZipFile is not a context manager in 2.6, this has been added in 2.7.\n",
"I've added this as another answer because it is generally not an answer to initial question. However, it can help to fix your problem.\nclass MyZipFile(zipfile.ZipFile): # Create class based on zipfile.ZipFile\n def __init__(file,... | [
9,
4,
2,
0
] | [] | [] | [
"contextmanager",
"python",
"with_statement"
] | stackoverflow_0007706563_contextmanager_python_with_statement.txt |
Q:
Python distutils builds extensions differently on different machines
I have been working on a Python extension module with lots of files. While building on one machine, python setup.py build will happily detect changed files, build just those files, and link the whole thing together, just like make. On another mac... | Python distutils builds extensions differently on different machines | I have been working on a Python extension module with lots of files. While building on one machine, python setup.py build will happily detect changed files, build just those files, and link the whole thing together, just like make. On another machine, however, a single change to any file triggers a recompile of all sou... | [
"I looked into the Mercurial repo and found this change:\nIssue #5372: Drop the reuse of .o files in Distutils' ccompiler (since Extension extra options may change the output without changing the .c file).\nIOW, it was a simplistic optimization that was removed.\n",
"I've tracked this down to a change in distutil... | [
2,
1
] | [] | [] | [
"build",
"dependencies",
"distutils",
"python"
] | stackoverflow_0003145933_build_dependencies_distutils_python.txt |
Q:
python re.sub() with pair or characters
I am trying to grab a string that is surrounded by "! and replace the first "!" with a "!_".
For example:
str(!test!).strip() -> str(!_test!).strip()
Here is the code I have so far:
print re.sub(r'!.*?!','!_', 'str(!test!).strip()')
With this code I grab too much and the re... | python re.sub() with pair or characters | I am trying to grab a string that is surrounded by "! and replace the first "!" with a "!_".
For example:
str(!test!).strip() -> str(!_test!).strip()
Here is the code I have so far:
print re.sub(r'!.*?!','!_', 'str(!test!).strip()')
With this code I grab too much and the result is:
str(!_).strip()
Any thoughts on how ... | [
"print re.sub(r'!(?=.*?!)', '!_', 'str(!test!).strip()')\n\nUses a positive lookahead.\nprint re.sub(r'!(.*?)!', r'!_\\1!', 'str(!test!).strip()')\n\nUses a backreference.\n",
"Exclude ! from the characters between the !s: use [^!] instead of .\nThen, capture the part of the RE you want to keep with (), and in th... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007715820_python_regex.txt |
Q:
python - count files (can't count values in a dictionary)
i want to count files in the command directory based on their extension.
So, i created a list with all the files in the cwd ,then a list with only the extensions and then i made a dict from that list.I made the dict with a count parameter but i don't know h... | python - count files (can't count values in a dictionary) | i want to count files in the command directory based on their extension.
So, i created a list with all the files in the cwd ,then a list with only the extensions and then i made a dict from that list.I made the dict with a count parameter but i don't know how to handle this.My dict looks like "{'txt':0,'doc':0}".
impo... | [
"Surely you just want count += i in your loop?\nAlthough there is a nice data structure that does all this for you: collections.Counter.\n",
"This is a perfect use for the collections.Counter class:\n>>> from collections import Counter\n>>> c = Counter(['foo', 'foo', 'bar', 'foo', 'bar', 'baz'])\n>>> c\n2: Counte... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007715909_python.txt |
Q:
Python: can function be defined inside of another function's argument list?
Is there a way to achieve something like this in python?
another_function( function(x) {return 2*x} )
A:
Yes:
another_function( lambda x: 2*x )
To be clear: this is taking place when another_function is called, not when it is defined.
... | Python: can function be defined inside of another function's argument list? | Is there a way to achieve something like this in python?
another_function( function(x) {return 2*x} )
| [
"Yes:\nanother_function( lambda x: 2*x )\n\nTo be clear: this is taking place when another_function is called, not when it is defined.\n",
"def another_function( function=lambda x: 2*x ):\n print(function(10)) #an example\n\nI'm not sure what happens with the example code you posted, but with the solution sho... | [
9,
0
] | [] | [] | [
"argument_passing",
"function",
"python"
] | stackoverflow_0007713265_argument_passing_function_python.txt |
Q:
What is the purpose of the `//` operator in python?
Possible Duplicate:
What is the reason for having '//' in Python?
What is the purpose of the // operator?
x=10
y=2
print x/y
print x//y
Both output 5 as the value.
A:
Integer division vs. float division:
>>> 5.0/3
3: 1.6666666666666667
>>> 5.0//3
4: 1.0
Or... | What is the purpose of the `//` operator in python? |
Possible Duplicate:
What is the reason for having '//' in Python?
What is the purpose of the // operator?
x=10
y=2
print x/y
print x//y
Both output 5 as the value.
| [
"Integer division vs. float division:\n>>> 5.0/3\n3: 1.6666666666666667\n>>> 5.0//3\n4: 1.0\n\nOr as they put it in the Python docs, // is \"(floored) quotient of x and y\". The above example was run in Python 2.7.2, which only behaves that way for floating point numbers. If you were to use integers in 2.7.2 you'... | [
23
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0007716367_operators_python.txt |
Q:
How do you specify the filename for the BlobstoreOutputWriter for a simple mapreduce job?
How or where do I specify the output_writer filename and content type for a GAE mapreduce job? This configuration below is working fine for me, but it creates a new blobstore entry with a new filename every time I run the job... | How do you specify the filename for the BlobstoreOutputWriter for a simple mapreduce job? | How or where do I specify the output_writer filename and content type for a GAE mapreduce job? This configuration below is working fine for me, but it creates a new blobstore entry with a new filename every time I run the job. I would like to be able to specify the filename and content type to be overwritten/replaced e... | [
"The output_writer stuff is still experimental. There's no provision for specifying output filenames yet. You can follow the example in the demo app and use indirection: Attach the BlobKey of the output blog to an Entity of your choice that holds your desired name).\nLook for\nyield StoreOutput(\"WordCount\", filek... | [
1
] | [] | [] | [
"google_app_engine",
"mapreduce",
"python"
] | stackoverflow_0007710919_google_app_engine_mapreduce_python.txt |
Q:
What are some recommended resources and tutorials for learning the VTK library toolkit?
Apart from the books available from Kitware, I am looking for some links to any resources that could help in learning the VTK library. Preferably, with example code and tutorials. Google results have not been terribly informa... | What are some recommended resources and tutorials for learning the VTK library toolkit? | Apart from the books available from Kitware, I am looking for some links to any resources that could help in learning the VTK library. Preferably, with example code and tutorials. Google results have not been terribly informative for me. So I am asking here for links to VTK resources.
| [
"I used vtk on my last project. I used it with C++ though, not python.\nI remember the forums, wiki and mailing lists had a lots of useful information and helpful people:\nhttp://www.vtk.org/VTK/project/getinvolved.html\nhttp://www.vtk.org/VTK/resources/applications.html \n",
"\nYou can buy the official books\nYo... | [
4,
2
] | [] | [] | [
"python",
"vtk"
] | stackoverflow_0000942657_python_vtk.txt |
Q:
Python: delete the files after i finish reading from FTP
My python script opens a gzip file from FTP and reads it. Every time I run the script .gz files are downloaded to my Harddisk (Sites/htdocs folder as its a python cgi). I dont want to download the files to my harddisk or else delete the files after execution... | Python: delete the files after i finish reading from FTP | My python script opens a gzip file from FTP and reads it. Every time I run the script .gz files are downloaded to my Harddisk (Sites/htdocs folder as its a python cgi). I dont want to download the files to my harddisk or else delete the files after execution of script.
Here is snapshot of my script:
u = 'http://hapmap.... | [
"os.unlink(filename1) should work. Also, use finally: in your try: block to close the file descriptor like so:\nimport os\nu = 'http://hapmap.ncbi.nlm.nih.gov/downloads/frequencies/2010-05_phaseIII/'\nfilename1 = 'allele_freqs_chr' + chromosomes[i] + '_' + populations[0] + '_phase3.3_nr.b36_fwd.txt.gz'\nurl = u + ... | [
3,
0
] | [] | [] | [
"gzip",
"python",
"url"
] | stackoverflow_0007716625_gzip_python_url.txt |
Q:
Python API for C++
I have a code on C++, that creates file and writes data to it. Is it possible to use Python's functions to use Python's functionality in my C++ code? For example, I'd like to do this:
# Content of function.py
from PIL import Image
imgObject = Image.open('myfile.jpg') # Create Image object
pixArr... | Python API for C++ | I have a code on C++, that creates file and writes data to it. Is it possible to use Python's functions to use Python's functionality in my C++ code? For example, I'd like to do this:
# Content of function.py
from PIL import Image
imgObject = Image.open('myfile.jpg') # Create Image object
pixArray = imgObject.load() # ... | [
"You may have a look to boost::python library which is really great for interfacing python and C++.\n"
] | [
1
] | [] | [] | [
"c++",
"cpython",
"python",
"python_imaging_library"
] | stackoverflow_0007716970_c++_cpython_python_python_imaging_library.txt |
Q:
What's a better way of overriding nested class members in Python?
I need to “override” some of the base class' nested class members, while keeping the rest intact.
This is what I do:
class InternGenericForm(ModelForm):
class Meta:
model = Intern
exclude = ('last_achievement', '... | What's a better way of overriding nested class members in Python? | I need to “override” some of the base class' nested class members, while keeping the rest intact.
This is what I do:
class InternGenericForm(ModelForm):
class Meta:
model = Intern
exclude = ('last_achievement', 'program',)
widgets = {
'name': TextInput(attrs={'pl... | [
"class InternGenericForm(ModelForm): \n class Meta:\n model = Intern\n exclude = ('last_achievement', 'program',)\n widgets = {\n 'name': TextInput(attrs={'placeholder': 'Имя и фамилия' }),\n }\n\nclass InternApplicationForm(InternGenericForm):\n class Met... | [
17
] | [] | [] | [
"class",
"inheritance",
"nested_class",
"python",
"syntax"
] | stackoverflow_0007717089_class_inheritance_nested_class_python_syntax.txt |
Q:
Python opencv not receiving camera feed
I've been trying to use the SimpleCV (www.simplecv.org) module to run image recognition and manipulation. Unfortunately, my incoming video feed has been quite finicky, and I'm not sure what I did wrong. Just using some basic sample code:
import cvwindow = cv.NamedWindow("cam... | Python opencv not receiving camera feed | I've been trying to use the SimpleCV (www.simplecv.org) module to run image recognition and manipulation. Unfortunately, my incoming video feed has been quite finicky, and I'm not sure what I did wrong. Just using some basic sample code:
import cvwindow = cv.NamedWindow("camera", 1)
capture = cv.CreateCameraCapture(0)
... | [
"I'm one of the SimpleCV developers. It appears you are trying to use the standard python openCV wrapper.\nWhat I recommend doing is just run the example here:\nhttps://github.com/sightmachine/SimpleCV/blob/develop/SimpleCV/examples/display/simplecam.py\nOr here is the code as well:\nimport time, webbrowser\nfrom ... | [
5
] | [] | [] | [
"camera",
"opencv",
"python",
"simplecv"
] | stackoverflow_0007438666_camera_opencv_python_simplecv.txt |
Q:
Are SQLite reads always hitting disk?
I have a Pylons application using SQLAlchemy with SQLite as backend. I would like to know if every read operation going to SQLite will always lead to a hard disk read (which is very slow compared to RAM) or some caching mechanisms are already involved.
does SQLite maintain a... | Are SQLite reads always hitting disk? | I have a Pylons application using SQLAlchemy with SQLite as backend. I would like to know if every read operation going to SQLite will always lead to a hard disk read (which is very slow compared to RAM) or some caching mechanisms are already involved.
does SQLite maintain a subset of the database in RAM for faster a... | [
"\nYes, SQLite has its own memory cache. Check PRAGMA cache_size for instance. Also, if you're looking for speedups, check PRAGMA temp_store. There is also API for implementing your own cache.\nThe SQLite database is just a file to the OS. Nothing is 'automatically' done for it. To ensure caching does happen, there... | [
3,
0
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0007710895_python_sqlalchemy_sqlite.txt |
Q:
How to select all locations of unique elements in numpy 2d array with bounding box around them?
I have a 2D numpy array I want to find the 'every' location of all the unique elements. We can find the unique elements using numpy.unique(numpyarray.). Here it comes the tricky part. Now I have to know all the location... | How to select all locations of unique elements in numpy 2d array with bounding box around them? | I have a 2D numpy array I want to find the 'every' location of all the unique elements. We can find the unique elements using numpy.unique(numpyarray.). Here it comes the tricky part. Now I have to know all the locations for every unique element. Lets consider the following example.
array([[1, 1, 2, 2],\
[1, 1,... | [
"The simple, brute force way to do it is to just use numpy.where.\nFor example, if you're just wanting the bounding box:\nimport numpy as np\n\nx = np.array([[1,1,2,2],\n [1,1,2,2],\n [3,3,4,4],\n [3,3,4,4]])\n\nfor val in np.unique(x):\n rows, cols = np.where(x == val)\n ... | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007717314_numpy_python.txt |
Q:
DLL in sub folder rather than in application folder
have created a dynamic python file (pyd) using VC++. Using cx_freeze, I have created an exe. In order for this program to work on other computers, I need to have a file msvcr100.dll in the applications folder. And I do get the desired output.
However the distrib... | DLL in sub folder rather than in application folder | have created a dynamic python file (pyd) using VC++. Using cx_freeze, I have created an exe. In order for this program to work on other computers, I need to have a file msvcr100.dll in the applications folder. And I do get the desired output.
However the distribution license for Microsoft clearly states that the dll f... | [
"I'm not sure when in your script the DLL is loaded, but assuming it's delayed to the point you can do something about it, then you can have a go at loading the library yourself:\nimport os\nimport ctypes\ntry:\n here = os.path.dirname(__file__)\nexcept NameError:\n here = os.getcwd()\ndll = ctypes.CDLL(os.pa... | [
1,
0
] | [] | [] | [
"cx_freeze",
"manifest",
"pyd",
"python",
"visual_c++"
] | stackoverflow_0007595709_cx_freeze_manifest_pyd_python_visual_c++.txt |
Q:
Selenium syntax for Verifications that work with Hudson / jenkins
I've gone through various tutorials and Stack Overflow posts and understand that Selenium can output XML test results in a way that Hudson can read/report them in HTML format.
What I don't understand is the syntax to use in Python, to get the result... | Selenium syntax for Verifications that work with Hudson / jenkins | I've gone through various tutorials and Stack Overflow posts and understand that Selenium can output XML test results in a way that Hudson can read/report them in HTML format.
What I don't understand is the syntax to use in Python, to get the results to look something like:
Testcase_LoginPage.VerifyButton1Present fa... | [
"You have only one test defined, so it can only report one test. One test is a test method, not an assert statement. You can have several asserts in one single test, as you may need to assert several results in order to confirm a successful test result. \nSo first step to your desired output would be to put your se... | [
2,
0
] | [] | [] | [
"hudson",
"jenkins",
"python",
"selenium"
] | stackoverflow_0007654729_hudson_jenkins_python_selenium.txt |
Q:
Which is faster and why? Set or List?
Lets say that I have a graph and want to see if b in N[a]. Which is the faster implementation and why?
a, b = range(2)
N = [set([b]), set([a,b])]
OR
N= [[b],[a,b]]
This is obviously oversimplified, but imagine that the graph becomes really dense.
A:
Membership testing in ... | Which is faster and why? Set or List? | Lets say that I have a graph and want to see if b in N[a]. Which is the faster implementation and why?
a, b = range(2)
N = [set([b]), set([a,b])]
OR
N= [[b],[a,b]]
This is obviously oversimplified, but imagine that the graph becomes really dense.
| [
"Membership testing in a set is vastly faster, especially for large sets. That is because the set uses a hash function to map to a bucket. Since Python implementations automatically resize that hash table, the speed can be constant (O(1)) no matter the size of the set (assuming the hash function is sufficiently goo... | [
42,
6,
3
] | [] | [] | [
"graph",
"list",
"python",
"set"
] | stackoverflow_0007717011_graph_list_python_set.txt |
Q:
Django South migration fails
I am trying to map some data onto a staging server and have run into an issue.
When running my migrations I get the following error.
django.db.utils.DatabaseError: column "item_name_id" cannot be cast to type "pg_catalog.int4"
Any ideas how I can resolve this?
Traceback (most recent c... | Django South migration fails | I am trying to map some data onto a staging server and have run into an issue.
When running my migrations I get the following error.
django.db.utils.DatabaseError: column "item_name_id" cannot be cast to type "pg_catalog.int4"
Any ideas how I can resolve this?
Traceback (most recent call last):
File "gecko/manage.py... | [
"Your question is tagged mysql yet the Traceback shows you're using the postgresql_psycopg2 backend. Could that be the problem?\nFix the tags on the question or set the right DATABASE_ENGINE in your settings.py.\n"
] | [
1
] | [] | [] | [
"django",
"django_south",
"postgresql",
"python"
] | stackoverflow_0007712212_django_django_south_postgresql_python.txt |
Q:
Python: what is the correct way to handle gzipped json?
I've found this snippet, which seems to do the job, but I can't understand why it uses StringIO. Isn't f already a file-like object? What is the need to read it, then make it look like a file again, only to read it again? I've tested it (well, a slightly modi... | Python: what is the correct way to handle gzipped json? | I've found this snippet, which seems to do the job, but I can't understand why it uses StringIO. Isn't f already a file-like object? What is the need to read it, then make it look like a file again, only to read it again? I've tested it (well, a slightly modified version of it), and it doesn't work without StringIO.
| [
"Seems to be a flaw in python standard library which is fixed in Python 3.2.\nsee http://www.enricozini.org/2011/cazzeggio/python-gzip/\nurllib and urllib2 file objects do not provide a method tell() as requested by gzip.\n",
"It's possible that the gunzip code needs a file-like object that has a seek method, whi... | [
1,
1,
0
] | [] | [] | [
"asp.net_web_api",
"gzip",
"json",
"python"
] | stackoverflow_0007717795_asp.net_web_api_gzip_json_python.txt |
Q:
Better way to filter the rows with python
import pprint
full_key_list = set(["F1", "F2", "F3", "F4", "F5"]) # all expected field
filt_key_list = set(["F2", "F5"]) # fields should not be included
cont_list = [] # stores all filtered documents
read_in_cont1 = { "F... | Better way to filter the rows with python | import pprint
full_key_list = set(["F1", "F2", "F3", "F4", "F5"]) # all expected field
filt_key_list = set(["F2", "F5"]) # fields should not be included
cont_list = [] # stores all filtered documents
read_in_cont1 = { "F1" : 1, "F2" : True, "F3" : 'abc', "F4" : 130,... | [
"cont_list = [dict((k,v) for k,v in d.iteritems() if k not in filt_key_list)\n for d in read_in_conts]\n\nor if you want a slightly more factored version:\nfilter_out_keys = lambda d, x: dict((k,v) for k,v in d.iteritems() if k not in x)\ncont_list = [filter_out_keys(d, filt_key_list) for d in read_in_c... | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007718038_python.txt |
Q:
splitting and escaped forward slashes in Python
I have a file containing perl-style regexs of the form /pattern/replace/ that I'm attempting to read into Python as a list of compiled patterns and their associated replacement strings. Below is what I've done so far.
def get_regex(filename):
regex = []
fi = ... | splitting and escaped forward slashes in Python | I have a file containing perl-style regexs of the form /pattern/replace/ that I'm attempting to read into Python as a list of compiled patterns and their associated replacement strings. Below is what I've done so far.
def get_regex(filename):
regex = []
fi = open(filename,'r')
text = [l for l in fi.readline... | [
"Not really, no. Your best bet would probably be to use re.split() instead, with a regex that uses a lookbehind to make sure a forward slash isn't escaped, e.g.\nUNESCAPED_SLASH_RE = re.compile(r'(?<!\\\\)/')\nptn, repl = UNESCAPED_SLASH_RE.split(line[1:])[:-1]\n\n"
] | [
3
] | [] | [] | [
"escaping",
"python",
"regex",
"replace"
] | stackoverflow_0007718081_escaping_python_regex_replace.txt |
Q:
Python Dictionary Ordered Pairs
Ok, I need to create a program that accepts ordered pairs divided by a space, and adds them to the dictionary.
I.e
points2dict(["3 5"])
{"3":"5"}
How do i make python recognize that the first number is the key and the second number is the value???
A:
Use split:
In [3]: pairs ... | Python Dictionary Ordered Pairs | Ok, I need to create a program that accepts ordered pairs divided by a space, and adds them to the dictionary.
I.e
points2dict(["3 5"])
{"3":"5"}
How do i make python recognize that the first number is the key and the second number is the value???
| [
"Use split:\nIn [3]: pairs = ['3 5', '10 2', '11 3']\n\nIn [4]: dict(p.split(' ', 1) for p in pairs)\nOut[4]: {'10': '2', '11': '3', '3': '5'}\n\n",
"values = [\n '3 5',\n '6 10',\n '20 30',\n '1 2'\n]\nprint dict(x.split() for x in values)\n# Prints: {'1': '2', '3': '5', '20': '30', '6': '10'}\n\n",
... | [
3,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007718208_dictionary_python.txt |
Q:
Python, empty file after csv writer.. again
My python program loops through a bunch of csv-files, read them, and write specific columns in the file to another csv file. While the program runs, i can see the files being written in the correct manner, but once the program is finished, all the files i've just written... | Python, empty file after csv writer.. again | My python program loops through a bunch of csv-files, read them, and write specific columns in the file to another csv file. While the program runs, i can see the files being written in the correct manner, but once the program is finished, all the files i've just written become empty.
The solution to all the other simi... | [
"savefile=savepath + \"\\\\\" + i is the error. If both \"d:\\\\project\\a\\x.csv\" and \"d:\\\\project\\b\\x.csv\" exist, then you will write to savepath + \"\\\\\" + i more than once. If the second path as an empty \"x.csv\", then it would overwrite the result with an empty file.\nTry this instead:\nimport os\n... | [
2,
0,
0
] | [] | [] | [
"csv",
"python",
"writer"
] | stackoverflow_0007717350_csv_python_writer.txt |
Q:
How to get the control over the selection in a gtk.IconView?
I want to change the opacity or color of a gtk.IconView select box (I want actually to make the selection more visible).
I noticed that the gtk.IconView widget had style properties selection-box-alpha & selection-box-color but only accessible for reading... | How to get the control over the selection in a gtk.IconView? | I want to change the opacity or color of a gtk.IconView select box (I want actually to make the selection more visible).
I noticed that the gtk.IconView widget had style properties selection-box-alpha & selection-box-color but only accessible for reading.
The set_select_function() method of the gtk.TreeSelection class ... | [
"You might be able to set the pixmap opacity by implementing a custom gtk.CellRenderer that draws the pixmap according to the selection state, and replacing the gtk.IconView's default cell renderer with your own.\n",
"In fact, we need to replace the gtk.IconView's default cell renderer by gtk.CellRendererPixbuf w... | [
1,
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0007698217_gtk_pygtk_python.txt |
Q:
Anonymous code blocks
Preface:
So far I've used Python as a full scale programming language. Now I like to use it to write down some notes (comments) with some calculation (Python code) here and there (I'm actually using Emacs and send the current buffer again and again to a running IPython instance).
The problem:... | Anonymous code blocks | Preface:
So far I've used Python as a full scale programming language. Now I like to use it to write down some notes (comments) with some calculation (Python code) here and there (I'm actually using Emacs and send the current buffer again and again to a running IPython instance).
The problem: I like to reuse some commo... | [
"If I want to simulate C/C++ blocks, this usually does the trick:\ndef _anon():\n d = 10\n A = d**2 * pi /4\n_anon()\n\nThese \"blocks\" are able to be nested.\n\nIf a small piece of initial boilerplate is acceptable, you can also use a decorator to call the function:\ndef block(function):\n function()\n\n... | [
7,
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005159247_python.txt |
Q:
Python is vs ==
Possible Duplicate:
String comparison in Python: is vs. ==
When is the == operator not equivalent to the is operator? (Python)
I'm pretty new to Python still. I heard someone say use is, not == because "this isn't C". But I had some code x is 5 and it was not working as expected.
So, following pr... | Python is vs == |
Possible Duplicate:
String comparison in Python: is vs. ==
When is the == operator not equivalent to the is operator? (Python)
I'm pretty new to Python still. I heard someone say use is, not == because "this isn't C". But I had some code x is 5 and it was not working as expected.
So, following proper Python/PEP styl... | [
"You should use == to compare two values. You should use is to see if two names are bound to the same object.\nYou should almost never use x is 5 because depending on the implementation small integers might be interned. This can lead to surprising results:\n>>> x = 256\n>>> x is 256\nTrue\n>>> x = 257\n>>> x is 257... | [
11,
2
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0007718790_operators_python.txt |
Q:
What's the best way excluding a query set from a queryset
I'm writing an inbox view and I want to exclude unseen messages from seen messages.
My code is :
def render_notifications(request):
unseen_notices = notification.Notice.objects.filter(recipient=request.user,unseen=True).order_by("-added")
notices = notif... | What's the best way excluding a query set from a queryset | I'm writing an inbox view and I want to exclude unseen messages from seen messages.
My code is :
def render_notifications(request):
unseen_notices = notification.Notice.objects.filter(recipient=request.user,unseen=True).order_by("-added")
notices = notification.Notice.objects.filter(recipient=request.user).exclude(i... | [
"Seem that you can do something like here:\n user_notices = notification.Notice.objects.filter(recipient=request.user)\n unseen_notices = user_notices.filter(unseen=True).order_by(\"-added\")\n notices = user_notices.exclude(unseen=True).order_by(\"-added\")\n\n",
"Django querysets are lazy. This explains why the... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007717699_django_python.txt |
Q:
Implement ascending sort in a python list
As part of a python assignment I'm trying to implement list sorting (ascending) without using the sort() method, I think my logic is correct but I keep getting an error:
sample=[23,44,12,1,6,87]
temp=0
for i in range(0,len(sample)):
if sample[i] > sample[i+1]:
... | Implement ascending sort in a python list | As part of a python assignment I'm trying to implement list sorting (ascending) without using the sort() method, I think my logic is correct but I keep getting an error:
sample=[23,44,12,1,6,87]
temp=0
for i in range(0,len(sample)):
if sample[i] > sample[i+1]:
sample[i]=temp
sample[i]=sample[i+1]
... | [
"check this: http://faculty.cs.niu.edu/~hutchins/csci241/sorting.htm\npython bubble sorting:\nsample=[23,44,12,1,6,87]\n\nsorted = False\nwhile not sorted:\n sorted = True\n for i in range(len(sample) - 1):\n if sample[i] > sample[i+1]:\n sorted = False\n sample[i], sample[i+1] = ... | [
1,
1,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0007718576_list_python_sorting.txt |
Q:
Why is set(None) invalid in python
>>> set(None)
*** TypeError: 'NoneType' object is not iterable
is a problem but not this:
>>> a=set()
>>> a.add(None)
Why?
A:
As the error message tells you, set() expects an iterable.
set([None])
Note: the same is true for list, tuple, ...
A:
Because the set initializer tak... | Why is set(None) invalid in python | >>> set(None)
*** TypeError: 'NoneType' object is not iterable
is a problem but not this:
>>> a=set()
>>> a.add(None)
Why?
| [
"As the error message tells you, set() expects an iterable.\nset([None])\n\nNote: the same is true for list, tuple, ...\n",
"Because the set initializer takes an object that must be iterable, but add() will take any element as long as its hashable. Since NoneType is not iterable, it raises an exception.\n\nclass... | [
14,
4
] | [] | [] | [
"python",
"set",
"types"
] | stackoverflow_0007719419_python_set_types.txt |
Q:
execute python script when directory is not empty - Directory Monitoring
I have a python script that converts images and videos withing a directory.
The problem, the python script executes manually but I need the script to execute automatically when a file is dropped into the directory under a linux platform.
Wh... | execute python script when directory is not empty - Directory Monitoring | I have a python script that converts images and videos withing a directory.
The problem, the python script executes manually but I need the script to execute automatically when a file is dropped into the directory under a linux platform.
What would be the best way to set a python script to watch/monitor a directory?
... | [
"The 'clean' way to do this is using the inotify system. There is the Pyinotify project if you want to use Python to interface with it.\nYou don't have to use inotify directly though - there are tools like icrond you can hook into. In fact, the person at that link looks to be trying to do something very similar to ... | [
2,
2,
1
] | [] | [] | [
"daemon",
"linux",
"python",
"shell"
] | stackoverflow_0007719685_daemon_linux_python_shell.txt |
Q:
Trying to use float() in column_property
I'm trying to convert a column into a float while assigning a column using column_property:
class voteinfo(Base):
__tablename__ = 'voteinfo'
id = Column(Integer, primary_key=True)
upvotes = Column(Integer)
downvotes = Column(Integer)
controversial = colu... | Trying to use float() in column_property | I'm trying to convert a column into a float while assigning a column using column_property:
class voteinfo(Base):
__tablename__ = 'voteinfo'
id = Column(Integer, primary_key=True)
upvotes = Column(Integer)
downvotes = Column(Integer)
controversial = column_property(float(upvotes - downvotes)/(abs(up... | [
"From the sqlalchemy docs, the best way to do this is to define a python @property. You also need to use the built-in sqlalchemy float type.\nfrom sqlalchemy.types import Float\n\nclass voteinfo(Base):\n __tablename__ = 'voteinfo'\n id = Column(Integer, primary_key=True)\n upvotes = Column(Integer)\n do... | [
3
] | [] | [] | [
"pyramid",
"python",
"sqlalchemy"
] | stackoverflow_0007720052_pyramid_python_sqlalchemy.txt |
Q:
Is there anyway to modify stat information like mtime or ctime manually in Python or any language at all?
I am trying the following code:
os.stat(path_name)[stat.ST_CTIME] = ctime
However, this gives the following error:
exceptions.TypeError: 'posix.stat_result' object does not support item assignment
Is there a... | Is there anyway to modify stat information like mtime or ctime manually in Python or any language at all? | I am trying the following code:
os.stat(path_name)[stat.ST_CTIME] = ctime
However, this gives the following error:
exceptions.TypeError: 'posix.stat_result' object does not support item assignment
Is there anyway to modify ctime?
Thanks!
| [
"os.utime(filename, timetuple) can be used to set the atime and mtime of a file. As far as I know there is no way to modify the ctime from userland without resorting to hacks such as playing with the clock or direct edition of the filesystem (which I really do not recommend), and this is true for any programming l... | [
8,
2,
1
] | [] | [] | [
"posix",
"python",
"stat"
] | stackoverflow_0005803765_posix_python_stat.txt |
Q:
inheriting a list to use it's in-place sort method
I'm trying to sort the contents of several files (sometimes moving a line from one file to another)
I would like to use the built-in adaptive merge sort that is and attribute of list. I tried inheriting the method from list, but I don't know if it needs more than... | inheriting a list to use it's in-place sort method | I'm trying to sort the contents of several files (sometimes moving a line from one file to another)
I would like to use the built-in adaptive merge sort that is and attribute of list. I tried inheriting the method from list, but I don't know if it needs more than __len__, __getitem__, and __setitem__. Yes. I want to... | [
"The sort method of lists is written in C (in CPython) and so does not need to use __getitem__ and __setitem__ methods at all. If it did use those methods it would slow the normal list.sort() down immensely\nYou may be able to store the file indices in a list and use list's builtin sort with a key function to do so... | [
1,
1,
1
] | [] | [] | [
"mmap",
"python",
"sorting"
] | stackoverflow_0007719523_mmap_python_sorting.txt |
Q:
using a python list as input for linux command that uses stdin as input
I am using python scripts to load data to a database bulk loader.
The input to the loader is stdin. I have been unable to get the correct syntax to call the unix based bulk loader passing the contents of a python list to be loaded.
I have bee... | using a python list as input for linux command that uses stdin as input | I am using python scripts to load data to a database bulk loader.
The input to the loader is stdin. I have been unable to get the correct syntax to call the unix based bulk loader passing the contents of a python list to be loaded.
I have been reading about Popen and PIPE but they have not been behaving as i expect.
T... | [
"If your data is short and simple, you could preformat the entire list and do it simple with subprocess like this:\nimport subprocess\ndata = [\"list\", \"of\", \"stuff\"]\nproc = subprocess.Popen([\"sql\", \"-c\", \"COPY table FROM stdin\"], stdin=subprocess.PIPE)\nproc.communicate(\"\\n\".join(data))\n\nIf the da... | [
5
] | [] | [] | [
"pipe",
"popen",
"python",
"stdin"
] | stackoverflow_0007720220_pipe_popen_python_stdin.txt |
Q:
Is there any document for the Python win32com operations on Powerpoint?
I have gat some samples about how to open a presentation and access the slides and shapes. But I want to do some more other operations(e.g. generate a thumbnail from a specified slide). What methods can I use? Is there any document illustratin... | Is there any document for the Python win32com operations on Powerpoint? | I have gat some samples about how to open a presentation and access the slides and shapes. But I want to do some more other operations(e.g. generate a thumbnail from a specified slide). What methods can I use? Is there any document illustrating all the functionalities?
| [
"Not to discourage you, but my experience using COM from Python is that you won't find many examples.\nI would be shocked (but happy to see) if anybody posted a big tutorial or reference using PowerPoint in Python. Probably the best you'll find, which you've probably already found, is this article\nHowever, if you... | [
9,
0
] | [] | [] | [
"document",
"powerpoint",
"python",
"win32com"
] | stackoverflow_0007708265_document_powerpoint_python_win32com.txt |
Q:
Python Web Services
Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?
A:
I'm not sure about an accepted standard, but I've found SOAPpy to be fairly straight-forward and useful library for handling SOAP-based web services.
SOAPy i... | Python Web Services | Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?
| [
"I'm not sure about an accepted standard, but I've found SOAPpy to be fairly straight-forward and useful library for handling SOAP-based web services.\n\nSOAPy is a SOAP/XML Schema Library for Python. Given either a WSDL or SDL document, SOAPy discovers the published API for a web service and exposes it to Python a... | [
1,
0,
0
] | [] | [] | [
"python",
"web_services"
] | stackoverflow_0000159802_python_web_services.txt |
Q:
How do I send multiple arguments when binding a widget to a function in python 2.7.2
Just wondering, How do I bind an entry field to (with the return key) a function that requires 2 arguments counting event as one of them without lambda or classes, just one function and 2 arguments:
def function(event,entry):#entr... | How do I send multiple arguments when binding a widget to a function in python 2.7.2 | Just wondering, How do I bind an entry field to (with the return key) a function that requires 2 arguments counting event as one of them without lambda or classes, just one function and 2 arguments:
def function(event,entry):#entry is the widget to be focused. also, entry is just a place holder NOT A WIDGET. entry MUST... | [
"When you write function(None,entry2) you /are/ calling it right away -- the function probably returns None, so essentially what you are doing is:\nfunction(None, entry2)\nentry1.bind(\"<Return>\", None)\n\nWhat you are probably looking for is this:\nentry1.bind(\"<Return>\", lambda e: function(entry2))\n\nThis gen... | [
3,
1
] | [
"Without a full example, it's difficult to provide a full answer. However there is one common error that is easily fixed: the second argument to bind should be a function name, not a function call.\nIf you change the bind statement to:\nentry1.bind(\"<Return>\", function)\n\nthe function will be called when the Re... | [
-1
] | [
"binding",
"event_handling",
"events",
"python",
"tkinter"
] | stackoverflow_0007717055_binding_event_handling_events_python_tkinter.txt |
Q:
Python __metaclass__ inheritance issue
My issue is that I am using a metaclass to wrap certain class methods in a timer for logging purposes.
For example:
class MyMeta(type):
@staticmethod
def time_method(method):
def __wrapper(self, *args, **kwargs):
start = time.time()
r... | Python __metaclass__ inheritance issue | My issue is that I am using a metaclass to wrap certain class methods in a timer for logging purposes.
For example:
class MyMeta(type):
@staticmethod
def time_method(method):
def __wrapper(self, *args, **kwargs):
start = time.time()
result = method(self, *args, **kwargs)
... | [
"Guard the timing code with an attribute. That way, only the outermost decorated method on an object will actually get timed.\n@staticmethod\ndef time_method(method):\n def __wrapper(self, *args, **kwargs):\n if hasattr(self, '_being_timed'):\n # We're being timed already; just run the method\n... | [
4,
1
] | [] | [] | [
"inheritance",
"metaclass",
"python"
] | stackoverflow_0007720274_inheritance_metaclass_python.txt |
Q:
What is the best way to implement a Tree Structure in python
What is the best way to implement a tree structure (generic - not binary) in python? My intuition would have the following skeleton:
class TNode(self, data):
#enter things for each individual node
class TStructure(self):
#enter code for implementi... | What is the best way to implement a Tree Structure in python | What is the best way to implement a tree structure (generic - not binary) in python? My intuition would have the following skeleton:
class TNode(self, data):
#enter things for each individual node
class TStructure(self):
#enter code for implementing nodes that reference each other.
| [
"look into networkx and the Graph object.\nsee here\nIf this is for homework and you have to implement from scratch I'll give you the hint that you probably want a class for nodes and a class for edges...\nEDIT:\nYou don't really need a structure class if you have a node class and an edge class something traversing... | [
1,
1
] | [] | [] | [
"algorithm",
"data_structures",
"python",
"tree"
] | stackoverflow_0007720435_algorithm_data_structures_python_tree.txt |
Q:
Setup.py for uninstalling via pip
According to another question, pip offers a facility for uninstalling eggs, which it's help also indicates.
I have a project that, once installed, has a structure in my local site-packages folder that looks like this:
projecta/
projecta-1.0-py2.6.egg-info/
Using an up to date vers... | Setup.py for uninstalling via pip | According to another question, pip offers a facility for uninstalling eggs, which it's help also indicates.
I have a project that, once installed, has a structure in my local site-packages folder that looks like this:
projecta/
projecta-1.0-py2.6.egg-info/
Using an up to date version, pip uninstall projecta asks me the... | [
"If I recall correctly pip knows how to uninstall packages installed via setuptools/distribute, not raw distutils.\nThere are some setuptools's features pip is based on - like --record option, which stores package metadata (and it is what allows pip to uninstal package related files).\nTry doing:\n$ pip install /pa... | [
3
] | [] | [] | [
"pip",
"python",
"uninstallation"
] | stackoverflow_0007689618_pip_python_uninstallation.txt |
Q:
Uploading a file to google docs via a Python script
I'm trying to upload a backup file from my server to my Google storage in a Python script. The backup file is an encrypted zip file (gpg file). It connects successfully, but fails transferring the file which the following error:
Traceback (most recent call last):... | Uploading a file to google docs via a Python script | I'm trying to upload a backup file from my server to my Google storage in a Python script. The backup file is an encrypted zip file (gpg file). It connects successfully, but fails transferring the file which the following error:
Traceback (most recent call last):
File "backup.py", line 37, in <module>
entry = gd_... | [
"Uploading files of any type are only allowed for Google Apps for Business accounts. A regular account cannot upload this filetype. See this link from the Google Docs API. \n",
"Good news: now Google Apps for Free accounts can also upload files of any type.\nThree key points here: \n\nUse resumable upload\nAppend... | [
2,
2
] | [] | [] | [
"google_api",
"google_docs",
"python",
"upload"
] | stackoverflow_0006679381_google_api_google_docs_python_upload.txt |
Q:
is there a way to make this code more terse?
Given a list of items, and a map from a predicate function to the "value" function, the code below applies "value" functions to the items satisfying the corresponding predicates:
my_re0 = re.compile(r'^([a-z]+)$')
my_re1 = re.compile(r'^([0-9]+)$')
my_map = [
(my_r... | is there a way to make this code more terse? | Given a list of items, and a map from a predicate function to the "value" function, the code below applies "value" functions to the items satisfying the corresponding predicates:
my_re0 = re.compile(r'^([a-z]+)$')
my_re1 = re.compile(r'^([0-9]+)$')
my_map = [
(my_re0.search, lambda x: x),
(my_re1.search, lambd... | [
"A bit less terse than Nate's ;-)\nfrom itertools import product\n\ncomb = product(my_map, ['abc','123','a1'])\nmapped = ((p(x),f) for (p,f),x in comb)\ngroups = (f(v.groups()) for v,f in mapped if v)\nprint next(groups), list(groups) # first match and the rest of them\n\n",
"[f(v.groups()) for x in ['abc','123',... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007720130_python.txt |
Q:
Find every third value and insert cr or newline in VIM
So I have several large datasets that I need to make more readable and currently I'm having to go in and move to each 3rd value and insert a newline. I've tried several things in VIM to get this to work, but none seem to return the value that I'm looking for. ... | Find every third value and insert cr or newline in VIM | So I have several large datasets that I need to make more readable and currently I'm having to go in and move to each 3rd value and insert a newline. I've tried several things in VIM to get this to work, but none seem to return the value that I'm looking for. Here's some of my data:
(0.96260310749184663, 4.383000820649... | [
"Two approaches\n1. ex commands and formatting\nMy first thought was textwidth:\n:se tw=50\n:g/./norm! gqq\n:%s/^[^(]/ &/g\n\nThis \n\nsets text width to 50 chars\nreformats each (nonempty) line\ninserts a space at the start of any lines which don't start with (\n\n2. use a macro\nAlternatively: make a macro\ngg\nq... | [
5,
5,
2,
1,
1,
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0007714278_python_vim.txt |
Q:
Getting macports django and python to work together
I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from ... | Getting macports django and python to work together | I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django.
In terminal echo $PATH gives:
echo $PATH
... | [
"First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash_profile file then ~/.profile will be ignored. You will have to copy the contents over.\nTo see what python version Macports has selected use:\nport select --list python\n\nwhich will show you something like this:\nA... | [
3,
1,
1,
1
] | [] | [] | [
"django",
"macos",
"python"
] | stackoverflow_0004296570_django_macos_python.txt |
Q:
How do I import a WAV song to python
I type
Import sound
mysound = sound.load_sound("Hello")
and I get this error
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> [evaluate A1.py]
Traceback (most recent call last)... | How do I import a WAV song to python | I type
Import sound
mysound = sound.load_sound("Hello")
and I get this error
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> [evaluate A1.py]
Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 4.... | [
"EDIT: Your error is first pointing to a file that does not exist (you may need the file extension or make sure the path is correct)\nYou also seem to be using Pygame.\n",
"import winsound\n\nsoundfile = \"c:\\Windows\\Media\\chimes.wav\"#Song/Track to play(MUST be wav, not sure haven't tested), include full... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007720728_python.txt |
Q:
instance.__dict__ & class.__dict__
Code goes first:
class A(object):
def foo(self):
self.foo = 'foo'
def bar(self):
self.bar = 'bar'
cls_dict = dict(A.__dict__) #not empty
a = A()
a_dict = dict(a.__dict__) #empty, why?
A:
In Python, everything is an object containing attributes. That ... | instance.__dict__ & class.__dict__ | Code goes first:
class A(object):
def foo(self):
self.foo = 'foo'
def bar(self):
self.bar = 'bar'
cls_dict = dict(A.__dict__) #not empty
a = A()
a_dict = dict(a.__dict__) #empty, why?
| [
"In Python, everything is an object containing attributes. That includes classes themselves. The whole object-oriented thing with classes which define methods and instances which can execute those methods with the varying data per-instance is just a protocol for looking up attributes in a series of objects.\nclass ... | [
12,
0
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0007720611_attributes_python.txt |
Q:
wxPython: global hotkey loop toggle
I'm trying to create a hotkey toggle(f12) that will turn on a loop when pressed once then turn that loop off when pressed again. The loop is a mouse click every .5 seconds when toggled on. I found a recipe for a hot keys on the wxpython site and I can get the loop to turn on but... | wxPython: global hotkey loop toggle | I'm trying to create a hotkey toggle(f12) that will turn on a loop when pressed once then turn that loop off when pressed again. The loop is a mouse click every .5 seconds when toggled on. I found a recipe for a hot keys on the wxpython site and I can get the loop to turn on but can't figure a way to get it to turn off... | [
"Your loop variable is locally scoped inside of handleHotKey. Because regHotKey2 is bound to handleHotKey2, which is a different listener, the event it generates will never affect the loop within handleHotKey. Besides that, the first line of handleHotKey2 is a return value, which will quit the function before the... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007563396_python_wxpython.txt |
Q:
Python 'No such file or directory' opening path `~/filename` with mode `w+`
I'm trying to open a file that doesn't exist with this line:
x = open("~/tweetly/auth", 'w+')
That should open it if it exists, and then wipe content to begin to write.
If it doesn't exist, it should create it...right?
It doesn't. I get t... | Python 'No such file or directory' opening path `~/filename` with mode `w+` | I'm trying to open a file that doesn't exist with this line:
x = open("~/tweetly/auth", 'w+')
That should open it if it exists, and then wipe content to begin to write.
If it doesn't exist, it should create it...right?
It doesn't. I get this error.
IOError: [Errno 2] No such file or directory: '~/tweetly/auth'
Ideas?... | [
"The ~ alias for the home directory is a shell-ism (something the shell does for you), not something you can use with the Python open command:\npax:~$ cd ~\n\npax:~$ ls qq.s\nqq.s\n\npax:~$ python\nPython 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) \n[GCC 4.5.2] on linux2\nType \"help\", \"copyright\", \"credits\" o... | [
4,
4
] | [] | [] | [
"error_handling",
"ioerror",
"python"
] | stackoverflow_0007721345_error_handling_ioerror_python.txt |
Q:
Understanding intermediary SQL statements in SQLAlchemy
So I have table, and I want to have users be able to view the table in whichever order they'd like. Here's an example:
class Thing(Base):
__tablename__ = 'thing'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(Dat... | Understanding intermediary SQL statements in SQLAlchemy | So I have table, and I want to have users be able to view the table in whichever order they'd like. Here's an example:
class Thing(Base):
__tablename__ = 'thing'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(DateTime, default=datetime.now())
def __init__(self, amount... | [
"Ans 1:\nWhen you are giving any syntax what exactly it will return you can check with type of that syntax like\nWhen you write\nIn [5]: Thing.amount.desc()\nOut[5]: <sqlalchemy.sql.expression._UnaryExpression object at 0x199a5d0>\n\nIt will create one object of type expression._UnaryExpression. So this expression ... | [
3
] | [] | [] | [
"pyramid",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0007719923_pyramid_python_sql_sqlalchemy.txt |
Q:
How to improve this python code?
I am doing a problem in which i have to code about this problem-
>>> getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
>>> getNumbers(9)
[81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
I am getting answers with my code but i am not satisfied with my code,please suggest some options ... | How to improve this python code? | I am doing a problem in which i have to code about this problem-
>>> getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
>>> getNumbers(9)
[81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
I am getting answers with my code but i am not satisfied with my code,please suggest some options to improve this code.
def getNumbers(n... | [
"Like this?\ndef getNumbers(n):\n return [i * i for i in range(-n, n + 1, 2)]\n\n"
] | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007721460_list_python.txt |
Q:
operator precedence: not and comparisons
I'm trying to understand python better and the lack of parentheses can be a bit confusing for some reason.
how is (not a < b < c) evaluated? Is it (not a) < b < c? or not (a < b < c)?
According to the reference manual, does not have a lower or higher precedence than < ? I'... | operator precedence: not and comparisons | I'm trying to understand python better and the lack of parentheses can be a bit confusing for some reason.
how is (not a < b < c) evaluated? Is it (not a) < b < c? or not (a < b < c)?
According to the reference manual, does not have a lower or higher precedence than < ? I'm assuming operators with higher precedence ev... | [
"What you're seeing in the 2.7 manual is all relational operators, including not in and is not, at the same precedence; boolean not is still one level lower in precedence and as such the relational comparison happens first.\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0007721541_python.txt |
Q:
Python self contained web application and server?
What is a good and easy way to distribute a web application and server bundled together, python way?
So I can say to a user "Here take this tar/whatever, unpack it and run blahblah.py" and blahblah.py will run a http/wsgi server and serve my application?
Im looking... | Python self contained web application and server? | What is a good and easy way to distribute a web application and server bundled together, python way?
So I can say to a user "Here take this tar/whatever, unpack it and run blahblah.py" and blahblah.py will run a http/wsgi server and serve my application?
Im looking for a stable production-ready multi-threaded wsgi-serv... | [
"CherryPy can act as a WSGI container.\n",
"You might find this discussion on reddit informative.\n",
"cherrypy is the easiest one to use, django is feature rich and tornado is more advanced with asynchrounous web server(in my opinion it is better than multithreaded web server).\nFor what you want, django is be... | [
2,
1,
0
] | [] | [] | [
"deployment",
"python"
] | stackoverflow_0007688442_deployment_python.txt |
Q:
Sending an HTML email programmatically or through free applications
I am attempting to send an HTML email in Python. I find that email browsers(not sure if thats the correct term) change my html/css especially concerning images. Such as if I have the following CSS:
.myclass { background-image: url(http"//mywebsite... | Sending an HTML email programmatically or through free applications | I am attempting to send an HTML email in Python. I find that email browsers(not sure if thats the correct term) change my html/css especially concerning images. Such as if I have the following CSS:
.myclass { background-image: url(http"//mywebsite.com/images/img1.png }
In Microsoft Outlook, it removes that line of CSS... | [
"Here is a good tutorial:\nhttp://www.smashingmagazine.com/2010/01/19/design-and-build-an-email-newsletter-without-losing-your-mind/\nHope this helps.\n"
] | [
2
] | [] | [] | [
"email",
"html",
"python"
] | stackoverflow_0007721663_email_html_python.txt |
Q:
RegEx in python, not sure what I am doing wrong
I am quite new to Python and I researched as much as I could before I decided I should ask a question here. So here is the problem:
I am not sure what I am doing wrong with my RegEx. I wanted to try the re.findall() out, so I thought I would write a small script that... | RegEx in python, not sure what I am doing wrong | I am quite new to Python and I researched as much as I could before I decided I should ask a question here. So here is the problem:
I am not sure what I am doing wrong with my RegEx. I wanted to try the re.findall() out, so I thought I would write a small script that would find phone numbers on webpages. Here is the co... | [
"/\\d{3}.\\d{3}.\\d{4}/g - The /../ part is to identify regex in other languages like Ruby and g is a flag, also not applicable to Python. Try removing them and use just \\d{3}.\\d{3}.\\d{4}\nAlso I think you wanted to use the output / response in the findall and not just web, which is why you are seeing the expect... | [
3,
0
] | [] | [] | [
"findall",
"python",
"regex",
"urllib"
] | stackoverflow_0007720941_findall_python_regex_urllib.txt |
Q:
Tornado translation facility and javascript
I am trying to make a bilingual website (English & Greek). I am using tornado and I put global function _() in my templates. The translation comes directly from a .csv. Everything is fine in html so I can write {{_("Hello")}} and if the user locale is Greek the word "Hel... | Tornado translation facility and javascript | I am trying to make a bilingual website (English & Greek). I am using tornado and I put global function _() in my templates. The translation comes directly from a .csv. Everything is fine in html so I can write {{_("Hello")}} and if the user locale is Greek the word "Hello" is translated in Greek. However, I have no id... | [
"A friend of mine suggested these two plugins:\n1) http://recursive-design.com/blog/2008/02/21/jquery-i18n-translation-plugin/\n2) http://keith-wood.name/localisation.html\nProbably we'll use these!\n"
] | [
0
] | [] | [] | [
"javascript",
"python",
"tornado"
] | stackoverflow_0007716620_javascript_python_tornado.txt |
Q:
Celery periodic_task running multiple times in parallel
I have some very simple periodic code using Celery's threading; it simply prints "Pre" and "Post" and sleep in between. It is adapted from this StackOverflow question and this linked website
from celery.task import task
from celery.task import periodic_task
f... | Celery periodic_task running multiple times in parallel | I have some very simple periodic code using Celery's threading; it simply prints "Pre" and "Post" and sleep in between. It is adapted from this StackOverflow question and this linked website
from celery.task import task
from celery.task import periodic_task
from django.core.cache import cache
from time import sleep
imp... | [
"How are you running celeryd? I'm not familiar with a threaded option.\nIf it's running multi-process then there are no \"global\" variables that are shared memory between workers.\nIf you want a counter shared between all workers, then I'd suggest you use cache.incr.\nE.g.:\nIn [1]: from django.core.cache import c... | [
3
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0007719203_celery_python.txt |
Q:
sql python - return sql variable
I have SQL command something like this:
DEFINE item_id_variable
BEGIN
INSERT INTO items (name, value, status)
VALUES (myname, myvalue, mystatus)
RETURNING item_id INTO item_id_variable;
The table has auto-incrementing attribute item_id and it's value for the row I just a... | sql python - return sql variable | I have SQL command something like this:
DEFINE item_id_variable
BEGIN
INSERT INTO items (name, value, status)
VALUES (myname, myvalue, mystatus)
RETURNING item_id INTO item_id_variable;
The table has auto-incrementing attribute item_id and it's value for the row I just added is in the item_id_variable. I tri... | [
"Have you tried cursor.fetchall() (for example)?\n",
"Read it How do I get the \"id\" after INSERT into MySQL database with Python?\nYou can get the last insert id by \"SELECT last_insert_id()\" or connection.insert_id()\n"
] | [
0,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0007723053_python_sql.txt |
Q:
Is there an IDE with a GUI builder for Python?
Possible Duplicate:
Which Python IDE has visual studio features?
Is there a good IDE for building GUI apps with Python
I'm looking for some kind of Visual Basic like builder for Python. I'm not fussed about intellisense or highlighting, I can program Python. I'm loo... | Is there an IDE with a GUI builder for Python? |
Possible Duplicate:
Which Python IDE has visual studio features?
Is there a good IDE for building GUI apps with Python
I'm looking for some kind of Visual Basic like builder for Python. I'm not fussed about intellisense or highlighting, I can program Python. I'm looking for the GUI builder aspect, where I can drag a... | [
"If you want to create a GUI using Qt, you may build it up with Qt Designer (a tool in the Qt Creator IDE), then convert forms in Python code by using the pyuic compiler that comes with PyQt.\n"
] | [
1
] | [] | [] | [
"ide",
"python",
"user_interface"
] | stackoverflow_0007723464_ide_python_user_interface.txt |
Q:
Where is the location of the fcntl module of python?
I'm on unix but I can't find the location of the fcntl module. I'm using Jython in my web development, and the existing program that I'm modifying needs that module. Can you give me a way to import it or for my code to be able to use this module? Thanks in advan... | Where is the location of the fcntl module of python? | I'm on unix but I can't find the location of the fcntl module. I'm using Jython in my web development, and the existing program that I'm modifying needs that module. Can you give me a way to import it or for my code to be able to use this module? Thanks in advance!
| [
"fcntl is a built-in module. It's not written in Python, but in C. Unfortunately, it hasn't been ported to Java, and according to this bug report, it's unlikely that it ever will be.\nTo answer your question: it's in the CPython source, here.\nThe problem is that fcntl is Unix-specific; your program was not portabl... | [
2
] | [] | [] | [
"jython",
"python",
"tomcat"
] | stackoverflow_0007723571_jython_python_tomcat.txt |
Q:
pygtk custom widgets displaying in separate window
I'm having trouble with custom widgets showing up in a separate window. Separate window not in the sense of all widgets being in a window, but they all come up separately with their own window decorations. I'm not sure where the problem would be, but I guessed it ... | pygtk custom widgets displaying in separate window | I'm having trouble with custom widgets showing up in a separate window. Separate window not in the sense of all widgets being in a window, but they all come up separately with their own window decorations. I'm not sure where the problem would be, but I guessed it might be in one of the following, maybe to do with how I... | [
"Instead of calling do_realize in __init__, I should be calling queue_draw. I got help on the pygtk irc.\n"
] | [
1
] | [] | [] | [
"gtk",
"pycairo",
"pygtk",
"python",
"widget"
] | stackoverflow_0007703430_gtk_pycairo_pygtk_python_widget.txt |
Q:
How can I quickly run a function over an array of every possible array of length L with given possible elements?
I have a function calc_dG that, for any array corresponding to a short DNA sequence (3 to 15 bases or so), gives me the binding energy of that sequence. Actually, it's just an array lookup. nndG is an a... | How can I quickly run a function over an array of every possible array of length L with given possible elements? | I have a function calc_dG that, for any array corresponding to a short DNA sequence (3 to 15 bases or so), gives me the binding energy of that sequence. Actually, it's just an array lookup. nndG is an array of binding energies for adjacent pairs of bases, and thus the binding energies can be calculated with nndG[4*S[:-... | [
"If I understand your problem correctly, you are maximizing a function f(i_1, i_2, ..., i_n) over integers in the set {0, 1, 2, 3}.\nYou can use a combination of iteration and vectorized indexing.\nimport numpy as np\nimport itertools\n\ndef cartesian_chunked(n, n_items=4, chunk_dim=3):\n if n > chunk_dim:\n ... | [
1
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0007721328_numpy_python_scipy.txt |
Q:
When do you use 'self' in Python?
Are you supposed to use self when referencing a member function in Python (within the same module)?
More generally, I was wondering when it is required to use self, not just for methods but for variables as well.
A:
Adding an answer because Oskarbi's isn't explicit.
You use sel... | When do you use 'self' in Python? | Are you supposed to use self when referencing a member function in Python (within the same module)?
More generally, I was wondering when it is required to use self, not just for methods but for variables as well.
| [
"Adding an answer because Oskarbi's isn't explicit.\nYou use self when:\n\nDefining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called.\nReferencing a class or instance attribute from inside an instance m... | [
46,
17,
4,
3
] | [] | [] | [
"python",
"self"
] | stackoverflow_0007721920_python_self.txt |
Q:
Postgres inheritance with SQLAlchemy
I have one question about make PostgreSQL table inheritance using SQLAlchemy.
I have this two tables:
CREATE TABLE his
(
idg integer,
idfk integer,
idh integer NOT NULL defautl nextval('his_seq'),
"type" character varying,
CONSTRAINT __his_pkey PRIMARY KEY (idh)
);
C... | Postgres inheritance with SQLAlchemy | I have one question about make PostgreSQL table inheritance using SQLAlchemy.
I have this two tables:
CREATE TABLE his
(
idg integer,
idfk integer,
idh integer NOT NULL defautl nextval('his_seq'),
"type" character varying,
CONSTRAINT __his_pkey PRIMARY KEY (idh)
);
CREATE TABLE data
(
"text" character vary... | [
"SQLAlchemy tries to be as portable as possible so it doesn't support many Postgres-specific features. Here is an answer given from SA guy to someone with similar problem:\nhttp://www.mail-archive.com/sqlalchemy@googlegroups.com/msg17443.html\n"
] | [
2
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0007169119_postgresql_python_sqlalchemy.txt |
Q:
How to split a file into dictionary Key/Value?
Basically I want to create a text file (well a few) with key/value pairs that I can then input into Python to create a dictionary with.
Then I'm going to call the key and use the resulting value in my equations.
Here's what I want my dictionary to look like when input... | How to split a file into dictionary Key/Value? | Basically I want to create a text file (well a few) with key/value pairs that I can then input into Python to create a dictionary with.
Then I'm going to call the key and use the resulting value in my equations.
Here's what I want my dictionary to look like when inputted into Python:
usD = {'TWENTYDOLLAR': 2000, 'TENDO... | [
"This problem is likely very well suited for json, pickle or any other serialization technique. However, if you want to preserve your input as a file consisting of key/value pairs, you could do the following.\nFile contents (with a delimiter of your choosing, in this case \"=\", but could be \",\", \"\\t\", \" \", ... | [
2,
0
] | [
"If you really have to read it from a txt file and you are free to decide the format then use Python itself as a format to keep it simple.\nHere's how your input file would look like -\nusD = {'TWENTYDOLLAR': 2000, \n 'TENDOLLAR': 1000, \n 'FIVEDOLLAR': 500, \n 'DOLLAR': 100, \n 'QUART... | [
-1
] | [
"dictionary",
"python"
] | stackoverflow_0007721597_dictionary_python.txt |
Q:
QRect Width and Height in pixels?
In a PyQt4 Gui, I require the careful placement of multiple QPainter Pixmaps.
When specifying the coordinates and height and width of the new Pixmaps, I require that all units be in pixels.
(Otherwise, my Gui would be ruined on a screen of a different resolution to my own).
When p... | QRect Width and Height in pixels? | In a PyQt4 Gui, I require the careful placement of multiple QPainter Pixmaps.
When specifying the coordinates and height and width of the new Pixmaps, I require that all units be in pixels.
(Otherwise, my Gui would be ruined on a screen of a different resolution to my own).
When placing the Pixmap, I use DrawPixmap( QR... | [
"In the QPainter class reference, you can find different overloading of the drawPixmap method. Reading the documentation tells that QPainter::drawPixamp(QRect, QPixmap) do exactly what you want. It might be a specific issue with pyqt where the format of the QRect is recognized more as a QRectF. You can also use the... | [
0
] | [] | [] | [
"pixel",
"pyqt4",
"python",
"qpainter",
"qt"
] | stackoverflow_0007724544_pixel_pyqt4_python_qpainter_qt.txt |
Q:
How to query Model.KeyProperty == None in Datastore Plus(NDB)
Suppose a NDB(version 0.7 & 0.8) model with key which can be None:
class Test(model.Model):
k = model.KeyProperty()
value = model.IntegerProperty()
count = Test.query(Test.k == None).count() # error
#count = Test.query(Test.k != None).count()... | How to query Model.KeyProperty == None in Datastore Plus(NDB) | Suppose a NDB(version 0.7 & 0.8) model with key which can be None:
class Test(model.Model):
k = model.KeyProperty()
value = model.IntegerProperty()
count = Test.query(Test.k == None).count() # error
#count = Test.query(Test.k != None).count() # error also
Only filtering key with None throws error.
File "/Ap... | [
"This looks like a bug in NDB. Can you file one on the issue tracker?\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007724252_google_app_engine_google_cloud_datastore_python.txt |
Q:
Set multiplicity for user defined classes
I want to use sets on some classes I've made. I want those sets to restrict the multiplicity of my objects of that class. However I have a problem. Consider this toy example:
class Thing(object):
def __init__(self, value):
self.value = value
def __eq__(se... | Set multiplicity for user defined classes | I want to use sets on some classes I've made. I want those sets to restrict the multiplicity of my objects of that class. However I have a problem. Consider this toy example:
class Thing(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.... | [
"You need to define the __hash__ method of your class to return a hashcode based on value. \nIn other words, you need to make your class hashable.\nclass Thing(object):\n\n def __init__(self, value):\n self.value = value\n\n def __eq__(self, other):\n return self.value == other.value\n\n def ... | [
9
] | [] | [] | [
"python"
] | stackoverflow_0007724737_python.txt |
Q:
Clustering with scipy - clusters via distance matrix, how to get back the original objects
I can't seam to find any simple enough tutorials or descriptions on clustering in scipy, so I'll try to explain my problem:
I try to cluster documents (hierarchical agglomerative clustering) , and have created a vector for e... | Clustering with scipy - clusters via distance matrix, how to get back the original objects | I can't seam to find any simple enough tutorials or descriptions on clustering in scipy, so I'll try to explain my problem:
I try to cluster documents (hierarchical agglomerative clustering) , and have created a vector for each document and produced a symmetric distance matrix. The vector_list contains (really long) ve... | [
"First off, you don't need to go through the entire process with cdist and linkage if you use fclusterdata instead of fcluster; that function you can feed an (n_documents, n_features) array of term counts, tf-idf values, or whatever your features are.\nThe output from fclusterdata is the same as that of fcluster: a... | [
3
] | [] | [] | [
"cluster_analysis",
"python",
"scipy"
] | stackoverflow_0007724635_cluster_analysis_python_scipy.txt |
Q:
how to convert regular numpy array to record array?
I read in a sequence of numbers with
np.array(f.read().split(),dtype=np.float64)
Then I convert this to a 2-D array using np.reshape().
After this, how do to convert arr to a record array? I've tried (something like) the following:
filename = 'unstructured-file... | how to convert regular numpy array to record array? | I read in a sequence of numbers with
np.array(f.read().split(),dtype=np.float64)
Then I convert this to a 2-D array using np.reshape().
After this, how do to convert arr to a record array? I've tried (something like) the following:
filename = 'unstructured-file.txt'
nfields = 3
names = ('r','g','b')
with open(filenam... | [
"To convert a plain numpy array to a structured array, use view:\nimport numpy as np\n\nfilename = 'unstructured-file.txt'\nnfields = 3\nnames = ('r','g','b')\nwith open(filename,'r') as f:\n arr = np.array(f.read().split(),dtype=np.float64)\n arr = arr.reshape(-1,nfields)\n out = arr.view(dtype=zip(names,... | [
5
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007724711_numpy_python.txt |
Q:
How are global objects handled in threading?
I would like to create a Pyramid app with an orm which I am writing (currently in deep alpha status). I want to plug the orm into the app sanely and thus I want to know how global objects are handled in multithreading.
In the file:
https://www.megiforge.pl/p/elephantopl... | How are global objects handled in threading? | I would like to create a Pyramid app with an orm which I am writing (currently in deep alpha status). I want to plug the orm into the app sanely and thus I want to know how global objects are handled in multithreading.
In the file:
https://www.megiforge.pl/p/elephantoplasty/source/tree/0.0.1/src/eplasty/ctx.py
you can ... | [
"Global variables are shared between all threads, so if you run those functions the threads will conflict with each other in unpredictable ways.\nTo do what you want you can use thread local data, using threading.local. You need to remove the global definition of ctx and then create the following function.\ndef get... | [
2
] | [] | [] | [
"global_variables",
"multithreading",
"orm",
"pyramid",
"python"
] | stackoverflow_0007723306_global_variables_multithreading_orm_pyramid_python.txt |
Q:
Use a class in the context of a different module
I want to modify some classes in the standard library to use a different set of globals the ones that other classes in that module use.
Example
This example is an example only:
# module_a.py
my_global = []
class A:
def __init__(self):
my_global.append(... | Use a class in the context of a different module | I want to modify some classes in the standard library to use a different set of globals the ones that other classes in that module use.
Example
This example is an example only:
# module_a.py
my_global = []
class A:
def __init__(self):
my_global.append(self)
class B:
def __init__(self):
my_glo... | [
"You can't change the globals without affecting all other users of the module, but what you sort of can do is create a private copy of the whole module.\nI trust you are familiar with sys.modules, and that if you remove a module from there, Python forgets it was imported, but old objects referencing it will continu... | [
5,
1,
1,
0,
0
] | [
"IMHO it is not possible to override global variables...\n",
"Globals are rarely a good idea.\nImplicit variables are rarely a good idea.\nAn implicitly-used global is easy to indict as also \"rarely good\".\nAdditionally, you don't want A.__init__() doing anything \"class-level\" like updating some mysterious c... | [
-2,
-4
] | [
"global",
"module",
"namespaces",
"python",
"python_3.x"
] | stackoverflow_0007495886_global_module_namespaces_python_python_3.x.txt |
Q:
Selenium, CSS, and Python: not being able to view default text in a textbox
I have a text field, which contains the default text 'abc'. When I write something inside this field or the cursor is inside this field then the default text disappears. The underlying HTML tag for this field is:
<div id="InputDefault" cla... | Selenium, CSS, and Python: not being able to view default text in a textbox | I have a text field, which contains the default text 'abc'. When I write something inside this field or the cursor is inside this field then the default text disappears. The underlying HTML tag for this field is:
<div id="InputDefault" class="defaultText" style="visibility: visible;">abc</div>
Now, manually everything... | [
"Use selenium.is_visible(locator). If it doesn't work then use selenium.is_text_present(value) or if (Expectedvalue == selobj.get_value(parameter)).\nIf it still doesn't work, refresh the page and try the above.\n"
] | [
-1
] | [] | [] | [
"css",
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0007722484_css_python_selenium_selenium_rc.txt |
Q:
Python - Using regex to find multiple matches and print them out
I need to find content of forms from HTML source file, I did some searching and found very good method to do that, but the problem is that it prints out only first found, how can I loop through it and output all form contents, not just first one?
lin... | Python - Using regex to find multiple matches and print them out | I need to find content of forms from HTML source file, I did some searching and found very good method to do that, but the problem is that it prints out only first found, how can I loop through it and output all form contents, not just first one?
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> mo... | [
"Do not use regular expressions to parse HTML.\nBut if you ever need to find all regexp matches in a string, use the findall function.\nimport re\nline = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'\nmatches = re.findall('<form>(.*?)</form>', line, re.DOTALL)\nprint(matches)\n\n# Outp... | [
103,
37,
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007724993_python_regex.txt |
Q:
UnicodeDecodeError when using QFileDialog getOpenFileName()
The code is like
dlg = PyQt4.QtGui.QFileDialog(self)
self.filename = dlg.getOpenFileName()
When the Dialog pops up, I click on a file having Chinese characters in its path. Then I get the UnicodeDecodeError.
I tried the toUtf8() function, but still ge... | UnicodeDecodeError when using QFileDialog getOpenFileName() | The code is like
dlg = PyQt4.QtGui.QFileDialog(self)
self.filename = dlg.getOpenFileName()
When the Dialog pops up, I click on a file having Chinese characters in its path. Then I get the UnicodeDecodeError.
I tried the toUtf8() function, but still get nowhere.
Unicode thing is always so difficult to understand. An... | [
"The UnicodeDecodeError thing probably happens after the code you posted. Anyway, try\nself.filename = PyQt4.QtGui.QFileDialog.getOpenFileName().decode('utf-8')\n\nBy the way, getOpenFilename() is a static method of QFileDialog, which means you don't have to create an instance to call it.\n"
] | [
2
] | [] | [] | [
"error_handling",
"pyqt4",
"python",
"unicode"
] | stackoverflow_0007726168_error_handling_pyqt4_python_unicode.txt |
Q:
show all information in the main process console
I got a program (written in python) who starts several processes.
Now I want that information (errors, warnings, prints etc.) from all started processes are displayed in the main process console.
How can I do this?
A:
You'll need to use pipes with the subprocess m... | show all information in the main process console | I got a program (written in python) who starts several processes.
Now I want that information (errors, warnings, prints etc.) from all started processes are displayed in the main process console.
How can I do this?
| [
"You'll need to use pipes with the subprocess module see\nhttp://docs.python.org/library/subprocess.html#replacing-shell-pipeline\n"
] | [
1
] | [] | [] | [
"console",
"process",
"python"
] | stackoverflow_0007726480_console_process_python.txt |
Q:
Fast way to convert array to tuple/list in python?
It seems like the time it takes to convert an array to a tuple scales linearly with the the length of the array. Is there a way to do this more efficient? I need to insert arrays with 5e+6 elements into a mysql database, but MySQLdb only seems to accept tuples or ... | Fast way to convert array to tuple/list in python? | It seems like the time it takes to convert an array to a tuple scales linearly with the the length of the array. Is there a way to do this more efficient? I need to insert arrays with 5e+6 elements into a mysql database, but MySQLdb only seems to accept tuples or lists as input to insertmany.
| [
"MySQLdb uses re and string interpolation to join parameterized SQL with arguments before passing the query to the server as a string. Clearly this is not the way to go -- not only are you converting the array to tuples, but also the tuples into strings.\nIn contrast oursql sends SQL queries to the MySQL server sep... | [
4
] | [] | [] | [
"mysql_python",
"numpy",
"python"
] | stackoverflow_0007726526_mysql_python_numpy_python.txt |
Q:
Python datetime.strptime() Eating lots of CPU Time
I have some log parsing code that needs to turn a timestamp into a datetime object. I am using datetime.strptime but this function is using a lot of cputime according to cProfile's cumtime column. The timestamps are in the format of 01/Nov/2010:07:49:33.
The curr... | Python datetime.strptime() Eating lots of CPU Time | I have some log parsing code that needs to turn a timestamp into a datetime object. I am using datetime.strptime but this function is using a lot of cputime according to cProfile's cumtime column. The timestamps are in the format of 01/Nov/2010:07:49:33.
The current function is:
new_entry['time'] = datetime.strptime(
... | [
"If those are fixed width formats then there is no need to parse the line - you can use slicing and a dictionary lookup to get the fields directly.\nmonth_abbreviations = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4,\n 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,\n 'Sep': 9, 'Oct':... | [
16,
3,
2,
2
] | [] | [] | [
"datetime",
"optimization",
"python"
] | stackoverflow_0004070900_datetime_optimization_python.txt |
Q:
Is Google App Engine compatible with Python translate()?
In the following I use translate() to eliminate punctuation from a string. I've been having a lot of problems with translate because it does not work with unicode. But now I noticed that the script works well in the development server but raises an error in ... | Is Google App Engine compatible with Python translate()? | In the following I use translate() to eliminate punctuation from a string. I've been having a lot of problems with translate because it does not work with unicode. But now I noticed that the script works well in the development server but raises an error in the production server.
The request is sent by chrome extension... | [
"Google App Engine runs Python 2.5.2. str.translate() requires a 256-character string as the first argument; None has only been an allowed value since Python 2.6.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007727000_google_app_engine_python.txt |
Q:
If statement looks to not extend to other templates
I have a problem with one of my if statements on my django template.
Currently I have this on my base.html which extends to other templates:
base.html
{% if user.is_superuser %}
<h2>Admin Menu</h2>
<table>
<tr>
{% if approved %}
... | If statement looks to not extend to other templates | I have a problem with one of my if statements on my django template.
Currently I have this on my base.html which extends to other templates:
base.html
{% if user.is_superuser %}
<h2>Admin Menu</h2>
<table>
<tr>
{% if approved %}
<td><a href="{% url rates-disable_rates %}" class="mbbu... | [
"It seems you're not providing the approved variable in your view, so it evaluates to '', which is false.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007727040_django_django_models_django_templates_django_views_python.txt |
Q:
searching for language recognition library in Python or web service
Is there any tool that provides language recognition functionality?
Like if I input a sentence of English, it will suggest that the string may be English.
I think I need one of the following stuff.
Python language recognition library.
Web servic... | searching for language recognition library in Python or web service | Is there any tool that provides language recognition functionality?
Like if I input a sentence of English, it will suggest that the string may be English.
I think I need one of the following stuff.
Python language recognition library.
Web service that provides such functionality.
Anyone can help?
| [
"I have used the GuessLanguage module pretty extensively. It detects 100+ languages and works really well for LONG pieces of text. English is very good. Other languages I am not sure. If you want to process short sentences at a time or tweets it is pretty bad as it was designed for doing detection on full articles.... | [
2,
1
] | [] | [] | [
"nlp",
"python",
"web_services"
] | stackoverflow_0007726957_nlp_python_web_services.txt |
Q:
make a increaseKey for list in python
assuming a list A with strings, and an offset x.
A=["a","b","c"]
x is int
len(A) is int
I need to serialize and return json J such that for each
n<len(A)
J[x+n]=a[n]
I currently use dict assigning, but It feels like their is something more efficient
instead of going over the e... | make a increaseKey for list in python | assuming a list A with strings, and an offset x.
A=["a","b","c"]
x is int
len(A) is int
I need to serialize and return json J such that for each
n<len(A)
J[x+n]=a[n]
I currently use dict assigning, but It feels like their is something more efficient
instead of going over the entire list.
answer needs to be O(1) or a co... | [
"If you really don't want to construct a dict from your list, you can use a hack that depends on implementation details of the json module:\nclass OffsetDict(dict):\n def __init__(self, lst, offset):\n self.lst = lst\n self.offset = offset\n def __nonzero__(self):\n return bool(self.lst)\... | [
2,
1,
0,
0
] | [] | [] | [
"adt",
"dictionary",
"python"
] | stackoverflow_0007726729_adt_dictionary_python.txt |
Q:
Nose ignores test with custom decorator
I have some relatively complex integration tests in my Python code. I simplified them greatly with a custom decorator and I'm really happy with the result. Here's a simple example of what my decorator looks like:
def specialTest(fn):
def wrapTest(self):
#do so... | Nose ignores test with custom decorator | I have some relatively complex integration tests in my Python code. I simplified them greatly with a custom decorator and I'm really happy with the result. Here's a simple example of what my decorator looks like:
def specialTest(fn):
def wrapTest(self):
#do some some important stuff
pass
retu... | [
"If I remember correctly, nose loads the test based on their names (functions whose name begins with test_). In the snippet you posted, you do not copy the __name__ attribute of the function in your wrapper function, so the name of the function returned is wrapTest and nose decides it's not a test.\nAn easy way to ... | [
24
] | [] | [] | [
"decorator",
"nose",
"python"
] | stackoverflow_0007727678_decorator_nose_python.txt |
Q:
SQLAlchemy - mapping one class to two tables
I have two implementations of database queue (they use different tables) and want them to use objects of the same class. So, they both look really similar:
class AbstractDBQueue(object):
def __init__(self, tablename):
self.tablename = tablename
self.... | SQLAlchemy - mapping one class to two tables | I have two implementations of database queue (they use different tables) and want them to use objects of the same class. So, they both look really similar:
class AbstractDBQueue(object):
def __init__(self, tablename):
self.tablename = tablename
self.metadata = MetaData()
self.engine = create... | [
"I think your problem relates to the tablename variable. It's a class variable which gets defined when you create the class, and then does not change. So, it will be the same for both of your instances, when they access it with self.tablename. To fix this, move it inside the init function, and make it a self.tablen... | [
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0007727478_mysql_python_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.