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:
Storing unpicklabe pygame.Surface objects in external files
So I've got a problem - I'm writing a game prototype in Python, using Pygame, and I want to save my games. All of the game-related data is in three instances of certain classes, and I want to save these three instances to a file. However, I've tried pic... | Storing unpicklabe pygame.Surface objects in external files | So I've got a problem - I'm writing a game prototype in Python, using Pygame, and I want to save my games. All of the game-related data is in three instances of certain classes, and I want to save these three instances to a file. However, I've tried pickling these instances, and it doesn't work. Instead, I get "Type... | [
"The basic point of pickling is that you should be able to serialise the object somehow. An SDL surface is an in memory object holding a lot of run time state. Trying to serialise it is not totally sensible. \nWhat you should do is to decouple the state of your game from the rendering components so that you can ser... | [
5,
2
] | [] | [] | [
"pickle",
"pygame",
"python",
"serialization"
] | stackoverflow_0005145664_pickle_pygame_python_serialization.txt |
Q:
PYMongo: Keep returning _id in every record after quering, How can I exclude this record?
I am having problem when I do a query to mongodb using pymongo.
I do not know how to avoid getting the _id for each record.
I am doing something like this,
result = db.meta.find(filters, [
'... | PYMongo: Keep returning _id in every record after quering, How can I exclude this record? | I am having problem when I do a query to mongodb using pymongo.
I do not know how to avoid getting the _id for each record.
I am doing something like this,
result = db.meta.find(filters, [
'model',
'fields.parent',
'field... | [
"You can exclude the id object this way:\ndb.meta.find({}, {\"_id\" : 0})\n\n",
"Does make any sense. The object id is core part of each document. Convert the BSON/JSON document to a native datastructure (depending on your implementation language) and remove _id on this level. Apart from that it does not make muc... | [
3,
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0004937817_mongodb_pymongo_python.txt |
Q:
In Python how do you put a program inside a program
I would like to take all my simple math programs for basic financial ratios and compile it into one program where I could print the list of the programs and allow the user to select the one in which he or she is wishing to run. How would this be accomplished?
Wh... | In Python how do you put a program inside a program | I would like to take all my simple math programs for basic financial ratios and compile it into one program where I could print the list of the programs and allow the user to select the one in which he or she is wishing to run. How would this be accomplished?
What I have tried so far has ended up in just running throu... | [
"I think I understand what you are looking for, but please comment if I'm not understanding you correctly.\nOne of the easiest ways to accomplish what you are looking for is to just use the python prompt itself. If you put all your programs in one file (making sure that there are no overlapping names) then what yo... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005146271_python.txt |
Q:
simple python program help!
This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
... | simple python program help! | This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Any ideas on why it's doing this?... | [
"You need to turn temp into an int:\n...\n\ntry:\n temp = int(temp)\nexcept TypeError:\n # Handle invalid integer\n print(\"%s is not a valid integer.\" % temp)\n sys.exit(1)\n\n...\n\n",
"In Python 3, the input() function always returns a string (this is different from Python 2, and could be the sour... | [
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005146487_python.txt |
Q:
App Engine: Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore
I'm currently using the blobstore to generate thumbnails for images, however, I like to store the dimensions of the thumbnail in the img tag, as it is good practise and helps speed up rendering and makes a... | App Engine: Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore | I'm currently using the blobstore to generate thumbnails for images, however, I like to store the dimensions of the thumbnail in the img tag, as it is good practise and helps speed up rendering and makes a partially loaded page look a bit nicer.
How would I calculate the dimensions of a thumbnail generated by the blobs... | [
"I see the problem. The reason is that C's rint is being used to calculate\nthe dimensions. Python does not have an equivalent rint implementation\nas it was taken out by Rossum in 1.6:\nhttp://markmail.org/message/4di24iqm7zhc4rwc\nYour only recourse right now is to implement your own rint in python.\nrint by defa... | [
4,
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"python",
"thumbnails"
] | stackoverflow_0005079471_blobstore_google_app_engine_python_thumbnails.txt |
Q:
Remove/Replace Error from Tuple in python
I have string of tuples
LL = [ ("text1",2,3,N/A), ("text2",N/A,5,6),("text3",N/A,5,N/A) ]
I need
LL = [ ("text1",2,3,-1), ("text2",-1,5,6), ("text2",-1,5,-1) ]
So simply remove N/A replace with -1. Do I need to read all lines?
Data download shows N/A, its not a varia... | Remove/Replace Error from Tuple in python | I have string of tuples
LL = [ ("text1",2,3,N/A), ("text2",N/A,5,6),("text3",N/A,5,N/A) ]
I need
LL = [ ("text1",2,3,-1), ("text2",-1,5,6), ("text2",-1,5,-1) ]
So simply remove N/A replace with -1. Do I need to read all lines?
Data download shows N/A, its not a variable.
LL is string
Using ("text2",N/A,5,6).
Run... | [
"This list comprehension will loop through each item in LL and replace the string \"N/A\" with -1.\nLL = [ (\"text1\",2,3,\"N/A\"), (\"text2\",\"N/A\",5,6),(\"text3\",\"N/A\",5,\"N/A\") ]\nLL = [tuple(x if x != \"N/A\" else -1 for x in i) for i in LL]\nprint LL\n# [('text1', 2, 3, -1), ('text2', -1, 5, 6), ('text3'... | [
1,
1,
1,
0,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0005145939_python_tuples.txt |
Q:
Python/Scipy 2D Interpolation (Non-uniform Data)
This is a follow-up question to my previous post: Python/Scipy Interpolation (map_coordinates)
Let's say I want to interpolate over a 2d rectangular area. My variable 'z' contains the data as shown below. Each column is at a constant value, however, each row of th... | Python/Scipy 2D Interpolation (Non-uniform Data) | This is a follow-up question to my previous post: Python/Scipy Interpolation (map_coordinates)
Let's say I want to interpolate over a 2d rectangular area. My variable 'z' contains the data as shown below. Each column is at a constant value, however, each row of the array may be at a different value as shown in the co... | [
"Looks like you got it. \nIn your upper code example and in your previous (linked) question you have structured data. Which can be interpolated using RectBivariateSpline or interp2d. This means you have data that can be described on a grid (all points on the grid have a known value). The grid doesn't necessaril... | [
18
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0005146025_interpolation_numpy_python_scipy.txt |
Q:
Renaming objects with Wing IDE
I am just transitioning from Eclipse to Wing IDE for my Python code. In Eclipse I had an option to "rename" objects. I could take any object defined in my code, it could be a variable or a function or a method or whatever, and I could rename it automatically in all the files that ref... | Renaming objects with Wing IDE | I am just transitioning from Eclipse to Wing IDE for my Python code. In Eclipse I had an option to "rename" objects. I could take any object defined in my code, it could be a variable or a function or a method or whatever, and I could rename it automatically in all the files that referenced it.
Is there a similar featu... | [
"The refactoruing is a feature asked for since 2002, but even then, the answer was already:\n\"search and replace\"\n\nBTW, one somewhat related thing we're doing is adding better global\n replace. [...] This isn't informed by source analysis but it's still a useful tool for some kinds of refactoring (like renamin... | [
4,
0
] | [] | [] | [
"eclipse",
"ide",
"python"
] | stackoverflow_0001292931_eclipse_ide_python.txt |
Q:
Prefer one class in libsvm (python)
I just started playing a bit with libsvm in python and got some simple classification to work.
The problem is that I'm constructing a face detection system, and I want a very low false rejection rate. The svm on the other hand seems to optimize for equal false rejection and fals... | Prefer one class in libsvm (python) | I just started playing a bit with libsvm in python and got some simple classification to work.
The problem is that I'm constructing a face detection system, and I want a very low false rejection rate. The svm on the other hand seems to optimize for equal false rejection and false acceptance. What options do I have here... | [
"SVMs are not usually thought of as a probabilistic model, but a maximally-discriminant model. Thus I have a hard time formulating your question in the context of what I know of SVMs.\nIn addition, the Python bindings that come with libSVM are not terribly performant and don't expose all the options of libSVM.\nTha... | [
2,
1
] | [] | [] | [
"classification",
"libsvm",
"python",
"svm"
] | stackoverflow_0004756937_classification_libsvm_python_svm.txt |
Q:
Objective-C/cocoa's equivalent to Python's os.path.split() to get directory name and file name
When I have a path, I can use os.path.split() in Python to get directory name, and file name.
>>> x = '/a/b/c/hello.txt'
>>> import os.path
>>> os.path.split(x)
('/a/b/c', 'hello.txt')
What's the equivalent function in ... | Objective-C/cocoa's equivalent to Python's os.path.split() to get directory name and file name | When I have a path, I can use os.path.split() in Python to get directory name, and file name.
>>> x = '/a/b/c/hello.txt'
>>> import os.path
>>> os.path.split(x)
('/a/b/c', 'hello.txt')
What's the equivalent function in Objective-C/cocoa?
| [
"NSString *a = @\"/a/b/c/hello.txt\";\nNSArray *path = [a pathComponents];\nNSArray *startOfPath = [path subarrayWithRange:NSMakeRange(0, [path count]-2)];\n[NSString pathWithComponents:startOfPath]; // /a/b/c\n[a lastPathComponent]; // hello.txt\n\n",
"There is an easier way (well, than messing with subarrays); ... | [
4,
3,
0
] | [] | [] | [
"objective_c",
"path",
"python"
] | stackoverflow_0005138677_objective_c_path_python.txt |
Q:
Why is my Python version different in a shell vs executing from a file
(In windows)
I have both Python 2.6 and 2.4 installed on a machine (for testing purposes). When I open a cmd and type python I get:
C:\>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help",... | Why is my Python version different in a shell vs executing from a file | (In windows)
I have both Python 2.6 and 2.4 installed on a machine (for testing purposes). When I open a cmd and type python I get:
C:\>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
However, when ... | [
"You need to review your file associations. In Windows Explorer choose Tools > Folder Options. On the File Types tab go find the .py extension and set it to the correct interpreter.\n",
"The list is maintained in the registry, but you can use the ftype program to access it, e.g.\nftype | find \"Python\"\n\nOr m... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005148133_python.txt |
Q:
Problem subclassing random.Random (python /CPython 2.6)
I have tried this code snippet in CPython 2.6 (original python implementation):
from random import Random, random
class Uniform(Random, object):
def __init__(self, min, max):
self._min =min
self._max =max
def randint(self):
... | Problem subclassing random.Random (python /CPython 2.6) | I have tried this code snippet in CPython 2.6 (original python implementation):
from random import Random, random
class Uniform(Random, object):
def __init__(self, min, max):
self._min =min
self._max =max
def randint(self):
return super(Uniform, self).randint (self._min, self._max)
... | [
"You need to call Random.__init__(self, seed) at the beginning of your constructor (the seed argument is optional):\ndef __init__(self, min, max):\n Random.__init__(self) # Use the default seed.\n self._min =min\n self._max =max\n\nAlso, I don't quite understand why you are explicitly extending object a... | [
0
] | [] | [] | [
"built_in",
"python",
"random",
"subclass"
] | stackoverflow_0005148198_built_in_python_random_subclass.txt |
Q:
Autogrowing list in Python?
I need a list-like object that will "autogrow" whenever a slot number greater or equal to its length is accessed, filling up all the newly created slots with some pre-specified default value. E.g.:
# hypothetical DefaultList class
x = DefaultList(list('abc'), default='*')
x[6] = 'g'
pr... | Autogrowing list in Python? | I need a list-like object that will "autogrow" whenever a slot number greater or equal to its length is accessed, filling up all the newly created slots with some pre-specified default value. E.g.:
# hypothetical DefaultList class
x = DefaultList(list('abc'), default='*')
x[6] = 'g'
print x[2], x[4], x[6], x[8] # sho... | [
"class DefaultList(list):\n def __init__(self,*args,**kwargs):\n list.__init__(self,*args)\n self.default=kwargs.get('default',None)\n def __getitem__(self,key):\n # retrieving an item does not expand the list\n if isinstance(key,slice):\n return [self[elt] for elt in ra... | [
3,
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005146473_list_python.txt |
Q:
Using Google App Engine for Website Load Testing
Azure, Amazon and other instance based cloud providers can be used to carry out website load tests (by spinning up numerous instances running programs that send requests to a set of URLs) and I was wondering if I would be able to do this with Google App Engine.
So f... | Using Google App Engine for Website Load Testing | Azure, Amazon and other instance based cloud providers can be used to carry out website load tests (by spinning up numerous instances running programs that send requests to a set of URLs) and I was wondering if I would be able to do this with Google App Engine.
So far, however it seems this is not the case. The only im... | [
"The taskqueue API allows 100 task invocations per second per queue with the following max active queues quota:\nFree: 10 active queues (not including the default queue)\nBilling: 100 active queues (not including the default queue)\nWith a single UrlFetch per task, multiplying [max number of active queues] * [max... | [
4,
2
] | [] | [] | [
"google_app_engine",
"python",
"stress_testing"
] | stackoverflow_0005140289_google_app_engine_python_stress_testing.txt |
Q:
How can I access directory-local variables in my major mode hooks?
I have defined a .dir-locals.el file with the following content:
((python-mode . ((cr/virtualenv-name . "saas"))))
In my .emacs I have the following function to retrieve this value and provide a virtualenv path:
(defun cr/virtualenv ()
(cond (cr... | How can I access directory-local variables in my major mode hooks? | I have defined a .dir-locals.el file with the following content:
((python-mode . ((cr/virtualenv-name . "saas"))))
In my .emacs I have the following function to retrieve this value and provide a virtualenv path:
(defun cr/virtualenv ()
(cond (cr/virtualenv-name (format "%s/%s" virtualenv-base cr/virtualenv-name))
... | [
"This happens because normal-mode calls (set-auto-mode) and (hack-local-variables) in that order.\nHowever hack-local-variables-hook is run after the local variables have been processed, which enables some solutions:\n\nThe first is to make Emacs run a new \"local variables hook\" for each major mode:\n(add-hook 'h... | [
19
] | [] | [] | [
"dot_emacs",
"emacs",
"python",
"python_mode"
] | stackoverflow_0005147060_dot_emacs_emacs_python_python_mode.txt |
Q:
Encrypt in C and decrypt in Python using AES
I was wondering if there is any straightforward way to encrypt text or string in C so it can easily be decrypted in python using shared key encryption (AES) ?
A:
I would recommend calling GPG, the Gnu Privacy Gaurd in C via GPGME. You can read the data with Python usi... | Encrypt in C and decrypt in Python using AES | I was wondering if there is any straightforward way to encrypt text or string in C so it can easily be decrypted in python using shared key encryption (AES) ?
| [
"I would recommend calling GPG, the Gnu Privacy Gaurd in C via GPGME. You can read the data with Python using python-gnupg. This is the most secure option since you are relying on an open source, peer reviewed, and widely used cryptography implementation (GPG). There are many, many security pitfalls when implementi... | [
2,
1
] | [] | [] | [
"aes",
"c",
"encryption",
"python"
] | stackoverflow_0005148210_aes_c_encryption_python.txt |
Q:
python list and sublist
I have to check if list1 is contained in list2. It also should check if it appears in that order in the list as well. If it's true, it should return true and false if it doesn't.
def check(lst1, lst2):
for x in lst1:
for y in lst2:
xx = lst1.sort()
yy = lst2
if x... | python list and sublist | I have to check if list1 is contained in list2. It also should check if it appears in that order in the list as well. If it's true, it should return true and false if it doesn't.
def check(lst1, lst2):
for x in lst1:
for y in lst2:
xx = lst1.sort()
yy = lst2
if xx != yy:
return F... | [
"I thought the problem was begging to be solved recursively, so I did:\ndef check(needle, haystack):\n if not needle:\n return True\n try:\n offset = haystack.index(needle[0])\n return check(needle[1:], haystack[offset+1:])\n except:\n return False\n\nEdit:\nBrief explanation: \nFirst we check if t... | [
3,
1,
0
] | [] | [] | [
"list",
"python",
"sublist"
] | stackoverflow_0005148462_list_python_sublist.txt |
Q:
how to convert value of column defined as character into integer in python
I had a postgresql query where I need to take column defined as character from table and then pass this value to the function where it only accepts integer.So in this case, how can i solve the problem??Can anyone help??
A:
Don't forget t... | how to convert value of column defined as character into integer in python | I had a postgresql query where I need to take column defined as character from table and then pass this value to the function where it only accepts integer.So in this case, how can i solve the problem??Can anyone help??
| [
"Don't forget to use try/except statements in conversion to avoid surprises like this:\nPython 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \n[GCC 4.4.5] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> a='a'\n>>> int(a)\nTraceback (most recent call last):\n File \"<stdin... | [
1,
0
] | [] | [] | [
"casting",
"python"
] | stackoverflow_0005148790_casting_python.txt |
Q:
How to fetch values in quotes using python
I have an XML file and I parsed in the data of the xml file to get a list as below:
humidity data="Humidity: 73%"
icon data="/ig/images/weather/cloudy.gif"
wind_condition data="Wind: N at 5 mph"
I want to write a python code where I can capture only the values in quotes a... | How to fetch values in quotes using python | I have an XML file and I parsed in the data of the xml file to get a list as below:
humidity data="Humidity: 73%"
icon data="/ig/images/weather/cloudy.gif"
wind_condition data="Wind: N at 5 mph"
I want to write a python code where I can capture only the values in quotes and put it in a list.
| [
"The following code shows how to parse XML using a proper XML parser. The xml stream is reconstructed from the partial information that you have supplied.\nxml_strg = \"\"\"<?xml version=\"1.0\"?>\n<xml_api_reply version=\"1\">\n <weather module_id=\"0\" tab_id=\"0\" mobile_row=\"0\" mobile_zipped=\"1\" row=\"0\... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005148019_python.txt |
Q:
Python question on parse routines with dicts, while loops, and assignments
I have some code from a much-maligned Python resource, if you ask SO, but I am trying to divine Python’s parse routine from it, regardless its didactic merits.
def princess_lives_here():
#<some messages and conditionals to keep you goin... | Python question on parse routines with dicts, while loops, and assignments | I have some code from a much-maligned Python resource, if you ask SO, but I am trying to divine Python’s parse routine from it, regardless its didactic merits.
def princess_lives_here():
#<some messages and conditionals to keep you going in the text-based game>
#<one of the conditionals end in a `return 'death'... | [
"After looking at the original code will analyze it for you:\n1) The program enters at the point:\nrunner(ROOMS, 'princess_lives_here')\n\n2) runner function gets a map (a list of available rooms where we can go) and a start point at the map. So, the previous call uses the map defined in the ROOMS dictionary and se... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005148615_python.txt |
Q:
Python/Django plugin for Dreamweaver
Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.
A:
I remember looking for a plugin too, but came across this stumbling block:
Designers are assumed to be comfortable with HTML code. The template system isn’t ... | Python/Django plugin for Dreamweaver | Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.
| [
"I remember looking for a plugin too, but came across this stumbling block:\n\nDesigners are assumed to be comfortable with HTML code. The template system isn’t designed so that templates necessarily are displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of a limitation and wouldn’t allow t... | [
6,
3,
2,
0
] | [] | [] | [
"django",
"dreamweaver",
"python"
] | stackoverflow_0000723652_django_dreamweaver_python.txt |
Q:
python: csv.reader & unicode (and postgres)
I have a CSV with a unicode character (the spanish ñ character). Trying to import this into a utf8-encoded postgres table. The following code:
reader = csv.reader(open(filename, 'r'), delimiter=',')
for row in reader:
values = [None if x == '' else x for x in row]
... | python: csv.reader & unicode (and postgres) | I have a CSV with a unicode character (the spanish ñ character). Trying to import this into a utf8-encoded postgres table. The following code:
reader = csv.reader(open(filename, 'r'), delimiter=',')
for row in reader:
values = [None if x == '' else x for x in row]
query = 'INSERT INTO %s.rosters VALUES(%s)' % ... | [
"Do you know that the CSV file is encoded in UTF-8? If it is, you'd see something like this:\n$ file foo.txt \nfoo.txt: UTF-8 Unicode text\n\nIf it doesn't say UTF-8, then you probably have to decode it with a different codec, such as ISO-8859-1.\n"
] | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0005148575_postgresql_python.txt |
Q:
AJAX & Python: Response text from python script is an object
Edited out silly mistake
I am using AJAX to access a python script, get some TEXT from the python script & display it on my webpage.
My Problem: is that the response text is this "undefined" when it should be this "bbbb"
I am confused as to where I am g... | AJAX & Python: Response text from python script is an object | Edited out silly mistake
I am using AJAX to access a python script, get some TEXT from the python script & display it on my webpage.
My Problem: is that the response text is this "undefined" when it should be this "bbbb"
I am confused as to where I am going wrong? Is it my python script is incorrect (not handling AJAX... | [
"You are getting undefined because you just did the post and didn't wait for the response to come back. Your alert call should be inside the status change, where you have return xmlhttp.responseText; right now. Remember, Javascript functions (except alert ironically) don't block.\n",
"Maybe you should use respo... | [
1,
0,
0
] | [] | [] | [
"ajax",
"cgi",
"python",
"wsgi"
] | stackoverflow_0005148966_ajax_cgi_python_wsgi.txt |
Q:
Python urlib and authentication
I need help authenticating logging into this site using urllib. I am using python 3, but I'm willing to revert to 2.x.
This is what I have sofar (basically from the documentation), it gives not errors, but its not logging in.
file =open("loggedinsource.html",'wb')
# Create an Open... | Python urlib and authentication | I need help authenticating logging into this site using urllib. I am using python 3, but I'm willing to revert to 2.x.
This is what I have sofar (basically from the documentation), it gives not errors, but its not logging in.
file =open("loggedinsource.html",'wb')
# Create an OpenerDirector with support for Basic HTT... | [
"The site you are trying to log into is not using HTTP basic auth; it is using a regular HTML form.\nIf you want to log into something like this, you probably want to look at something like mechanize\n"
] | [
1
] | [] | [] | [
"authentication",
"python",
"urllib"
] | stackoverflow_0005147195_authentication_python_urllib.txt |
Q:
Are there any methods that returns just the decimal after a division? (Python3)
In python 3, are there any methods that would return just the decimal value after a division?
For example, if I divided 4 by 5 in this method, it would return 8.
A:
Use floating-point division. e.g.:
(11.0 / 5) % 1 = 0.20000000000000... | Are there any methods that returns just the decimal after a division? (Python3) | In python 3, are there any methods that would return just the decimal value after a division?
For example, if I divided 4 by 5 in this method, it would return 8.
| [
"Use floating-point division. e.g.:\n(11.0 / 5) % 1 = 0.20000000000000018\n\n(1.0 * 11 / 5) % 1 = 0.20000000000000018\n\n",
"How about this?\n>>> int(((4.0 / 5.0) % 1) * 10)\n8\n\n",
"You can easily calculate it using int, for a generic number a:\nint(10*a)%10\n\nHowever, note that this only works for positive ... | [
2,
1,
0,
0
] | [] | [] | [
"division",
"math",
"python"
] | stackoverflow_0005149178_division_math_python.txt |
Q:
Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?
The destroyed() signal can be trapped for a QObject, but I would like to simply test if the Python object still references a valid C++ Qt object. Is there a method for doing so directly?
A:
If you import the sip module... | Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed? | The destroyed() signal can be trapped for a QObject, but I would like to simply test if the Python object still references a valid C++ Qt object. Is there a method for doing so directly?
| [
"If you import the sip module you can call its .isdeleted function.\nimport sip\nfrom PyQt4.QtCore import QObject\n\nq = QObject()\nsip.isdeleted(q)\nFalse\n\nsip.delete(q)\nq\n<PyQt4.QtCore.QObject object at 0x017CCA98>\n\nq.isdeleted(q)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\... | [
15,
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt"
] | stackoverflow_0005122451_pyqt_pyqt4_python_qt.txt |
Q:
Django URL Config for javascript files
Hey guys - I am having trouble setting up my Django urls file correctly for the following thing!
<script type="text/javascript" src="/javascript/HashMap.js"></script>
What happens is the file is attempted to get found : http://localhost/javascript/HashMap.js but this URL doe... | Django URL Config for javascript files | Hey guys - I am having trouble setting up my Django urls file correctly for the following thing!
<script type="text/javascript" src="/javascript/HashMap.js"></script>
What happens is the file is attempted to get found : http://localhost/javascript/HashMap.js but this URL does not match any within the URL Config and th... | [
"You need to serve your JavaScript as a static file.\nHow you do this in production depends on what Web server you're running with. Django doesn't normally serve up static files.\nFor example, for Apache, you'd put this in your Apache config:\nAlias /javascript/ /usr/local/wsgi/static/javascript/\n\nThen you can p... | [
3,
1,
0
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0005149327_django_javascript_python.txt |
Q:
python minidom parse XML feed with colon in results
I am trying to parse an XML feed that displays NFL schedules, one of the attributes is the game time and it looks like this GameTime="8:30 PM"
Here's a clip of what the XML looks like
<Schedule Season="2010" Timezone="Eastern">
<Game gameId="1" Week="1" GameDat... | python minidom parse XML feed with colon in results | I am trying to parse an XML feed that displays NFL schedules, one of the attributes is the game time and it looks like this GameTime="8:30 PM"
Here's a clip of what the XML looks like
<Schedule Season="2010" Timezone="Eastern">
<Game gameId="1" Week="1" GameDate="2010-09-09" AwayTeam="MIN" HomeTeam="NO" GameTime="8:3... | [
"I tried to reproduce your error, but it printed just fine for me.\nI tried loading your data from a string within the Python module, I tried loading your data from a named file, and I tried loading your data from a file object. They all handled the colon just fine.\nThe only difference now seems to be the way you... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0005148523_python_xml.txt |
Q:
Python Core Library and PEP8
I was trying to understand why Python is said to be a beautiful language. I was directed to the beauty of PEP 8... and it was strange. In fact it says that you can use any convention you want, just be consistent... and suddenly I found some strange things in the core library:
request()... | Python Core Library and PEP8 | I was trying to understand why Python is said to be a beautiful language. I was directed to the beauty of PEP 8... and it was strange. In fact it says that you can use any convention you want, just be consistent... and suddenly I found some strange things in the core library:
request()
getresponse()
set_debuglevel()
en... | [
"PEP 8 recommends using underscores as the default choice, but leaving them out is generally done for one of two reasons:\n\nconsistency with some other API (e.g. the current module, or a standard interface)\nbecause leaving them out doesn't hurt readability (or even improves it)\n\nTo address the specific examples... | [
10,
4,
2
] | [] | [] | [
"pep8",
"python"
] | stackoverflow_0005148707_pep8_python.txt |
Q:
Letter frequency in python
I need to make a program that prints out the frequency of letters in a text
file and compares that frequency with that of another in python.
So far I am able to print the number of times a letter occurs, but the
percentage frequency I get is wrong. I think it is because I need my program... | Letter frequency in python | I need to make a program that prints out the frequency of letters in a text
file and compares that frequency with that of another in python.
So far I am able to print the number of times a letter occurs, but the
percentage frequency I get is wrong. I think it is because I need my program to count only
the number of let... | [
"You could use the translator recipe to drop all characters not in alpha.\nSince doing so makes letters contain nothing but characters from alpha, n is now the correct denominator.\nYou could then use a collections.defaultdict(int) to count the occurrences of the letters:\nimport collections\nimport string\n\ndef t... | [
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005148903_python.txt |
Q:
Good Web hosts that support Ruby and Python?
I love Python and Ruby equally and I simply cannot standardize on one. I love Heroku, but it can get a speck pricey and is totally specific to Rails.
Is there a decently inexpensive host, or many, that adequately supports both Ruby and Python frameworks as well as offer... | Good Web hosts that support Ruby and Python? | I love Python and Ruby equally and I simply cannot standardize on one. I love Heroku, but it can get a speck pricey and is totally specific to Rails.
Is there a decently inexpensive host, or many, that adequately supports both Ruby and Python frameworks as well as offering common LAMPish support?
Yeah... I wanna know i... | [
"Well, if you're going for cheap, you'll need to go with shared hosting. VPS solutions will cost you more or less double what you pay for shared hosting.\nAnyway, for shared hosting, I'll recommend dreamhost.com. They obviously support standard LAMP, and performance is pretty good in my experience.\nFurther more, t... | [
2,
0,
0,
0,
0
] | [] | [] | [
"apache",
"django",
"python",
"ruby",
"ruby_on_rails_3"
] | stackoverflow_0005149127_apache_django_python_ruby_ruby_on_rails_3.txt |
Q:
AppEngine: Can I fetch an internal url?
Does anyone know, if I can fetch an internal AppEngine url from within my AppEngine app?
The official URL Fetch Python API doesn´t cover that.
http://code.google.com/intl/et-EE/appengine/docs/python/urlfetch/overview.html
I tried different possibilities, but as it seems noth... | AppEngine: Can I fetch an internal url? | Does anyone know, if I can fetch an internal AppEngine url from within my AppEngine app?
The official URL Fetch Python API doesn´t cover that.
http://code.google.com/intl/et-EE/appengine/docs/python/urlfetch/overview.html
I tried different possibilities, but as it seems nothing works. Does anyone did that before?
urlli... | [
"This will not work at all with the development server. It is single-threaded, so trying to load one of your app's URL's while inside one of its request handlers will hang until the URLFetch times out.\nIt should work with no problems at all in production.\nTo get around the development server limitation, you shoul... | [
6
] | [] | [] | [
"fetch",
"google_app_engine",
"python",
"url"
] | stackoverflow_0005149500_fetch_google_app_engine_python_url.txt |
Q:
UnicodeEncodeError on djangoappengine
I've downloaded the djangoappengine project sample django-guestbook from www.allbuttonspressed.com to test how it works but the following error message is shown when I to access the URL localhost:8000
Traceback (most recent call last):
File
"/usr/local/google_appengine/go... | UnicodeEncodeError on djangoappengine | I've downloaded the djangoappengine project sample django-guestbook from www.allbuttonspressed.com to test how it works but the following error message is shown when I to access the URL localhost:8000
Traceback (most recent call last):
File
"/usr/local/google_appengine/google/appengine/tools/dev_appserver.py",
l... | [
"Well u'\\xe1' is a lowercase A with an accent mark --> á\nso my guess is that perhaps you used this character in a configuration file or you've stored the project in a directory that has the character in it? And then app engine is trying to use that in an environment variable name and that has to be ASCII.\n",
"... | [
1,
0
] | [] | [] | [
"django",
"djangoappengine",
"google_app_engine",
"python"
] | stackoverflow_0005148925_django_djangoappengine_google_app_engine_python.txt |
Q:
How can I override property setting for a dict-like object?
I'm writing a C binding, and the C structure that I'm wrapping has some string-indexed property values.
I'd like to expose these as a dict in python.
So far, I've got a function get_properties, which returns all the object's properties as a single dict. ... | How can I override property setting for a dict-like object? | I'm writing a C binding, and the C structure that I'm wrapping has some string-indexed property values.
I'd like to expose these as a dict in python.
So far, I've got a function get_properties, which returns all the object's properties as a single dict. I wrapped this using the property function in the class definitio... | [
"Okay, Mike's answer gave me the idea to solve this by returning from the property's getter with an extended dict class, in which I override __setitem__ based on the context:\nclass MyClass(object):\n def get_properties():\n ... (call C function and convert to dict)\n def set_property():\n ... (... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005146170_python.txt |
Q:
combine multiple vector shapes with low wasted space
I have an algorithm written in Python that creates and outputs a large amount of vector shapes. These shapes are all roughly triangular. Currently each is saved as a separate dxf file. I now want to laser-cut them and I'd like to do it with minimal waste.
What I... | combine multiple vector shapes with low wasted space | I have an algorithm written in Python that creates and outputs a large amount of vector shapes. These shapes are all roughly triangular. Currently each is saved as a separate dxf file. I now want to laser-cut them and I'd like to do it with minimal waste.
What I'm looking for is a way to combine them without an unreaso... | [
"Optimal 2d shape layout for cutting sheet goods is a hard problem, with active research. The \"panel cutting\" problem assumes rectangular shapes. Non-rectangular shapes are much harder.\nTry searching for \"shape nesting algorithms\".\n"
] | [
2
] | [] | [] | [
"algorithm",
"python",
"vector_graphics"
] | stackoverflow_0005148928_algorithm_python_vector_graphics.txt |
Q:
Python regular expression with wiki text
I'm trying to change wikitext into normal text using Python regular expressions substitution. There are two formatting rules regarding wiki link.
[[Name of page]]
[[Name of page | Text to display]]
(http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet)
Here is some text tha... | Python regular expression with wiki text | I'm trying to change wikitext into normal text using Python regular expressions substitution. There are two formatting rules regarding wiki link.
[[Name of page]]
[[Name of page | Text to display]]
(http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet)
Here is some text that gives me a headache.
The CD is composed alm... | [
"wikilink_rx = re.compile(r'\\[\\[(?:[^|\\]]*\\|)?([^\\]]+)\\]\\]')\nreturn wikilink_rx.sub(r'\\1', the_string)\n\nExample: http://ideone.com/7oxuz\nNote: you may also find some MediaWiki parsers in http://www.mediawiki.org/wiki/Alternative_parsers.\n",
"You're going down the wrong path. Wiki markup is notoriousl... | [
7,
2,
0,
0
] | [] | [] | [
"python",
"regex",
"wiki"
] | stackoverflow_0004929082_python_regex_wiki.txt |
Q:
Python - network buffer handling question
I want to design a game server in python. The game will mostly just be passing small packets filled with ints, strings, and bytes stuffed into one message. As I'm using a different language to write the game, a normal packet would be sent like so:
Writebyte(buffer, 5); // ... | Python - network buffer handling question | I want to design a game server in python. The game will mostly just be passing small packets filled with ints, strings, and bytes stuffed into one message. As I'm using a different language to write the game, a normal packet would be sent like so:
Writebyte(buffer, 5); // Delimit type of message
Writestring(buffer, "He... | [
"I would recommend using Google Protocol Buffers. Protocol Buffers gives you a multi-language, fast, extensible message serialization framework. You can easily add fields later, parse messages in most popular languages, and embed message types within other message types. It will save you a lot of time as compared t... | [
0,
0
] | [] | [] | [
"networking",
"python",
"struct"
] | stackoverflow_0005148688_networking_python_struct.txt |
Q:
where are the .pyc files?
I am a complete newb to python, hence a silly question.
As i understand, upon first execution of a *.py program, byte code is created into *.pyc and used until a change in *.py file.
Where might this *.pyc bytecode be found in a project?
I would think bin, but nothing is there
A:
A *.p... | where are the .pyc files? | I am a complete newb to python, hence a silly question.
As i understand, upon first execution of a *.py program, byte code is created into *.pyc and used until a change in *.py file.
Where might this *.pyc bytecode be found in a project?
I would think bin, but nothing is there
| [
"A *.pyc file is created for imported modules, and they are placed in the same directory containing the .py file. However... no .pyc file is created for the main script for your program. In other words... if you call \"python myscript.py\" on the command line, there will be no .pyc file for myscript.py.\nThis is ... | [
37,
24,
1,
0
] | [] | [] | [
"bytecode",
"python"
] | stackoverflow_0005149832_bytecode_python.txt |
Q:
Best text miner to use with python
I want to use a easy-to-use text miner with my python code. I will be mainly using the classification algorithms - Naive Bayes, KNN and such.
Please let me know what's the best option here - Weka? NLTK? SVM? or something else?
Thanks!
A:
I would go with NLTK since it's written... | Best text miner to use with python | I want to use a easy-to-use text miner with my python code. I will be mainly using the classification algorithms - Naive Bayes, KNN and such.
Please let me know what's the best option here - Weka? NLTK? SVM? or something else?
Thanks!
| [
"I would go with NLTK since it's written in Python\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005150053_python.txt |
Q:
simple question on python's split
Not sure why last print is off? Please see comments for specific question
john = ['john doe', 44, 32000]
jane = ['jane doe', 23, 12000]
people = [john, jane]
for p in people:
#===========================================================================
# p[0] prints "j... | simple question on python's split | Not sure why last print is off? Please see comments for specific question
john = ['john doe', 44, 32000]
jane = ['jane doe', 23, 12000]
people = [john, jane]
for p in people:
#===========================================================================
# p[0] prints "john doe" as expected
# p[0].split()... | [
"\np[0].split() returns a list of strings\nfor x in... deals with each string in the list\nx[0] is therefore the first character in the string\n\nyou probably want to get rid of the subscript after 'x'.\n",
"Use it like this\nfor p in people: \n #================================================================... | [
4,
0,
0
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0005150163_python_split_string.txt |
Q:
Using sqlite3 within Google App Engine?
I am trying to deploy my Python + Django project to the Google App Engine. Right now it works fine on my local computer, but when I try running it as a project within the Google App Engine, I get the following error.
ImproperlyConfigured: 'django.db.backends.sqlite3' isn't a... | Using sqlite3 within Google App Engine? | I am trying to deploy my Python + Django project to the Google App Engine. Right now it works fine on my local computer, but when I try running it as a project within the Google App Engine, I get the following error.
ImproperlyConfigured: 'django.db.backends.sqlite3' isn't an available database backend.
Try using djan... | [
"Google App Engine requires that you use its own datastore, rather than sqlite or another database. There is a project that will allow you to use pretty much regular Django models on App Engine called django-nonrel. You can find more information about setting it up here: http://code.google.com/appengine/articles/... | [
12
] | [] | [] | [
"django",
"google_app_engine",
"python",
"sqlite"
] | stackoverflow_0005150115_django_google_app_engine_python_sqlite.txt |
Q:
Plotting a table/chart/grid in Python
Assume the user inputs his file. The format is something like:
Name\t182909876\n
Name 2\t090090090\n
etc...
I want to plot this data onto a chart, a grid, or a table.
data_list = []
with infile as f:
data = [map(str, line.split('\t')) for line in f]
A:
matplotlib is wh... | Plotting a table/chart/grid in Python | Assume the user inputs his file. The format is something like:
Name\t182909876\n
Name 2\t090090090\n
etc...
I want to plot this data onto a chart, a grid, or a table.
data_list = []
with infile as f:
data = [map(str, line.split('\t')) for line in f]
| [
"matplotlib is what you need to plot numbers. Seeing that your code above generates nested lists of strings, you might have to improvise ..\n"
] | [
1
] | [] | [] | [
"grid",
"list",
"nested",
"python",
"wxpython"
] | stackoverflow_0005149417_grid_list_nested_python_wxpython.txt |
Q:
Add Property to Django Result Object
I'm trying to add a property or two to a Django result object before I serialize it. I'm fairly weak in my Python skills, so here we go.
I want to do:
products = Product.objects.all()
products.totalPages = 10
products.currentPage = 1
data = serializers.serialize('json', produc... | Add Property to Django Result Object | I'm trying to add a property or two to a Django result object before I serialize it. I'm fairly weak in my Python skills, so here we go.
I want to do:
products = Product.objects.all()
products.totalPages = 10
products.currentPage = 1
data = serializers.serialize('json', products)
Without trying to add the totalPages ... | [
"Not sure where you would like those attrs to go onto that \"list\" that serialize returns. Maybe you would like the data to be in a key in the final result:\nimport json\n\nfrom django.core import serializers\n\nproducts = Product.objects.all()\n# data is a python list\ndata = json.loads(serializers.serialize('js... | [
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005149849_django_python.txt |
Q:
Replacing synonyms in a corpus using WordNet and NLTK - python
Trying to write simple python script which will use NLTK to find and replace synonyms in txt file.
Following code gives me error:
Traceback (most recent call last):
File "C:\Users\Nedim\Documents\sinon2.py", line 21, in <module>
change(word)
Fi... | Replacing synonyms in a corpus using WordNet and NLTK - python | Trying to write simple python script which will use NLTK to find and replace synonyms in txt file.
Following code gives me error:
Traceback (most recent call last):
File "C:\Users\Nedim\Documents\sinon2.py", line 21, in <module>
change(word)
File "C:\Users\Nedim\Documents\sinon2.py", line 4, in change
synon... | [
"This isn't terribly efficient, and this would not replace a single synonym. because there could be multiple synonyms for each word. Which you could chose from,\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus.reader.plaintext import PlaintextCorpusReader\n\n\ncorpus_root = 'C://Users//tester//Desktop//'\nw... | [
2,
1
] | [] | [] | [
"corpus",
"file",
"nlp",
"nltk",
"python"
] | stackoverflow_0005148377_corpus_file_nlp_nltk_python.txt |
Q:
Python maxes one core while c++ doesn't
I wrote a simple program(calculating the number of steps for the numbers 1-10^10 using the collatz conjecture)in both python and c++. They were nearly identical, and neither were written for multithreading. I ran the one in python and according to my system manager, one core... | Python maxes one core while c++ doesn't | I wrote a simple program(calculating the number of steps for the numbers 1-10^10 using the collatz conjecture)in both python and c++. They were nearly identical, and neither were written for multithreading. I ran the one in python and according to my system manager, one core went straight to 100% usage, the others stay... | [
"Python is, in general, quite slow at raw number crunching. This is because it uses its full, general purpose object model for everything, including numbers. You can contrast this with Java and C++, which have \"native types\" which don't offer any of the niceties of a real class (methods, inheritance, data attribu... | [
3
] | [] | [] | [
"c++",
"multithreading",
"python"
] | stackoverflow_0005150550_c++_multithreading_python.txt |
Q:
Python twisted defer and getProcessOutputAndValue question
Folks,
This seems like a basic program and I cannot understand what is going wrong here. When run the program just waits and does not output anything on console, pressing control-c does not output anything either. Please advise.
My understanding is as foll... | Python twisted defer and getProcessOutputAndValue question | Folks,
This seems like a basic program and I cannot understand what is going wrong here. When run the program just waits and does not output anything on console, pressing control-c does not output anything either. Please advise.
My understanding is as follows:
(i) Reactor is run and callLater causes runProgram to be ca... | [
"You don't need the yield - the return value from getProcessOutputAndValue is already a Deferred.\n",
"As has already been stated yield is unnecessary there. To use yield you'd rewrite runProgram like:\nfrom twisted.internet import defer\n\n@defer.inlineCallbacks\ndef runProgram():\n command = ['lrt']\n tr... | [
2,
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0005150211_python_twisted.txt |
Q:
Efficient way to make two pairs in python
I would like to make two pairs from pairs.
A pair consists of two elements, and a two-pair consists of two pairs.
Here is the list of constraints:
In a pair, order of elements is important: (element1, element2) != (element2, element1)
In a two-pair, order of pairs is not ... | Efficient way to make two pairs in python | I would like to make two pairs from pairs.
A pair consists of two elements, and a two-pair consists of two pairs.
Here is the list of constraints:
In a pair, order of elements is important: (element1, element2) != (element2, element1)
In a two-pair, order of pairs is not important: (pair1, pair2) == (pair2, pair1)
I ... | [
"You would probably be better off sticking to standard python datastructures. tuple for Pair and set for TwoPair (although you might write a set subclass to add the __hash__ method).\nFor example:\nimport operator\n\nclass TwoPairs(set):\n def __hash__(self):\n return reduce(operator.xor, map(hash, self))\n\nRe... | [
3,
2
] | [] | [] | [
"algorithm",
"data_structures",
"python"
] | stackoverflow_0005150803_algorithm_data_structures_python.txt |
Q:
Rewrite views.py without using locals()
I have the following template:
<!DOCTYPE HTML PUBLIC "=//W3C//DTD HTML 4.01//EN">
<html land="en">
<head>
<title>Some Meta Data</title>
</head>
<body>
<ul>
{% for key,values in meta %}
<li> {{ key }}, {{ values }} </li>
{% endfor %}
</ul>
... | Rewrite views.py without using locals() | I have the following template:
<!DOCTYPE HTML PUBLIC "=//W3C//DTD HTML 4.01//EN">
<html land="en">
<head>
<title>Some Meta Data</title>
</head>
<body>
<ul>
{% for key,values in meta %}
<li> {{ key }}, {{ values }} </li>
{% endfor %}
</ul>
</body>
</html>
And corresponding views.py:... | [
"Your view can just be:\ndef display_meta(request):\n meta = request.META.items()\n return render_to_response('meta.html', {\"meta\": meta})\n\nSince you'll have to iterate meta to generate the template you don't have to do it in the view. Also the second argument of render_to_response can be a dictionary of... | [
5
] | [] | [] | [
"django",
"python",
"views"
] | stackoverflow_0005150993_django_python_views.txt |
Q:
How make work import of python26.zip on windows
I need to deploy a embeded version of python26.
I have it working under windows folowing the setup of http://www.portablepython.com/.
However after read this I try to pack everything into a zip file, and left out python.exe, python26.dll. However, that not work if py... | How make work import of python26.zip on windows | I need to deploy a embeded version of python26.
I have it working under windows folowing the setup of http://www.portablepython.com/.
However after read this I try to pack everything into a zip file, and left out python.exe, python26.dll. However, that not work if python is not pre-installed.
Also, I try pre-compilling... | [
"Py2EXE will do this for you, it fits nicely with distutils, so with a couple dozen lines of declaration in setup.py you'll get a nice windows application package without any python dependencies. Also, you can integrate further with Innosetup which gives you a great single-file-installer package.\n",
"Perhaps loo... | [
0,
0
] | [] | [] | [
"embedding",
"installation",
"python"
] | stackoverflow_0003648146_embedding_installation_python.txt |
Q:
Using python to split a string with delimiter, while ignoring the delimiter and escape quotes inside quotes
I am trying to split a string based on the location of a delimiter (I am trying to remove comments from Fortran code). I can split using ! in the following string:
x = '''print "hi!" ! Remove me'''
pattern =... | Using python to split a string with delimiter, while ignoring the delimiter and escape quotes inside quotes | I am trying to split a string based on the location of a delimiter (I am trying to remove comments from Fortran code). I can split using ! in the following string:
x = '''print "hi!" ! Remove me'''
pattern = '''(?:[^!"]|"[^"]*")+'''
y = re.search(pattern, x)
However, this fails if the string contains escape quotes, e.... | [
"Here's a proven regex (from Mastering Regular Expressions) for matching double-quoted string literals which may contain backslash-escaped quotes:\nr'\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"'\n\nWithin the delimiting quotes, it consumes any pair of characters that starts with a backslash without bothering to identify the... | [
3,
2,
2
] | [] | [] | [
"delimiter",
"python",
"regex"
] | stackoverflow_0005150398_delimiter_python_regex.txt |
Q:
Multiuser environment using python,GAE,django
My application is working fine for single user.
Now i am modifying it for multiuser.
How to approach for doing same.
(first user will have his specific data. second user will have his own specific data.)
I am new to python, django and Google App Engine.
Regards,
darsh... | Multiuser environment using python,GAE,django | My application is working fine for single user.
Now i am modifying it for multiuser.
How to approach for doing same.
(first user will have his specific data. second user will have his own specific data.)
I am new to python, django and Google App Engine.
Regards,
darshana
| [
"This is confusing. Could you possibly be talking of the admin as the single user?\nAnyway, Django has an authentication framework that handles multiple user capabilities. Here is the documentation, it provides models and views that you could readily use.\nAs for having specific data, you will need to create a User... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0005151103_django_google_app_engine_python.txt |
Q:
Is there any automated tool to generate a script for me to view and edit data based on database table
Currently, I am having Apache running, a PostgreSQL database, and several Python CGI script. I just don't want to write additional script to manipulate the following simple table structure.
Machine Name | IP Addre... | Is there any automated tool to generate a script for me to view and edit data based on database table | Currently, I am having Apache running, a PostgreSQL database, and several Python CGI script. I just don't want to write additional script to manipulate the following simple table structure.
Machine Name | IP Address
=========================
I was wondering, is there any tool, which can help me to auto generate a scri... | [
"Would mysitemaker do what you need? How about phppgadmin?\nhttp://sourceforge.net/projects/mysitemaker/\nhttp://phppgadmin.sourceforge.net/\n"
] | [
2
] | [] | [] | [
"postgresql",
"python",
"web_applications"
] | stackoverflow_0005151415_postgresql_python_web_applications.txt |
Q:
check if string is in abc order
So the function should count the number of times the letters in uppercase are out of abc order.
>>> abc('ABBZHDL')
2
Above, z and d are out of order.
>>> abc('ABCD')
0
>>> abc('DCBA')
4
My code:
def abc(check):
order=ABCDEFGHIJKLMNOPQRSTUVWXYZ
for c in check:
... | check if string is in abc order | So the function should count the number of times the letters in uppercase are out of abc order.
>>> abc('ABBZHDL')
2
Above, z and d are out of order.
>>> abc('ABCD')
0
>>> abc('DCBA')
4
My code:
def abc(check):
order=ABCDEFGHIJKLMNOPQRSTUVWXYZ
for c in check:
if check != order:
#then I get... | [
"The question is ill-defined. One solution to a nearby question would be using the builtin sorted():\ndef abc(s):\n count = 0\n s = ''.join(i for i in s if i.isupper())\n l = sorted(s)\n for i,c in enumerate(s):\n if l[i] != c:\n count += 1\n return count\n\nIt counts all of the pl... | [
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005150140_python_string.txt |
Q:
How can I properly send a command to Maya using os.getcwd() in Python
So I'm using sockets to send some output to maya. Unfortunately what I'm getting back from Maya doesn't make sense at all. I'm trying to quote a variable, while escaping the quote, but once it gets to Maya it fails. Here's the code:
currentDir =... | How can I properly send a command to Maya using os.getcwd() in Python | So I'm using sockets to send some output to maya. Unfortunately what I'm getting back from Maya doesn't make sense at all. I'm trying to quote a variable, while escaping the quote, but once it gets to Maya it fails. Here's the code:
currentDir = os.getcwd()
maya.send('python("import os; import sys; os.chdir(\''+current... | [
"Ended up being a very simple fix:\npath = os.getcwd()\nconvertPath = path.replace('\\\\','/')\n\nI take no credit for the answer though. I got the answer from http://forums.cgsociety.org/showpost.php?p=6890246&postcount=2 from r4inm4ker. :)\n"
] | [
1
] | [] | [] | [
"macos",
"python",
"string"
] | stackoverflow_0005150593_macos_python_string.txt |
Q:
Issue on dropdown menu with Django
I have an html page where the designation of employees can be selected via a drop down menu. And the selected option in the drop down menu displays employees of that corresponding designation. I am able to display the employees on selecting the designation from drop-down menu. Th... | Issue on dropdown menu with Django | I have an html page where the designation of employees can be selected via a drop down menu. And the selected option in the drop down menu displays employees of that corresponding designation. I am able to display the employees on selecting the designation from drop-down menu. The choices in drop-down are 'Select A Des... | [
"As far as I can understand your question, you are having a problem with rendering the correct value for Designation. You need to fix the errors in your code first. Why is selected=True inside the select tag? And you have a hanging 'selected' inside the first option tag. Something like:\nDesignation:\n <select n... | [
1,
0
] | [] | [] | [
"django",
"django_views",
"html",
"python"
] | stackoverflow_0005151084_django_django_views_html_python.txt |
Q:
Printing alternate lines using python
I have a text file like
1
2
3
4
5
6
7
8
9
10
... and so on.
How do I write a program to print the first 2 lines then skip 3 then print 2 lines (that's the pattern.)
I'm a complete noob.
Any help will be appreciated.
thanks.
A:
Based on line enumeration and assuming a 5-ite... | Printing alternate lines using python | I have a text file like
1
2
3
4
5
6
7
8
9
10
... and so on.
How do I write a program to print the first 2 lines then skip 3 then print 2 lines (that's the pattern.)
I'm a complete noob.
Any help will be appreciated.
thanks.
| [
"Based on line enumeration and assuming a 5-item cycle (display first two items, skip next three items):\nfor i, line in enumerate(file('myfile.txt')):\n\n if i % 5 in (0, 1):\n print line\n\n",
"I don't know if there's a pattern for this, really. You could just file.readlines() the entire thing and use a... | [
4,
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005150768_python.txt |
Q:
Invalid command 'WSGIReloadMechanism' in my Apache site's config file
I am trying to deploy a Django project and am using Apache2 with mod_wsgi. Here are the relevant lines in my Apache conf file:
WSGIScriptReloading On
WSGIDaemonProcess myprojectcom
WSGIReloadMechanism Process
WSGIProcessGroup myprojectcom
WSGIA... | Invalid command 'WSGIReloadMechanism' in my Apache site's config file | I am trying to deploy a Django project and am using Apache2 with mod_wsgi. Here are the relevant lines in my Apache conf file:
WSGIScriptReloading On
WSGIDaemonProcess myprojectcom
WSGIReloadMechanism Process
WSGIProcessGroup myprojectcom
WSGIApplicationGroup myprojectcom
WSGIPassAuthorization On
WSGIScriptAlias / /h... | [
"Remove the whole line:\nWSGIReloadMechanism Process\n\nIt isn't needed any more and the directive was removed completely in mod_wsgi 3.X.\nYou should preferable not rely on old blog posts for how to set up mod_wsgi and use the actual mod_wsgi documentation on the mod_wsgi site instead.\n"
] | [
6
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"ubuntu"
] | stackoverflow_0005150980_apache_django_mod_wsgi_python_ubuntu.txt |
Q:
Store python classes as pickles in GAE?
I am porting a Python investing application to Google App Engine. Every market that you can trade in is a plugin: for example the stocks trading and FOREX trading are all plugins.
The application stores the portfolio (which is a Portfolio class instance containing the active... | Store python classes as pickles in GAE? | I am porting a Python investing application to Google App Engine. Every market that you can trade in is a plugin: for example the stocks trading and FOREX trading are all plugins.
The application stores the portfolio (which is a Portfolio class instance containing the active investments (class instances) and history) a... | [
"The best solution would be to use the Datastore data models, but you'll have to rewrite parts of your app. Using Pickle for data persistance, especially involving much data, is not a good pratice.\n",
"The key advantages of using Django are its ORM and template system. The ORM is not very useful with datastore ... | [
1,
0
] | [] | [] | [
"google_app_engine",
"pickle",
"python"
] | stackoverflow_0003532417_google_app_engine_pickle_python.txt |
Q:
Which Python exception should I throw?
I'm writing some code to manipulate the Windows clipboard. The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API:
if OpenClipboard(None):
# Access the clipboard here
else:
# Handle failure
This function can fai... | Which Python exception should I throw? | I'm writing some code to manipulate the Windows clipboard. The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API:
if OpenClipboard(None):
# Access the clipboard here
else:
# Handle failure
This function can fail. So if it does, I would like to raise an e... | [
"It is better to avoid raising standard exceptions directly. Create your own exception class, inherit it from the most appropriate one (WindowsError is ok) and raise it. This way you'll avoid confusion between your own errors and system errors.\n",
"WindowsError seems a reasonable choice, and it will record extra... | [
3,
1,
1
] | [] | [] | [
"exception",
"python",
"windows"
] | stackoverflow_0005152522_exception_python_windows.txt |
Q:
python subprocess.popen get into an infinite loop
I'm trying to run the folowing command on a sub process and collecting the output.
nmap -n -PN -sT -T4 -p 445,139 10.11.1.0/24 --exclude matrix
this command return an error which is fine by me.
The problem is when i'm doing this from python like this:
import subp... | python subprocess.popen get into an infinite loop | I'm trying to run the folowing command on a sub process and collecting the output.
nmap -n -PN -sT -T4 -p 445,139 10.11.1.0/24 --exclude matrix
this command return an error which is fine by me.
The problem is when i'm doing this from python like this:
import subprocess
nmap_process = subprocess.Popen(command, stdout=... | [
"import subprocess\ncmd = \"nmap -n -PN -sT -T4 -p 445,139 10.11.1.0/24 --exclude matrix\"\npro = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\npro.communicate() #[0] is stdout [1] is stderr :P\n\nself.nmap_process.communicate() seems to be your problem. Are you creating this inside a ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005152230_python.txt |
Q:
Minimized html preview in div
How you can realize a minimized view of a html page in a div (like google preview)?
http://img228.imageshack.us/i/minimized.png/
edit: ok.. i see its a picture on google, probably a minimized screenshot.
A:
google displays an image thumbnail, so you would need to generate an image u... | Minimized html preview in div | How you can realize a minimized view of a html page in a div (like google preview)?
http://img228.imageshack.us/i/minimized.png/
edit: ok.. i see its a picture on google, probably a minimized screenshot.
| [
"google displays an image thumbnail, so you would need to generate an image using GD or ImageMagic. \nThe general flow would be \n\nFetch page content, including stylesheets and all images via curl (potentially tricky to capture all the embedded files but shouldn't be beyond a competent PHP programmer\nConstruct a ... | [
0,
0
] | [] | [] | [
"python",
"qt",
"web_applications"
] | stackoverflow_0005152986_python_qt_web_applications.txt |
Q:
Special Character problem in regexp by python
I apply some regular expression on xml file to find and replace values. Normally it works.(I heard the voices saying "use xml parsers". Meanwhile I can not.) But if there is a special character in the value, it ruins everything.
Think I have a xml file like below:
<fi... | Special Character problem in regexp by python | I apply some regular expression on xml file to find and replace values. Normally it works.(I heard the voices saying "use xml parsers". Meanwhile I can not.) But if there is a special character in the value, it ruins everything.
Think I have a xml file like below:
<fieldset>
<idle1>
<value>something\\n</value>
... | [
"I don't understand your explanations. \nPersonnaly, I wrote this:\nimport re\n\nRE = ('(^([ \\t]+)<(idle2)>(?:\\n|\\r\\n?)[ \\t]+<value>)'\n '(.*?)'\n '(?=</value>(?:\\n|\\r\\n?)\\\\2</\\\\3>)')\n\nprint repr(ch),'\\n'\nprint ch\nprint '\\n-------------------------------------------------'\nprint repr(re... | [
1,
0
] | [] | [] | [
"python",
"regex",
"string_literals"
] | stackoverflow_0005151967_python_regex_string_literals.txt |
Q:
XML parsing of a CDATA element
I want to parse xml which contains a CDATA element in the following format
<showtimes><![CDATA[6:50 PM,https://www.movietickets.com/purchase.asp?afid=rgncom&house_id=6446&language=2&movie_id=87050&perft=18:50&perfd=03012011,9:40 PM,https://www.movietickets.com/purchase.asp?afid=rgnco... | XML parsing of a CDATA element | I want to parse xml which contains a CDATA element in the following format
<showtimes><![CDATA[6:50 PM,https://www.movietickets.com/purchase.asp?afid=rgncom&house_id=6446&language=2&movie_id=87050&perft=18:50&perfd=03012011,9:40 PM,https://www.movietickets.com/purchase.asp?afid=rgncom&house_id=6446&language=2&movie_id=... | [
"This shouldn't be any problem - e.g. with lxml:\nfrom lxml import etree\n\ninput = '<showtimes><![CDATA[6:50 PM,https://www.movietickets.com/purchase.asp?afid=rgncom&house_id=6446&language=2&movie_id=87050&perft=18:50&perfd=03012011,9:40 PM,https://www.movietickets.com/purchase.asp?afid=rgncom&house_id=6446&langua... | [
4,
1,
0
] | [] | [] | [
"cdata",
"python",
"xml"
] | stackoverflow_0005153693_cdata_python_xml.txt |
Q:
Django, want to update the form without having to open the form again
I have a form called edit order. From my form there is a bit at the end where it updates the current item status date. It updates, but only if I was to close the form after clicking on the button called save_status. Is there a way where if I was... | Django, want to update the form without having to open the form again | I have a form called edit order. From my form there is a bit at the end where it updates the current item status date. It updates, but only if I was to close the form after clicking on the button called save_status. Is there a way where if I was to click on the button called save_status, then could the web page refresh... | [
"I can't understand where you are having problems. You've updated the form - so now just send the updated form back to the context, rather than redirecting to a new page.\n"
] | [
2
] | [] | [] | [
"django",
"forms",
"html",
"python"
] | stackoverflow_0005153531_django_forms_html_python.txt |
Q:
Create Python class where the attributes is defined dynamically
Sorry if this has been asked before. Is it possible to create class in Python dynamically where attributes is not defined in the __init__ method of the class.
For example with this class
class Person(object):
def __init__(self):
...
I can dynam... | Create Python class where the attributes is defined dynamically | Sorry if this has been asked before. Is it possible to create class in Python dynamically where attributes is not defined in the __init__ method of the class.
For example with this class
class Person(object):
def __init__(self):
...
I can dynamically put in the attributes during initialization like this:
person ... | [
"The easiest way to do this is to assign the keyword argument dict to the __dict__ attribute of the class:\nclass Person(object):\n def __init__(self, **kw):\n self.__dict__ = kw\nperson = Person(name='Joe')\nprint person.name\n\nprints\nJoe\n\nTo add attributes after object creation, use\ndef add_attribu... | [
14,
0
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0005154197_metaprogramming_python.txt |
Q:
stani python editor documentation
Has anybody got any idea where one can get documentation for stani python editor? The doc folder in the package is empty and I have searched the internet with no luck..
A:
Use a docbook-to-man command on the spe.sgml file. Once you do that you can use the man command.
If you ... | stani python editor documentation | Has anybody got any idea where one can get documentation for stani python editor? The doc folder in the package is empty and I have searched the internet with no luck..
| [
"Use a docbook-to-man command on the spe.sgml file. Once you do that you can use the man command. \nIf you dont want to use man, you can just look at the file, or try epcEdit. I looked at the documentation inside the file.. and there isn't much there.\nSo good luck ;)\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005154291_python.txt |
Q:
What thread-safe data persistence objects are available in Python for data persistence?
What Python thread-safe data persistence objects are available for data persistence? I need something that's similar to shelve. It's best if I can just change only a little bit of code instead of re-writing all parts related to... | What thread-safe data persistence objects are available in Python for data persistence? | What Python thread-safe data persistence objects are available for data persistence? I need something that's similar to shelve. It's best if I can just change only a little bit of code instead of re-writing all parts related to data persistence.
I Googled about this a bit but didn't find too much useful information.
| [
"Look at the ZODB providing native object persistence:\nhttp://www.zodb.org/\n"
] | [
4
] | [] | [] | [
"persistence",
"python",
"thread_safety"
] | stackoverflow_0005154157_persistence_python_thread_safety.txt |
Q:
how to use GWT for python app
I have developed my app using python in google app engine. Now I want to create GUI for my app and for that I want to use advantage of GWT.
So is it possible to use GWT with python app?
If yes then which is easiest way because I have seen pyjamas but I need other then that
A:
Just c... | how to use GWT for python app | I have developed my app using python in google app engine. Now I want to create GUI for my app and for that I want to use advantage of GWT.
So is it possible to use GWT with python app?
If yes then which is easiest way because I have seen pyjamas but I need other then that
| [
"Just create a REST/JSON service in Python: Recommendations of Python REST (web services) framework?\nThen consume this service with GWT (points 2, 3, and 4): http://code.google.com/webtoolkit/doc/latest/tutorial/JSON.html\n",
"I think not just out of the box, but have you had a look at gwt-python-rpc? Have a loo... | [
1,
0
] | [] | [] | [
"google_app_engine",
"gwt",
"python"
] | stackoverflow_0005154443_google_app_engine_gwt_python.txt |
Q:
Django on python2.5
AppEngine needs Python2.5.
Ubuntu 2010.10 comes with Python 2.6.6 and I didn't want to interfere with it, so I downloaded and compiled Python 2.5 in my home directory.
Then I downloaded Django-1.2.5.tar.gz, and ran "sudo python setup.py install".
Problem: "import django" says "ImportError: No ... | Django on python2.5 | AppEngine needs Python2.5.
Ubuntu 2010.10 comes with Python 2.6.6 and I didn't want to interfere with it, so I downloaded and compiled Python 2.5 in my home directory.
Then I downloaded Django-1.2.5.tar.gz, and ran "sudo python setup.py install".
Problem: "import django" says "ImportError: No module named django"
I gu... | [
"Install python2.5 with synaptic, then you will be able to use easy_install2.5 to install django. If you don't have the python2.5 in your package list you can put django on your python2.5 system path and be with it\nto view the system path do:\n\npython2.5 \n import sys\n sys.path\n\n"
] | [
0
] | [] | [] | [
"django",
"python",
"ubuntu_10.10"
] | stackoverflow_0005154479_django_python_ubuntu_10.10.txt |
Q:
Model Form extra fields
So I have the added an extra field to a form through a model, & using these choices:
A_CHOICES = (
('none', 'none'),
# further conversion table
class MyForm(ModelForm):
extra_field_a = ChoiceField(choices=A_CHOICES)
If this field is not 'none' then I want to use its value for a ... | Model Form extra fields | So I have the added an extra field to a form through a model, & using these choices:
A_CHOICES = (
('none', 'none'),
# further conversion table
class MyForm(ModelForm):
extra_field_a = ChoiceField(choices=A_CHOICES)
If this field is not 'none' then I want to use its value for a field in the model, but i'm u... | [
"That's exactly how you would retrieve it. Funky syntax aside, where is the NameError? self is undefined? Where did you put this code.\nYou would generally place this type of field specific code in the clean_FOO methods.\nhttp://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation\ndef clea... | [
1
] | [] | [] | [
"django",
"django_models",
"forms",
"python"
] | stackoverflow_0005154519_django_django_models_forms_python.txt |
Q:
Fill dates from Python groupby
I have a collection of news article objects which I wish to display archived by distinct month. I've used itertools.groupby to create a list of Python objects ordered in such a way:
news_grouped = [
{'date': key, 'list': list(val)}
for key, val in groupby(obj_list,
... | Fill dates from Python groupby | I have a collection of news article objects which I wish to display archived by distinct month. I've used itertools.groupby to create a list of Python objects ordered in such a way:
news_grouped = [
{'date': key, 'list': list(val)}
for key, val in groupby(obj_list,
(lambda v: datet... | [
"As suggested by Space_C0wb0y go for a dictionary, if you like use an ordered dict which is part of the collections module since 2.7.\n\nget the oldest article\ncreate the dict keys mapping to empty lists by looping from oldest.pub_date to today in month steps\nloop through all items and append to the appropriate l... | [
0
] | [] | [] | [
"django",
"python",
"python_itertools"
] | stackoverflow_0005154484_django_python_python_itertools.txt |
Q:
Subclassing numpy ndarray problem
I would like to subclass numpy ndarray. However, I cannot change the array. Why self = ... does not change the array? Thanks.
import numpy as np
class Data(np.ndarray):
def __new__(cls, inputarr):
obj = np.asarray(inputarr).view(cls)
return obj
def remov... | Subclassing numpy ndarray problem | I would like to subclass numpy ndarray. However, I cannot change the array. Why self = ... does not change the array? Thanks.
import numpy as np
class Data(np.ndarray):
def __new__(cls, inputarr):
obj = np.asarray(inputarr).view(cls)
return obj
def remove_some(self, t):
test_cols, tes... | [
"The reason you are not getting the result you expect is because you are re-assigning self within the method remove_some. You are just creating a new local variable self. If your array shape were not to change, you could simply do self[:] = ... and you could keep the reference to self and all would be well, but y... | [
6,
5,
3
] | [] | [] | [
"numpy",
"python",
"recarray",
"subclass"
] | stackoverflow_0005149269_numpy_python_recarray_subclass.txt |
Q:
Whats the alternative to 'yield' function in Django
The 'yield' function streams the output to the browser i.e. it appends the value to the response.
My requirement is that instead of "appending", is there any built in function which overwrites the old value, or just say does not append the new value to the old on... | Whats the alternative to 'yield' function in Django | The 'yield' function streams the output to the browser i.e. it appends the value to the response.
My requirement is that instead of "appending", is there any built in function which overwrites the old value, or just say does not append the new value to the old one..?
To explain my requirement:
following is the function... | [
"You can't overwrite things you've already sent to the browser. This is a remote network connection, remember: once something has been sent, it's been sent.\nYou'll need to do something clever with javascript or CSS to get the result you want.\n",
"This response thing looks quite dirty.\nGenerally speaking most o... | [
3,
0
] | [] | [] | [
"django",
"file_upload",
"python",
"yield_keyword"
] | stackoverflow_0005154773_django_file_upload_python_yield_keyword.txt |
Q:
Python: Most accurate way to play time the playing of sound samples
There are plenty of question and answers about playing sound samples in Python, but I'm interested to know the most accurate way to time the playing of samples. Suppose I'm writing a bit of Python capable of playing a complex rhythm made up from s... | Python: Most accurate way to play time the playing of sound samples | There are plenty of question and answers about playing sound samples in Python, but I'm interested to know the most accurate way to time the playing of samples. Suppose I'm writing a bit of Python capable of playing a complex rhythm made up from samples of drum hits: I want the timer-based triggering of my audio sample... | [
"For sound samples I only have experience with SDL which you can use through the Pygame package:\nhttp://www.pygame.org/docs/ref/mixer.html\nWhile I can't speak to its performance with the kind of application you have in mind SDL is used in a fair number of games so I imagine it's performance is fairly solid. I ca... | [
0
] | [] | [] | [
"audio",
"python",
"timer"
] | stackoverflow_0005154610_audio_python_timer.txt |
Q:
get path of python binary that's executing the script
I have a Pylons controller (irrelevant but explains why I have this need) say starter.py that starts another process using:
retcode = subprocess.call(('python','/path/to/myScript.py'))
now since the app runs in a virtual env python is not the right binary to c... | get path of python binary that's executing the script | I have a Pylons controller (irrelevant but explains why I have this need) say starter.py that starts another process using:
retcode = subprocess.call(('python','/path/to/myScript.py'))
now since the app runs in a virtual env python is not the right binary to call since it has no access to site-packages installed in my... | [
"The path is available in sys.executable.\n"
] | [
103
] | [] | [] | [
"pylons",
"python",
"virtualenv"
] | stackoverflow_0005155079_pylons_python_virtualenv.txt |
Q:
print all available tuples in python from a debugger
I realized there is a memory leak in one python script. Which occupied around 25MB first, and after 15 days it is more than 500 MB.
I followed many different ways, and not able to get into the root of the problem as am a python newbie...
Finally, I got this fol... | print all available tuples in python from a debugger | I realized there is a memory leak in one python script. Which occupied around 25MB first, and after 15 days it is more than 500 MB.
I followed many different ways, and not able to get into the root of the problem as am a python newbie...
Finally, I got this following
objgraph.show_most_common_types(limit=20)
tuple ... | [
"Am I reading correctly that the same script is running for 15 days non-stop?\nFor such long-running processes periodic restart is a good practice and it's much easier to do than eliminating all memory leaks.\nUpdate: Look at this answer, it seems to do exactly what you need -- print all newly added objects that we... | [
2,
0
] | [] | [] | [
"memory_leaks",
"python"
] | stackoverflow_0005151898_memory_leaks_python.txt |
Q:
how many times is a line of code executed when the program is running?
Is there some tool that tells me the time the program dwells on each line/block of code in python?
Thanks.
Karthick
A:
Look at the profiler that is part of the standard Python distribution. The Python docs include some examples.
A:
I'm a bi... | how many times is a line of code executed when the program is running? | Is there some tool that tells me the time the program dwells on each line/block of code in python?
Thanks.
Karthick
| [
"Look at the profiler that is part of the standard Python distribution. The Python docs include some examples.\n",
"I'm a big fan of line_profiler and kernprof:\nhttp://packages.python.org/line_profiler/\n"
] | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0005155002_python.txt |
Q:
Create Output file with multiple lines (Python)
I have an file with a specific data I would like to pull.
The file looks like this:
DS User ID 1
random garbage
random garbage
DS N user name 1
random garbage
DS User ID 2
random garbage
random garbage
DS N user name 2
So far I have:
import sys... | Create Output file with multiple lines (Python) | I have an file with a specific data I would like to pull.
The file looks like this:
DS User ID 1
random garbage
random garbage
DS N user name 1
random garbage
DS User ID 2
random garbage
random garbage
DS N user name 2
So far I have:
import sys
import re
f = open(sys.argv[1])
strToSearch = "... | [
"It's difficult to provide a robust solution without understanding the actual input data format, how much flexibility is allowed, and how the parsed data is going to be used.\nFrom just the sample input/output given above, one can quickly cook up a working sample code:\nout = open(\"test.dat\", \"a\") # output file... | [
5,
4,
1,
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0005154913_python_text.txt |
Q:
Python's equivalent of Java's statement.getGeneratedKeys()?
Is there an API in Python's sqlite3 module similar to Java's statement.getGeneratedKeys()? If not, what is the best way to get recently autogenerated keys in Python with sqlite3?
A:
You need to use the SQLite function last_insert_rowid(). From the SQLi... | Python's equivalent of Java's statement.getGeneratedKeys()? | Is there an API in Python's sqlite3 module similar to Java's statement.getGeneratedKeys()? If not, what is the best way to get recently autogenerated keys in Python with sqlite3?
| [
"You need to use the SQLite function last_insert_rowid(). From the SQLite documentation:\n\nThe last_insert_rowid() function\n returns the ROWID of the last row\n insert from the database connection\n which invoked the function. The\n last_insert_rowid() SQL function is a\n wrapper around the\n sqlite3_last_i... | [
0
] | [] | [] | [
"database",
"java",
"jdbc",
"python",
"sqlite"
] | stackoverflow_0005156058_database_java_jdbc_python_sqlite.txt |
Q:
python creating tmp directory permissions
I'm using a python script to create a copy of a linux filesystem. I'm having trouble with the permissions on the created /tmp directory. The /tmp directory should have 1777 permissions, i.e.:
ls -l /
drwxrwxrwt 17 root root 16384 2011-03-01 09:50 tmp
when I do the ... | python creating tmp directory permissions | I'm using a python script to create a copy of a linux filesystem. I'm having trouble with the permissions on the created /tmp directory. The /tmp directory should have 1777 permissions, i.e.:
ls -l /
drwxrwxrwt 17 root root 16384 2011-03-01 09:50 tmp
when I do the following,
os.mkdir('/mnt/tmp',1777)
I get st... | [
"You should provide the permissions as an octal number. In Python 2.x, simply use 01777 instead of 1777. In Python 3.x, use 0o1777.\n",
"Your permission should be in octal (777 in octal is 511 in decimal).\nIn Python, like in C, 0555 is 555 in base 8 (octal).\nIf you want 1777 in octal, use 01777 in your code.\... | [
9,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0005156268_linux_python.txt |
Q:
Python: Accepting Raw Input While Another Thread Checks For Messages
I am trying to write a basic chat client in Python for a project and have completed the task, easy. However when I handed it in they asked if I could get it to accept user input while checking for messages (an extra unmarked task for people who c... | Python: Accepting Raw Input While Another Thread Checks For Messages | I am trying to write a basic chat client in Python for a project and have completed the task, easy. However when I handed it in they asked if I could get it to accept user input while checking for messages (an extra unmarked task for people who complete work early).
I assume this is something to do with threading, so I... | [
"Not a real answer to your question but as an aside you may want to to look at eventlet.\nIt allows you to have co-routines which will enable you to handle the kind of things you want to do but in a way thats very easy to read/understand and (imho) very pythonic.\nHeres a great video to get you started: PyCon 2010:... | [
1,
0
] | [] | [] | [
"chat",
"python"
] | stackoverflow_0005156103_chat_python.txt |
Q:
create a dict of lists from a string
I want to convert a string such as 'a=b,a=c,a=d,b=e' into a dict of lists {'a': ['b', 'c', 'd'], 'b': ['e']} in Python 2.6.
My current solution is this:
def merge(d1, d2):
for k, v in d2.items():
if k in d1:
if type(d1[k]) != type(list()):
... | create a dict of lists from a string | I want to convert a string such as 'a=b,a=c,a=d,b=e' into a dict of lists {'a': ['b', 'c', 'd'], 'b': ['e']} in Python 2.6.
My current solution is this:
def merge(d1, d2):
for k, v in d2.items():
if k in d1:
if type(d1[k]) != type(list()):
d1[k] = list(d1[k])
d1[k].ap... | [
"d = {}\nfor i in 'a=b,a=c,a=d,b=e'.split(\",\"):\n k,v = i.split(\"=\")\n d.setdefault(k,[]).append(v)\nprint d\n\nor, if you're using python > 2.4, you can use defaultdict\nfrom collections import defaultdict\n\nd = defaultdict(list)\nfor i in 'a=b,a=c,a=d,b=e'.split(\",\"):\n k,v = i.split(\"=\")\n d... | [
13,
6,
0,
0
] | [] | [] | [
"dictionary",
"list",
"merge",
"python"
] | stackoverflow_0005155434_dictionary_list_merge_python.txt |
Q:
Communicate with running process via STDOUT
i have created a running process which listens for input:
listen = Popen(["home/user/listen"], stdout=PIPE, stdin=PIPE)
It runs and awaits input from STDIN/STDOUT.
Unfortunately, it seems that I can't execute anything I send to the process, i.e. like you would by pressi... | Communicate with running process via STDOUT | i have created a running process which listens for input:
listen = Popen(["home/user/listen"], stdout=PIPE, stdin=PIPE)
It runs and awaits input from STDIN/STDOUT.
Unfortunately, it seems that I can't execute anything I send to the process, i.e. like you would by pressing "Enter", e.g.
listen.communicate("Test")
or
l... | [
"Does home/user/listen wait for the line end? If so, add \\n at the end of your commands, like listen.communicate(\"Test\\n\").\n",
"I found a solution:\nlisten.stdin.write(\"%s\" %input)\nlisten.stdin.write(\"\\n\")\n\n"
] | [
1,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0005156318_linux_python.txt |
Q:
python: libraries for parsing email
Are there libraries for email message parsing (particularly, from Gmail's IMAP server) in Python (except for the standard email library)?
Or if not, maybe there is some C++ library for this purpose (and I'll be able to use it through SWIG)?
A:
This question does not make sen... | python: libraries for parsing email | Are there libraries for email message parsing (particularly, from Gmail's IMAP server) in Python (except for the standard email library)?
Or if not, maybe there is some C++ library for this purpose (and I'll be able to use it through SWIG)?
| [
"This question does not make sense. You can access GMail either using IMAP or POP3.\nAnd for parsing retrieved emails you use the 'email' module of Python. Python provides support for all this out-of-the-box \"all batteries included\".\n",
"http://libgmail.sourceforge.net/ is a Python bindings to Gmail. Also you ... | [
0,
0
] | [] | [] | [
"email",
"python"
] | stackoverflow_0005156422_email_python.txt |
Q:
Reading a private key generated with Putty in ezPyCrypto
I used Putty Key Generator to create a private key, called Putty-Private.ppk. I can use this private key with Pageant and Putty to connect to the servers of my hosting provider.
Now, I want to connect to the server with xmlrpc based remote API. To do this I... | Reading a private key generated with Putty in ezPyCrypto | I used Putty Key Generator to create a private key, called Putty-Private.ppk. I can use this private key with Pageant and Putty to connect to the servers of my hosting provider.
Now, I want to connect to the server with xmlrpc based remote API. To do this I installed ezPyCrypto which is advised by many as an easy to u... | [
"The .ppk extension makes me guess the private key comes from \"Save private key\" in puttygen. This file format is not supported by pretty much anything except PuTTY itself. I can't find what private key format ezPyCrypto expects, but you might have better luck with a private key file made from \"Conversions -> Ex... | [
2
] | [] | [] | [
"encryption",
"putty",
"pycrypto",
"python"
] | stackoverflow_0005152159_encryption_putty_pycrypto_python.txt |
Q:
How can I filter duplicate rows efficiently in Python?
My question looks like a classic one, but I cannot find the exact same question in stackoverflow. I hope mine is not a duplicate question.
I have a large file. The file has many rows and fixed columns. I am interested in columns A and B among all columns. The ... | How can I filter duplicate rows efficiently in Python? | My question looks like a classic one, but I cannot find the exact same question in stackoverflow. I hope mine is not a duplicate question.
I have a large file. The file has many rows and fixed columns. I am interested in columns A and B among all columns. The goal is that I would like to get rows, where (1) the value i... | [
"Does the original order need to be maintained? If not, it looks pretty similar to what groupby does, and you might get some performance boost out of using built-in methods.\nPerhaps something like this (untested!):\ns = sorted(oldlist, key=lambda e: (e.getA(), e.getB()))\ninteresting = (g for k,g in itertools.gro... | [
0,
0,
0,
0,
0
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0005147163_duplicates_python.txt |
Q:
TypeError: object.__new__() takes no parameters when using inheritance
Hey,
I'm having a hard time implementing something, that I guess shouldn't be hard. I've been reading many posts, and I still can't figure it out, though it is probably answered, and I might just simply not understand the answer :/
So, I have ... | TypeError: object.__new__() takes no parameters when using inheritance | Hey,
I'm having a hard time implementing something, that I guess shouldn't be hard. I've been reading many posts, and I still can't figure it out, though it is probably answered, and I might just simply not understand the answer :/
So, I have a class, defining an algorithm file three_dpll.py in logics/ and a couple of... | [
"Your class three_dpll also has a method three_dpll. When you \nreturn three_dpll(...)\n\nyou are creating an instance of that class (instead of calling the method, which is probably what you wanted to do). The class has no __init__() function that could handle the arguments that you are giving. That is what the er... | [
3
] | [] | [] | [
"inheritance",
"python",
"typeerror"
] | stackoverflow_0005156409_inheritance_python_typeerror.txt |
Q:
Unable to import RRDtool in Python
I am trying to import RRDtool into Python as I want to access an RRD database using Python, but when I am trying to import rrdtool I am getting the following error.
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "lice... | Unable to import RRDtool in Python | I am trying to import RRDtool into Python as I want to access an RRD database using Python, but when I am trying to import rrdtool I am getting the following error.
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sy... | [
"Well, the problem is solved just by executing the following command.\n\nsudo apt-get install python-rrd\n\n",
"It is unlikely that Python modules are located inside a 'bin' folder. And importing files from some configured path requires that the referred path is a proper Python package. It means it must contain a... | [
2,
0,
0,
0
] | [] | [] | [
"configuration",
"python",
"rrd",
"rrdtool"
] | stackoverflow_0005128741_configuration_python_rrd_rrdtool.txt |
Q:
Looking for clustering message framework for Python
I'm looking for a messaging framework to build up a cluster in Python (something similar to Apache Tribes).
Are there any such frameworks in Python?
A:
I am not too familiar with Apache Tribes but have you looked at Pyro?
http://www.xs4all.nl/~irmen/pyro3/
| Looking for clustering message framework for Python | I'm looking for a messaging framework to build up a cluster in Python (something similar to Apache Tribes).
Are there any such frameworks in Python?
| [
"I am not too familiar with Apache Tribes but have you looked at Pyro?\nhttp://www.xs4all.nl/~irmen/pyro3/\n"
] | [
2
] | [] | [] | [
"cluster_computing",
"distributed_objects",
"p2p",
"python"
] | stackoverflow_0005157094_cluster_computing_distributed_objects_p2p_python.txt |
Q:
how to insert data from lineEdit to tableWidget in PyQt4?
I am new in PyQt,currently working on a form where user will insert data into lineEdit and after submitting the data will be shown in the tablewidget.
I am reading data fro lineEdit and printing it but unfortunately not finding any way to add lineEdit data... | how to insert data from lineEdit to tableWidget in PyQt4? | I am new in PyQt,currently working on a form where user will insert data into lineEdit and after submitting the data will be shown in the tablewidget.
I am reading data fro lineEdit and printing it but unfortunately not finding any way to add lineEdit data to the tableWidget.The data should appear in the exact cell.
I... | [
"Are you adding a row with insertRow() first? Here's a quick example app that works for me. Set the row and column when calling setItem(). \nfrom PyQt4.QtGui import QApplication, QLineEdit, QTableWidget, QTableWidgetItem, \\\n QWidget, QVBoxLayout\n\nclass Window(QWidget):\n def __init__(self, parent=None):\n... | [
2
] | [] | [] | [
"pyqt4",
"python",
"uitableview"
] | stackoverflow_0003953001_pyqt4_python_uitableview.txt |
Q:
How to pass the remote IP to a proxied service? - Nginx
I'm running a service in localhost at 127.0.01:8000
and I'm proxying this by using:
proxy_pass http://127.0.0.1:8000;
Problem is that I need to pass the user's IP address to the service.
Any ideas?
A:
I send the real IP to django by setting a custom heade... | How to pass the remote IP to a proxied service? - Nginx | I'm running a service in localhost at 127.0.01:8000
and I'm proxying this by using:
proxy_pass http://127.0.0.1:8000;
Problem is that I need to pass the user's IP address to the service.
Any ideas?
| [
"I send the real IP to django by setting a custom header:\nproxy_set_header X-Real-IP $remote_addr;\nThose headers are available in request.META\n",
"See http://wiki.nginx.org/HttpRealIpModule\n"
] | [
20,
3
] | [] | [] | [
"django",
"gevent",
"nginx",
"python",
"ubuntu"
] | stackoverflow_0004880283_django_gevent_nginx_python_ubuntu.txt |
Q:
organizing pools for multiple urls massive download
I'm developing polish blogosphere monitoring website and I'm looking for "best practice" with handling
massive content download in python.
Here is sample sheme of a workflow:
Description:
I've categorized database of rss feeds (around 1000). Every hour or so I... | organizing pools for multiple urls massive download | I'm developing polish blogosphere monitoring website and I'm looking for "best practice" with handling
massive content download in python.
Here is sample sheme of a workflow:
Description:
I've categorized database of rss feeds (around 1000). Every hour or so I should check feeds if there are some new items posted. I... | [
"This approach sounds fine on initial read. The example here shows how to limit concurrency https://bitbucket.org/denis/gevent/src/tip/examples/dns_mass_resolve.py\n"
] | [
0
] | [] | [] | [
"asynchronous",
"download",
"gevent",
"python"
] | stackoverflow_0004361659_asynchronous_download_gevent_python.txt |
Q:
How to click a link that has javascript:__doPostBack in href?
I am writing a screen scraper script in python with module 'mechanize' and I would like to use the mechanize.click_link() method on a link that has javascript:__doPostBack in href.
I believe the page I am trying to parse is using AJAX.
Note: mech is th... | How to click a link that has javascript:__doPostBack in href? | I am writing a screen scraper script in python with module 'mechanize' and I would like to use the mechanize.click_link() method on a link that has javascript:__doPostBack in href.
I believe the page I am trying to parse is using AJAX.
Note: mech is the mechanize.Browser()
>>> next_link.__class__.__name__
'Link'
>>> n... | [
"I don't use mechanize, but I do a lot of web scraping myself with python.\nWhen I run into a javascript function like __doPostBack, I do the following:\nI access the web site in Firefox, and use the HttpFox extension to see the parameters of the POST request the browser sent to the web server when clicking the rel... | [
10,
1,
0
] | [] | [] | [
"javascript",
"mechanize",
"python"
] | stackoverflow_0001418000_javascript_mechanize_python.txt |
Q:
Google Static Maps API: Generating a static map with paths
I'm trying to generate a static google map with some points on it, and some lines connecting these points (I'm soon going to make the lines correspond with the driving directions, but that comes later). Right now I've got code like this to generate the URL... | Google Static Maps API: Generating a static map with paths | I'm trying to generate a static google map with some points on it, and some lines connecting these points (I'm soon going to make the lines correspond with the driving directions, but that comes later). Right now I've got code like this to generate the URL:
def getStaticMapAddress(self, route):
url = "http://maps.g... | [
"There is something wrong with the color parameter of the paths. The following URI works for me:\nhttp://maps.google.com/maps/api/staticmap?center=50.8202008,-0.1324898&zoom=6&size=400x400&markers=50.8202008,-0.1324898|51.447341,-0.0761212|51.4608947,-2.5884312&path=weight:5|50.8202008,-0.1324898|51.447341,-0.07612... | [
9
] | [] | [] | [
"google_maps",
"google_static_maps",
"python"
] | stackoverflow_0005083549_google_maps_google_static_maps_python.txt |
Q:
python cache library
Before reinventing the wheel, I was wondering if there was a non-Django cache library that was similar to the one provided with Django. Basically, it would allow different backends (ideally, file and memcached to start) to be used just like Django's cache, and then behave identically regardles... | python cache library | Before reinventing the wheel, I was wondering if there was a non-Django cache library that was similar to the one provided with Django. Basically, it would allow different backends (ideally, file and memcached to start) to be used just like Django's cache, and then behave identically regardless of backend used.
I've se... | [
"Take a look at Beaker's documentation at https://beaker.readthedocs.io/en/latest/caching.html\n",
"Beaker as said is the way to go. It supports multiple backends including Memcached.\n"
] | [
6,
1
] | [] | [] | [
"caching",
"memcached",
"python"
] | stackoverflow_0005157696_caching_memcached_python.txt |
Q:
Overwriting __getattr__ makes help(…) fail with TypeError
I have a container class (subclassed from list) where I have overridden the geattr method;
def __getattr__(self, name):
def _multiplexed(*args, **kwargs):
return [getattr(R, name)(*args, **kwargs) for R in self]
return _multiplexed
The trou... | Overwriting __getattr__ makes help(…) fail with TypeError | I have a container class (subclassed from list) where I have overridden the geattr method;
def __getattr__(self, name):
def _multiplexed(*args, **kwargs):
return [getattr(R, name)(*args, **kwargs) for R in self]
return _multiplexed
The trouble is that now I can't ask Python for help about my object. W... | [
"Looking at the pydoc source code, the culprit is:\ngetattr(thing, '__name__', None)\n\nThat tries to look up thing.__name__, and if it fails, returns None instead. Except, in your case, it doesn't fail; it gets a value back from __getattr__ instead.\nIf you're overriding __getattr__, it's a good idea to special ca... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005157746_python.txt |
Q:
How can I run a certain function for a specific time in Python?
For example i have function do_something() and I want it to run for exactly 1 second (and not .923 seconds. It won't do. However 0.999 is acceptable.)
However it is very very important that the do_something must exactly run for 1 second. I was thinkin... | How can I run a certain function for a specific time in Python? | For example i have function do_something() and I want it to run for exactly 1 second (and not .923 seconds. It won't do. However 0.999 is acceptable.)
However it is very very important that the do_something must exactly run for 1 second. I was thinking of using UNIX time stamp and calculate the seconds. But I am really... | [
"I gather from comments that there's a while loop in here somewhere. Here's a class that subclasses Thread, based on the source code for _Timer in the threading module. I know you said you decided against threading, but this is just a timer control thread; do_something executes in the main thread. So this should be... | [
2,
1,
0
] | [] | [] | [
"python",
"real_time"
] | stackoverflow_0005157753_python_real_time.txt |
Q:
Python: MySQLdb: Error: 1064 "You have an error in your SQL syntax."
I'm new to MySQLdb and Python. I'm trying to execute the following statement:
header_string = 'number_one, number_two, number_three'
values = '1, 2, 3'
cursor.execute("""INSERT INTO my_table (%s) VALUES (%s)""", (header_string, values))
and it r... | Python: MySQLdb: Error: 1064 "You have an error in your SQL syntax." | I'm new to MySQLdb and Python. I'm trying to execute the following statement:
header_string = 'number_one, number_two, number_three'
values = '1, 2, 3'
cursor.execute("""INSERT INTO my_table (%s) VALUES (%s)""", (header_string, values))
and it returns with the following error:
Error: 1064 "You have an error in your SQ... | [
"Try:\nheader_string = ('number_one','number_two','number_three')\nvalues = (1,2,3)\ncursor.execute(\"\"\"INSERT INTO my_table (%s,%s,%s) VALUES (%s,%s,%s)\"\"\", (header_string+values))\n\n"
] | [
5
] | [
"Try \ncursor.execute(\"\"\"INSERT INTO my_table (%s) VALUES (%s)\"\"\" % (header_string, values))\n\n"
] | [
-1
] | [
"mysql",
"mysql_error_1064",
"python",
"sql"
] | stackoverflow_0005158531_mysql_mysql_error_1064_python_sql.txt |
Q:
Python: Global Variables From Within Functions + Curses
I am being very, very confused...
Basically trying to declare a global variable pointing to a curses window so I can use a debug command however it complains AttributeError: 'NoneType' object has no attribute 'addstr' which implies it is not being set? Please... | Python: Global Variables From Within Functions + Curses | I am being very, very confused...
Basically trying to declare a global variable pointing to a curses window so I can use a debug command however it complains AttributeError: 'NoneType' object has no attribute 'addstr' which implies it is not being set? Please help!
wDebug = None
def start(stdscr):
curses.nocbreak(... | [
"You need to use a global statement:\nwDebug = None\n\ndef start(stdscr):\n global wDebug\n #...\n wDebug = curses.newwin(5, screenSize[1], 0, 0);\n\nFrom the documentation:\n\nIt would be impossible to assign to a global variable without global\n\n"
] | [
1
] | [] | [] | [
"curses",
"python"
] | stackoverflow_0005158727_curses_python.txt |
Q:
Python script for automatic background changing in Ubuntu
Could you write(or hint at) a Python script that changes the Ubuntu desktop background automatically from a website(like Flickr or deviantArt)? How can I start the script at startup?
A:
Not python but a direction: http://www.webupd8.org/2009/09/real-time-... | Python script for automatic background changing in Ubuntu | Could you write(or hint at) a Python script that changes the Ubuntu desktop background automatically from a website(like Flickr or deviantArt)? How can I start the script at startup?
| [
"Not python but a direction: http://www.webupd8.org/2009/09/real-time-earth-wallpaper-for-linux.html\n"
] | [
0
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0005158757_python_ubuntu.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.