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:
Using set in Python inside a loop
I have the following list in Python:
[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
I want to group them into [[1,2,7],[3,4,6,9]]
My code to do this looks like this:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for lfi in lf:
if lfi.intersection(set(li)):
lfi=lfi.union(set(li))
break
else:
lf.append(set(li))
lf is my final list. I do a loop over l and lf and when I find an intersection between an element from l and another from lf, I would like to merge them (union)
But I can't figure out why this is not working. The first to elements of the list l are being inserted with the append command, but the union is not working.
My final list lf looks like [set([1, 2]), set([3, 4])]
It seems to be something pretty basic, but I'm not familiar with sets.
I appreciate any help
Thanks
A:
The problem is here:
lfi=lfi.union(set(li))
You are not modifying the set. You are creating a new set which is then discarded. The original set is still in the lf array. Use update instead:
lfi.update(li)
This modifies the original set instead of creating a new one. The result after making this change:
[set([1, 2, 7]), set([9, 3, 4, 6])]
A:
Here is another way to write the same thing
For sets,
& means intersection
|= means update
I have also used map(set,l) so that you are not recreating the same set over and over
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in map(set,l):
for lfi in lf:
if lfi & li:
lfi |= li
break
else:
lf.append(li)
A:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for i, lfi in enumerate(lf):
if lfi.intersection(set(li)):
lfi=lfi.union(set(li))
lf[i] = lfi #You forgot to update the list
break
else:
lf.append(set(li))
|
Using set in Python inside a loop
|
I have the following list in Python:
[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
I want to group them into [[1,2,7],[3,4,6,9]]
My code to do this looks like this:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for lfi in lf:
if lfi.intersection(set(li)):
lfi=lfi.union(set(li))
break
else:
lf.append(set(li))
lf is my final list. I do a loop over l and lf and when I find an intersection between an element from l and another from lf, I would like to merge them (union)
But I can't figure out why this is not working. The first to elements of the list l are being inserted with the append command, but the union is not working.
My final list lf looks like [set([1, 2]), set([3, 4])]
It seems to be something pretty basic, but I'm not familiar with sets.
I appreciate any help
Thanks
|
[
"The problem is here:\nlfi=lfi.union(set(li))\n\nYou are not modifying the set. You are creating a new set which is then discarded. The original set is still in the lf array. Use update instead:\nlfi.update(li)\n\nThis modifies the original set instead of creating a new one. The result after making this change:\n[set([1, 2, 7]), set([9, 3, 4, 6])]\n\n",
"Here is another way to write the same thing\nFor sets,\n& means intersection\n|= means update \nI have also used map(set,l) so that you are not recreating the same set over and over\nl=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]\nlf=[]\nfor li in map(set,l):\n for lfi in lf:\n if lfi & li:\n lfi |= li\n break\n else:\n lf.append(li)\n\n",
"l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]\nlf=[]\nfor li in l:\n for i, lfi in enumerate(lf):\n\n if lfi.intersection(set(li)):\n lfi=lfi.union(set(li)) \n lf[i] = lfi #You forgot to update the list\n break\n else:\n lf.append(set(li))\n\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"dataset",
"python"
] |
stackoverflow_0002519682_dataset_python.txt
|
Q:
Importing a function/class from a Python module of the same name
I have a Python package mymodule with a sub-package utils (i.e. a subdirectory which contains modules each with a function). The functions have the same name as the file/module in which they live.
I would like to be able to access the functions as follows,
from mymodule.utils import a_function
Strangely however, sometimes I can import functions using the above notation, however other times I cannot. I have not been able to work out why though (recently, for example, I renamed a function and the file it was in and reflected this rename in the utils.__init__.py file but it no longer imported as a functions (rather as a module) in one of my scripts.
The utils.__init__.py reads something like,
__all__ = ['a_function', 'b_function' ...]
from a_function import a_function
from b_function import b_function
...
mymodule.__init__.py has no reference to utils
Ideas?
A:
Do your utils functions need to import other utils functions? (or import other modules that import other utils functions). Suppose for example that a_function.py contains contains "from mymodule.utils import b_function". Here's your utils.py with a bunch of extra comments:
# interpreter is executing utils.py
# Right now, utils.a_function and utils.b_function are modules
# The following line executes the a_function module,
# then rebinds a_function to a_function.a_function
from a_function import a_function
# The following line executes the b_function module,
# then rebinds b_function to b_function.b_function
from b_function import b_function
When the a_function module is first imported by utils.py, utils.b_function is a module not a function. Any module that states "from mymodule.utils import b_function" before the last line is executed will end up with a reference to the b_function module instead of the b_function function.
In general, I find that the from somemodule import something idiom is fraught with peril for any large project. It's great for short scripts, but once you start introducing circular import dependencies you run into problems and need to be careful about where you use it.
As a compromise between safety and saving on typing, I'd use from mymodule import utils then call utils.a_function(). That way, you will always get the object bound to utils.a_function right now instead of whatever happened to be bound to utils.a_function during import.
|
Importing a function/class from a Python module of the same name
|
I have a Python package mymodule with a sub-package utils (i.e. a subdirectory which contains modules each with a function). The functions have the same name as the file/module in which they live.
I would like to be able to access the functions as follows,
from mymodule.utils import a_function
Strangely however, sometimes I can import functions using the above notation, however other times I cannot. I have not been able to work out why though (recently, for example, I renamed a function and the file it was in and reflected this rename in the utils.__init__.py file but it no longer imported as a functions (rather as a module) in one of my scripts.
The utils.__init__.py reads something like,
__all__ = ['a_function', 'b_function' ...]
from a_function import a_function
from b_function import b_function
...
mymodule.__init__.py has no reference to utils
Ideas?
|
[
"Do your utils functions need to import other utils functions? (or import other modules that import other utils functions). Suppose for example that a_function.py contains contains \"from mymodule.utils import b_function\". Here's your utils.py with a bunch of extra comments:\n# interpreter is executing utils.py\n# Right now, utils.a_function and utils.b_function are modules\n\n# The following line executes the a_function module, \n# then rebinds a_function to a_function.a_function\nfrom a_function import a_function \n\n# The following line executes the b_function module, \n# then rebinds b_function to b_function.b_function\nfrom b_function import b_function\n\nWhen the a_function module is first imported by utils.py, utils.b_function is a module not a function. Any module that states \"from mymodule.utils import b_function\" before the last line is executed will end up with a reference to the b_function module instead of the b_function function.\nIn general, I find that the from somemodule import something idiom is fraught with peril for any large project. It's great for short scripts, but once you start introducing circular import dependencies you run into problems and need to be careful about where you use it.\nAs a compromise between safety and saving on typing, I'd use from mymodule import utils then call utils.a_function(). That way, you will always get the object bound to utils.a_function right now instead of whatever happened to be bound to utils.a_function during import.\n"
] |
[
7
] |
[] |
[] |
[
"import",
"module",
"python"
] |
stackoverflow_0002519511_import_module_python.txt
|
Q:
Python OSError not reporting errors
Ive got this snippet that Im using to convert image files to tiff. I want to be informed when a file fails to convert. Imagemagick exits 0 when successfully run, so I figured the following snippet would report the issue. However no errors are being reported at all.
def image(filePath,dirPath,fileUUID,shortFile):
try:
os.system("convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif")
except OSError, e:
print >>sys.stderr, "image conversion failed: %s" % (e.errno, e.strerror)
sys.exit(-1)
A:
os.system() does not throw an exception if the return value is non-zero. What you should do is capture the return value and check that:
ret = os.system(...)
if ret == ...:
Of course, what you should also do is replace os.system() with subprocess.
A:
A better think will be to use check_call from the subprocess module, it raises CalledProcessError when the subprocess returned a non zero value.
A:
You can access ImageMagick directly through Python using PythonMagick (download here). A more popular tool for image manipulation is PIL.
A:
+ is generally a bad way to build strings in Python.
I would tend to replace "convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif" with
import os.path
"convert %s +compress %s.tif" % (filePath, os.path.join(dirPath, shortFile))
That being said, you'd replace the whole os.system call using
from subprocess import check_call, CalledProcessError
newFile = "%s.tif" % (filePath, os.path.join(dirPath, shortFile)
command = ["convert", filePath, "+compress", newFile]
try:
check_call(command)
except CalledProcessError as e:
...
|
Python OSError not reporting errors
|
Ive got this snippet that Im using to convert image files to tiff. I want to be informed when a file fails to convert. Imagemagick exits 0 when successfully run, so I figured the following snippet would report the issue. However no errors are being reported at all.
def image(filePath,dirPath,fileUUID,shortFile):
try:
os.system("convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif")
except OSError, e:
print >>sys.stderr, "image conversion failed: %s" % (e.errno, e.strerror)
sys.exit(-1)
|
[
"os.system() does not throw an exception if the return value is non-zero. What you should do is capture the return value and check that:\nret = os.system(...)\nif ret == ...:\n\nOf course, what you should also do is replace os.system() with subprocess.\n",
"A better think will be to use check_call from the subprocess module, it raises CalledProcessError when the subprocess returned a non zero value.\n",
"You can access ImageMagick directly through Python using PythonMagick (download here). A more popular tool for image manipulation is PIL.\n",
"+ is generally a bad way to build strings in Python. \nI would tend to replace \"convert \" + filePath + \" +compress \" + dirPath + \"/\" + shortFile + \".tif\" with\nimport os.path\n\"convert %s +compress %s.tif\" % (filePath, os.path.join(dirPath, shortFile))\n\nThat being said, you'd replace the whole os.system call using\nfrom subprocess import check_call, CalledProcessError\n\nnewFile = \"%s.tif\" % (filePath, os.path.join(dirPath, shortFile)\ncommand = [\"convert\", filePath, \"+compress\", newFile]\ntry:\n check_call(command)\nexcept CalledProcessError as e:\n ...\n\n"
] |
[
5,
3,
1,
0
] |
[] |
[] |
[
"imagemagick",
"python"
] |
stackoverflow_0002520325_imagemagick_python.txt
|
Q:
Django templates crashes with no sense
Hello I'm trying to use google visualization API along with django templates system. I got an error that don't know how to fix. The error is the following:
invalid_block_tag
raise self.error(token, "Invalid block tag: '%s'" % command)
django.template.TemplateSyntaxError: Invalid block tag: 'endfor'
The code is:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'time');
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn('number', 'z');
data.addRows([
{% for d in datos &}
[new Date({{d.instante|date:"Y, m, d, H, i, s"}}), {{d.x}}, {{d.y}}, {{d.z}}]
{% if not forloop.last %},{% endif %}
]);
{% endfor %}
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
Thanks you all!
A:
You goofed your for tag:
{% for d in datos %}
|
Django templates crashes with no sense
|
Hello I'm trying to use google visualization API along with django templates system. I got an error that don't know how to fix. The error is the following:
invalid_block_tag
raise self.error(token, "Invalid block tag: '%s'" % command)
django.template.TemplateSyntaxError: Invalid block tag: 'endfor'
The code is:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'time');
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn('number', 'z');
data.addRows([
{% for d in datos &}
[new Date({{d.instante|date:"Y, m, d, H, i, s"}}), {{d.x}}, {{d.y}}, {{d.z}}]
{% if not forloop.last %},{% endif %}
]);
{% endfor %}
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
Thanks you all!
|
[
"You goofed your for tag:\n{% for d in datos %}\n\n"
] |
[
2
] |
[] |
[] |
[
"django_templates",
"python"
] |
stackoverflow_0002520618_django_templates_python.txt
|
Q:
mongokit and django
I'm looking for good tutorial or really simple code to integrate mongokit and django
A:
http://www.peterbe.com/plog/how-and-why-to-use-django-mongokit would seem to cover this. BTW this was the first result on google for search term "mongokit django".
|
mongokit and django
|
I'm looking for good tutorial or really simple code to integrate mongokit and django
|
[
"http://www.peterbe.com/plog/how-and-why-to-use-django-mongokit would seem to cover this. BTW this was the first result on google for search term \"mongokit django\".\n"
] |
[
5
] |
[] |
[] |
[
"django",
"mongodb",
"python"
] |
stackoverflow_0002520440_django_mongodb_python.txt
|
Q:
What algorithms are suitable for this simple machine learning problem?
I have a what I think is a simple machine learning question.
Here is the basic problem: I am repeatedly given a new object and a list of descriptions about the object. For example: new_object: 'bob' new_object_descriptions: ['tall','old','funny']. I then have to use some kind of machine learning to find previously handled objects that have the 10 or less most similar descriptions, for example, past_similar_objects: ['frank','steve','joe']. Next, I have an algorithm that can directly measure whether these objects are indeed similar to bob, for example, correct_objects: ['steve','joe']. The classifier is then given this feedback training of successful matches. Then this loop repeats with a new object.
a
Here's the pseudo-code:
Classifier=new_classifier()
while True:
new_object,new_object_descriptions = get_new_object_and_descriptions()
past_similar_objects = Classifier.classify(new_object,new_object_descriptions)
correct_objects = calc_successful_matches(new_object,past_similar_objects)
Classifier.train_successful_matches(object,correct_objects)
But, there are some stipulations that may limit what classifier can be used:
There will be millions of objects put into this classifier so classification and training needs to scale well to millions of object types and still be fast. I believe this disqualifies something like a spam classifier that is optimal for just two types: spam or not spam. (Update: I could probably narrow this to thousands of objects instead of millions, if that is a problem.)
Again, I prefer speed when millions of objects are being classified, over accuracy.
Update: The classifier should return the 10 (or fewer) most similar objects, based on feedback from past training. Without this limit, an obvious cheat would be for the classifier could just return all past objects :)
What are decent, fast machine learning algorithms for this purpose?
Note: The calc_successful_matches distance metric is extremely expensive to calculate and that's why I'm using a fast machine learning algorithm to try to guess which objects will be close before I actually do the expensive calculation.
A:
An algorithm that seems to meet your requirements (and is perhaps similar to what John the Statistician is suggesting) is Semantic Hashing. The basic idea is that it trains a deep belief network (a type of neural network that some have called 'neural networks 2.0' and is a very active area of research right now) to create a hash of the list of descriptions of an object into binary number such that the Hamming distance between the numbers correspond to similar objects. Since this just requires bitwise operations it can be pretty fast, and since you can use it to create a nearest neighbor-style algorithm it naturally generalizes to a very large number of classes. This is very good state of the art stuff. Downside: it's not trivial to understand and implement, and requires some parameter tuning. The author provides some Matlab code here. A somewhat easier algorithm to implement and is closely related to this one is Locality Sensitive Hashing.
Now that you say that you have an expensive distance function you want to approximate quickly, I'm reminded of another very interesting algorithm that does this, Boostmap. This one uses boosting to create a fast metric which approximates an expensive to calculate metric. In a certain sense it's similar to the above idea but the algorithms used are different. The authors of this paper have several papers on related techniques, all pretty good quality (published in top conferences) that you might want to check out.
A:
You could use the vector space model (http://en.wikipedia.org/wiki/Vector_space_model). I think what you are trying to learn is how to weight terms in considering how close two object description vectors are to each other, say for example in terms of a simplified mutual information. This could be very efficient as you could hash from terms to vectors, which means you wouldn't have to compare objects without shared features. The naive model would then have an adjustable weight per term (this could either be per term per vector, per term overall, or both), as well as a threshold. The vector space model is a widely used technique (for example, in Apache Lucene, which you might be able to use for this problem), so you'll be able to find out a lot about it through further searches.
Let me give a very simple formulation of this in terms of your example. Given bob: ['tall','old','funny'], I retrieve
frank: ['young','short,'funny']
steve: ['tall','old','grumpy']
joe: ['tall','old']
as I am maintaining a hash from funny->{frank,...}, tall->{steve, joe,...}, and old->{steve, joe,...}
I calculate something like the overall mutual information: weight of shared tags/weight of bob's tags. If that weight is over the threshold, I include them in the list.
When training, if I make a mistake I modify the shared tags. If my error was including frank, I reduce the weight for funny, while if I make a mistake by not including Steve or Joe, I increase the weight for tall and old.
You can make this as sophisticated as you'd like, for example by including weights for conjunctions of terms.
A:
do you really need a machine learning algorithm for this? What is your metric for similarity? You've mentioned the dimensionality of the number of objects, what about the size of the trait set for each person? Are there a maximum number of trait types? I might try something like this:
1) Have a dictionary mapping trait to a list of names named map
for each person p
for each trait t in p
map[t].add(p);
2) then when I want to find the closest person, I'd take my dictionary and create a new temp one:
dictionary mapping name to count called cnt
for each trait t in my person of interest
for each person p in map[t]
cnt[p]++;
then the entry with the highest count is closest
The benefit here is the map is only created once. if the traits per person is small, and the types of available traits are large, then the algorithm should be fast.
A:
SVM is pretty fast. LIBSVM for Python, in particular, provides a very decent implementation of Support Vector Machine for classification.
A:
This project departs from typical classification applications in two notable ways:
Rather than outputting the class which the new object is thought to belong to (or possibly outputting an array of these classes, each with probability / confidence level), the "classifier" provides a list of "neighbors" which are "close enough" to the new object.
With each new classification, an objective function, independent from the classifier, provides the list of the correct "neighbors"; in turn the corrected list (a subset of the list provided by the classifier ?) is then used to train the classifier
The idea behind the second point is probably that future objects submitted to the classifier and with similar to the current object should get better "classified" (be associated with a more correct set of previously seen objects) since the on-going training re-enforces connections to positive (correct) matches, while weakening the connection to objects which the classifier initially got wrong.
These two characteristics introduce distinct problems.
- The fact that the output is a list of objects rather than a "prototype" (or category identifier of sorts) make it difficult to scale as the number of objects seen so far grows toward the millions of instances as suggested in the question.
- The fact that the training is done on the basis of a subset of the matches found by the classifier, may introduce over-fitting, whereby the classifier could become "blind" to features (dimensions) which it, accidentally, didn't weight as important/relevant, in the early parts of the training. (I may be assuming too much with regards to the objective function in charge of producing the list of "correct" objects)
Possibly, the scaling concern could be handled by having a two-step process, with a first classifier, based the K-Means algorithm or something similar, which would produce a subset of the overall object collection (of objects previously seen) as plausible matches for the current object (effectively filtering out say 70% or more of collection). These possible matches would then be evaluated on the basis of Vector Space Model (particularly relevant if the feature dimensions are based on factors rather than values) or some other models. The underlying assumption for this two-step process is that the object collection will effectively expose clusters (it may just be relatively evenly distributed along the various dimensions).
Another way to further limit the number of candidates to evaluate, as the size of the previously seen objects grows, is to remove near duplicates and to only compare with one of these (but to supply the full duplicate list in the result, assuming that if the new object is close to the "representative" of this near duplicate class, all members of the class would also match)
The issue of over-fitting is trickier to handle. A possible approach would be to [sometimes] randomly add objects to the matching list which the classifier would not normally include. The extra objects could be added on the basis of their distance relative distance to the new object (i.e. making it a bit more probable that a relatively close object be added)
A:
What you describe is somewhat similar to the Locally Weighted Learning algorithm, which given a query instance, it trains a model locally around the neighboring instances weighted by their distances to the query one.
Weka (Java) has an implementation of this in weka.classifiers.lazy.LWL
|
What algorithms are suitable for this simple machine learning problem?
|
I have a what I think is a simple machine learning question.
Here is the basic problem: I am repeatedly given a new object and a list of descriptions about the object. For example: new_object: 'bob' new_object_descriptions: ['tall','old','funny']. I then have to use some kind of machine learning to find previously handled objects that have the 10 or less most similar descriptions, for example, past_similar_objects: ['frank','steve','joe']. Next, I have an algorithm that can directly measure whether these objects are indeed similar to bob, for example, correct_objects: ['steve','joe']. The classifier is then given this feedback training of successful matches. Then this loop repeats with a new object.
a
Here's the pseudo-code:
Classifier=new_classifier()
while True:
new_object,new_object_descriptions = get_new_object_and_descriptions()
past_similar_objects = Classifier.classify(new_object,new_object_descriptions)
correct_objects = calc_successful_matches(new_object,past_similar_objects)
Classifier.train_successful_matches(object,correct_objects)
But, there are some stipulations that may limit what classifier can be used:
There will be millions of objects put into this classifier so classification and training needs to scale well to millions of object types and still be fast. I believe this disqualifies something like a spam classifier that is optimal for just two types: spam or not spam. (Update: I could probably narrow this to thousands of objects instead of millions, if that is a problem.)
Again, I prefer speed when millions of objects are being classified, over accuracy.
Update: The classifier should return the 10 (or fewer) most similar objects, based on feedback from past training. Without this limit, an obvious cheat would be for the classifier could just return all past objects :)
What are decent, fast machine learning algorithms for this purpose?
Note: The calc_successful_matches distance metric is extremely expensive to calculate and that's why I'm using a fast machine learning algorithm to try to guess which objects will be close before I actually do the expensive calculation.
|
[
"An algorithm that seems to meet your requirements (and is perhaps similar to what John the Statistician is suggesting) is Semantic Hashing. The basic idea is that it trains a deep belief network (a type of neural network that some have called 'neural networks 2.0' and is a very active area of research right now) to create a hash of the list of descriptions of an object into binary number such that the Hamming distance between the numbers correspond to similar objects. Since this just requires bitwise operations it can be pretty fast, and since you can use it to create a nearest neighbor-style algorithm it naturally generalizes to a very large number of classes. This is very good state of the art stuff. Downside: it's not trivial to understand and implement, and requires some parameter tuning. The author provides some Matlab code here. A somewhat easier algorithm to implement and is closely related to this one is Locality Sensitive Hashing. \nNow that you say that you have an expensive distance function you want to approximate quickly, I'm reminded of another very interesting algorithm that does this, Boostmap. This one uses boosting to create a fast metric which approximates an expensive to calculate metric. In a certain sense it's similar to the above idea but the algorithms used are different. The authors of this paper have several papers on related techniques, all pretty good quality (published in top conferences) that you might want to check out.\n",
"You could use the vector space model (http://en.wikipedia.org/wiki/Vector_space_model). I think what you are trying to learn is how to weight terms in considering how close two object description vectors are to each other, say for example in terms of a simplified mutual information. This could be very efficient as you could hash from terms to vectors, which means you wouldn't have to compare objects without shared features. The naive model would then have an adjustable weight per term (this could either be per term per vector, per term overall, or both), as well as a threshold. The vector space model is a widely used technique (for example, in Apache Lucene, which you might be able to use for this problem), so you'll be able to find out a lot about it through further searches. \nLet me give a very simple formulation of this in terms of your example. Given bob: ['tall','old','funny'], I retrieve\nfrank: ['young','short,'funny']\nsteve: ['tall','old','grumpy']\njoe: ['tall','old']\nas I am maintaining a hash from funny->{frank,...}, tall->{steve, joe,...}, and old->{steve, joe,...}\nI calculate something like the overall mutual information: weight of shared tags/weight of bob's tags. If that weight is over the threshold, I include them in the list. \nWhen training, if I make a mistake I modify the shared tags. If my error was including frank, I reduce the weight for funny, while if I make a mistake by not including Steve or Joe, I increase the weight for tall and old.\nYou can make this as sophisticated as you'd like, for example by including weights for conjunctions of terms.\n",
"do you really need a machine learning algorithm for this? What is your metric for similarity? You've mentioned the dimensionality of the number of objects, what about the size of the trait set for each person? Are there a maximum number of trait types? I might try something like this:\n1) Have a dictionary mapping trait to a list of names named map\nfor each person p\nfor each trait t in p\nmap[t].add(p);\n2) then when I want to find the closest person, I'd take my dictionary and create a new temp one:\ndictionary mapping name to count called cnt\nfor each trait t in my person of interest\nfor each person p in map[t]\ncnt[p]++;\nthen the entry with the highest count is closest\n\nThe benefit here is the map is only created once. if the traits per person is small, and the types of available traits are large, then the algorithm should be fast.\n",
"SVM is pretty fast. LIBSVM for Python, in particular, provides a very decent implementation of Support Vector Machine for classification.\n",
"This project departs from typical classification applications in two notable ways:\n\nRather than outputting the class which the new object is thought to belong to (or possibly outputting an array of these classes, each with probability / confidence level), the \"classifier\" provides a list of \"neighbors\" which are \"close enough\" to the new object.\nWith each new classification, an objective function, independent from the classifier, provides the list of the correct \"neighbors\"; in turn the corrected list (a subset of the list provided by the classifier ?) is then used to train the classifier\n\nThe idea behind the second point is probably that future objects submitted to the classifier and with similar to the current object should get better \"classified\" (be associated with a more correct set of previously seen objects) since the on-going training re-enforces connections to positive (correct) matches, while weakening the connection to objects which the classifier initially got wrong.\nThese two characteristics introduce distinct problems.\n - The fact that the output is a list of objects rather than a \"prototype\" (or category identifier of sorts) make it difficult to scale as the number of objects seen so far grows toward the millions of instances as suggested in the question.\n - The fact that the training is done on the basis of a subset of the matches found by the classifier, may introduce over-fitting, whereby the classifier could become \"blind\" to features (dimensions) which it, accidentally, didn't weight as important/relevant, in the early parts of the training. (I may be assuming too much with regards to the objective function in charge of producing the list of \"correct\" objects)\nPossibly, the scaling concern could be handled by having a two-step process, with a first classifier, based the K-Means algorithm or something similar, which would produce a subset of the overall object collection (of objects previously seen) as plausible matches for the current object (effectively filtering out say 70% or more of collection). These possible matches would then be evaluated on the basis of Vector Space Model (particularly relevant if the feature dimensions are based on factors rather than values) or some other models. The underlying assumption for this two-step process is that the object collection will effectively expose clusters (it may just be relatively evenly distributed along the various dimensions).\nAnother way to further limit the number of candidates to evaluate, as the size of the previously seen objects grows, is to remove near duplicates and to only compare with one of these (but to supply the full duplicate list in the result, assuming that if the new object is close to the \"representative\" of this near duplicate class, all members of the class would also match)\nThe issue of over-fitting is trickier to handle. A possible approach would be to [sometimes] randomly add objects to the matching list which the classifier would not normally include. The extra objects could be added on the basis of their distance relative distance to the new object (i.e. making it a bit more probable that a relatively close object be added)\n",
"What you describe is somewhat similar to the Locally Weighted Learning algorithm, which given a query instance, it trains a model locally around the neighboring instances weighted by their distances to the query one.\nWeka (Java) has an implementation of this in weka.classifiers.lazy.LWL\n"
] |
[
9,
3,
3,
2,
1,
1
] |
[] |
[] |
[
"artificial_intelligence",
"classification",
"machine_learning",
"neural_network",
"python"
] |
stackoverflow_0002520018_artificial_intelligence_classification_machine_learning_neural_network_python.txt
|
Q:
Django OpenID django-openid-auth Login Error
I get the following error when attempting to use django-openid-auth OpenID discovery error: No usable OpenID services found for *******@gmail.com
I have followed the instructions that come with it, though it seems there is something I am missing. the installation is on my localhost.
A:
Are you supplying an email address or URL? OpenID needs a URL and *******@gmail.com is an email address.
|
Django OpenID django-openid-auth Login Error
|
I get the following error when attempting to use django-openid-auth OpenID discovery error: No usable OpenID services found for *******@gmail.com
I have followed the instructions that come with it, though it seems there is something I am missing. the installation is on my localhost.
|
[
"Are you supplying an email address or URL? OpenID needs a URL and *******@gmail.com is an email address.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"openid",
"python"
] |
stackoverflow_0002520144_django_openid_python.txt
|
Q:
Avoid IF statement after condition has been met
I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.
I have an if condition to test the divisor value in order to avoid the div by zero, but I am wondering that there is a performance impact that evaluating this if will have for each run in subsequent loops, especially since I know it's of no use anymore.
How should this be coded? in Python?
A:
Don't worry. An if (a != 0) is cheap.
The alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).
A:
I would wrap your call in try/except blocks. They are very cheap in python, and cost about as much as a pass statement if an exception isn't thrown. Python is designed so that you should make your calls and parse any errors instead of always asking permission.
Example code:
def print_divide(x,y):
try:
print x/y
except ZeroDivisionError:
pass
A:
I'm with Thilo: I think it should be pretty cheap.
If you really care, you should time the code and find out whether the slight overhead is unacceptable. I suspect not.
|
Avoid IF statement after condition has been met
|
I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.
I have an if condition to test the divisor value in order to avoid the div by zero, but I am wondering that there is a performance impact that evaluating this if will have for each run in subsequent loops, especially since I know it's of no use anymore.
How should this be coded? in Python?
|
[
"Don't worry. An if (a != 0) is cheap.\nThe alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).\n",
"I would wrap your call in try/except blocks. They are very cheap in python, and cost about as much as a pass statement if an exception isn't thrown. Python is designed so that you should make your calls and parse any errors instead of always asking permission.\nExample code:\ndef print_divide(x,y):\n try:\n print x/y\n except ZeroDivisionError:\n pass\n\n",
"I'm with Thilo: I think it should be pretty cheap.\nIf you really care, you should time the code and find out whether the slight overhead is unacceptable. I suspect not.\n"
] |
[
9,
6,
1
] |
[] |
[] |
[
"if_statement",
"performance",
"python"
] |
stackoverflow_0002521558_if_statement_performance_python.txt
|
Q:
scoping error in recursive closure
why does this work:
def function1():
a = 10
def function2():
print a
function2()
but this does not:
def function1():
a = 10
def function2():
print a
a -= 1
if a>0:
function2()
function2()
I get this error:
UnboundLocalError: local variable 'a' referenced before assignment
A:
The error doesn't seem to be very descriptive of the root problem. Mike explains the messages but that does not explain the root cause.
The actual problem is that in python you cannot assign to closed over variables. So in function2 'a' is read only. When you assign to it you create a new variable which, as Mike points out, you read before you write.
If you want to assign to the to the outer variable from the inner scope you have to cheat like so:
def function1():
al = [10]
def function2():
print al[0]
al[0] -= 1
if al[0]>0:
function2()
function2()
So al is immutable but its contents are not and you can change them without creating a new variable.
A:
It should be noted that this is a syntax glitch in Python. Python itself (at the bytecode level) can assign to these variables just fine; there's simply no syntax in 2.x to indicate that you want to do so. It assumes that if you assign to a variable in a nesting level, you mean for it to be a local to it.
This is a huge shortcoming; being able to assign to closures is fundamental. I've worked around this with charlieb's hack several times.
Python 3 fixes this with the very awkwardly-named "nonlocal" keyword:
def function1():
a = 10
def function2():
nonlocal a
print(a)
a -= 1
if a>0:
function2()
function2()
function1()
It's very poor that this syntax is only available in 3.x; most people are stuck in 2.x, and have to continue using hacks to work around this problem. This badly needs to be backported to 2.x.
http://www.python.org/dev/peps/pep-3104/
A:
In the non-working snippet, you assign to a when you say "a -= 1". Because of that, inside function2, a is local to that scope, not taken the enclosing scope. Python's closures are lexical—it does not dynamically look for a in function2's frame and if it has not been assigned go and look for it in function1's frame.
Note that this doesn't depend on the recursiveness or using closures at all. Consider the example of this function
def foo():
print a
a = 4
Calling it will get you an UnboundLocalError too. (Without a = 4 it would either use the global a or, if there isn't one, raise a NameError.) Because a is potentially assigned within that scope, it is local.
If I was designing this function, I might use an approach more like
def function1():
a = 10
def function2(a=a):
print a
a -= 1
if a > 0:
function2(a)
function2()
(or of course for a in xrange(10, -1, -1): print a ;-) )
|
scoping error in recursive closure
|
why does this work:
def function1():
a = 10
def function2():
print a
function2()
but this does not:
def function1():
a = 10
def function2():
print a
a -= 1
if a>0:
function2()
function2()
I get this error:
UnboundLocalError: local variable 'a' referenced before assignment
|
[
"The error doesn't seem to be very descriptive of the root problem. Mike explains the messages but that does not explain the root cause.\nThe actual problem is that in python you cannot assign to closed over variables. So in function2 'a' is read only. When you assign to it you create a new variable which, as Mike points out, you read before you write.\nIf you want to assign to the to the outer variable from the inner scope you have to cheat like so:\ndef function1():\n al = [10]\n def function2():\n print al[0]\n al[0] -= 1\n if al[0]>0:\n function2()\n function2()\n\nSo al is immutable but its contents are not and you can change them without creating a new variable.\n",
"It should be noted that this is a syntax glitch in Python. Python itself (at the bytecode level) can assign to these variables just fine; there's simply no syntax in 2.x to indicate that you want to do so. It assumes that if you assign to a variable in a nesting level, you mean for it to be a local to it.\nThis is a huge shortcoming; being able to assign to closures is fundamental. I've worked around this with charlieb's hack several times.\nPython 3 fixes this with the very awkwardly-named \"nonlocal\" keyword:\ndef function1():\n a = 10\n def function2():\n nonlocal a\n print(a)\n a -= 1\n if a>0:\n function2()\n function2()\nfunction1()\n\nIt's very poor that this syntax is only available in 3.x; most people are stuck in 2.x, and have to continue using hacks to work around this problem. This badly needs to be backported to 2.x.\nhttp://www.python.org/dev/peps/pep-3104/\n",
"In the non-working snippet, you assign to a when you say \"a -= 1\". Because of that, inside function2, a is local to that scope, not taken the enclosing scope. Python's closures are lexical—it does not dynamically look for a in function2's frame and if it has not been assigned go and look for it in function1's frame.\nNote that this doesn't depend on the recursiveness or using closures at all. Consider the example of this function\ndef foo():\n print a\n a = 4\n\nCalling it will get you an UnboundLocalError too. (Without a = 4 it would either use the global a or, if there isn't one, raise a NameError.) Because a is potentially assigned within that scope, it is local.\n\nIf I was designing this function, I might use an approach more like\ndef function1():\n a = 10\n def function2(a=a):\n print a\n a -= 1\n if a > 0:\n function2(a)\n function2()\n\n(or of course for a in xrange(10, -1, -1): print a ;-) )\n"
] |
[
14,
5,
3
] |
[] |
[] |
[
"closures",
"python",
"recursion",
"scope"
] |
stackoverflow_0002516652_closures_python_recursion_scope.txt
|
Q:
Possible to use Python with Intel's Atom Developer SDK (C/C++)?
So I've made a game in Python and PyGame. Now I'm interested in submitting the game to Intel's March Developer Challenge. However, the developer challenge requires use of Intel's Atom Developer SDK (http://appdeveloper.intel.com/en-us/sdk), which only has API's for C and C++.
I'm new to Python and PyGame, and have no experience in C or C++. My question is, would it be possible to somehow implement Intel's Atom SDK through/with/from a Python application (as the first link above suggests)?
I've read up a little bit on embedding/extending Python into/with C, but I'm not entirely sure what to embed or where. I mean, I know I can do things like this in C:
#include <Python.h>
int
main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
But what do I do about all my dependencies on Python and Pygame, for people that don't have those installed on their machines? Normally Py2Exe takes care of compacting the required dependencies (I've managed to package my game into an exe/zip), but how do I take care of that stuff in the context of embedding within C? Can I somehow work with py2exe on this, or do I need to do something entirely different for embedding within C?
It seems like it would be a lot easier to go the route of extending Python with the C validation code, rather than trying to embed my whole game within C, but I think that's not an option, "because the library provided is currently only available as a Visual Studio 2008 '.lib'", meaning the application has to be compiled with Visual Studio...?
Any help, thoughts, or ideas are much appreciated!
You can find the complete SDK Developer's Guide on the intel site above, but here is their "Hello World" using the C Language API:
#include <stdio.h>
#include “adpcore.h”
int main( int argc, char* argv[] )
{
ADP_RET_CODE ret_code;
const ADP_APPLICATIONID myApplicationID = {{
0x12345678,0x11112222,0x33331234,0x567890ab}};
if ((ret_code = ADP_Initialize()) != ADP_SUCCESS ){
printf( “ERROR: exiting” );
exit( -1 );
}
if (( ret_code = ADP_IsAuthorized( myApplicationId )) == ADP_AUTHORIZED )
printf( “Hello World” );
else
printf( “Not authorized to run” );
exit 0;
}
35 Page SDK Developer Guide: http:// appdeveloper.intel.com/sites/files/pages/SDK%20Developer%20Guide.pdf
A:
Don't drop down to bare C if you can help it. Write bindings using Cython.
|
Possible to use Python with Intel's Atom Developer SDK (C/C++)?
|
So I've made a game in Python and PyGame. Now I'm interested in submitting the game to Intel's March Developer Challenge. However, the developer challenge requires use of Intel's Atom Developer SDK (http://appdeveloper.intel.com/en-us/sdk), which only has API's for C and C++.
I'm new to Python and PyGame, and have no experience in C or C++. My question is, would it be possible to somehow implement Intel's Atom SDK through/with/from a Python application (as the first link above suggests)?
I've read up a little bit on embedding/extending Python into/with C, but I'm not entirely sure what to embed or where. I mean, I know I can do things like this in C:
#include <Python.h>
int
main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
But what do I do about all my dependencies on Python and Pygame, for people that don't have those installed on their machines? Normally Py2Exe takes care of compacting the required dependencies (I've managed to package my game into an exe/zip), but how do I take care of that stuff in the context of embedding within C? Can I somehow work with py2exe on this, or do I need to do something entirely different for embedding within C?
It seems like it would be a lot easier to go the route of extending Python with the C validation code, rather than trying to embed my whole game within C, but I think that's not an option, "because the library provided is currently only available as a Visual Studio 2008 '.lib'", meaning the application has to be compiled with Visual Studio...?
Any help, thoughts, or ideas are much appreciated!
You can find the complete SDK Developer's Guide on the intel site above, but here is their "Hello World" using the C Language API:
#include <stdio.h>
#include “adpcore.h”
int main( int argc, char* argv[] )
{
ADP_RET_CODE ret_code;
const ADP_APPLICATIONID myApplicationID = {{
0x12345678,0x11112222,0x33331234,0x567890ab}};
if ((ret_code = ADP_Initialize()) != ADP_SUCCESS ){
printf( “ERROR: exiting” );
exit( -1 );
}
if (( ret_code = ADP_IsAuthorized( myApplicationId )) == ADP_AUTHORIZED )
printf( “Hello World” );
else
printf( “Not authorized to run” );
exit 0;
}
35 Page SDK Developer Guide: http:// appdeveloper.intel.com/sites/files/pages/SDK%20Developer%20Guide.pdf
|
[
"Don't drop down to bare C if you can help it. Write bindings using Cython.\n"
] |
[
1
] |
[] |
[] |
[
"c",
"intel_atom",
"pygame",
"python",
"visual_studio"
] |
stackoverflow_0002521774_c_intel_atom_pygame_python_visual_studio.txt
|
Q:
Problem simulating a key press on Python for Symbian platform on a Nokia 5th ed phone
I am developing an app for Nokia 5800 Music Express (S60 5th edition) using PyS60 (Python for S60) ,I want to simulate a KeyPress say if a message comes,I detect a message and Press a Key.
There does exist a Keypress module for PyS60 for 2nd edition phones which allows this. However I have not been able to install it on my 5th ed phone. Is this module portable? If yes then how do I install it (I get certificate error) and If no then any alternatives for simulating a key press on a 5th edition touch phone?
A:
There are compatibility breaks between 2nd and 3rd editions so binaries developed on one won't work on the other.
There's also a keypress module for 3rd edition. It should also work on 5th edition but I haven't tested it myself.
|
Problem simulating a key press on Python for Symbian platform on a Nokia 5th ed phone
|
I am developing an app for Nokia 5800 Music Express (S60 5th edition) using PyS60 (Python for S60) ,I want to simulate a KeyPress say if a message comes,I detect a message and Press a Key.
There does exist a Keypress module for PyS60 for 2nd edition phones which allows this. However I have not been able to install it on my 5th ed phone. Is this module portable? If yes then how do I install it (I get certificate error) and If no then any alternatives for simulating a key press on a 5th edition touch phone?
|
[
"There are compatibility breaks between 2nd and 3rd editions so binaries developed on one won't work on the other.\nThere's also a keypress module for 3rd edition. It should also work on 5th edition but I haven't tested it myself.\n"
] |
[
0
] |
[] |
[] |
[
"nokia",
"pys60",
"python",
"symbian"
] |
stackoverflow_0002522033_nokia_pys60_python_symbian.txt
|
Q:
Query for model by key
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the user we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.
A:
There's a really easy way around this: Retrieve two records, and filter out the user's own one, if it's present.
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
other = db.Query(User).filter('partner =', None).fetch(2)
other = [u for u in other if u.key() != user.key()]
if other:
# connect user with other[0]
else:
# no one to connect to!
|
Query for model by key
|
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the user we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.
|
[
"There's a really easy way around this: Retrieve two records, and filter out the user's own one, if it's present.\ndef text_message(self, msg):\n user = User.get_or_insert(msg.sender)\n\n if not user.partner:\n # user doesn't have a partner, find them one\n other = db.Query(User).filter('partner =', None).fetch(2)\n other = [u for u in other if u.key() != user.key()]\n if other:\n # connect user with other[0]\n else:\n # no one to connect to!\n\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002521012_google_app_engine_google_cloud_datastore_python.txt
|
Q:
How to reduce latency of data sent through a REST api
I have an application which obtains data in JSON format from one of our other servers. The problem I am facing is, there is is significant delay when when requesting for this information. Since a lot of data is passed (approx 1000 records per request where each record is pretty huge) is there a way that compression would help reducing the speed. If so which compression scheme would you recommend.
I read on another thread that they pattern of data also matters a lot on they type of compression that needs to be used. The pattern of data is consistent and resembles the following
:desc=>some_description
:url=>some_url
:content=>some_content
:score=>some_score
:more_attributes=>more_data
Can someone recommend a solution to how I could reduce this delay. They delay is approx 6-8 seconds. I'm using Ruby on Rails to develop this application and the server providing the data uses Python for the most part.
A:
I would first look at how much of this 8s delay is related to:
Server side processing (how much took for the data to be generated)
There are a lot of techniques to improve this time, including:
DB indexes
caching
a faster to_json library
Some excellent resources are the NewRelic podcasts on Rails scalability http://railslab.newrelic.com/2009/02/09/episode-7-fragment-caching
Transmission delay(how much time took for the data to be sent between the server and the client)
if the keys are pretty much the same, you may implement the sollution from Compression algorithm for JSON encoded packets? ; You may want to look at https://github.com/WebReflection/json.hpack/wiki/specs-details and http://www.nwhite.net/?p=242
in addition to this, you may also compress (gzip) it from your frontend server
http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
http://wiki.nginx.org/NginxHttpGzipModule
If the data structure is constant and you can also try to implement a binary service, that is much much faster, includes compression, but also more difficult to mantain, like thrift:
http://www.igvita.com/2007/11/30/ruby-web-services-with-facebooks-thrift/
If this is suitable to your needs, maybe you can make some kind of a versioning/cache system server-side, and send only the records that were modified (but that is pretty heavy to implement)
A:
gzip might significantly reduce the size of text data and optimize load speeds. It's also recommended by YSlow.
|
How to reduce latency of data sent through a REST api
|
I have an application which obtains data in JSON format from one of our other servers. The problem I am facing is, there is is significant delay when when requesting for this information. Since a lot of data is passed (approx 1000 records per request where each record is pretty huge) is there a way that compression would help reducing the speed. If so which compression scheme would you recommend.
I read on another thread that they pattern of data also matters a lot on they type of compression that needs to be used. The pattern of data is consistent and resembles the following
:desc=>some_description
:url=>some_url
:content=>some_content
:score=>some_score
:more_attributes=>more_data
Can someone recommend a solution to how I could reduce this delay. They delay is approx 6-8 seconds. I'm using Ruby on Rails to develop this application and the server providing the data uses Python for the most part.
|
[
"I would first look at how much of this 8s delay is related to:\n\nServer side processing (how much took for the data to be generated)\nThere are a lot of techniques to improve this time, including:\n\nDB indexes\ncaching\na faster to_json library\n\n\nSome excellent resources are the NewRelic podcasts on Rails scalability http://railslab.newrelic.com/2009/02/09/episode-7-fragment-caching\n\nTransmission delay(how much time took for the data to be sent between the server and the client)\n\nif the keys are pretty much the same, you may implement the sollution from Compression algorithm for JSON encoded packets? ; You may want to look at https://github.com/WebReflection/json.hpack/wiki/specs-details and http://www.nwhite.net/?p=242 \nin addition to this, you may also compress (gzip) it from your frontend server\nhttp://httpd.apache.org/docs/2.0/mod/mod_deflate.html\nhttp://wiki.nginx.org/NginxHttpGzipModule\nIf the data structure is constant and you can also try to implement a binary service, that is much much faster, includes compression, but also more difficult to mantain, like thrift:\nhttp://www.igvita.com/2007/11/30/ruby-web-services-with-facebooks-thrift/\nIf this is suitable to your needs, maybe you can make some kind of a versioning/cache system server-side, and send only the records that were modified (but that is pretty heavy to implement)\n\n\n",
"gzip might significantly reduce the size of text data and optimize load speeds. It's also recommended by YSlow.\n"
] |
[
6,
3
] |
[] |
[] |
[
"compression",
"latency",
"networking",
"python",
"ruby_on_rails"
] |
stackoverflow_0002522204_compression_latency_networking_python_ruby_on_rails.txt
|
Q:
does cProfile profile calls inside threads?
I ran cprofile on a bit of code, which among other things spawns several threads that do most of the work.
When I looked at the output of the profiling, I see no logging of all the functions that were called inside the threads. I am sure they were called, as they do stuff that is easy to see such as writing to a DB etc.
Does cProfile not profile threads? Am I missing something?
A:
Found the answer here: link
It's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the profiler documentation.
If you also want to profile threads, you'll want to look at the threading.setprofile() function in the docs.
|
does cProfile profile calls inside threads?
|
I ran cprofile on a bit of code, which among other things spawns several threads that do most of the work.
When I looked at the output of the profiling, I see no logging of all the functions that were called inside the threads. I am sure they were called, as they do stuff that is easy to see such as writing to a DB etc.
Does cProfile not profile threads? Am I missing something?
|
[
"Found the answer here: link\n\nIt's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the profiler documentation.\n If you also want to profile threads, you'll want to look at the threading.setprofile() function in the docs.\n\n"
] |
[
8
] |
[] |
[] |
[
"cprofile",
"multithreading",
"python"
] |
stackoverflow_0002522452_cprofile_multithreading_python.txt
|
Q:
Is it possible to autoload a file based on the namespace in PHP?
Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.
index.php
<?php
use Hello\World;
World::greet();
Hello/World.php
<?php
namespace Hello\World;
function greet() { echo 'Hello, World!'; }
Would this be possible?
A:
Yes, have a look at the example of spl_autoload_register
namespace Foobar;
class Foo {
static public function test($name) {
print '[['. $name .']]';
}
}
spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
new InexistentClass;
The above example will output something similar to:
[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...
Here is a link to a Autoloader builder, that
is a command line application to automate the process of generating an autoload include file.
|
Is it possible to autoload a file based on the namespace in PHP?
|
Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.
index.php
<?php
use Hello\World;
World::greet();
Hello/World.php
<?php
namespace Hello\World;
function greet() { echo 'Hello, World!'; }
Would this be possible?
|
[
"Yes, have a look at the example of spl_autoload_register\nnamespace Foobar;\n\nclass Foo {\n static public function test($name) {\n print '[['. $name .']]';\n }\n}\n\nspl_autoload_register(__NAMESPACE__ .'\\Foo::test'); // As of PHP 5.3.0\n\nnew InexistentClass;\n\n\nThe above example will output something similar to:\n\n[[Foobar\\InexistentClass]]\nFatal error: Class 'Foobar\\InexistentClass' not found in ...\n\n\nHere is a link to a Autoloader builder, that\n\nis a command line application to automate the process of generating an autoload include file.\n\n"
] |
[
5
] |
[] |
[] |
[
"autoload",
"module",
"namespaces",
"php",
"python"
] |
stackoverflow_0002522801_autoload_module_namespaces_php_python.txt
|
Q:
Iterating over consecutive sublists in Python
Does Python offer a way to iterate over all "consecutive sublists" of a given list L - i.e. sublists of L where any two consecutive elements are also consecutive in L - or should I write my own?
(Example: if L = [1, 2, 3], then the set over which I want to iterate is {[1], [2], [3], [1, 2], [2,3], [1, 2, 3]}. [1, 3] is skipped since 1 and 3 are not consecutive in L.)
A:
I don't think there's a built-in for exactly that; but it probably wouldn't be too difficult to code up by hand - you're basically just looping through all of the possible lengths from 1 to L.length, and then taking all substrings of each length.
You could probably use itertools.chain() to combine the sequences for each length of substring together into a generator for all of them.
Example:
>>> a = [1,2,3,4]
>>> list(
... itertools.chain(
... *[[a[i:i+q] for q in xrange(1,len(a)-i+1)] for i in xrange(len(a))]
... )
... )
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
If you prefer them in the increasing-length-and-then-lexographical-order sequence that you described, you'd want this instead:
itertools.chain(*[[a[q:i+q] for q in xrange(len(a)-i+1)] for i in xrange(1,len(a)+1)])
A:
This should work:
def sublists(lst):
for sublen in xrange(1,len(lst)+1):
for idx in xrange(0,len(lst)-sublen+1):
yield lst[idx:idx+sublen]
A:
Try something like this:
def iter_sublists(l):
n = len(l)+1
for i in xrange(n):
for j in xrange(i+1, n):
yield l[i:j]
>>> print list(iter_sublists([1,2,3]))
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
|
Iterating over consecutive sublists in Python
|
Does Python offer a way to iterate over all "consecutive sublists" of a given list L - i.e. sublists of L where any two consecutive elements are also consecutive in L - or should I write my own?
(Example: if L = [1, 2, 3], then the set over which I want to iterate is {[1], [2], [3], [1, 2], [2,3], [1, 2, 3]}. [1, 3] is skipped since 1 and 3 are not consecutive in L.)
|
[
"I don't think there's a built-in for exactly that; but it probably wouldn't be too difficult to code up by hand - you're basically just looping through all of the possible lengths from 1 to L.length, and then taking all substrings of each length.\nYou could probably use itertools.chain() to combine the sequences for each length of substring together into a generator for all of them.\nExample:\n>>> a = [1,2,3,4]\n>>> list(\n... itertools.chain(\n... *[[a[i:i+q] for q in xrange(1,len(a)-i+1)] for i in xrange(len(a))]\n... )\n... )\n[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]\n\nIf you prefer them in the increasing-length-and-then-lexographical-order sequence that you described, you'd want this instead:\nitertools.chain(*[[a[q:i+q] for q in xrange(len(a)-i+1)] for i in xrange(1,len(a)+1)])\n\n",
"This should work:\ndef sublists(lst):\n for sublen in xrange(1,len(lst)+1):\n for idx in xrange(0,len(lst)-sublen+1):\n yield lst[idx:idx+sublen]\n\n",
"Try something like this:\ndef iter_sublists(l):\n n = len(l)+1\n for i in xrange(n):\n for j in xrange(i+1, n):\n yield l[i:j]\n\n>>> print list(iter_sublists([1,2,3]))\n[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"iterator",
"python"
] |
stackoverflow_0002523236_iterator_python.txt
|
Q:
requiring set of files to be made before running function in Ruffus pipeline
I'm using ruffus to write a pipeline. I have a function that gets called in parallel many times and it creates several files. I'd like to make a function "combineFiles()" that gets called after all those files have been made. Since they run in parallel on a cluster, they will not all finish together. I wrote a function 'getFilenames()' that returns the set of filenames that need to be created, but how can I make combineFiles() wait for them to be there?
I tried the following:
@pipelineFunction
@files(getFilenames)
def combineFiles(filenames):
# I should only be called if every file in the list 'filenames' exists
I've also tried the decorator:
@merge(getFilenames)
but this does not work either. combineFiles still gets errorneously called before the files given by getFilenames are made. How can I make combineFiles conditional on those files being there?
thanks.
A:
I am the developer of Ruffus. I am not sure I entirely understand what you are trying to do but here goes:
Waiting for jobs which take a different amount of time to finish in order to run the next stage of your pipeline is exactly what Ruffus is about so this hopefully is straightforward.
The first question is do you know which files are being created up front, i.e. before the pipeline is run? Lets start by assuming you do.
from ruffus import *
filenames = ["one.file", "two.file", "three.file"]
Let us write a dummy function which creates a file each time it is called. In Ruffus, any input and output file names are contained in the first two parameters respectively. We have no input file name, so our function calls should look like this:
create_file(None, "one.file")
create_file(None, "two.file")
create_file(None, "three.file")
The definition of create_file would look like this:
@files([(None, fn) for fn in filenames])
def create_file(no_input_file_name, output_file_name):
open(output_file_name, "w").write("dummy file")
Each of these files would be created in 3 separate calls to create_file. These can be run in parallel if you wish.
pipeline_run([create_file], multiprocess = 5)
Now to combine the files. The "@Merge" decorator is indeed set up precisely for this. We just need to link it up to the previous function :
@merge(create_file, "merge.file")
def merge_file(input_file_names, output_file_name):
output_file = open(output_file_name, "w")
for i in input_file_names:
output_file.write(open(i).read())
This will only call merge_file when all the files are ready from the three calls to create_file().
The entire code is as follows:
from ruffus import *
filenames = ["one.file", "two.file", "three.file"]
from random import randint
from time import sleep
@files([(None, fn) for fn in filenames])
def create_file(no_input_file_name, output_file_name):
# simulate create file process of indeterminate complexity
sleep(randint(1,5))
open(output_file_name, "w").write("dummy file")
@merge(create_file, "merge.file")
def merge_file(input_file_names, output_file_name):
output_file = open(output_file_name, "w")
for i in input_file_names:
output_file.write(open(i).read())
pipeline_run([merge_file], multiprocess = 5)
And this is the result:
>>> pipeline_run([merge_file], multiprocess = 5)
Job = [None -> two.file] completed
Job = [None -> three.file] completed
Job = [None -> one.file] completed
Completed Task = create_file
Job = [[one.file, three.file, two.file] -> merge.file] completed
Completed Task = merge_file
|
requiring set of files to be made before running function in Ruffus pipeline
|
I'm using ruffus to write a pipeline. I have a function that gets called in parallel many times and it creates several files. I'd like to make a function "combineFiles()" that gets called after all those files have been made. Since they run in parallel on a cluster, they will not all finish together. I wrote a function 'getFilenames()' that returns the set of filenames that need to be created, but how can I make combineFiles() wait for them to be there?
I tried the following:
@pipelineFunction
@files(getFilenames)
def combineFiles(filenames):
# I should only be called if every file in the list 'filenames' exists
I've also tried the decorator:
@merge(getFilenames)
but this does not work either. combineFiles still gets errorneously called before the files given by getFilenames are made. How can I make combineFiles conditional on those files being there?
thanks.
|
[
"I am the developer of Ruffus. I am not sure I entirely understand what you are trying to do but here goes:\nWaiting for jobs which take a different amount of time to finish in order to run the next stage of your pipeline is exactly what Ruffus is about so this hopefully is straightforward.\nThe first question is do you know which files are being created up front, i.e. before the pipeline is run? Lets start by assuming you do.\nfrom ruffus import *\nfilenames = [\"one.file\", \"two.file\", \"three.file\"]\n\nLet us write a dummy function which creates a file each time it is called. In Ruffus, any input and output file names are contained in the first two parameters respectively. We have no input file name, so our function calls should look like this:\ncreate_file(None, \"one.file\")\ncreate_file(None, \"two.file\")\ncreate_file(None, \"three.file\")\n\nThe definition of create_file would look like this:\n@files([(None, fn) for fn in filenames])\ndef create_file(no_input_file_name, output_file_name):\n open(output_file_name, \"w\").write(\"dummy file\")\n\nEach of these files would be created in 3 separate calls to create_file. These can be run in parallel if you wish.\npipeline_run([create_file], multiprocess = 5)\n\nNow to combine the files. The \"@Merge\" decorator is indeed set up precisely for this. We just need to link it up to the previous function :\n@merge(create_file, \"merge.file\")\ndef merge_file(input_file_names, output_file_name):\n output_file = open(output_file_name, \"w\")\n for i in input_file_names:\n output_file.write(open(i).read())\n\nThis will only call merge_file when all the files are ready from the three calls to create_file().\nThe entire code is as follows:\nfrom ruffus import *\nfilenames = [\"one.file\", \"two.file\", \"three.file\"]\n\nfrom random import randint\nfrom time import sleep\n\n@files([(None, fn) for fn in filenames])\ndef create_file(no_input_file_name, output_file_name):\n # simulate create file process of indeterminate complexity\n sleep(randint(1,5))\n open(output_file_name, \"w\").write(\"dummy file\")\n\n@merge(create_file, \"merge.file\")\ndef merge_file(input_file_names, output_file_name):\n output_file = open(output_file_name, \"w\")\n for i in input_file_names:\n output_file.write(open(i).read())\n\n\npipeline_run([merge_file], multiprocess = 5)\n\nAnd this is the result:\n>>> pipeline_run([merge_file], multiprocess = 5)\n\n Job = [None -> two.file] completed\n Job = [None -> three.file] completed\n Job = [None -> one.file] completed\nCompleted Task = create_file\n Job = [[one.file, three.file, two.file] -> merge.file] completed\nCompleted Task = merge_file\n\n"
] |
[
2
] |
[] |
[] |
[
"cluster_computing",
"distributed_computing",
"pipeline",
"python",
"ruffus"
] |
stackoverflow_0002465953_cluster_computing_distributed_computing_pipeline_python_ruffus.txt
|
Q:
Proper way to set object instance variables
I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean:
class User(object):
def setName(self,name):
#Do sanity checks on name
self._name = name
def setPassword(self,password):
#Check password length > 6 characters
#Encrypt to md5
self._password = password
def commit(self):
#Commit to database
>>u = User()
>>u.setName('Jason Martinez')
>>u.setPassword('linebreak')
>>u.commit()
Is this the right approach?
Should I declare class variables up top?
Should I use a _ in front of all the class variables to make them private?
Thanks for helping out.
A:
It's generally correct, AFAIK, but you could clean it up with properties.
class User(object):
def _setName(self, name=None):
self._name = name
def _getName(self):
return self._name
def _setPassword(self, password):
self._password = password
def _getPassword(self):
return self._password
def commit(self):
pass
name = property(_getName, _setName)
password = property(_getPassword, _setPassword)
>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()
There's a also a convenient decorator-based syntax, the docs explain that too.
A:
using a single _ does not make your attributes private: it is a convention telling that it is an internal attribute and should not under normal circumstances be accessed by external code. With your code it also means password and name are read only.
I strongly suggest using an initialiser for your class which will initialize your attributes, even if to a default value such as None : it will make things easier in you commit method where you won't have to check for the existence of the _name and _password attributes (with hasattr).
Use Pylint on your code.
A:
There are no class variables in that code, only instance attributes. And use properties instead of accessors. And do create the instance attributes in the initializer, preferably from values passed in:
class User(object):
def __init__(self, name, password='!!'):
self.name = name
self.password = password
...
A:
Others already pointed that out: avoid using setters and getters and use simple attribute access if you don't need to perform additional logic when getting/setting your attribute.
If you do need that additional logic then use properties.
If you have many parameters to pass to an instance initializer consider using separate object or dictionary holding all parameters:
>>> class User(object):
... def __init__(self, params):
... self.__dict__.update(params)
...
>>> params = {
... 'username': 'john',
... 'password': 'linebreak',
... }
>>> user = User(params)
>>> user.username
'john'
>>> user.password
'linebreak'
P.S. In your case you don't need to declare your attributes at the class level.
Usually that's done if you want to share the same value across all class instances:
>>> class User(object):
... type = 'superuser'
...
>>> user = User()
>>> user2 = User()
>>>
>>> user.type
'superuser'
>>> user2.type
'superuser'
>>>
>>> user2.type = 'instance superuser'
>>>
>>> user.type
'superuser'
>>> user2.type
'instance superuser'
>>> User.type
'superuser'
|
Proper way to set object instance variables
|
I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean:
class User(object):
def setName(self,name):
#Do sanity checks on name
self._name = name
def setPassword(self,password):
#Check password length > 6 characters
#Encrypt to md5
self._password = password
def commit(self):
#Commit to database
>>u = User()
>>u.setName('Jason Martinez')
>>u.setPassword('linebreak')
>>u.commit()
Is this the right approach?
Should I declare class variables up top?
Should I use a _ in front of all the class variables to make them private?
Thanks for helping out.
|
[
"It's generally correct, AFAIK, but you could clean it up with properties.\nclass User(object):\n\n def _setName(self, name=None):\n self._name = name\n\n def _getName(self):\n return self._name\n\n def _setPassword(self, password):\n self._password = password\n\n def _getPassword(self):\n return self._password\n\n def commit(self):\n pass\n\n name = property(_getName, _setName)\n password = property(_getPassword, _setPassword)\n\n>>u = User()\n>>u.name = 'Jason Martinez'\n>>u.password = 'linebreak'\n>>u.commit()\n\nThere's a also a convenient decorator-based syntax, the docs explain that too.\n",
"using a single _ does not make your attributes private: it is a convention telling that it is an internal attribute and should not under normal circumstances be accessed by external code. With your code it also means password and name are read only. \nI strongly suggest using an initialiser for your class which will initialize your attributes, even if to a default value such as None : it will make things easier in you commit method where you won't have to check for the existence of the _name and _password attributes (with hasattr). \nUse Pylint on your code. \n",
"There are no class variables in that code, only instance attributes. And use properties instead of accessors. And do create the instance attributes in the initializer, preferably from values passed in:\nclass User(object):\n def __init__(self, name, password='!!'):\n self.name = name\n self.password = password\n\n ...\n\n",
"Others already pointed that out: avoid using setters and getters and use simple attribute access if you don't need to perform additional logic when getting/setting your attribute.\nIf you do need that additional logic then use properties.\nIf you have many parameters to pass to an instance initializer consider using separate object or dictionary holding all parameters:\n>>> class User(object):\n... def __init__(self, params):\n... self.__dict__.update(params)\n... \n\n>>> params = {\n... 'username': 'john',\n... 'password': 'linebreak',\n... }\n>>> user = User(params)\n>>> user.username\n'john'\n>>> user.password\n'linebreak'\n\nP.S. In your case you don't need to declare your attributes at the class level.\nUsually that's done if you want to share the same value across all class instances:\n>>> class User(object):\n... type = 'superuser'\n... \n>>> user = User()\n>>> user2 = User()\n>>> \n>>> user.type\n'superuser'\n>>> user2.type\n'superuser'\n>>> \n>>> user2.type = 'instance superuser'\n>>> \n>>> user.type\n'superuser'\n>>> user2.type\n'instance superuser'\n>>> User.type\n'superuser'\n\n"
] |
[
23,
9,
3,
2
] |
[] |
[] |
[
"oop",
"pylons",
"python"
] |
stackoverflow_0002521753_oop_pylons_python.txt
|
Q:
Easiest ways to generate graphs from Python?
I'm using Python to process CSV files filled with data that I want to run calculations on, and then graph. I'm looking for a library to use that I can send processed CSV information to, or a dict of some sort, and then choose different graphing styles with.
Does anyone have any recommendations?
A:
I'm personally using matplotlib and am very happy with it.
A:
Matplotlib and Gnuplot.py are popular choices. I've used both.
A:
For client-side charts Open Flash Chart or Google Charts Tools.
A:
I've been using matplotlib for about 3 years now to plot experimental data. Before I was using Excel and that was just a pain. I've been happy with matplotlib ever since. It's great and very powerful.
A:
There is pychart or PyCha, both of which I have not used but have been considering myself.
A:
It depends on the kind of graph you want,
most of the time, i'm using matplotlib but sometimespydot is good.
The various layout algorithms are good for me when dealing with huge graphs
|
Easiest ways to generate graphs from Python?
|
I'm using Python to process CSV files filled with data that I want to run calculations on, and then graph. I'm looking for a library to use that I can send processed CSV information to, or a dict of some sort, and then choose different graphing styles with.
Does anyone have any recommendations?
|
[
"I'm personally using matplotlib and am very happy with it.\n",
"Matplotlib and Gnuplot.py are popular choices. I've used both.\n",
"For client-side charts Open Flash Chart or Google Charts Tools.\n",
"I've been using matplotlib for about 3 years now to plot experimental data. Before I was using Excel and that was just a pain. I've been happy with matplotlib ever since. It's great and very powerful.\n",
"There is pychart or PyCha, both of which I have not used but have been considering myself. \n",
"It depends on the kind of graph you want,\nmost of the time, i'm using matplotlib but sometimespydot is good.\nThe various layout algorithms are good for me when dealing with huge graphs\n"
] |
[
10,
7,
4,
3,
1,
1
] |
[] |
[] |
[
"google_visualization",
"graph",
"python",
"visualization"
] |
stackoverflow_0002523689_google_visualization_graph_python_visualization.txt
|
Q:
LXML E builder for java?
There is one thing I really love about LXML, and that the E builder. I love that I can throw XML together like this:
message = E.Person(
E.Name(
E.First("jack")
E.Last("Ripper")
)
E.PhoneNumber("555-555-5555")
)
To make:
<Person>
<Name>
<First>Jack</First>
<Last>Ripper</Last>
</Name>
<PhoneNumber>555-555-5555</PhoneNumber>
</Person>
As opposed to the painstaking way DOM works.
I am going to be moving a bunch of my software to Java soon and it is very very heavy on its usage of E. Does Java have anything near equivalent to that usage?
A:
will be hard with pure Java, but if you can use Groovy in your projects then you could use the MarkupBuilder which comes very close to what you're asking for
def xml = new MarkupBuilder(writer)
xml.records() {
car(name:'HSV Maloo', make:'Holden', year:2006) {
country('Australia')
record(type:'speed', 'Production Pickup Truck with speed of 271kph')
}
}
|
LXML E builder for java?
|
There is one thing I really love about LXML, and that the E builder. I love that I can throw XML together like this:
message = E.Person(
E.Name(
E.First("jack")
E.Last("Ripper")
)
E.PhoneNumber("555-555-5555")
)
To make:
<Person>
<Name>
<First>Jack</First>
<Last>Ripper</Last>
</Name>
<PhoneNumber>555-555-5555</PhoneNumber>
</Person>
As opposed to the painstaking way DOM works.
I am going to be moving a bunch of my software to Java soon and it is very very heavy on its usage of E. Does Java have anything near equivalent to that usage?
|
[
"will be hard with pure Java, but if you can use Groovy in your projects then you could use the MarkupBuilder which comes very close to what you're asking for\ndef xml = new MarkupBuilder(writer)\nxml.records() {\n car(name:'HSV Maloo', make:'Holden', year:2006) {\n country('Australia')\n record(type:'speed', 'Production Pickup Truck with speed of 271kph')\n }\n}\n\n"
] |
[
2
] |
[] |
[] |
[
"java",
"lxml",
"python"
] |
stackoverflow_0002523715_java_lxml_python.txt
|
Q:
Python PyQt Timer Firmata
I am pretty new to python and working with firmata I am trying to play around with an arduino .
Here is what I want to happen:
Set arduino up with an LED as a
digital out
Set potentiometer to analog 0
Set PyQt timer up to update
potentiometer position in
application
Set a threshold in PyQt to turn
LED on (Analog in has 1024bit
resolution, so say 800 as the
threshold)
I am using this firmata library : Link
Here is the code that I am having trouble with:
import sys
from PyQt4 import QtCore, QtGui
from firmata import *
# Arduino setup
self.a = Arduino('COM3')
self.a.pin_mode(13, firmata.OUTPUT)
# Create timer
self.appTimer = QtCore.QTimer(self)
self.appTimer.start(100)
self.appTimer.event(self.updateAppTimer())
def updateAppTimer(self):
self.analogPosition = self.a.analog_read(self, 0)
self.ui.lblPositionValue.setNum()
I am getting the error message:
Traceback (most recent call last):
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 138, in
myapp = MainWindow()
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 56, in init
self.appTimer.event(self.updateAppTimer())
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 60, in updateAppTimer
self.analogPosition = self.a.analog_read(self, 0)
TypeError: analog_read() takes exactly 2 arguments (3 given)
If I take 'self' out I get the same error message but that only 1 argument is given
What is python doing implicitly that I am not aware of?
Blockquote
A:
Self didn't need to be passed. I have no clue why it failed the first time, or why self is included already.
A:
In your code 'a' is the class instance, so all methods, bound to it, already have self pointers passed as first params.
Welcome to python, someday you'd like it :)
In contra, you can call any method as unbound (and I'm sure you do it in every constructor of any derived class). Syntax is:
instance = Type()
#bound method.
instance.methodName(params)
#unbound method call, 'instance' is the instance of some object, pointer to witch
#you want to pass to method. These calls are similar.
Type.methodName(instance, params)
|
Python PyQt Timer Firmata
|
I am pretty new to python and working with firmata I am trying to play around with an arduino .
Here is what I want to happen:
Set arduino up with an LED as a
digital out
Set potentiometer to analog 0
Set PyQt timer up to update
potentiometer position in
application
Set a threshold in PyQt to turn
LED on (Analog in has 1024bit
resolution, so say 800 as the
threshold)
I am using this firmata library : Link
Here is the code that I am having trouble with:
import sys
from PyQt4 import QtCore, QtGui
from firmata import *
# Arduino setup
self.a = Arduino('COM3')
self.a.pin_mode(13, firmata.OUTPUT)
# Create timer
self.appTimer = QtCore.QTimer(self)
self.appTimer.start(100)
self.appTimer.event(self.updateAppTimer())
def updateAppTimer(self):
self.analogPosition = self.a.analog_read(self, 0)
self.ui.lblPositionValue.setNum()
I am getting the error message:
Traceback (most recent call last):
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 138, in
myapp = MainWindow()
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 56, in init
self.appTimer.event(self.updateAppTimer())
File "D:\Programming\Eclipse\IO Demo\src\control.py", line 60, in updateAppTimer
self.analogPosition = self.a.analog_read(self, 0)
TypeError: analog_read() takes exactly 2 arguments (3 given)
If I take 'self' out I get the same error message but that only 1 argument is given
What is python doing implicitly that I am not aware of?
Blockquote
|
[
"Self didn't need to be passed. I have no clue why it failed the first time, or why self is included already.\n",
"In your code 'a' is the class instance, so all methods, bound to it, already have self pointers passed as first params. \nWelcome to python, someday you'd like it :)\nIn contra, you can call any method as unbound (and I'm sure you do it in every constructor of any derived class). Syntax is:\ninstance = Type()\n#bound method.\ninstance.methodName(params)\n\n#unbound method call, 'instance' is the instance of some object, pointer to witch\n#you want to pass to method. These calls are similar.\nType.methodName(instance, params)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arduino",
"firmata",
"pyqt",
"python"
] |
stackoverflow_0002519699_arduino_firmata_pyqt_python.txt
|
Q:
How to connect a variable to Entry widget?
I'm trying to associate a variable with a Tkinter entry widget, in a way that:
Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like that first.
Whenever the variable gets changed (by some other part of the programm), I want the entry value displayed to be adjusted automatically. I believe that this could work via the textvariable.
I read the example on http://effbot.org/tkinterbook/entry.htm, but it is not exactly helping me for what I have in mind. I have a feeling that there is a way of ensuring the first condition with using entry's "validate". Any ideas?
A:
I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.
You can also set trace on variables, e.g. to write to stdout.
from tkinter import *
root = Tk()
root.title("MyApp")
myvar = StringVar()
def mywarWritten(*args):
print "mywarWritten",myvar.get()
myvar.trace("w", mywarWritten)
label = Label(root, textvariable=myvar)
label.pack()
text_entry = Entry(root, textvariable=myvar)
text_entry.pack()
root.mainloop()
|
How to connect a variable to Entry widget?
|
I'm trying to associate a variable with a Tkinter entry widget, in a way that:
Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like that first.
Whenever the variable gets changed (by some other part of the programm), I want the entry value displayed to be adjusted automatically. I believe that this could work via the textvariable.
I read the example on http://effbot.org/tkinterbook/entry.htm, but it is not exactly helping me for what I have in mind. I have a feeling that there is a way of ensuring the first condition with using entry's "validate". Any ideas?
|
[
"I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.\nYou can also set trace on variables, e.g. to write to stdout.\nfrom tkinter import *\n\n\nroot = Tk()\nroot.title(\"MyApp\")\n\nmyvar = StringVar()\n\ndef mywarWritten(*args):\n print \"mywarWritten\",myvar.get()\n\nmyvar.trace(\"w\", mywarWritten)\n\nlabel = Label(root, textvariable=myvar)\nlabel.pack()\n\ntext_entry = Entry(root, textvariable=myvar)\ntext_entry.pack()\n\nroot.mainloop()\n\n"
] |
[
15
] |
[] |
[] |
[
"python",
"tkinter",
"tkinter_entry",
"validation",
"variables"
] |
stackoverflow_0002524031_python_tkinter_tkinter_entry_validation_variables.txt
|
Q:
How can I add a code that is always executed by Waf before exit?
I want to make Waf generate a beep when it finishes the execution of any command that took more than 10 seconds.
I don't know how do add this and assure that the code executes when Waf exits.
This should run for any Waf command not only build.
I checked the Waf book but I wasn't able to find any indication about how should I do this.
A:
In your wscript module, you can use the Python standard library's atexit to register callables that you want to be called when the process exit. For example:
import atexit
import time
class MayBeep(object):
def __init__(self, deadline=10.0):
self.deadline = time.time() + deadline
def __call__(self):
if time.time() > self.deadline():
print '\7'
atexit.register(MayBeep())
... rest of your wscript module ...
Of course you may use something better than print '\7' for beeping purposes (all the way to full-fledged multimedia extravaganzas, depending on what other Python extensions you import and use), but this code answers the Q's title -- "add code that's always executed on exit".
|
How can I add a code that is always executed by Waf before exit?
|
I want to make Waf generate a beep when it finishes the execution of any command that took more than 10 seconds.
I don't know how do add this and assure that the code executes when Waf exits.
This should run for any Waf command not only build.
I checked the Waf book but I wasn't able to find any indication about how should I do this.
|
[
"In your wscript module, you can use the Python standard library's atexit to register callables that you want to be called when the process exit. For example:\nimport atexit\nimport time\n\nclass MayBeep(object):\n def __init__(self, deadline=10.0):\n self.deadline = time.time() + deadline\n def __call__(self):\n if time.time() > self.deadline():\n print '\\7'\n\natexit.register(MayBeep())\n\n... rest of your wscript module ...\n\nOf course you may use something better than print '\\7' for beeping purposes (all the way to full-fledged multimedia extravaganzas, depending on what other Python extensions you import and use), but this code answers the Q's title -- \"add code that's always executed on exit\".\n"
] |
[
4
] |
[] |
[] |
[
"python",
"waf"
] |
stackoverflow_0002522773_python_waf.txt
|
Q:
Entity references and lxml
Here's the code I have:
from cStringIO import StringIO
from lxml import etree
xml = StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY test "This is a test">
]>
<root>
<sub>&test;</sub>
</root>''')
d1 = etree.parse(xml)
print '%r' % d1.find('/sub').text
parser = etree.XMLParser(resolve_entities=False)
d2 = etree.parse(xml, parser=parser)
print '%r' % d2.find('/sub').text
Here's the output:
'This is a test'
None
How do I get lxml to give me '&test;', i.e., the raw entity reference?
A:
The "unresolved" Entity is left as child node of the element node sub
>>> print d2.find('/sub')[0]
&test;
>>> d2.find('/sub').getchildren()
[&test;]
|
Entity references and lxml
|
Here's the code I have:
from cStringIO import StringIO
from lxml import etree
xml = StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY test "This is a test">
]>
<root>
<sub>&test;</sub>
</root>''')
d1 = etree.parse(xml)
print '%r' % d1.find('/sub').text
parser = etree.XMLParser(resolve_entities=False)
d2 = etree.parse(xml, parser=parser)
print '%r' % d2.find('/sub').text
Here's the output:
'This is a test'
None
How do I get lxml to give me '&test;', i.e., the raw entity reference?
|
[
"The \"unresolved\" Entity is left as child node of the element node sub\n>>> print d2.find('/sub')[0]\n&test;\n>>> d2.find('/sub').getchildren()\n[&test;]\n\n"
] |
[
19
] |
[] |
[] |
[
"lxml",
"python",
"xml"
] |
stackoverflow_0002524299_lxml_python_xml.txt
|
Q:
Japanese in python function
I wrote a function in Python which is used to tell me whether the two words are similar or not.
Now I want to pass Japanese text in my same function. It is giving error "not a ascii character." I tried using utf-8 encoding, but then it giving the same error
Non-ASCII character '\xe3' in file
Is there any way to do that? I cant generate the msg file for that since the 2 keyword will be not be constant.
Here goes the code
def filterKeyword(keyword, adText, filterType):
if (filterType == 'contains'):
try :
adtext = str.lower(adText)
keyword = str.lower(keyword)
if (adtext.find(keyword)!=-1):
return '0'
except:
return '1'
if (filterType == 'exact'):
var = cmp(str.lower(adText), str.lower(keyword))
if(var == 0 ):
return '0'
return '1'
I have used the following:
filterKeyword(unicode('ポケモン').encode("utf-8"), unicode('黄色のポケモン').encode("utf-8"), 'contains')
filterKeyword('ポケモン'.encode("utf-8"), '黄色のポケモン'.encode("utf-8"), 'contains')
Both of them are giving the error.
A:
This worked for me:
# -*- coding: utf-8 -*-
def filterKeyword(keyword, adText, filterType):
# same as yours
filterKeyword(u'ポケモン', u'黄色のポケモン', 'contains')
A:
Please do not do this:
adtext = str.lower(adText)
keyword = str.lower(keyword)
Please do this:
adtext= adText.lower()
keyword = keyword.lower()
Please do not do this:
cmp(str.lower(adText), str.lower(keyword))
Please do this:
return adText.lower() == keyword.lower()
Please do not do this:
try:
# something
except:
# handler
Please provide a specific exception. A generic (superclass) like Exception is fine. There are some non-exception errors which you cannot meaningfully catch.
try:
# something
except Exception:
# handler
Also, it's really unlikely that catching an exception would return True.
Please do not do this:
return '1'
return '0'
It's unlikely you want to return a character. It's more likely you want to return True or False.
return True
return False
Your code will work, if you do things properly.
>>> u'ポケモン'.lower() == u'黄色のポケモン'.lower()
False
>>> u'ポケモン'.lower() in u'黄色のポケモン'.lower()
True
A:
Don't use UTF-8. Use unicodes.
A:
Put:
# -*- coding: utf-8 -*-
In one of the first two lines of your script. This way the interpreter will know what encoding is used for the code and strings in it.
And use Unicode strings wherever possible. If you have luck the function may work well with the Unicode (e.g. u"something…" instead of "something...") arguments even if it was not written with Unicode in mind.
A:
I would just like to note well:
unicode('ポケモン') (a non-unicode string constant passed to the unicode() constructor)
IS NOT THE SAME AS
u'ポケモン' (a unicode string constant)
|
Japanese in python function
|
I wrote a function in Python which is used to tell me whether the two words are similar or not.
Now I want to pass Japanese text in my same function. It is giving error "not a ascii character." I tried using utf-8 encoding, but then it giving the same error
Non-ASCII character '\xe3' in file
Is there any way to do that? I cant generate the msg file for that since the 2 keyword will be not be constant.
Here goes the code
def filterKeyword(keyword, adText, filterType):
if (filterType == 'contains'):
try :
adtext = str.lower(adText)
keyword = str.lower(keyword)
if (adtext.find(keyword)!=-1):
return '0'
except:
return '1'
if (filterType == 'exact'):
var = cmp(str.lower(adText), str.lower(keyword))
if(var == 0 ):
return '0'
return '1'
I have used the following:
filterKeyword(unicode('ポケモン').encode("utf-8"), unicode('黄色のポケモン').encode("utf-8"), 'contains')
filterKeyword('ポケモン'.encode("utf-8"), '黄色のポケモン'.encode("utf-8"), 'contains')
Both of them are giving the error.
|
[
"This worked for me:\n# -*- coding: utf-8 -*-\n\ndef filterKeyword(keyword, adText, filterType):\n # same as yours\n\nfilterKeyword(u'ポケモン', u'黄色のポケモン', 'contains')\n\n",
"Please do not do this:\nadtext = str.lower(adText)\nkeyword = str.lower(keyword)\n\nPlease do this:\nadtext= adText.lower()\nkeyword = keyword.lower()\n\nPlease do not do this:\ncmp(str.lower(adText), str.lower(keyword))\n\nPlease do this:\nreturn adText.lower() == keyword.lower()\n\nPlease do not do this:\ntry:\n # something\nexcept:\n # handler\n\nPlease provide a specific exception. A generic (superclass) like Exception is fine. There are some non-exception errors which you cannot meaningfully catch.\ntry:\n # something\nexcept Exception:\n # handler\n\nAlso, it's really unlikely that catching an exception would return True.\nPlease do not do this:\nreturn '1' \nreturn '0'\n\nIt's unlikely you want to return a character. It's more likely you want to return True or False.\nreturn True\nreturn False\n\nYour code will work, if you do things properly.\n>>> u'ポケモン'.lower() == u'黄色のポケモン'.lower()\nFalse\n>>> u'ポケモン'.lower() in u'黄色のポケモン'.lower()\nTrue\n\n",
"Don't use UTF-8. Use unicodes.\n",
"Put:\n# -*- coding: utf-8 -*-\n\nIn one of the first two lines of your script. This way the interpreter will know what encoding is used for the code and strings in it.\nAnd use Unicode strings wherever possible. If you have luck the function may work well with the Unicode (e.g. u\"something…\" instead of \"something...\") arguments even if it was not written with Unicode in mind.\n",
"I would just like to note well:\nunicode('ポケモン') (a non-unicode string constant passed to the unicode() constructor)\nIS NOT THE SAME AS\nu'ポケモン' (a unicode string constant)\n"
] |
[
3,
1,
0,
0,
0
] |
[] |
[] |
[
"internationalization",
"python"
] |
stackoverflow_0002522408_internationalization_python.txt
|
Q:
command CHOICE in DOS batch replacement/reproduction in python
I want to reproduce the behavior of the command CHOICE in DOS batch but with python.
raw_input requires the user to type whatever then press the ENTER/RETURN key. What I really want is for the user to press a single key and the script to continue from there.
A:
For Unix, it uses sys, tty, termios modules.
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
For Windows, it uses msvcrt module.
import msvcrt
ch = msvcrt.getch()
Source
A:
A small utility class to read single characters from standard input : http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
|
command CHOICE in DOS batch replacement/reproduction in python
|
I want to reproduce the behavior of the command CHOICE in DOS batch but with python.
raw_input requires the user to type whatever then press the ENTER/RETURN key. What I really want is for the user to press a single key and the script to continue from there.
|
[
"For Unix, it uses sys, tty, termios modules.\nimport sys, tty, termios\nfd = sys.stdin.fileno()\nold_settings = termios.tcgetattr(fd)\ntty.setraw(sys.stdin.fileno())\nch = sys.stdin.read(1)\n\nFor Windows, it uses msvcrt module.\nimport msvcrt\nch = msvcrt.getch()\n\nSource\n",
"A small utility class to read single characters from standard input : http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/\n"
] |
[
3,
2
] |
[] |
[] |
[
"batch_file",
"python"
] |
stackoverflow_0002524693_batch_file_python.txt
|
Q:
Django: testing get query
Okay, so I am sick of writing this...
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
I want to be able to grab a single object without testing the filtered results.
In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a 'None'. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line.
Is there any way to do what I have described?
A:
The django-annoying project includes a get_object_or_None shortcut which does this, although it's trivial to write it yourself.
A:
Create a custom Manager which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definitions:
class MyManager(models.Manager):
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
except self.model.DoesNotExist:
return None
class MyModel(models.Model):
objects = MyManager()
Usage:
MyModel.objects.get_or_none(asdf=something)
|
Django: testing get query
|
Okay, so I am sick of writing this...
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
I want to be able to grab a single object without testing the filtered results.
In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a 'None'. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line.
Is there any way to do what I have described?
|
[
"The django-annoying project includes a get_object_or_None shortcut which does this, although it's trivial to write it yourself.\n",
"Create a custom Manager which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definitions:\nclass MyManager(models.Manager):\n def get_or_none(self, **kwargs):\n try:\n return self.get(**kwargs)\n except self.model.DoesNotExist:\n return None\n\nclass MyModel(models.Model):\n objects = MyManager()\n\nUsage:\nMyModel.objects.get_or_none(asdf=something)\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"django_models",
"django_queryset",
"python"
] |
stackoverflow_0002525026_django_django_models_django_queryset_python.txt
|
Q:
Map only certain parts of the class to a database using SQLAlchemy?
When mapping an object using SQLAlchemy, is there a way to only map certain elements of a class to a database, or does it have to be a 1:1 mapping?
Example:
class User(object):
def __init__(self, name, username, password, year_of_birth):
self.name = name
self.username = username
self.password = password
self.year_of_birth = year_of_birth
Say, for whatever reason, I only wish to map the name, username and password to the database and leave out the year_of_birth. Is that possible and will this create problems?
Edit - 25/03/2010
Additionally, say I want to map username and year_of_birth to a separate database. Will this database and the one above still be connected (via username)?
A:
Your mapper can specify what columns to map, you could even map a single table to multiple objects and multiple tables to a single object.
Here's the documentation for mapping a single object multiple times: http://www.sqlalchemy.org/docs/05/mappers.html#multiple-mappers-for-one-class
What you want is to configure what columns to map/not to map. This can be done by customizing the column properties. Docs: http://www.sqlalchemy.org/docs/05/mappers.html#customizing-column-properties
Example:
mapper(User, users_table, include_properties=['user_id', 'user_name'])
mapper(Address, addresses_table, exclude_properties=['street', 'city', 'state', 'zip'])
|
Map only certain parts of the class to a database using SQLAlchemy?
|
When mapping an object using SQLAlchemy, is there a way to only map certain elements of a class to a database, or does it have to be a 1:1 mapping?
Example:
class User(object):
def __init__(self, name, username, password, year_of_birth):
self.name = name
self.username = username
self.password = password
self.year_of_birth = year_of_birth
Say, for whatever reason, I only wish to map the name, username and password to the database and leave out the year_of_birth. Is that possible and will this create problems?
Edit - 25/03/2010
Additionally, say I want to map username and year_of_birth to a separate database. Will this database and the one above still be connected (via username)?
|
[
"Your mapper can specify what columns to map, you could even map a single table to multiple objects and multiple tables to a single object.\nHere's the documentation for mapping a single object multiple times: http://www.sqlalchemy.org/docs/05/mappers.html#multiple-mappers-for-one-class\nWhat you want is to configure what columns to map/not to map. This can be done by customizing the column properties. Docs: http://www.sqlalchemy.org/docs/05/mappers.html#customizing-column-properties\nExample:\nmapper(User, users_table, include_properties=['user_id', 'user_name'])\n\nmapper(Address, addresses_table, exclude_properties=['street', 'city', 'state', 'zip'])\n\n"
] |
[
2
] |
[] |
[] |
[
"database",
"python",
"sqlalchemy"
] |
stackoverflow_0002519287_database_python_sqlalchemy.txt
|
Q:
How can I catch non valid ASCII characters in Panic Coda?
Sometimes I get errors while coding, because of typing some combination of keys (eg. ALT + SHIFT + SQUARE BRACKET) in a wrong way. So I get Syntax Error in Python, but I can't see where the illegal character is, 'cause Coda do not show it to me. Any solution?
A:
Python uses the 7-bit ASCII character set for program text. So all you need to do is convert your program to ASCII by going to text > convert to ASCII. Any bad characters will automatically be removed. If you want to specifically know which characters were the bad ones, you can use diff to compare changed and unchanged versions.
|
How can I catch non valid ASCII characters in Panic Coda?
|
Sometimes I get errors while coding, because of typing some combination of keys (eg. ALT + SHIFT + SQUARE BRACKET) in a wrong way. So I get Syntax Error in Python, but I can't see where the illegal character is, 'cause Coda do not show it to me. Any solution?
|
[
"Python uses the 7-bit ASCII character set for program text. So all you need to do is convert your program to ASCII by going to text > convert to ASCII. Any bad characters will automatically be removed. If you want to specifically know which characters were the bad ones, you can use diff to compare changed and unchanged versions.\n"
] |
[
1
] |
[] |
[] |
[
"ascii",
"coda",
"python"
] |
stackoverflow_0002525002_ascii_coda_python.txt
|
Q:
Capture subprocess output
I learned that when executing commands in Python, I should use subprocess.
What I'm trying to achieve is to encode a file via ffmpeg and observe the program output until the file is done. Ffmpeg logs the progress to stderr.
If I try something like this:
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
complete = False
while not complete:
stderr = child.communicate()
# Get progress
print "Progress here later"
if child.poll() is not None:
complete = True
time.sleep(2)
the programm does not continue after calling child.communicate() and waits for the command to complete. Is there any other way to follow the output?
A:
communicate() blocks until the child process returns, so the rest of the lines in your loop will only get executed after the child process has finished running. Reading from stderr will block too, unless you read character by character like so:
import subprocess
import sys
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
while True:
out = child.stderr.read(1)
if out == '' and child.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
This will provide you with real-time output. Taken from Nadia's answer here.
A:
.communicate() "Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate."
Instead, you should be able to just read from child.stderr like an ordinary file.
|
Capture subprocess output
|
I learned that when executing commands in Python, I should use subprocess.
What I'm trying to achieve is to encode a file via ffmpeg and observe the program output until the file is done. Ffmpeg logs the progress to stderr.
If I try something like this:
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
complete = False
while not complete:
stderr = child.communicate()
# Get progress
print "Progress here later"
if child.poll() is not None:
complete = True
time.sleep(2)
the programm does not continue after calling child.communicate() and waits for the command to complete. Is there any other way to follow the output?
|
[
"communicate() blocks until the child process returns, so the rest of the lines in your loop will only get executed after the child process has finished running. Reading from stderr will block too, unless you read character by character like so:\nimport subprocess\nimport sys\nchild = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)\nwhile True:\n out = child.stderr.read(1)\n if out == '' and child.poll() != None:\n break\n if out != '':\n sys.stdout.write(out)\n sys.stdout.flush()\n\nThis will provide you with real-time output. Taken from Nadia's answer here.\n",
".communicate() \"Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.\"\nInstead, you should be able to just read from child.stderr like an ordinary file.\n"
] |
[
27,
1
] |
[] |
[] |
[
"python",
"subprocess"
] |
stackoverflow_0002525263_python_subprocess.txt
|
Q:
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
Update:
This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):
Solution:
r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$'
Original Question (albeit, after 3 edits)
I'm using Python and I'm not trying to extract the value, but rather test to make sure it fits the pattern.
allowed values:
spam123-spam-eggs-eggs1
spam123-eggs123
spam
1234
eggs123
Not allowed values:
eggs1-
-spam123
spam--spam
I just can't have a dash at the starting or the end. There is a question on here that works in the opposite direction by getting the string value after the fact, but I simply need to test for the value so that I can disallow it. Also, it can be a maximum of 25 chars long, but a minimum of 4 chars long. Also, no 2 dashes can touch each other.
Here's what I've come up with after some experimentation with lookbehind, etc:
# Nothing here
A:
Try this regular expression:
^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
This regular expression does only allow hyphens to separate sequences of one or more characters of [a-zA-Z0-9].
Edit Following up your comment: The expression (…)* allows the part inside the group to be repeated zero or more times. That means
a(bc)*
is the same as
a|abc|abcbc|abcbcbc|abcbcbcbc|…
Edit Now that you changed the requirements: As you probably don’t want to restrict each hyphen separated part of the words in its length, you will need a look-ahead assertion to take the length into account:
(?=[a-zA-Z0-9-]{4,25}$)^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
A:
The current regex is simple and fairly readable. Rather than making it long and complicated, have you considered applying the other constraints with normal Python string processing tools?
import re
def fits_pattern(string):
if (4 <= len(string) <= 25 and
"--" not in string and
not string.startswith("-") and
not string.endswith("-")):
return re.match(r"[a-zA-Z0-9\-]", string)
else:
return None
A:
It should be something like this:
^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
You are telling it to look for only one char, either a-z, A-Z, 0-9 or -, that is what [] does.
So if you do [abc] you will match only "a", or "b" or "c". not "abc"
Have fun.
A:
If you simply don't want a dash at the end and beginning, try ^[^-].*?[^-]$
Edit: Bah, you keep changing it.
|
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
|
Update:
This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):
Solution:
r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$'
Original Question (albeit, after 3 edits)
I'm using Python and I'm not trying to extract the value, but rather test to make sure it fits the pattern.
allowed values:
spam123-spam-eggs-eggs1
spam123-eggs123
spam
1234
eggs123
Not allowed values:
eggs1-
-spam123
spam--spam
I just can't have a dash at the starting or the end. There is a question on here that works in the opposite direction by getting the string value after the fact, but I simply need to test for the value so that I can disallow it. Also, it can be a maximum of 25 chars long, but a minimum of 4 chars long. Also, no 2 dashes can touch each other.
Here's what I've come up with after some experimentation with lookbehind, etc:
# Nothing here
|
[
"Try this regular expression:\n^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$\n\nThis regular expression does only allow hyphens to separate sequences of one or more characters of [a-zA-Z0-9].\n\nEdit Following up your comment: The expression (…)* allows the part inside the group to be repeated zero or more times. That means\na(bc)*\n\nis the same as\na|abc|abcbc|abcbcbc|abcbcbcbc|…\n\n\nEdit Now that you changed the requirements: As you probably don’t want to restrict each hyphen separated part of the words in its length, you will need a look-ahead assertion to take the length into account:\n(?=[a-zA-Z0-9-]{4,25}$)^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$\n\n",
"The current regex is simple and fairly readable. Rather than making it long and complicated, have you considered applying the other constraints with normal Python string processing tools?\nimport re\n\ndef fits_pattern(string):\n if (4 <= len(string) <= 25 and\n \"--\" not in string and\n not string.startswith(\"-\") and\n not string.endswith(\"-\")):\n\n return re.match(r\"[a-zA-Z0-9\\-]\", string)\n else:\n return None\n\n",
"It should be something like this:\n^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$\n\nYou are telling it to look for only one char, either a-z, A-Z, 0-9 or -, that is what [] does.\nSo if you do [abc] you will match only \"a\", or \"b\" or \"c\". not \"abc\"\nHave fun.\n",
"If you simply don't want a dash at the end and beginning, try ^[^-].*?[^-]$\nEdit: Bah, you keep changing it. \n"
] |
[
17,
4,
2,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002525327_python_regex.txt
|
Q:
Matching first set of elements with xpath
I have an xml document that looks like this.
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
I would like to construct an xpath that returns only the first set:
<bar type="artist"/> Bob Marley </a>
<bar type="artist"/> Peter Tosh </a>
<bar type="artist"/> Marlon Wayans </a>
How would one go about this? I have tried //bar[@type='artist'] but it's obvious there's more to this. Thanks in advance.
A:
In order to get only sub elements of some "indexed" node:
//foo[1]/bar[@type='artist']
Exmaple in C#:
string xml =
@"<root>
<foo>
<bar type='artist'> Artist 1 </bar>
<bar type='artist'> Artist 2 </bar>
<bar type='artist'> Artist 3 </bar>
</foo>
<foo>
<bar type='artist'> Artist 1 </bar>
<bar type='artist'> Artist 2 </bar>
<bar type='artist'> Artist 3 </bar>
<bar type='artist'> Artist 4 </bar>
</foo>
</root>";
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
Assert.That(document.SelectNodes(@"/root/foo[1]/bar[@type='artist']").Count,
Is.EqualTo(3));
Assert.That(document.SelectNodes(@"//foo[1]/bar[@type='artist']").Count,
Is.EqualTo(3));
|
Matching first set of elements with xpath
|
I have an xml document that looks like this.
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
I would like to construct an xpath that returns only the first set:
<bar type="artist"/> Bob Marley </a>
<bar type="artist"/> Peter Tosh </a>
<bar type="artist"/> Marlon Wayans </a>
How would one go about this? I have tried //bar[@type='artist'] but it's obvious there's more to this. Thanks in advance.
|
[
"In order to get only sub elements of some \"indexed\" node:\n//foo[1]/bar[@type='artist']\n\nExmaple in C#:\nstring xml =\n @\"<root>\n <foo>\n <bar type='artist'> Artist 1 </bar>\n <bar type='artist'> Artist 2 </bar>\n <bar type='artist'> Artist 3 </bar>\n </foo>\n <foo>\n <bar type='artist'> Artist 1 </bar>\n <bar type='artist'> Artist 2 </bar>\n <bar type='artist'> Artist 3 </bar>\n <bar type='artist'> Artist 4 </bar>\n </foo>\n </root>\";\nXmlDocument document = new XmlDocument();\ndocument.LoadXml(xml);\n\nAssert.That(document.SelectNodes(@\"/root/foo[1]/bar[@type='artist']\").Count,\n Is.EqualTo(3));\nAssert.That(document.SelectNodes(@\"//foo[1]/bar[@type='artist']\").Count,\n Is.EqualTo(3));\n\n"
] |
[
2
] |
[] |
[] |
[
"lxml",
"python",
"xpath"
] |
stackoverflow_0002525627_lxml_python_xpath.txt
|
Q:
QTreeWidget insertTopLevelItem - index given not accurately displayed in Tree?
I am unable to properly insert a QTreeWidgetItem at a specific index, in this case I am removing all QTreeWidgetItems from the tree, doing a custom sort on their Date Objects and then inserting them back into the QTreeWidget.
However, upon inserting (even one at a time) the QTreeWidgetItem is not inserted into the correct place.
The code below prints out:
index 0: 0
index 0: 1 index 1: 0
index 0: 2 index 1: 1 index 2: 0
index 0: 3 index 1: 2 index 2: 0 index 3: 1
index 0: 4 index 1: 2 index 2: 0 index 3: 1 index 4: 3
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0])
self.insertTopLevelItem(0, childrenList[1])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1])
self.insertTopLevelItem(0, childrenList[2])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1]), ' index 2: ', \
self.indexOfTopLevelItem(childrenList[2])
self.insertTopLevelItem(0, childrenList[3])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1]), ' index 2: ',\
self.indexOfTopLevelItem(childrenList[2]), 'index 3: ',\
self.indexOfTopLevelItem(childrenList[3])
self.insertTopLevelItem(0, childrenList[4])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]),\
' index 1: ', self.indexOfTopLevelItem(childrenList[1]),\
' index 2: ', self.indexOfTopLevelItem(childrenList[2]),\
'index 3: ', self.indexOfTopLevelItem(childrenList[3]),\
'index 4: ', self.indexOfTopLevelItem(childrenList[4])
A:
You can do your custom sort without a need to refill tree. You just need to overload item's 'less' operator.
Note, that QT figures out, what to draw in the cell, what size it should be, what text should it contain, by looking in item's
virtual QVariant data ( int column, int role ) const
when you create an item, you provide some string to constructor for item to show. This string is placed into data(.., QtCore.Qt.EditRole), so, the equivalent of passing data into constuctor is to set data with:
virtual void setData ( int column, int role, const QVariant & value)
Internally, data is just an array, you can place anything youn want, and indexes of it are roles (Qt.EditRole is 2, Qt.ToolTipRole is 3 etc.), so we just let some role to contain our data, tell comparison operator to compare these values, and tell setData set DisplayRole when we set our, let's say, ValueRole. Here is the sample:
class TreeItem(QtGui.QTreeWidgetItem):
PythonValueRole = QtCore.Qt.UserRole
#values are list of python objects, that have __str__ and can be compared
def __init__(self, tree, values):
QtGui.QTreeWidgetItem.__init__(self, tree)
i = 0
for v in values:
self.setData(i, TreeItem.PythonValueRole, v)
i += 1
#overridden to simplify data assigning. When called with PythonValueRole, passes
#that object's string representation to DisplayRole and EditRole
def setData(self, col, role, value):
if role == TreeItem.PythonValueRole:
QtGui.QTreeWidgetItem.setData(self, col, TreeItem.PythonValueRole, value)
# sets DisplayRole and EditRole
QtGui.QTreeWidgetItem.setData(self, col, QtCore.Qt.EditRole, str(value))
QtGui.QTreeWidgetItem.setData(self, col, QtCore.Qt.DisplayRole, str(value))
else:
QtGui.QTreeWidgetItem.setData(self, col, role, value)
def __lt__(self, other):
c = self.treeWidget().sortColumn()
return self.data(c, TreeItem.PythonValueRole).toPyObject() <
other.data(c, TreeItem.PythonValueRole).toPyObject()
I've tested, it works fine. Of cource, you can avoid inheritance and override lt directly, since we had duck typing, use UserRole itself to hold your data and set data do display directly with setData(col, role, val), or even hold only text in edit/display role and convert it in datetime only while comparing, but it seems ugly.
Note, that data() contains QVariant. When you set data, your py object automatcally converts, and you need to call toPyObject() to get your value back as it was.
A:
The problem must be elsewhere in your code. Maybe you aren't removing the items properly? Because the following works:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
app = QApplication(sys.argv)
tree = QTreeWidget()
items = [QTreeWidgetItem(['index %i' % i]) for i in range(5)]
for item in items:
tree.insertTopLevelItem(0, item)
print 'indexes: '
for item in items:
print tree.indexOfTopLevelItem(item),
tree.show()
app.exec_()
|
QTreeWidget insertTopLevelItem - index given not accurately displayed in Tree?
|
I am unable to properly insert a QTreeWidgetItem at a specific index, in this case I am removing all QTreeWidgetItems from the tree, doing a custom sort on their Date Objects and then inserting them back into the QTreeWidget.
However, upon inserting (even one at a time) the QTreeWidgetItem is not inserted into the correct place.
The code below prints out:
index 0: 0
index 0: 1 index 1: 0
index 0: 2 index 1: 1 index 2: 0
index 0: 3 index 1: 2 index 2: 0 index 3: 1
index 0: 4 index 1: 2 index 2: 0 index 3: 1 index 4: 3
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0])
self.insertTopLevelItem(0, childrenList[1])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1])
self.insertTopLevelItem(0, childrenList[2])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1]), ' index 2: ', \
self.indexOfTopLevelItem(childrenList[2])
self.insertTopLevelItem(0, childrenList[3])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]), ' index 1: ',\
self.indexOfTopLevelItem(childrenList[1]), ' index 2: ',\
self.indexOfTopLevelItem(childrenList[2]), 'index 3: ',\
self.indexOfTopLevelItem(childrenList[3])
self.insertTopLevelItem(0, childrenList[4])
print 'index 0: ', self.indexOfTopLevelItem(childrenList[0]),\
' index 1: ', self.indexOfTopLevelItem(childrenList[1]),\
' index 2: ', self.indexOfTopLevelItem(childrenList[2]),\
'index 3: ', self.indexOfTopLevelItem(childrenList[3]),\
'index 4: ', self.indexOfTopLevelItem(childrenList[4])
|
[
"You can do your custom sort without a need to refill tree. You just need to overload item's 'less' operator.\nNote, that QT figures out, what to draw in the cell, what size it should be, what text should it contain, by looking in item's\nvirtual QVariant data ( int column, int role ) const\n\nwhen you create an item, you provide some string to constructor for item to show. This string is placed into data(.., QtCore.Qt.EditRole), so, the equivalent of passing data into constuctor is to set data with:\nvirtual void setData ( int column, int role, const QVariant & value)\n\nInternally, data is just an array, you can place anything youn want, and indexes of it are roles (Qt.EditRole is 2, Qt.ToolTipRole is 3 etc.), so we just let some role to contain our data, tell comparison operator to compare these values, and tell setData set DisplayRole when we set our, let's say, ValueRole. Here is the sample:\nclass TreeItem(QtGui.QTreeWidgetItem):\n\n PythonValueRole = QtCore.Qt.UserRole\n\n #values are list of python objects, that have __str__ and can be compared\n def __init__(self, tree, values):\n QtGui.QTreeWidgetItem.__init__(self, tree)\n i = 0\n for v in values:\n self.setData(i, TreeItem.PythonValueRole, v)\n i += 1\n\n #overridden to simplify data assigning. When called with PythonValueRole, passes\n #that object's string representation to DisplayRole and EditRole\n def setData(self, col, role, value):\n if role == TreeItem.PythonValueRole:\n QtGui.QTreeWidgetItem.setData(self, col, TreeItem.PythonValueRole, value)\n # sets DisplayRole and EditRole\n QtGui.QTreeWidgetItem.setData(self, col, QtCore.Qt.EditRole, str(value)) \n QtGui.QTreeWidgetItem.setData(self, col, QtCore.Qt.DisplayRole, str(value))\n else:\n QtGui.QTreeWidgetItem.setData(self, col, role, value)\n\n def __lt__(self, other):\n c = self.treeWidget().sortColumn()\n return self.data(c, TreeItem.PythonValueRole).toPyObject() < \n other.data(c, TreeItem.PythonValueRole).toPyObject()\n\nI've tested, it works fine. Of cource, you can avoid inheritance and override lt directly, since we had duck typing, use UserRole itself to hold your data and set data do display directly with setData(col, role, val), or even hold only text in edit/display role and convert it in datetime only while comparing, but it seems ugly.\nNote, that data() contains QVariant. When you set data, your py object automatcally converts, and you need to call toPyObject() to get your value back as it was. \n",
"The problem must be elsewhere in your code. Maybe you aren't removing the items properly? Because the following works:\nimport sys\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\napp = QApplication(sys.argv)\n\ntree = QTreeWidget()\nitems = [QTreeWidgetItem(['index %i' % i]) for i in range(5)]\n\nfor item in items:\n tree.insertTopLevelItem(0, item)\n\nprint 'indexes: '\nfor item in items:\n print tree.indexOfTopLevelItem(item),\n\ntree.show()\n\napp.exec_()\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"qtreewidget",
"qtreewidgetitem"
] |
stackoverflow_0002520282_pyqt_python_qt_qtreewidget_qtreewidgetitem.txt
|
Q:
Access is denied error with pregenerated .pyc or .pyo files
I am getting an Access is denied error while I am trying to run the .pyo file by double click or from the command prompt.
Lets say I have abc.py (keeping main method entry point) which imports files xyz.py and imports wx etc.
I generate the .pyo file. But once I try to run abc.pyo I get the access is denied error.
I am not getting why this happening? Any help will really appreciated.
(I am using windows xp as os).
I am making .pyo from .py as following.
I am having a .bat file CompileAllToPyo.bat which have
python -O Compileall.py
The Compileall.py keep the follwoing things
import os
import compileall
os.popen3(cmdLine, 'b')
compileall.compile_dir('.', force=1)
This is all the info
Thanks
A:
You can tell the system that your hw.pyo file is "executable", for example (in Linux, MacOSX, or any other Unix-y system) by executing the command chmod +w hw.pyo at the terminal shell prompt. Consider, for example, the following short and simple shell session:
$ cat >hw.py
print('hello world')
$ python2.5 -O -c'import hw'
hello world
$ ./hw.pyo
bash: ./hw.pyo: Permission denied
$ chmod +x hw.pyo
$ ./hw.pyo
hello world
$
By default, .pyo (and .pyc) files are not marked as executable because they're mostly meant to be imported, not directly executed (indeed, note that we're explicitly using a Python import statement to create the .pyo file!); however, as this example shows, it's quite easy to make one of them "executable as the main script". BTW, observe also:
$ cat >hw.py
print('hello world from ' + __name__)
$ python2.5 -O -c'import hw'
hello world from hw
$ chmod +x hw.pyo
$ ./hw.pyo
hello world from __main__
$
The __name__ is what tells the module whether it's being imported (so the first "hello world" says "from hw") or run as the main script (so the second one says "from __main__"). That's the reason modules that are designed to be used both ways normally end with if __name__ == '__main__': main() or the like, where main is a function that, this way, gets called iff the module's running as the main script (it's always best to have all substantial code execute in a function, not at a module's top level).
A:
You don't "run" a .pyo file, as it's not an executable. You can give it to the python interpreter in lieu of the .py file, but in general, you should use a .py file as your entry point, so that the .pyc or .pyo file can be recreated when necessary.
$ python imported.pyo
Success!
$ ./imported.pyo
bash: ./imported.pyo: Permission denied
|
Access is denied error with pregenerated .pyc or .pyo files
|
I am getting an Access is denied error while I am trying to run the .pyo file by double click or from the command prompt.
Lets say I have abc.py (keeping main method entry point) which imports files xyz.py and imports wx etc.
I generate the .pyo file. But once I try to run abc.pyo I get the access is denied error.
I am not getting why this happening? Any help will really appreciated.
(I am using windows xp as os).
I am making .pyo from .py as following.
I am having a .bat file CompileAllToPyo.bat which have
python -O Compileall.py
The Compileall.py keep the follwoing things
import os
import compileall
os.popen3(cmdLine, 'b')
compileall.compile_dir('.', force=1)
This is all the info
Thanks
|
[
"You can tell the system that your hw.pyo file is \"executable\", for example (in Linux, MacOSX, or any other Unix-y system) by executing the command chmod +w hw.pyo at the terminal shell prompt. Consider, for example, the following short and simple shell session:\n$ cat >hw.py\nprint('hello world')\n$ python2.5 -O -c'import hw'\nhello world\n$ ./hw.pyo\nbash: ./hw.pyo: Permission denied\n$ chmod +x hw.pyo\n$ ./hw.pyo\nhello world\n$ \n\nBy default, .pyo (and .pyc) files are not marked as executable because they're mostly meant to be imported, not directly executed (indeed, note that we're explicitly using a Python import statement to create the .pyo file!); however, as this example shows, it's quite easy to make one of them \"executable as the main script\". BTW, observe also:\n$ cat >hw.py\nprint('hello world from ' + __name__)\n$ python2.5 -O -c'import hw'\nhello world from hw\n$ chmod +x hw.pyo\n$ ./hw.pyo\nhello world from __main__\n$ \n\nThe __name__ is what tells the module whether it's being imported (so the first \"hello world\" says \"from hw\") or run as the main script (so the second one says \"from __main__\"). That's the reason modules that are designed to be used both ways normally end with if __name__ == '__main__': main() or the like, where main is a function that, this way, gets called iff the module's running as the main script (it's always best to have all substantial code execute in a function, not at a module's top level).\n",
"You don't \"run\" a .pyo file, as it's not an executable. You can give it to the python interpreter in lieu of the .py file, but in general, you should use a .py file as your entry point, so that the .pyc or .pyo file can be recreated when necessary.\n$ python imported.pyo\nSuccess!\n$ ./imported.pyo\nbash: ./imported.pyo: Permission denied\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002523961_python_wxpython.txt
|
Q:
Writing code translator from Python to C?
I was asked to write a code translator that would take a Python program and produce a C program. Do you have any ideas how could I approach this problem or is it even possible?
A:
Shedskin: http://code.google.com/p/shedskin/
Boost Python: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/index.html
PyCXX: http://cxx.sourceforge.net/
Cython: http://www.cython.org/
from http://wiki.python.org/moin/compile%20Python%20to%20C, there's a list of related projects.
Pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/
psyco: http://psyco.sourceforge.net/
RPython: http://code.google.com/p/rpython/
A:
There's a fundamental question here: is the intent to basically create a Python compiler that uses C as a back-end, or to convert the program to C and maintain the C afterward?
Writing a compiler that produces (really ugly) C as its output probably isn't trivial -- a compiler rarely is, and generating code for Python will be more difficult than for a lot of other languages (dynamic typing, in particular, is hard to compile, at least to very efficient output). OTOH, at least the parser will be a lot easier than for some languages.
If by "translating", you mean converting Python to C that's readable and maintainable, that's a whole different question -- it's substantially more difficult, to put it mildly. Realistically, I doubt any machine translation will be worth much -- there are just too large of differences in how you normally approach problems in Python and C for there to be much hope of a decent machine translation.
A:
It's hard to believe that nobody has mentioned Cython -- pretty much the de facto standard for this type of job, in my opinion: http://www.cython.org/
A:
Have a look at Shedskin. It does exactly that (well, to C++ and for a subset of Python and its modules). But it should be able to provide valuable insight as how to approach this particular problem (although writing your own will certainly not be a trivial task).
|
Writing code translator from Python to C?
|
I was asked to write a code translator that would take a Python program and produce a C program. Do you have any ideas how could I approach this problem or is it even possible?
|
[
"Shedskin: http://code.google.com/p/shedskin/\nBoost Python: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/index.html\nPyCXX: http://cxx.sourceforge.net/\nCython: http://www.cython.org/\nfrom http://wiki.python.org/moin/compile%20Python%20to%20C, there's a list of related projects.\nPyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/\npsyco: http://psyco.sourceforge.net/\nRPython: http://code.google.com/p/rpython/\n",
"There's a fundamental question here: is the intent to basically create a Python compiler that uses C as a back-end, or to convert the program to C and maintain the C afterward?\nWriting a compiler that produces (really ugly) C as its output probably isn't trivial -- a compiler rarely is, and generating code for Python will be more difficult than for a lot of other languages (dynamic typing, in particular, is hard to compile, at least to very efficient output). OTOH, at least the parser will be a lot easier than for some languages.\nIf by \"translating\", you mean converting Python to C that's readable and maintainable, that's a whole different question -- it's substantially more difficult, to put it mildly. Realistically, I doubt any machine translation will be worth much -- there are just too large of differences in how you normally approach problems in Python and C for there to be much hope of a decent machine translation.\n",
"It's hard to believe that nobody has mentioned Cython -- pretty much the de facto standard for this type of job, in my opinion: http://www.cython.org/\n",
"Have a look at Shedskin. It does exactly that (well, to C++ and for a subset of Python and its modules). But it should be able to provide valuable insight as how to approach this particular problem (although writing your own will certainly not be a trivial task).\n"
] |
[
25,
7,
4,
3
] |
[] |
[] |
[
"c",
"code_translation",
"python"
] |
stackoverflow_0002525518_c_code_translation_python.txt
|
Q:
Inconsistency in modified/created/accessed time on mac
I'm having trouble using os.utime to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from /usr/bin/python). It's not consistent with the touch utility, and it's not consistent with the properties displayed in the Finder's "get info" window.
Consider the following command sequence. The 'created' and 'modified' times in the plain text refer to the attributes shown in the "get info" window in the finder. As a reminder, os.utime takes arguments (filename, (atime, mtime)).
>>> import os
>>> open('tempfile','w').close()
'created' and 'modified' are both the current time.
>>> os.utime('tempfile', (1000000000, 1500000000) )
'created' is the current time, 'modified' is July 13, 2017.
>>> os.utime('tempfile', (1000000000, 1000000000) )
'created' and 'modified' are both September 8, 2001.
>>> os.path.getmtime('tempfile')
1000000000.0
>>> os.path.getctime('tempfile')
1269021939.0
>>> os.path.getatime('tempfile')
1269021951.0
...but the os.path.get?time and os.stat don't reflect it.
>>> os.utime('tempfile', (1500000000, 1000000000) )
'created' and 'modified' are still both September 8, 2001.
>>> os.utime('tempfile', (1500000000, 1500000000) )
'created' is September 8, 2001, 'modified' is July 13, 2017.
I'm not sure if this is a Python problem or a Mac stat problem. When I exit the Python shell and run
touch -a -t 200011221234 tempfile
neither the modification nor the creation times are changed, as expected. Then I run
touch -m -t 200011221234 tempfile
and both 'created' and 'modified' times are changed.
Does anyone have any idea what's going on? How do I change the modification and creation times consistently on the mac? (Yes, I am aware that on Unixy systems there is no "creation time.")
Result from running Chris Johnsen's script:
seth@local:~$ /usr/bin/python timetest.py tempfile 5
initial:
(1269631281.0, 1269631281.0, 1269631281.0, 1269631281, 1269631281, 1269631281)
test: (1000000000, 1000000000)
(1000000000.0, 1000000000.0, 1269631281.0, 1000000000, 1000000000, 1269631281)
(1269631281.0, 1000000000.0, 1269631281.0, 1269631281, 1000000000, 1269631281)
test: (1000000000, 1500000000)
(1000000000.0, 1500000000.0, 1269631286.0, 1000000000, 1500000000, 1269631286)
(1269631286.0, 1500000000.0, 1269631286.0, 1269631286, 1500000000, 1269631286)
test: (1500000000, 1000000000)
(1500000000.0, 1000000000.0, 1269631291.0, 1500000000, 1000000000, 1269631291)
(1269631291.0, 1000000000.0, 1269631291.0, 1269631291, 1000000000, 1269631291)
test: (1500000000, 1500000000)
(1500000000.0, 1500000000.0, 1269631296.0, 1500000000, 1500000000, 1269631296)
(1269631296.0, 1500000000.0, 1269631296.0, 1269631296, 1500000000, 1269631296)
At the end of the exercise, the 'created' date as visible in the finder is 9/8/01 and the 'modified' date is 7/13/17. (The access date, thanks to presumably spotlight as you suggest and as I've read about, is roughly 'now.') The created and modified dates visible in the finder still make no sense.
A:
POSIX atime, mtime, ctime
It might help if you included a full script and its actual and expected outputs instead of the REPL fragments.
import sys, os, stat, time
def get_times(p):
s = os.stat(p)
return (
os.path.getatime(p),
os.path.getmtime(p),
os.path.getctime(p),
s[stat.ST_ATIME],
s[stat.ST_MTIME],
s[stat.ST_CTIME],
)
def main(p, delay=1):
delay = float(delay)
(a,b) = (1000000000, 1500000000)
open(p,'w').close()
print 'initial:'
print get_times(p)
for t in [ (a,a), (a,b), (b,a), (b,b) ]:
print
print 'test:', t
os.utime(p,t)
print get_times(p)
time.sleep(delay)
print get_times(p)
main(*sys.argv[1:])
I get this on my 10.4 system with cd "$HOME" && python test.py tempfile 5 (system default Python 2.3.6 and MacPorts Python 2.6.4 both give the same result (leaving out the initial times and ctime, of course)):
% python /tmp/test.py tempfile 5
initial:
(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)
test: (1000000000, 1000000000)
(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)
(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)
test: (1000000000, 1500000000)
(1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886)
(1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886)
test: (1500000000, 1000000000)
(1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891)
(1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891)
test: (1500000000, 1500000000)
(1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896)
(1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896)
That seems reasonable. I wonder what you get.
I have heard that Spotlight can sometimes aggressively reset atime due to re-indexing changed files. I would not expect it to re-index a file that has only undergone utime()/utimes(), but I suppose it is possible. To eliminate Spotlight as a possible complication use a file in a location that is not indexed by Spotlight (e.g. /tmp/testfile).
Date Created in Finder
(shown as “Created:” in Get Info windows of Finder)
If you have the Developer tools installed, you can use /Developer/Tools/GetFileInfo to see the HFS creationDate. I added the following lines after every print get_times(p) line:
sys.stdout.flush()
os.system('/Developer/Tools/GetFileInfo ' + p)
I also changed the iteration to match your initial description ([ (a,b), (a,a), (b,a), (b,b) ]).
The result now looks like this:
% rm /tmp/tempfile; python /tmp/test.py /tmp/tempfile 1
initial:
(1269636574.0, 1269636574.0, 1269636574.0, 1269636574, 1269636574, 1269636574)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 03/26/2010 15:49:34
modified: 03/26/2010 15:49:34
test: (1000000000, 1500000000)
(1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 03/26/2010 15:49:34
modified: 07/13/2017 21:40:00
(1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 03/26/2010 15:49:34
modified: 07/13/2017 21:40:00
test: (1000000000, 1000000000)
(1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 09/08/2001 20:46:40
(1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 09/08/2001 20:46:40
test: (1500000000, 1000000000)
(1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 09/08/2001 20:46:40
(1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 09/08/2001 20:46:40
test: (1500000000, 1500000000)
(1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 07/13/2017 21:40:00
(1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578)
file: "/private/tmp/tempfile"
type: ""
creator: ""
attributes: avbstclinmedz
created: 09/08/2001 20:46:40
modified: 07/13/2017 21:40:00
This seems to be consistent with your observations from your Get Info window in Finder. My interpretation (borne out by other experimentation) is that the HFS creationDate is updated by utime, but it only ever goes backwards (never forwards). If you want to update the HFS creationDate to a newer value, then you probably will have to use a Mac-specific API to do it.
One other note: you may have to switch windows a bit to get the Get Info window to update. On my system, its display does not automatically update unless I switch windows either to or from the Get Info window.
|
Inconsistency in modified/created/accessed time on mac
|
I'm having trouble using os.utime to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from /usr/bin/python). It's not consistent with the touch utility, and it's not consistent with the properties displayed in the Finder's "get info" window.
Consider the following command sequence. The 'created' and 'modified' times in the plain text refer to the attributes shown in the "get info" window in the finder. As a reminder, os.utime takes arguments (filename, (atime, mtime)).
>>> import os
>>> open('tempfile','w').close()
'created' and 'modified' are both the current time.
>>> os.utime('tempfile', (1000000000, 1500000000) )
'created' is the current time, 'modified' is July 13, 2017.
>>> os.utime('tempfile', (1000000000, 1000000000) )
'created' and 'modified' are both September 8, 2001.
>>> os.path.getmtime('tempfile')
1000000000.0
>>> os.path.getctime('tempfile')
1269021939.0
>>> os.path.getatime('tempfile')
1269021951.0
...but the os.path.get?time and os.stat don't reflect it.
>>> os.utime('tempfile', (1500000000, 1000000000) )
'created' and 'modified' are still both September 8, 2001.
>>> os.utime('tempfile', (1500000000, 1500000000) )
'created' is September 8, 2001, 'modified' is July 13, 2017.
I'm not sure if this is a Python problem or a Mac stat problem. When I exit the Python shell and run
touch -a -t 200011221234 tempfile
neither the modification nor the creation times are changed, as expected. Then I run
touch -m -t 200011221234 tempfile
and both 'created' and 'modified' times are changed.
Does anyone have any idea what's going on? How do I change the modification and creation times consistently on the mac? (Yes, I am aware that on Unixy systems there is no "creation time.")
Result from running Chris Johnsen's script:
seth@local:~$ /usr/bin/python timetest.py tempfile 5
initial:
(1269631281.0, 1269631281.0, 1269631281.0, 1269631281, 1269631281, 1269631281)
test: (1000000000, 1000000000)
(1000000000.0, 1000000000.0, 1269631281.0, 1000000000, 1000000000, 1269631281)
(1269631281.0, 1000000000.0, 1269631281.0, 1269631281, 1000000000, 1269631281)
test: (1000000000, 1500000000)
(1000000000.0, 1500000000.0, 1269631286.0, 1000000000, 1500000000, 1269631286)
(1269631286.0, 1500000000.0, 1269631286.0, 1269631286, 1500000000, 1269631286)
test: (1500000000, 1000000000)
(1500000000.0, 1000000000.0, 1269631291.0, 1500000000, 1000000000, 1269631291)
(1269631291.0, 1000000000.0, 1269631291.0, 1269631291, 1000000000, 1269631291)
test: (1500000000, 1500000000)
(1500000000.0, 1500000000.0, 1269631296.0, 1500000000, 1500000000, 1269631296)
(1269631296.0, 1500000000.0, 1269631296.0, 1269631296, 1500000000, 1269631296)
At the end of the exercise, the 'created' date as visible in the finder is 9/8/01 and the 'modified' date is 7/13/17. (The access date, thanks to presumably spotlight as you suggest and as I've read about, is roughly 'now.') The created and modified dates visible in the finder still make no sense.
|
[
"POSIX atime, mtime, ctime\nIt might help if you included a full script and its actual and expected outputs instead of the REPL fragments.\nimport sys, os, stat, time\n\ndef get_times(p):\n s = os.stat(p)\n return ( \n os.path.getatime(p),\n os.path.getmtime(p),\n os.path.getctime(p),\n s[stat.ST_ATIME],\n s[stat.ST_MTIME],\n s[stat.ST_CTIME],\n )\n\ndef main(p, delay=1):\n delay = float(delay)\n (a,b) = (1000000000, 1500000000)\n\n open(p,'w').close()\n\n print 'initial:'\n print get_times(p)\n\n for t in [ (a,a), (a,b), (b,a), (b,b) ]:\n print\n print 'test:', t\n os.utime(p,t)\n print get_times(p)\n time.sleep(delay)\n print get_times(p)\n\nmain(*sys.argv[1:])\n\nI get this on my 10.4 system with cd \"$HOME\" && python test.py tempfile 5 (system default Python 2.3.6 and MacPorts Python 2.6.4 both give the same result (leaving out the initial times and ctime, of course)):\n% python /tmp/test.py tempfile 5\ninitial:\n(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)\n\ntest: (1000000000, 1000000000)\n(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)\n(1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881)\n\ntest: (1000000000, 1500000000)\n(1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886)\n(1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886)\n\ntest: (1500000000, 1000000000)\n(1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891)\n(1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891)\n\ntest: (1500000000, 1500000000)\n(1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896)\n(1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896)\n\nThat seems reasonable. I wonder what you get.\nI have heard that Spotlight can sometimes aggressively reset atime due to re-indexing changed files. I would not expect it to re-index a file that has only undergone utime()/utimes(), but I suppose it is possible. To eliminate Spotlight as a possible complication use a file in a location that is not indexed by Spotlight (e.g. /tmp/testfile).\nDate Created in Finder\n(shown as “Created:” in Get Info windows of Finder)\nIf you have the Developer tools installed, you can use /Developer/Tools/GetFileInfo to see the HFS creationDate. I added the following lines after every print get_times(p) line:\nsys.stdout.flush()\nos.system('/Developer/Tools/GetFileInfo ' + p)\n\nI also changed the iteration to match your initial description ([ (a,b), (a,a), (b,a), (b,b) ]).\nThe result now looks like this:\n% rm /tmp/tempfile; python /tmp/test.py /tmp/tempfile 1\ninitial:\n(1269636574.0, 1269636574.0, 1269636574.0, 1269636574, 1269636574, 1269636574)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 03/26/2010 15:49:34\nmodified: 03/26/2010 15:49:34\n\ntest: (1000000000, 1500000000)\n(1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 03/26/2010 15:49:34\nmodified: 07/13/2017 21:40:00\n(1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 03/26/2010 15:49:34\nmodified: 07/13/2017 21:40:00\n\ntest: (1000000000, 1000000000)\n(1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 09/08/2001 20:46:40\n(1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 09/08/2001 20:46:40\n\ntest: (1500000000, 1000000000)\n(1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 09/08/2001 20:46:40\n(1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 09/08/2001 20:46:40\n\ntest: (1500000000, 1500000000)\n(1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 07/13/2017 21:40:00\n(1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578)\nfile: \"/private/tmp/tempfile\"\ntype: \"\"\ncreator: \"\"\nattributes: avbstclinmedz\ncreated: 09/08/2001 20:46:40\nmodified: 07/13/2017 21:40:00\n\nThis seems to be consistent with your observations from your Get Info window in Finder. My interpretation (borne out by other experimentation) is that the HFS creationDate is updated by utime, but it only ever goes backwards (never forwards). If you want to update the HFS creationDate to a newer value, then you probably will have to use a Mac-specific API to do it.\nOne other note: you may have to switch windows a bit to get the Get Info window to update. On my system, its display does not automatically update unless I switch windows either to or from the Get Info window.\n"
] |
[
5
] |
[] |
[] |
[
"macos",
"python",
"stat",
"touch"
] |
stackoverflow_0002479690_macos_python_stat_touch.txt
|
Q:
WebService client libraries for Python and Perl
I want to access web service in Python or/and Perl scripts. What are the most popular and reliable libraries today?
I read this question, and I know about SOAPpy and ZSI. Can anybody say something about this libraries? Are they reliable enough for use in production?
A:
If you're talking about SOAP then for Python I would definitely recommend suds :
https://fedorahosted.org/suds/
A:
Checking couple of libraries for SOAP (including suds) only ZSI worked reliably for me. It is not complicated to use and it just works(tm). I recommend that.
A:
Perl has fantastic CPAN libraries available for doing SOAP. Probably the easiest would be SOAP::Lite:
SOAP::Lite is a collection of Perl modules which provides a simple and lightweight interface to the Simple Object Access Protocol (SOAP) both on client and server side.
See more on the CPAN page.
|
WebService client libraries for Python and Perl
|
I want to access web service in Python or/and Perl scripts. What are the most popular and reliable libraries today?
I read this question, and I know about SOAPpy and ZSI. Can anybody say something about this libraries? Are they reliable enough for use in production?
|
[
"If you're talking about SOAP then for Python I would definitely recommend suds :\nhttps://fedorahosted.org/suds/\n",
"Checking couple of libraries for SOAP (including suds) only ZSI worked reliably for me. It is not complicated to use and it just works(tm). I recommend that.\n",
"Perl has fantastic CPAN libraries available for doing SOAP. Probably the easiest would be SOAP::Lite:\n\nSOAP::Lite is a collection of Perl modules which provides a simple and lightweight interface to the Simple Object Access Protocol (SOAP) both on client and server side.\n\nSee more on the CPAN page.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"perl",
"python",
"web_services"
] |
stackoverflow_0002524195_perl_python_web_services.txt
|
Q:
Automatically Update Field when a Different Field is Changed
I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud is set to the current date).
Is there a way to make this happen automatically or do I need to check what fields have changed each time I save an object and then update the related "_ud" fields.
Thanks a lot!
A:
Either write Field children that update both fields or use server-side triggers.
A:
Thanks for your help. I ended up modifying the model's save method, which I think will work:
def save(self):
current_date = date.today()
if self.id:
try:
old = UserProfile.objects.get(pk = self.id)
fields = UserProfile._meta.fields
for field in fields:
field_name = field.name
date_name = field_name + '_ud'
if not field_name.endswith('_ud') and date_name in fields:
if self.__dict__[field_name] != old.__dict__[field_name]:
self.__dict__[date_name] = current_date
self.date_updated = current_date
except UserProfile.DoesNotExit:
pass
super(UserProfile, self).save()
|
Automatically Update Field when a Different Field is Changed
|
I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud is set to the current date).
Is there a way to make this happen automatically or do I need to check what fields have changed each time I save an object and then update the related "_ud" fields.
Thanks a lot!
|
[
"Either write Field children that update both fields or use server-side triggers.\n",
"Thanks for your help. I ended up modifying the model's save method, which I think will work:\ndef save(self):\n current_date = date.today()\n if self.id:\n try:\n old = UserProfile.objects.get(pk = self.id)\n fields = UserProfile._meta.fields\n for field in fields:\n field_name = field.name\n date_name = field_name + '_ud'\n if not field_name.endswith('_ud') and date_name in fields:\n if self.__dict__[field_name] != old.__dict__[field_name]:\n self.__dict__[date_name] = current_date\n self.date_updated = current_date\n except UserProfile.DoesNotExit:\n pass\n super(UserProfile, self).save()\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"django_forms",
"django_models",
"python"
] |
stackoverflow_0002521793_django_django_forms_django_models_python.txt
|
Q:
Proper way in Python to raise errors while setting variables
What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it?
Is it bad to print errors from a class?
Do I have to return False if I'm raising an exception?
Just want to make sure that I'm doing things right. Below is some sample code:
@property
def password(self):
return self._password
@password.setter
def password(self,password):
# Check that password has been completed
try:
# Check that password has a length of 6 characters
if (len(password) < 6):
raise NameError('Your password must be greater \
than 6 characters')
except NameError:
print 'Please choose a password'
return False
except TypeError:
print 'Please choose a password'
return False
#Set the password
self._password = password
#Encrypt the password
password_md5 = md5.new()
password_md5.update(password)
self._password_md5 = password_md5.hexdigest()
A:
Your code is out of a context so is not obvious the right choice. Following some tips:
Don't use NameError exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use ValueError or TypeError if the exception concerns the value or the type of the parameter;
Don't print error messages. Raise meaningful exceptions with a meaningful error message:
raise ValueError("password must be longer than 6 characters")
Returning a value from a setter is meaningless while assignment is not an expression, i.e. you cannot check the value of an assignment:
if (user.password = 'short'): ...
Just raise an exception in the setter and let the code that set the property handle it.
Example:
class Test:
minlen = 6
@property
def password(self):
return self._password
@password.setter
def password(self, value):
if not isinstance(value, basestring):
raise TypeError("password must be a string")
if len(value) < self.minlen:
raise ValueError("password must be at least %d character len" % \
self.minlen)
self._password = value
Look also at this forms handling library, there the validators , here an example, are entities in their own: they can be set dynamically with higher control and less coupled code, but maybe this is much more than you need.
A:
The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define.
While it is possible to return a success/fail flag or error code from the function as you have done, it is not recommended - it is easy for the caller to forget to check the return value and have errors get lost. Besides you are returning a value from a property setter - this is meaningless in Python since assignments are not expressions and cannot return a value.
You should also never print a message for the user in your exception handling - what if you later want to use the function or class in a GUI program? In that case your print statement will have nowhere to print to. Logging an error to a logfile (using Python's logging module) is often helpful for debugging though.
A:
Generally, you should indicate errors that propagate by using exceptions. If you discover an error by something you just checked and you can deal with it immediately, there is no need to raise an exception.
In the particular case of a setter, of example, returning False or anything else won't help. Setting instance variables you have to check is very suboptimal, since then you could miss an error on accident.
print is not usually a good response to an error. In this case, it sounds like you want to tell the end user they need to use a different password. It sounds like you should call a method that causes the webpage with the form to explain to the user what went wrong; you could call the method that does that in your class or raise an exception that will propagate and eventually be caught and used for that purpose. (This is general advice. I don't know enough about Pylons to tell you how it wants you to do this.)
You should not raise your own NameError exceptions. NameError prettymuch always indicates a typo in your program, and as such you usually do not want to catch it. By catching it, you introduce unnecessary uncertainty into a program. This looks like it might be something more like ValueError or a subclass thereof (class InvalidPasswordError(ValueError): pass).
I do not understand why you check TypeError. You should always understand what would have caused an exception you caught. If you do in this case, that's great; I can't figure out what error would raise TypeError that you could sanely deal with by prompting the user.
Your technique of receiving the password in plaintext and storing its md5 hash is not very secure. You should look into something like AuthKit that could make this process more secure and abstracted.
|
Proper way in Python to raise errors while setting variables
|
What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it?
Is it bad to print errors from a class?
Do I have to return False if I'm raising an exception?
Just want to make sure that I'm doing things right. Below is some sample code:
@property
def password(self):
return self._password
@password.setter
def password(self,password):
# Check that password has been completed
try:
# Check that password has a length of 6 characters
if (len(password) < 6):
raise NameError('Your password must be greater \
than 6 characters')
except NameError:
print 'Please choose a password'
return False
except TypeError:
print 'Please choose a password'
return False
#Set the password
self._password = password
#Encrypt the password
password_md5 = md5.new()
password_md5.update(password)
self._password_md5 = password_md5.hexdigest()
|
[
"Your code is out of a context so is not obvious the right choice. Following some tips:\n\nDon't use NameError exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use ValueError or TypeError if the exception concerns the value or the type of the parameter;\nDon't print error messages. Raise meaningful exceptions with a meaningful error message:\nraise ValueError(\"password must be longer than 6 characters\")\n\nReturning a value from a setter is meaningless while assignment is not an expression, i.e. you cannot check the value of an assignment:\nif (user.password = 'short'): ...\n\nJust raise an exception in the setter and let the code that set the property handle it.\n\nExample:\nclass Test:\n\n minlen = 6\n\n @property\n def password(self):\n return self._password\n\n @password.setter\n def password(self, value):\n if not isinstance(value, basestring):\n raise TypeError(\"password must be a string\")\n if len(value) < self.minlen:\n raise ValueError(\"password must be at least %d character len\" % \\\n self.minlen)\n self._password = value\n\nLook also at this forms handling library, there the validators , here an example, are entities in their own: they can be set dynamically with higher control and less coupled code, but maybe this is much more than you need.\n",
"The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define. \nWhile it is possible to return a success/fail flag or error code from the function as you have done, it is not recommended - it is easy for the caller to forget to check the return value and have errors get lost. Besides you are returning a value from a property setter - this is meaningless in Python since assignments are not expressions and cannot return a value.\nYou should also never print a message for the user in your exception handling - what if you later want to use the function or class in a GUI program? In that case your print statement will have nowhere to print to. Logging an error to a logfile (using Python's logging module) is often helpful for debugging though.\n",
"Generally, you should indicate errors that propagate by using exceptions. If you discover an error by something you just checked and you can deal with it immediately, there is no need to raise an exception. \nIn the particular case of a setter, of example, returning False or anything else won't help. Setting instance variables you have to check is very suboptimal, since then you could miss an error on accident.\nprint is not usually a good response to an error. In this case, it sounds like you want to tell the end user they need to use a different password. It sounds like you should call a method that causes the webpage with the form to explain to the user what went wrong; you could call the method that does that in your class or raise an exception that will propagate and eventually be caught and used for that purpose. (This is general advice. I don't know enough about Pylons to tell you how it wants you to do this.)\nYou should not raise your own NameError exceptions. NameError prettymuch always indicates a typo in your program, and as such you usually do not want to catch it. By catching it, you introduce unnecessary uncertainty into a program. This looks like it might be something more like ValueError or a subclass thereof (class InvalidPasswordError(ValueError): pass).\nI do not understand why you check TypeError. You should always understand what would have caused an exception you caught. If you do in this case, that's great; I can't figure out what error would raise TypeError that you could sanely deal with by prompting the user.\nYour technique of receiving the password in plaintext and storing its md5 hash is not very secure. You should look into something like AuthKit that could make this process more secure and abstracted.\n"
] |
[
67,
10,
4
] |
[] |
[] |
[
"error_handling",
"python"
] |
stackoverflow_0002525845_error_handling_python.txt
|
Q:
How do I get the path of the Python script I am running in?
Duplicate:
In Python, how do I get the path and name of the file that is currently executing?
How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename - not the full path as I do on Windows.
No matter where my application is launched from, I want to open files that are relative to my script file(s).
A:
Use this to get the path of the current file. It will resolve any symlinks in the path.
import os
file_path = os.path.realpath(__file__)
This works fine on my mac. It won't work from the Python interpreter (you need to be executing a Python file).
A:
import os
print os.path.abspath(__file__)
A:
7.2 of Dive Into Python: Finding the Path.
import sys, os
print('sys.argv[0] =', sys.argv[0])
pathname = os.path.dirname(sys.argv[0])
print('path =', pathname)
print('full path =', os.path.abspath(pathname))
A:
The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:
os.path.dirname(sys.argv[0])
Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment
|
How do I get the path of the Python script I am running in?
|
Duplicate:
In Python, how do I get the path and name of the file that is currently executing?
How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename - not the full path as I do on Windows.
No matter where my application is launched from, I want to open files that are relative to my script file(s).
|
[
"Use this to get the path of the current file. It will resolve any symlinks in the path.\nimport os\n\nfile_path = os.path.realpath(__file__)\n\nThis works fine on my mac. It won't work from the Python interpreter (you need to be executing a Python file).\n",
"import os\nprint os.path.abspath(__file__)\n\n",
"7.2 of Dive Into Python: Finding the Path.\nimport sys, os\n\nprint('sys.argv[0] =', sys.argv[0]) \npathname = os.path.dirname(sys.argv[0]) \nprint('path =', pathname)\nprint('full path =', os.path.abspath(pathname)) \n\n",
"The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:\nos.path.dirname(sys.argv[0])\n\nPy2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment\n"
] |
[
607,
155,
142,
50
] |
[
"If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.\nOf course, there are better solutions, as posted. I just kind of like mine.\n"
] |
[
-7
] |
[
"path",
"python"
] |
stackoverflow_0000595305_path_python.txt
|
Q:
Settings module not found deploying django on a shared server
I'm trying to deploy my django project on a shared hosting as describe here
I have my project on /home/user/www/testa
I'm using this script
#!/usr/bin/python
import sys, os
sys.path.append("/home/user/bin/python")
sys.path.append('/home/user/www/testa')
os.chdir("/home/user/www/testa")
os.environ['DJANGO_SETTINGS_MODULE'] = "settings.py"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
And here's the error I get when trying to run it from shell:
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Traceback (most recent call last):
File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 558, in run
File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 1118, in handler
File "/home/user/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
self.load_middleware()
File "/home/user/lib/python2.4/site-packages/django/core/handlers/base.py", line 33, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/home/user/lib/python2.4/site-packages/django/utils/functional.py", line 269, in __getattr__
self._setup()
File "/home/usr/lib/python2.4/site-packages/django/conf/__init__.py", line 40, in _setup
self._wrapped = Settings(settings_module)
File "/home/user/lib/python2.4/site-packages/django/conf/__init__.py", line 75, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings.py' (Is it on sys.path? Does it have syntax errors?): No module named settings.py
Content-Type: text/html
Unhandled Exception
Unhandled Exception
An unhandled exception was thrown by the application.
What am I doing wrong?
Running the script from the browser just gives me an internal server error.
A:
The line
os.environ['DJANGO_SETTINGS_MODULE'] = "settings.py"
should be more like
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
based on how you're setting up sys.path. That environment variable is supposed to contain the path to the module as it should be imported by Python, not the actual filename of the module.
Basically, the way you've got it now is making Django do something like this internally:
import settings.py
I.e., it's trying to import a py module from inside a settings module.
|
Settings module not found deploying django on a shared server
|
I'm trying to deploy my django project on a shared hosting as describe here
I have my project on /home/user/www/testa
I'm using this script
#!/usr/bin/python
import sys, os
sys.path.append("/home/user/bin/python")
sys.path.append('/home/user/www/testa')
os.chdir("/home/user/www/testa")
os.environ['DJANGO_SETTINGS_MODULE'] = "settings.py"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
And here's the error I get when trying to run it from shell:
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Traceback (most recent call last):
File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 558, in run
File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 1118, in handler
File "/home/user/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
self.load_middleware()
File "/home/user/lib/python2.4/site-packages/django/core/handlers/base.py", line 33, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/home/user/lib/python2.4/site-packages/django/utils/functional.py", line 269, in __getattr__
self._setup()
File "/home/usr/lib/python2.4/site-packages/django/conf/__init__.py", line 40, in _setup
self._wrapped = Settings(settings_module)
File "/home/user/lib/python2.4/site-packages/django/conf/__init__.py", line 75, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings.py' (Is it on sys.path? Does it have syntax errors?): No module named settings.py
Content-Type: text/html
Unhandled Exception
Unhandled Exception
An unhandled exception was thrown by the application.
What am I doing wrong?
Running the script from the browser just gives me an internal server error.
|
[
"The line\nos.environ['DJANGO_SETTINGS_MODULE'] = \"settings.py\"\n\nshould be more like\nos.environ['DJANGO_SETTINGS_MODULE'] = \"settings\"\n\nbased on how you're setting up sys.path. That environment variable is supposed to contain the path to the module as it should be imported by Python, not the actual filename of the module.\nBasically, the way you've got it now is making Django do something like this internally:\nimport settings.py\n\nI.e., it's trying to import a py module from inside a settings module.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"fastcgi",
"python"
] |
stackoverflow_0002526172_django_fastcgi_python.txt
|
Q:
GQL how to select by UserProperty
Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?
class Atable(BaseModel):
owner = db.UserProperty()
(...)
--------- // --------------
query = "SELECT * FROM Atable WHERE owner=", users.get_current_user()
results = db.GqlQuery(query)
How can I fix that search?
Thanks :)
I've started with the appengine database yesterday so be gentle :)
A:
You could try the GQL way:
results = db.GqlQuery("SELECT * FROM Atable WHERE owner = :1", users.get_current_user().key())
or the Python Query way:
query = db.Query(Atable)
results = query.filter('owner =', users.get_current_user())
A:
query = GqlQuery("SELECT * FROM Atable WHERE owner = :1", users.get_current_user())
A:
The python query way is probably easier if you just need to get some data for that user.
For example in your class Something(db.Model), you can define:
@staticmethod
def get_something_by_user(user):
query = db.Query(Something).filter('users =', user)
result = query.fetch(limit=1000)
return result
Then you call it by doing this:
user = users.GetCurrentUser()
results = Something.get_something_by_user(user)
|
GQL how to select by UserProperty
|
Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?
class Atable(BaseModel):
owner = db.UserProperty()
(...)
--------- // --------------
query = "SELECT * FROM Atable WHERE owner=", users.get_current_user()
results = db.GqlQuery(query)
How can I fix that search?
Thanks :)
I've started with the appengine database yesterday so be gentle :)
|
[
"You could try the GQL way:\nresults = db.GqlQuery(\"SELECT * FROM Atable WHERE owner = :1\", users.get_current_user().key())\n\nor the Python Query way:\nquery = db.Query(Atable)\nresults = query.filter('owner =', users.get_current_user())\n\n",
"query = GqlQuery(\"SELECT * FROM Atable WHERE owner = :1\", users.get_current_user())\n\n",
"The python query way is probably easier if you just need to get some data for that user.\nFor example in your class Something(db.Model), you can define: \n@staticmethod\ndef get_something_by_user(user):\n\n query = db.Query(Something).filter('users =', user)\n result = query.fetch(limit=1000)\n\n return result\n\nThen you call it by doing this:\nuser = users.GetCurrentUser()\nresults = Something.get_something_by_user(user)\n\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002525180_django_google_app_engine_python.txt
|
Q:
Creating a "less"-like console pager interface for pysqlite3 database
I would like to add some interactive capability to a python CLI application I've writen that stores data in a SQLite3 database. Currently, my app reads-in a certain type of file, parses and analyzes, puts the analysis data into the db, and spits the formatted records to stdout (which I generally pipe to a file). There are on the order of a million records in this file. Ideally, I would like to eliminate that text file situation altogether and just loop after that "parse and analyze" part, displaying a screen's worth of records, and allowing the user to page through them and enter some commands that will edit the records. The backend part I know how to do.
Can anyone suggest a good starting point for creating that pager frontend either directly in the console (like the pager "less"), through ncurses, or some other system?
A:
You might want to take a look at urwid. It is a console user interface library for Python. The examples should be more than enough to convince you that this is what you want, if you really want to go text-console UI.
I'd use something like pygtk instead though.
A:
After looking around a bit, I found that less and other pagers actually use curses. When I thought of curses I always imagined the blue-boxed interface with menus and mouse interaction. These are library add-ons for curses, which offer exactly the basic terminal selection and editing control functionality I'm looking for.
Tutorial on Python Curses Programming
Curses Programming with Python
On the backend, when the user attempts to move the cursor above or below the currently displayed records, I'll have sqlite fetch me the next appropriate set of records for display.
|
Creating a "less"-like console pager interface for pysqlite3 database
|
I would like to add some interactive capability to a python CLI application I've writen that stores data in a SQLite3 database. Currently, my app reads-in a certain type of file, parses and analyzes, puts the analysis data into the db, and spits the formatted records to stdout (which I generally pipe to a file). There are on the order of a million records in this file. Ideally, I would like to eliminate that text file situation altogether and just loop after that "parse and analyze" part, displaying a screen's worth of records, and allowing the user to page through them and enter some commands that will edit the records. The backend part I know how to do.
Can anyone suggest a good starting point for creating that pager frontend either directly in the console (like the pager "less"), through ncurses, or some other system?
|
[
"You might want to take a look at urwid. It is a console user interface library for Python. The examples should be more than enough to convince you that this is what you want, if you really want to go text-console UI.\nI'd use something like pygtk instead though.\n",
"After looking around a bit, I found that less and other pagers actually use curses. When I thought of curses I always imagined the blue-boxed interface with menus and mouse interaction. These are library add-ons for curses, which offer exactly the basic terminal selection and editing control functionality I'm looking for.\nTutorial on Python Curses Programming\nCurses Programming with Python\nOn the backend, when the user attempts to move the cursor above or below the currently displayed records, I'll have sqlite fetch me the next appropriate set of records for display.\n"
] |
[
2,
2
] |
[] |
[] |
[
"linux",
"python",
"sqlite"
] |
stackoverflow_0002526212_linux_python_sqlite.txt
|
Q:
Game login authentication and security
First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet manipulation. Considering how small this game will be and the limited user base, I doubt we will have serious issues, but would like to try our best to limit problems. I am not sure where to start or what methods I should use, or what's worth it. For example, sending data to the server such as login name and password.
I was told his information should be encrypted when sending, so in-case someone was viewing it (with whatever means), that they couldn't get into the account. However, if someone is able to capture the encrypted string, wouldn't this string always work since it's decrypted server side? In other words, someone could just capture the packet, reuse it, and still gain access to the account?
The main goal I am really looking for is to make sure the players are logging into the game with the client we provide, and to make sure it's 'secure' (broad, I know). I have looked around at different methods such as Public and Private Key encryption, which I am sure any hex editor could eventually find. There are many other methods that seem way over my head at the moment and leave the impression of overkill.
I realize nothing is 100% secure. I am just looking for any input or reading material (links) to accomplish the main goal stated above. Would appreciate any help, thanks.
A:
This is a tough problem, because the code runs on the client. The replay problem can be solved by using a challenge by letting the server sending a random token which the client adds to the string to be encrypted. This way, the password string will be different each time, and replaying the encrypted string doesn't work (as the server checks if the encrypted password has the last sent token)
The problem is that the encryption key has to be stored on the client, and it's possible to retrieve that key.
A:
The simple answer to how to protect the password going over the wire, replay attacks, and message tampering is: use SSL. Yes, there are other things you can do with challenge-response authentication schemes for the login part of it, but it sounds like you really want the whole channel protected anyway. Use SSL at the socket layer and then you don't have to do anything else complicated with how you send your credentials.
A:
As for how to protect the client... The most realistic thing is to say that you don't. When you're writing the server code, never trust any data that the client sends you. Never give the client any information you don't want the player to have.
In some games, like chess (or really anything turn-based), that actually works pretty well, because it's very easy for the server to verify that the move passed in by the client is a legal move.
In other games, those restrictions aren't so practical, and then I don't know what you'd do, from a code perspective. I'd try to shift the problem to a social one at that point: Are the other players people you'd trust to bring their own dice to your gaming table? If not, can you play with someone else?
A:
Although it might conceivably be overkill for this specific application (small game, limited user base), you should seriously consider using oAuth, since this application gives you a great chance to learn this technology (which is really solid and widespread, and spreading more and more!-) to apply it in the future -- it's been designed and implemented by excellent programmers with strong security background. You can study their tutorial to get a solid understanding and background, then use libraries such as python-oauth2 to implement oauth simply and productively in your desktop application.
|
Game login authentication and security
|
First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet manipulation. Considering how small this game will be and the limited user base, I doubt we will have serious issues, but would like to try our best to limit problems. I am not sure where to start or what methods I should use, or what's worth it. For example, sending data to the server such as login name and password.
I was told his information should be encrypted when sending, so in-case someone was viewing it (with whatever means), that they couldn't get into the account. However, if someone is able to capture the encrypted string, wouldn't this string always work since it's decrypted server side? In other words, someone could just capture the packet, reuse it, and still gain access to the account?
The main goal I am really looking for is to make sure the players are logging into the game with the client we provide, and to make sure it's 'secure' (broad, I know). I have looked around at different methods such as Public and Private Key encryption, which I am sure any hex editor could eventually find. There are many other methods that seem way over my head at the moment and leave the impression of overkill.
I realize nothing is 100% secure. I am just looking for any input or reading material (links) to accomplish the main goal stated above. Would appreciate any help, thanks.
|
[
"This is a tough problem, because the code runs on the client. The replay problem can be solved by using a challenge by letting the server sending a random token which the client adds to the string to be encrypted. This way, the password string will be different each time, and replaying the encrypted string doesn't work (as the server checks if the encrypted password has the last sent token)\nThe problem is that the encryption key has to be stored on the client, and it's possible to retrieve that key.\n",
"The simple answer to how to protect the password going over the wire, replay attacks, and message tampering is: use SSL. Yes, there are other things you can do with challenge-response authentication schemes for the login part of it, but it sounds like you really want the whole channel protected anyway. Use SSL at the socket layer and then you don't have to do anything else complicated with how you send your credentials.\n",
"As for how to protect the client... The most realistic thing is to say that you don't. When you're writing the server code, never trust any data that the client sends you. Never give the client any information you don't want the player to have.\nIn some games, like chess (or really anything turn-based), that actually works pretty well, because it's very easy for the server to verify that the move passed in by the client is a legal move.\nIn other games, those restrictions aren't so practical, and then I don't know what you'd do, from a code perspective. I'd try to shift the problem to a social one at that point: Are the other players people you'd trust to bring their own dice to your gaming table? If not, can you play with someone else?\n",
"Although it might conceivably be overkill for this specific application (small game, limited user base), you should seriously consider using oAuth, since this application gives you a great chance to learn this technology (which is really solid and widespread, and spreading more and more!-) to apply it in the future -- it's been designed and implemented by excellent programmers with strong security background. You can study their tutorial to get a solid understanding and background, then use libraries such as python-oauth2 to implement oauth simply and productively in your desktop application.\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"authentication",
"python",
"security"
] |
stackoverflow_0002526110_authentication_python_security.txt
|
Q:
Can I avoid a threaded UDP socket in Python dropping data?
First off, I'm new to Python and learning on the job, so be gentle!
I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Image using a gtk.gdk.pixbuf). I'm using queues for communicating data between threads.
My problem is that if I start only threads 1 and 3 (so skip the file writing for now), it seems that I lose some data after the first few samples. After this drop it looks fine. Even by letting thread 1 complete before running thread 3, this apparent drop is still there.
Apologies for the length of code snippet (I've removed the thread that writes to file), but I felt removing code would just prompt questions. Hope someone can shed some light :-)
import socket
import threading
import Queue
import numpy
import gtk
gtk.gdk.threads_init()
import gtk.glade
import pygtk
class readFromUDPSocket(threading.Thread):
def __init__(self, socketUDP, readDataQueue, packetSize, numScans):
threading.Thread.__init__(self)
self.socketUDP = socketUDP
self.readDataQueue = readDataQueue
self.packetSize = packetSize
self.numScans = numScans
def run(self):
for scan in range(1, self.numScans + 1):
buffer = self.socketUDP.recv(self.packetSize)
self.readDataQueue.put(buffer)
self.socketUDP.close()
print 'myServer finished!'
class displayWithGTK(threading.Thread):
def __init__(self, displayDataQueue, image, viewArea):
threading.Thread.__init__(self)
self.displayDataQueue = displayDataQueue
self.image = image
self.viewWidth = viewArea[0]
self.viewHeight = viewArea[1]
self.displayData = numpy.zeros((self.viewHeight, self.viewWidth, 3), dtype=numpy.uint16)
def run(self):
scan = 0
try:
while True:
if not scan % self.viewWidth: scan = 0
buffer = self.displayDataQueue.get(timeout=0.1)
self.displayData[:, scan, 0] = numpy.fromstring(buffer, dtype=numpy.uint16)
self.displayData[:, scan, 1] = numpy.fromstring(buffer, dtype=numpy.uint16)
self.displayData[:, scan, 2] = numpy.fromstring(buffer, dtype=numpy.uint16)
gtk.gdk.threads_enter()
self.myPixbuf = gtk.gdk.pixbuf_new_from_data(self.displayData.tostring(), gtk.gdk.COLORSPACE_RGB,
False, 8, self.viewWidth, self.viewHeight, self.viewWidth * 3)
self.image.set_from_pixbuf(self.myPixbuf)
self.image.show()
gtk.gdk.threads_leave()
scan += 1
except Queue.Empty:
print 'myDisplay finished!'
pass
def quitGUI(obj):
print 'Currently active threads: %s' % threading.enumerate()
gtk.main_quit()
if __name__ == '__main__':
# Create socket (IPv4 protocol, datagram (UDP)) and bind to address
socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = '192.168.1.5'
port = 1024
socketUDP.bind((host, port))
# Data parameters
samplesPerScan = 256
packetsPerSecond = 1200
packetSize = 512
duration = 1 # For now, set a fixed duration to log data
numScans = int(packetsPerSecond * duration)
# Create array to store data
data = numpy.zeros((samplesPerScan, numScans), dtype=numpy.uint16)
# Create queue for displaying from
readDataQueue = Queue.Queue(numScans)
# Build GUI from Glade XML file
builder = gtk.Builder()
builder.add_from_file('GroundVue.glade')
window = builder.get_object('mainwindow')
window.connect('destroy', quitGUI)
view = builder.get_object('viewport')
image = gtk.Image()
view.add(image)
viewArea = (1200, samplesPerScan)
# Instantiate & start threads
myServer = readFromUDPSocket(socketUDP, readDataQueue, packetSize, numScans)
myDisplay = displayWithGTK(readDataQueue, image, viewArea)
myServer.start()
myDisplay.start()
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
print 'gtk.main finished!'
A:
UDP doesn't verify the target received it (like TCP does) - you must implement retransmission and such in your applications if you want to ensure all of the data arrives. Do you control the sending UDP source?
A:
UDP is, by definition, unreliable. You must not write programs that expect UDP datagrams to always get through.
Packets are dropped all the time in TCP too, but your program does not need to care, because TCP applications cannot process packets; the TCP stack shows your application a stream of bytes. There is a lot of machinery there to make sure that if you send bytes 'ABCD', you will see 'A' 'B' 'C' 'D' on the end. You may get any possible collection of packets, of course: 'ABC', 'D', or 'AB', CD', etc. Or you may just see 'ABC', and then nothing.
TCP isn't "reliable" because it can magically make your network cables never fail or break; the guarantee that it provides is that up until the point where the stream breaks, you will see everything in order. And after the stream breaks, you'll see nothing.
In UDP there is no such guarantee. If you send four UDP datagrams, 'AB', 'CD', 'EF' 'GH', you may receive all of them, or none of them, or half of them, or just one of them. You may receive them in any order. The only guarantee that UDP tries to provide is that you won't see a message with 'ABCD' in it, because those bytes are in different datagrams.
To sum up: this has nothing to do with Python, or threads, or GTK. It's just a basic fact of life on networks based in physical reality: sometimes the electrical characteristics of your wires are not conducive to getting your messages all the way across them.
You may be able to reduce the complexity of your program by using Twisted, specifically, the listenUDP API, because then you won't be needing to juggle threads or their interaction with GTK: you can just call methods directly on the widget in question from your datagramReceived method. But this won't fix your underlying problem: UDP just drops data sometimes, period. The real solution is to convince your data source to use TCP instead.
|
Can I avoid a threaded UDP socket in Python dropping data?
|
First off, I'm new to Python and learning on the job, so be gentle!
I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Image using a gtk.gdk.pixbuf). I'm using queues for communicating data between threads.
My problem is that if I start only threads 1 and 3 (so skip the file writing for now), it seems that I lose some data after the first few samples. After this drop it looks fine. Even by letting thread 1 complete before running thread 3, this apparent drop is still there.
Apologies for the length of code snippet (I've removed the thread that writes to file), but I felt removing code would just prompt questions. Hope someone can shed some light :-)
import socket
import threading
import Queue
import numpy
import gtk
gtk.gdk.threads_init()
import gtk.glade
import pygtk
class readFromUDPSocket(threading.Thread):
def __init__(self, socketUDP, readDataQueue, packetSize, numScans):
threading.Thread.__init__(self)
self.socketUDP = socketUDP
self.readDataQueue = readDataQueue
self.packetSize = packetSize
self.numScans = numScans
def run(self):
for scan in range(1, self.numScans + 1):
buffer = self.socketUDP.recv(self.packetSize)
self.readDataQueue.put(buffer)
self.socketUDP.close()
print 'myServer finished!'
class displayWithGTK(threading.Thread):
def __init__(self, displayDataQueue, image, viewArea):
threading.Thread.__init__(self)
self.displayDataQueue = displayDataQueue
self.image = image
self.viewWidth = viewArea[0]
self.viewHeight = viewArea[1]
self.displayData = numpy.zeros((self.viewHeight, self.viewWidth, 3), dtype=numpy.uint16)
def run(self):
scan = 0
try:
while True:
if not scan % self.viewWidth: scan = 0
buffer = self.displayDataQueue.get(timeout=0.1)
self.displayData[:, scan, 0] = numpy.fromstring(buffer, dtype=numpy.uint16)
self.displayData[:, scan, 1] = numpy.fromstring(buffer, dtype=numpy.uint16)
self.displayData[:, scan, 2] = numpy.fromstring(buffer, dtype=numpy.uint16)
gtk.gdk.threads_enter()
self.myPixbuf = gtk.gdk.pixbuf_new_from_data(self.displayData.tostring(), gtk.gdk.COLORSPACE_RGB,
False, 8, self.viewWidth, self.viewHeight, self.viewWidth * 3)
self.image.set_from_pixbuf(self.myPixbuf)
self.image.show()
gtk.gdk.threads_leave()
scan += 1
except Queue.Empty:
print 'myDisplay finished!'
pass
def quitGUI(obj):
print 'Currently active threads: %s' % threading.enumerate()
gtk.main_quit()
if __name__ == '__main__':
# Create socket (IPv4 protocol, datagram (UDP)) and bind to address
socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = '192.168.1.5'
port = 1024
socketUDP.bind((host, port))
# Data parameters
samplesPerScan = 256
packetsPerSecond = 1200
packetSize = 512
duration = 1 # For now, set a fixed duration to log data
numScans = int(packetsPerSecond * duration)
# Create array to store data
data = numpy.zeros((samplesPerScan, numScans), dtype=numpy.uint16)
# Create queue for displaying from
readDataQueue = Queue.Queue(numScans)
# Build GUI from Glade XML file
builder = gtk.Builder()
builder.add_from_file('GroundVue.glade')
window = builder.get_object('mainwindow')
window.connect('destroy', quitGUI)
view = builder.get_object('viewport')
image = gtk.Image()
view.add(image)
viewArea = (1200, samplesPerScan)
# Instantiate & start threads
myServer = readFromUDPSocket(socketUDP, readDataQueue, packetSize, numScans)
myDisplay = displayWithGTK(readDataQueue, image, viewArea)
myServer.start()
myDisplay.start()
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
print 'gtk.main finished!'
|
[
"UDP doesn't verify the target received it (like TCP does) - you must implement retransmission and such in your applications if you want to ensure all of the data arrives. Do you control the sending UDP source?\n",
"UDP is, by definition, unreliable. You must not write programs that expect UDP datagrams to always get through.\nPackets are dropped all the time in TCP too, but your program does not need to care, because TCP applications cannot process packets; the TCP stack shows your application a stream of bytes. There is a lot of machinery there to make sure that if you send bytes 'ABCD', you will see 'A' 'B' 'C' 'D' on the end. You may get any possible collection of packets, of course: 'ABC', 'D', or 'AB', CD', etc. Or you may just see 'ABC', and then nothing.\nTCP isn't \"reliable\" because it can magically make your network cables never fail or break; the guarantee that it provides is that up until the point where the stream breaks, you will see everything in order. And after the stream breaks, you'll see nothing.\nIn UDP there is no such guarantee. If you send four UDP datagrams, 'AB', 'CD', 'EF' 'GH', you may receive all of them, or none of them, or half of them, or just one of them. You may receive them in any order. The only guarantee that UDP tries to provide is that you won't see a message with 'ABCD' in it, because those bytes are in different datagrams.\nTo sum up: this has nothing to do with Python, or threads, or GTK. It's just a basic fact of life on networks based in physical reality: sometimes the electrical characteristics of your wires are not conducive to getting your messages all the way across them.\nYou may be able to reduce the complexity of your program by using Twisted, specifically, the listenUDP API, because then you won't be needing to juggle threads or their interaction with GTK: you can just call methods directly on the widget in question from your datagramReceived method. But this won't fix your underlying problem: UDP just drops data sometimes, period. The real solution is to convince your data source to use TCP instead.\n"
] |
[
4,
2
] |
[
"Edit - Struck out listen/accept sentence, thanks Daniel, I was just coming to remove it when I saw your comment :)\nI'd suggest that this is a network programming issue, rather than python per-se.\nYou've set a packet-per-second rate and a duration to define the number of recv calls you make to your UDP socket. I don't see a listen or accept call to the socket, I'll assume that recv handles that as you say you receive some data. You've not mentioned the generation of the data.\nYou've defined how many reads you're expecting to make, so I'd assume that the code makes that many receives before exiting, so my conclusion would be that your recv packetSize is insufficient and therefore one read isn't pulling an entire datagram, then the subsequent recv is pulling the next part of the previous datagram.\nCan't you look at the data you have received and determine what is missing? What data are you \"losing\"? How do you know it's lost?\nFurthermore, you could use wireshark to verify that your host is actually receiving the data at the same time as verifying the size of the datagrams. Match the capture against the data your recv thread is providing.\n\nUpdate\nYou say that you're losing data, but not what it is. I see two possibilities for data-loss:\n\nTruncating packets \nDropping packets\n\nYou've said that the payload size is the same size as that which you are passing to recv, so I'll take it that you're not truncating.\nSo the factors for dropping packets are a combination of rate of receipt, rate of read-from-receive-buffer and receive-buffer size.\nYour calls to Queue.put may be slowing down your rate of read.\nSo, first determine that you can read 1200 packets per second by modifying readFromUDPSocket to not Queue.put, but count the number of receives and report time taken.\nOnce you've determined that you can call recv fast enough, the next step is working out what is slowing you down. I suspect it may be your use of Queue, I suggest batching payloads in N-sized groups for placing on the Queue so that you're not trying to call put at 12Hz.\nSeeing as you want to sustain a rate of 1200 reads per second I don't think you'll get very far by increasing the receive buffer on the socket.\n",
"Firstly; can you set the recv buffer size for the socket? If so, set it to something very large as this will let the UDP stack buffer more datagrams for you. \nSecondly; if you can use asynchronous I/O then post multiple recv calls at once (again this allows the stack to service more datagrams before it starts to drop them).\nThirdly; you could try unrolling your loop a little and reading multiple datagrams before placing them in your queue; could the locking on the queue be causing the recv thread to run slowly??\nFinally; the datagrams may be being dropped elsewhere on the network, there may be nothing that you can do, that the U in UDP...\n",
"It seems that the problem is with the source. There are two issues:\n\nLooking at Wireshark the source is not consistently transmitting 1200 packets-per-second. Possibly, as Len pointed out, a problem with the outbound stack dropping data. BTW the source is a programmable card with an ethernet port connected to my machine.\nThe other issue is the after the first 15 packets or so of data there is always a drop. What I discovered is that if I recv 20 packets in the initialisation part of the readFromUDPSocket thread, I can then read the data fine, e.g.\n\nclass readFromUDPSocket(threading.Thread):\n\n def __init__(self, socketUDP, readDataQueue, packetSize, numScans):\n threading.Thread.__init__(self)\n self.socketUDP = socketUDP\n self.readDataQueue = readDataQueue\n self.packetSize = packetSize\n self.numScans = numScans\n for i in range(0, 20):\n buffer = self.socketUDP.recv(self.packetSize)\n\n def run(self):\n for scan in range(1, self.numScans + 1):\n buffer = self.socketUDP.recv(self.packetSize)\n self.readDataQueue.put(buffer)\n self.socketUDP.close()\n print 'myServer finished!'\n\nNot sure what this points to?! I think all of this rules out not being able to recv and put fast enough though.\n"
] |
[
-1,
-1,
-1
] |
[
"gtk",
"multithreading",
"pygtk",
"python",
"sockets"
] |
stackoverflow_0002456727_gtk_multithreading_pygtk_python_sockets.txt
|
Q:
pyInotify performance
I have a very large directory tree I am wanting pyInotify to watch.
Is it better to have pyInotify watch the entire tree or is it better to have a number of watches reporting changes to specific files ?
Thanks
A:
If you're going to watch only a few files in a huge tree, it makes sense to watch individual files. On the other hand, if you're going to watch almost all files in the tree, watching the entire tree instead makes sense. To know the point of turn exactly, you must benchmark both to see which one performs better.
|
pyInotify performance
|
I have a very large directory tree I am wanting pyInotify to watch.
Is it better to have pyInotify watch the entire tree or is it better to have a number of watches reporting changes to specific files ?
Thanks
|
[
"If you're going to watch only a few files in a huge tree, it makes sense to watch individual files. On the other hand, if you're going to watch almost all files in the tree, watching the entire tree instead makes sense. To know the point of turn exactly, you must benchmark both to see which one performs better.\n"
] |
[
0
] |
[] |
[] |
[
"pyinotify",
"python"
] |
stackoverflow_0002526273_pyinotify_python.txt
|
Q:
Python Permutation Program Flow help
i found this code at activestate, it takes a string and prints permutations of the string.
I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!
import sys
def printList(alist, blist=[]):
if not len(alist): print ''.join(blist)
for i in range(len(alist)):
blist.append(alist.pop(i))
printList(alist, blist)
alist.insert(i, blist.pop())
if __name__ == '__main__':
k = 'love'
if len(sys.argv) > 1: k = sys.argv[1]
printList(list(k))
A:
You can figure out how printList behaves by drawing a recursion tree. Each node consists of two elements: an alist and a blist. The root has the alist with the initial sequence of items you want to permute, and an empty blist.
Each node of the tree has one branch for each element of that node's alist; you move from a 'father' node to each one of its 'children' by choosing an element from the father's alist and:
assigning to the child's alist the father's alist minus that element;
assigning to the child's blist the father's blist plus that element appended to its end.
The leafs have an empty alist, and since following different paths from the root to the leafs you have to choose elements from the root's alist in different orders, the blist of the leafs themselves contain all the various permutations of the root's alist.
For example ([abc],[] == alist,blist):
[abc],[]
/ | \
a/ b| \c
/ | \
[bc],[a] [ac],[b] [ab],[c]
/ \
b/ \c
/ \
[c],[ab] [b],[ac]
| |
c| |b
| |
[],[abc] [],[acb]
def printList(alist, blist=[]):
# if alist is empty, we are in a 'leaf' in the recursion tree;
# then blist contains one permutation; print it
if not len(alist): print ''.join(blist)
# ELSE, for each possible position in alist,
for i in range(len(alist)):
# move the element at that position from alist to the end of blist
blist.append(alist.pop(i))
# go to the 'children' node and do the printing job for its subtree
printList(alist, blist)
# then move back the element from the end of blist to its original
# position in alist, so we can continue with the for loop
# without altering alist
alist.insert(i, blist.pop())
A:
To understand it clearly remove the loop with alist=love and blist initialized to []:
The 4 printlist calls in the for loop will now be(at first level of recursion):
printList("ove","l");
printList("lve","o");
printList("loe","v");
printList("lov","e");
Each of these printList calls has bList initialized to all possible permutations of one lettered lists, and alist has the remaining 3 letters. This is will continue until alist becomes empty and all the letters are in blist (and the printing happens if not len(alist): print ''.join(blist))
In the second level of recursion for example
printList("ove","l") will result in 3 calls
printList("ve","lo");
printList("oe","lv");
printList("ov","le");
Total permutations = 4(firstlevel) * 3(2nd level) * 2 * 1
A:
Shameless plug - Here is an elementary permutation code in python along with explanation from my blog.
Playing with recursion - string permutation
|
Python Permutation Program Flow help
|
i found this code at activestate, it takes a string and prints permutations of the string.
I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!
import sys
def printList(alist, blist=[]):
if not len(alist): print ''.join(blist)
for i in range(len(alist)):
blist.append(alist.pop(i))
printList(alist, blist)
alist.insert(i, blist.pop())
if __name__ == '__main__':
k = 'love'
if len(sys.argv) > 1: k = sys.argv[1]
printList(list(k))
|
[
"You can figure out how printList behaves by drawing a recursion tree. Each node consists of two elements: an alist and a blist. The root has the alist with the initial sequence of items you want to permute, and an empty blist.\nEach node of the tree has one branch for each element of that node's alist; you move from a 'father' node to each one of its 'children' by choosing an element from the father's alist and:\n\nassigning to the child's alist the father's alist minus that element;\nassigning to the child's blist the father's blist plus that element appended to its end.\n\nThe leafs have an empty alist, and since following different paths from the root to the leafs you have to choose elements from the root's alist in different orders, the blist of the leafs themselves contain all the various permutations of the root's alist.\nFor example ([abc],[] == alist,blist):\n [abc],[] \n / | \\\n a/ b| \\c\n / | \\\n [bc],[a] [ac],[b] [ab],[c]\n / \\\n b/ \\c\n / \\\n [c],[ab] [b],[ac]\n | |\n c| |b\n | |\n [],[abc] [],[acb]\n\n\ndef printList(alist, blist=[]):\n # if alist is empty, we are in a 'leaf' in the recursion tree;\n # then blist contains one permutation; print it\n if not len(alist): print ''.join(blist)\n\n # ELSE, for each possible position in alist,\n for i in range(len(alist)):\n\n # move the element at that position from alist to the end of blist\n blist.append(alist.pop(i))\n\n # go to the 'children' node and do the printing job for its subtree\n printList(alist, blist)\n\n # then move back the element from the end of blist to its original\n # position in alist, so we can continue with the for loop\n # without altering alist\n alist.insert(i, blist.pop())\n\n",
"To understand it clearly remove the loop with alist=love and blist initialized to []:\nThe 4 printlist calls in the for loop will now be(at first level of recursion):\n printList(\"ove\",\"l\");\n printList(\"lve\",\"o\");\n printList(\"loe\",\"v\");\n printList(\"lov\",\"e\");\n\nEach of these printList calls has bList initialized to all possible permutations of one lettered lists, and alist has the remaining 3 letters. This is will continue until alist becomes empty and all the letters are in blist (and the printing happens if not len(alist): print ''.join(blist)) \nIn the second level of recursion for example\n printList(\"ove\",\"l\") will result in 3 calls\n\n printList(\"ve\",\"lo\");\n printList(\"oe\",\"lv\");\n printList(\"ov\",\"le\");\n\nTotal permutations = 4(firstlevel) * 3(2nd level) * 2 * 1 \n",
"Shameless plug - Here is an elementary permutation code in python along with explanation from my blog.\nPlaying with recursion - string permutation\n"
] |
[
6,
3,
0
] |
[] |
[] |
[
"python",
"recursion",
"workflow"
] |
stackoverflow_0002526540_python_recursion_workflow.txt
|
Q:
How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?
So, I have three tables:
The class defenitions:
engine = create_engine('sqlite://test.db', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key = True)
title = Column(String)
description = Column(String)
link = Column(String)
pubDate = Column(DateTime)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key = True)
username = Column(String)
password = Column(String)
sessionId = Column(String)
class Subscription(Base):
__tablename__ = 'subscription'
userId = Column(Integer, ForeignKey('user.id'), primary_key=True)
channelId = Column(Integer, ForeignKey('channel.id'), primary_key=True)
NOTE: I know user.username should be unique, need to fix that, and I'm not sure why SQLalchemy creates some row names with the double-quotes.
And I'm trying to come up with a way to retrieve all of the channels, as well as an indication on what channels one particular user (identified by user.sessionId together with user.id) has a subscription on.
For example, say we have four channels: channel1, channel2, channel3, channel4; a user: user1; who has a subscription on channel1 and channel4. The query for user1 would return something like:
channel.id | channel.title | subscribed
---------------------------------------
1 channel1 True
2 channel2 False
3 channel3 False
4 channel4 True
This is a best-case result, but since I have absolutely no clue as how to accomplish the subscribed column, I've been instead trying to get the particular users id in the rows where the user has a subscription and where a subscription is missing, just leave it blank.
The database engine that I'm using together with SQLalchemy atm. is sqlite3
I've been scratching my head over this for two days now, I've no problem joining together all three by way of the subscription table but then all of the channels where the user does not have a subscription gets omitted.
I hope I've managed to describe my problem sufficiently, thanks in advance.
EDIT: Managed to solve this in a slightly clunky way involving a sub-query:
# What a messy SQL query!
stmt = query(Subscription).filter_by(userId = uid()).join((User, Subscription.userId == User.id)).filter_by(sessionId = id()).subquery()
subs = aliased(Subscription, stmt)
results = query(Channel.id, Channel.title, subs.userId).outerjoin((subs, subs.channelId == Channel.id))
However, I'll be continuing to search for a more elegant solution, so answers are still very much welcomed.
A:
Option-1:
Subscription is just a many-to-many relation object, and I would suggest that you model it as such rather then as a separate class. See Configuring Many-to-Many Relationships documentation of SQLAlchemy/declarative.
You model with the test code becomes:
from sqlalchemy import create_engine, Column, Integer, DateTime, String, ForeignKey, Table
from sqlalchemy.orm import relation, scoped_session, sessionmaker, eagerload
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine, autoflush=True))
Base = declarative_base()
t_subscription = Table('subscription', Base.metadata,
Column('userId', Integer, ForeignKey('user.id')),
Column('channelId', Integer, ForeignKey('channel.id')),
)
class Channel(Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key = True)
title = Column(String)
description = Column(String)
link = Column(String)
pubDate = Column(DateTime)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key = True)
username = Column(String)
password = Column(String)
sessionId = Column(String)
channels = relation("Channel", secondary=t_subscription)
# NOTE: no need for this class
# class Subscription(Base):
# ...
Base.metadata.create_all(engine)
# ######################
# Add test data
c1 = Channel()
c1.title = 'channel-1'
c2 = Channel()
c2.title = 'channel-2'
c3 = Channel()
c3.title = 'channel-3'
c4 = Channel()
c4.title = 'channel-4'
session.add(c1)
session.add(c2)
session.add(c3)
session.add(c4)
u1 = User()
u1.username ='user1'
session.add(u1)
u1.channels.append(c1)
u1.channels.append(c3)
u2 = User()
u2.username ='user2'
session.add(u2)
u2.channels.append(c2)
session.commit()
# ######################
# clean the session and test the code
session.expunge_all()
# retrieve all (I assume those are not that many)
channels = session.query(Channel).all()
# get subscription info for the user
#q = session.query(User)
# use eagerload(...) so that all 'subscription' table data is loaded with the user itself, and not as a separate query
q = session.query(User).options(eagerload(User.channels))
for u in q.all():
for c in channels:
print (c.id, c.title, (c in u.channels))
which produces following output:
(1, u'channel-1', True)
(2, u'channel-2', False)
(3, u'channel-3', True)
(4, u'channel-4', False)
(1, u'channel-1', False)
(2, u'channel-2', True)
(3, u'channel-3', False)
(4, u'channel-4', False)
Please note the use of eagerload, which will issue only 1 SELECT statement instead of 1 for each User when channels are asked for.
Option-2:
But if you want to keep you model and just create an SA query that would give you the columns as you ask, following query should do the job:
from sqlalchemy import and_
from sqlalchemy.sql.expression import case
#...
q = (session.query(#User.username,
Channel.id, Channel.title,
case([(Subscription.channelId == None, False)], else_=True)
).outerjoin((Subscription,
and_(Subscription.userId==User.id,
Subscription.channelId==Channel.id))
)
)
# optionally filter by user
q = q.filter(User.id == uid()) # assuming uid() is the function that provides user.id
q = q.filter(User.sessionId == id()) # assuming uid() is the function that provides user.sessionId
res = q.all()
for r in res:
print r
The output is absolutely the same as in the option-1 above.
A:
To make this a little easyer I've added relationships to your model, that way you can just do user.subscriptions to get all the subscriptions.
engine = create_engine('sqlite://test.db', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key = True)
title = Column(String)
description = Column(String)
link = Column(String)
pubDate = Column(DateTime)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key = True)
username = Column(String)
password = Column(String)
sessionId = Column(String)
class Subscription(Base):
__tablename__ = 'subscription'
userId = Column(Integer, ForeignKey('user.id'), primary_key=True)
user = relationship(User, primaryjoin=userId == User.id, backref='subscriptions')
channelId = Column(Integer, ForeignKey('channel.id'), primary_key=True)
channel = relationship(channel, primaryjoin=channelId == channel.id, backref='subscriptions')
results = session.query(
Channel.id,
Channel.title,
Channel.subscriptions.any().label('subscribed'),
)
for channel in results:
print channel.id, channel.title, channel.subscribed
A:
Don't query from the user. Query from the Channel.
user = query(User).filter_by(id=1).one()
for channel in query(Channel).all():
print channel.id, channel.title, user in channel.subscriptions.user
That way you get all the channels, not just the ones that are associated with the user in question.
|
How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?
|
So, I have three tables:
The class defenitions:
engine = create_engine('sqlite://test.db', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key = True)
title = Column(String)
description = Column(String)
link = Column(String)
pubDate = Column(DateTime)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key = True)
username = Column(String)
password = Column(String)
sessionId = Column(String)
class Subscription(Base):
__tablename__ = 'subscription'
userId = Column(Integer, ForeignKey('user.id'), primary_key=True)
channelId = Column(Integer, ForeignKey('channel.id'), primary_key=True)
NOTE: I know user.username should be unique, need to fix that, and I'm not sure why SQLalchemy creates some row names with the double-quotes.
And I'm trying to come up with a way to retrieve all of the channels, as well as an indication on what channels one particular user (identified by user.sessionId together with user.id) has a subscription on.
For example, say we have four channels: channel1, channel2, channel3, channel4; a user: user1; who has a subscription on channel1 and channel4. The query for user1 would return something like:
channel.id | channel.title | subscribed
---------------------------------------
1 channel1 True
2 channel2 False
3 channel3 False
4 channel4 True
This is a best-case result, but since I have absolutely no clue as how to accomplish the subscribed column, I've been instead trying to get the particular users id in the rows where the user has a subscription and where a subscription is missing, just leave it blank.
The database engine that I'm using together with SQLalchemy atm. is sqlite3
I've been scratching my head over this for two days now, I've no problem joining together all three by way of the subscription table but then all of the channels where the user does not have a subscription gets omitted.
I hope I've managed to describe my problem sufficiently, thanks in advance.
EDIT: Managed to solve this in a slightly clunky way involving a sub-query:
# What a messy SQL query!
stmt = query(Subscription).filter_by(userId = uid()).join((User, Subscription.userId == User.id)).filter_by(sessionId = id()).subquery()
subs = aliased(Subscription, stmt)
results = query(Channel.id, Channel.title, subs.userId).outerjoin((subs, subs.channelId == Channel.id))
However, I'll be continuing to search for a more elegant solution, so answers are still very much welcomed.
|
[
"Option-1:\nSubscription is just a many-to-many relation object, and I would suggest that you model it as such rather then as a separate class. See Configuring Many-to-Many Relationships documentation of SQLAlchemy/declarative. \nYou model with the test code becomes:\nfrom sqlalchemy import create_engine, Column, Integer, DateTime, String, ForeignKey, Table\nfrom sqlalchemy.orm import relation, scoped_session, sessionmaker, eagerload\nfrom sqlalchemy.ext.declarative import declarative_base\n\nengine = create_engine('sqlite:///:memory:', echo=True)\nsession = scoped_session(sessionmaker(bind=engine, autoflush=True))\nBase = declarative_base()\n\nt_subscription = Table('subscription', Base.metadata,\n Column('userId', Integer, ForeignKey('user.id')),\n Column('channelId', Integer, ForeignKey('channel.id')),\n)\n\nclass Channel(Base):\n __tablename__ = 'channel'\n\n id = Column(Integer, primary_key = True)\n title = Column(String)\n description = Column(String)\n link = Column(String)\n pubDate = Column(DateTime)\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key = True)\n username = Column(String)\n password = Column(String)\n sessionId = Column(String)\n\n channels = relation(\"Channel\", secondary=t_subscription)\n\n# NOTE: no need for this class\n# class Subscription(Base):\n # ...\n\nBase.metadata.create_all(engine)\n\n\n# ######################\n# Add test data\nc1 = Channel()\nc1.title = 'channel-1'\nc2 = Channel()\nc2.title = 'channel-2'\nc3 = Channel()\nc3.title = 'channel-3'\nc4 = Channel()\nc4.title = 'channel-4'\nsession.add(c1)\nsession.add(c2)\nsession.add(c3)\nsession.add(c4)\nu1 = User()\nu1.username ='user1'\nsession.add(u1)\nu1.channels.append(c1)\nu1.channels.append(c3)\nu2 = User()\nu2.username ='user2'\nsession.add(u2)\nu2.channels.append(c2)\nsession.commit()\n\n\n# ######################\n# clean the session and test the code\nsession.expunge_all()\n\n# retrieve all (I assume those are not that many)\nchannels = session.query(Channel).all()\n\n# get subscription info for the user\n#q = session.query(User)\n# use eagerload(...) so that all 'subscription' table data is loaded with the user itself, and not as a separate query\nq = session.query(User).options(eagerload(User.channels))\nfor u in q.all():\n for c in channels:\n print (c.id, c.title, (c in u.channels))\n\nwhich produces following output:\n(1, u'channel-1', True)\n(2, u'channel-2', False)\n(3, u'channel-3', True)\n(4, u'channel-4', False)\n(1, u'channel-1', False)\n(2, u'channel-2', True)\n(3, u'channel-3', False)\n(4, u'channel-4', False)\n\nPlease note the use of eagerload, which will issue only 1 SELECT statement instead of 1 for each User when channels are asked for.\nOption-2:\nBut if you want to keep you model and just create an SA query that would give you the columns as you ask, following query should do the job:\nfrom sqlalchemy import and_\nfrom sqlalchemy.sql.expression import case\n#...\nq = (session.query(#User.username, \n Channel.id, Channel.title, \n case([(Subscription.channelId == None, False)], else_=True)\n ).outerjoin((Subscription, \n and_(Subscription.userId==User.id, \n Subscription.channelId==Channel.id))\n )\n )\n# optionally filter by user\nq = q.filter(User.id == uid()) # assuming uid() is the function that provides user.id\nq = q.filter(User.sessionId == id()) # assuming uid() is the function that provides user.sessionId\nres = q.all()\nfor r in res:\n print r\n\nThe output is absolutely the same as in the option-1 above.\n",
"To make this a little easyer I've added relationships to your model, that way you can just do user.subscriptions to get all the subscriptions.\nengine = create_engine('sqlite://test.db', echo=False)\nSQLSession = sessionmaker(bind=engine)\nBase = declarative_base()\n\nclass Channel(Base):\n __tablename__ = 'channel'\n\n id = Column(Integer, primary_key = True)\n title = Column(String)\n description = Column(String)\n link = Column(String)\n pubDate = Column(DateTime)\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key = True)\n username = Column(String)\n password = Column(String)\n sessionId = Column(String)\n\nclass Subscription(Base):\n __tablename__ = 'subscription'\n\n userId = Column(Integer, ForeignKey('user.id'), primary_key=True)\n user = relationship(User, primaryjoin=userId == User.id, backref='subscriptions')\n channelId = Column(Integer, ForeignKey('channel.id'), primary_key=True)\n channel = relationship(channel, primaryjoin=channelId == channel.id, backref='subscriptions')\n\nresults = session.query(\n Channel.id,\n Channel.title,\n Channel.subscriptions.any().label('subscribed'),\n)\n\nfor channel in results:\n print channel.id, channel.title, channel.subscribed\n\n",
"Don't query from the user. Query from the Channel.\nuser = query(User).filter_by(id=1).one()\nfor channel in query(Channel).all():\n print channel.id, channel.title, user in channel.subscriptions.user\n\nThat way you get all the channels, not just the ones that are associated with the user in question.\n"
] |
[
14,
1,
0
] |
[] |
[] |
[
"python",
"sql",
"sqlalchemy",
"sqlite"
] |
stackoverflow_0002524600_python_sql_sqlalchemy_sqlite.txt
|
Q:
How do I make a dialog box that waits for user response?
When you tkSimpleDialog.askinteger, the program stalls and waits for user input. What are the basics of writing my own method that would have the same effect? I want to make the same kind of dialog box, I just want to be able to request more information.
The problem that I'm having is that when I open the new window using Tk.Toplevel, the program does not wait for user input the way tkSimpleDialog.askinteger does.
A:
First off, if you can use some other widget system like PyGtk or PyQt, you should seriously consider it. Tkinter is ancient, and the newer libraries have a lot more functionality (read: more things you don't have to reinvent). I've used PyGtk and like it a lot more than Tkinter, which I used in the old Python 1.x days.
That said, in Tkinter, you need to do this:
widget.wait_window(window)
This ties up the event loop waiting for the user to dismiss the dialog.
Reference: http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm
|
How do I make a dialog box that waits for user response?
|
When you tkSimpleDialog.askinteger, the program stalls and waits for user input. What are the basics of writing my own method that would have the same effect? I want to make the same kind of dialog box, I just want to be able to request more information.
The problem that I'm having is that when I open the new window using Tk.Toplevel, the program does not wait for user input the way tkSimpleDialog.askinteger does.
|
[
"First off, if you can use some other widget system like PyGtk or PyQt, you should seriously consider it. Tkinter is ancient, and the newer libraries have a lot more functionality (read: more things you don't have to reinvent). I've used PyGtk and like it a lot more than Tkinter, which I used in the old Python 1.x days.\nThat said, in Tkinter, you need to do this:\nwidget.wait_window(window)\n\nThis ties up the event loop waiting for the user to dismiss the dialog.\nReference: http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002527247_python_tkinter.txt
|
Q:
How do I install a python package
I want to install this python package:
http://pypi.python.org/pypi/netifaces/0.5
But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?
Thanks in advance
A:
From http://pypi.python.org/pypi:
to use a package from this index
either "pip install package" or
download, unpack and "python setup.py
install" it.
That said, often distributions of Linux package a lot in their repositories, so try those too.
A:
Check easy_install : http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install
A:
You can download the binary for windows from here or use easy_install as the above poster said
http://alastairs-place.net/2007/03/netifaces/netifaces-0.4-py2.4-win32.egg
|
How do I install a python package
|
I want to install this python package:
http://pypi.python.org/pypi/netifaces/0.5
But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?
Thanks in advance
|
[
"From http://pypi.python.org/pypi:\n\nto use a package from this index\n either \"pip install package\" or\n download, unpack and \"python setup.py\n install\" it.\n\nThat said, often distributions of Linux package a lot in their repositories, so try those too.\n",
"Check easy_install : http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install\n",
"You can download the binary for windows from here or use easy_install as the above poster said\nhttp://alastairs-place.net/2007/03/netifaces/netifaces-0.4-py2.4-win32.egg \n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"installation",
"linux",
"package",
"python"
] |
stackoverflow_0002527461_installation_linux_package_python.txt
|
Q:
Error handling with Python + Pylons
What is the proper way to handle errors with Python + Pylons?
Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire script terminating to an error page?
Should there be any error handling in the controller itself?
I hope I am explaining myself clearly.
Thank you.
A:
What are you using to validate your forms? I'm using formalchemy. It validates the input data using built-in and custom validators, and feeds a list with the errors it finds. You can then display that list in any way you want in your template.
Documentation here.
A:
I use formencode @validate decorator. It is possible to write custom validator for it but the problem with handling exceptions that occur in the model after validation still exists.
You could write custom action decorator similar to formencode one which will handle your model exceptions and populate c.form_errors.
A:
Not pretending to be production-ready solution, just as an example. Actually I've copied most of decorator code from pylons.decorators:
from decorator import decorator
from webob import UnicodeMultiDict
class ModelException(Exception):
pass
def handle_exceptions(form):
def wrapper(fn, self, *args,**kwargs):
try:
return fn(self, *args, **kwargs)
except ModelException, e:
errors = str(e)
params = request.POST
is_unicode_params = isinstance(params, UnicodeMultiDict)
params = params.mixed()
request.environ['pylons.routes_dict']['action'] = form
response = self._dispatch_call()
# XXX: Legacy WSGIResponse support
legacy_response = False
if hasattr(response, 'content'):
form_content = ''.join(response.content)
legacy_response = True
else:
form_content = response
response = self._py_object.response
# If the form_content is an exception response, return it
if hasattr(form_content, '_exception'):
return form_content
form_content = htmlfill.render(form_content, defaults=params,
errors=errors)
if legacy_response:
# Let the Controller merge the legacy response
response.content = form_content
return response
else:
return form_content
return decorator(wrapper)
class HelloFormSchema(Schema):
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.UnicodeString(not_empty=True)
email = formencode.validators.UnicodeString(not_empty=True)
class HelloController(BaseController):
def new(self):
return render('/hello/new.html')
def view(self):
return 'created'
@handle_exceptions(form='new')
@validate(schema=HelloFormSchema(), form='new')
@restrict("POST")
def create(self):
#here is code interacting with model which potentially could raise exception:
if self.form_result['name'] == 'doe':
raise ModelException('user already exists!')
return redirect(url(controller='hello', action='view'))
new.html:
${h.form(h.url(controller='hello', action='create'), 'post')}
<dl>
<dt>Name</dt>
<dd>${h.text('name')}</dd>
<dt>Email</dt>
<dd>${h.text('email')}</dd>
<dd>
${h.submit('create', 'Create')}
</dd>
</dl>
${h.end_form()}
|
Error handling with Python + Pylons
|
What is the proper way to handle errors with Python + Pylons?
Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire script terminating to an error page?
Should there be any error handling in the controller itself?
I hope I am explaining myself clearly.
Thank you.
|
[
"What are you using to validate your forms? I'm using formalchemy. It validates the input data using built-in and custom validators, and feeds a list with the errors it finds. You can then display that list in any way you want in your template.\nDocumentation here.\n",
"I use formencode @validate decorator. It is possible to write custom validator for it but the problem with handling exceptions that occur in the model after validation still exists.\nYou could write custom action decorator similar to formencode one which will handle your model exceptions and populate c.form_errors.\n",
"Not pretending to be production-ready solution, just as an example. Actually I've copied most of decorator code from pylons.decorators:\nfrom decorator import decorator\nfrom webob import UnicodeMultiDict\n\nclass ModelException(Exception):\n pass\n\ndef handle_exceptions(form):\n def wrapper(fn, self, *args,**kwargs):\n try:\n return fn(self, *args, **kwargs)\n except ModelException, e:\n errors = str(e)\n params = request.POST\n\n is_unicode_params = isinstance(params, UnicodeMultiDict)\n params = params.mixed()\n\n\n request.environ['pylons.routes_dict']['action'] = form\n response = self._dispatch_call()\n # XXX: Legacy WSGIResponse support\n legacy_response = False\n if hasattr(response, 'content'):\n form_content = ''.join(response.content)\n legacy_response = True\n else:\n form_content = response\n response = self._py_object.response\n\n # If the form_content is an exception response, return it\n if hasattr(form_content, '_exception'):\n return form_content\n\n form_content = htmlfill.render(form_content, defaults=params,\n errors=errors)\n if legacy_response:\n # Let the Controller merge the legacy response\n response.content = form_content\n return response\n else:\n return form_content\n return decorator(wrapper)\n\n\nclass HelloFormSchema(Schema):\n allow_extra_fields = True\n filter_extra_fields = True\n name = formencode.validators.UnicodeString(not_empty=True)\n email = formencode.validators.UnicodeString(not_empty=True)\n\nclass HelloController(BaseController):\n def new(self):\n return render('/hello/new.html')\n\n def view(self):\n return 'created'\n\n @handle_exceptions(form='new')\n @validate(schema=HelloFormSchema(), form='new')\n @restrict(\"POST\")\n def create(self):\n #here is code interacting with model which potentially could raise exception:\n if self.form_result['name'] == 'doe':\n raise ModelException('user already exists!')\n return redirect(url(controller='hello', action='view'))\n\nnew.html:\n${h.form(h.url(controller='hello', action='create'), 'post')}\n<dl>\n <dt>Name</dt>\n <dd>${h.text('name')}</dd>\n <dt>Email</dt>\n <dd>${h.text('email')}</dd>\n <dd>\n ${h.submit('create', 'Create')}\n </dd>\n</dl>\n${h.end_form()}\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"error_handling",
"pylons",
"python"
] |
stackoverflow_0002526458_error_handling_pylons_python.txt
|
Q:
compare two files in python
in a.txt i have the text(line one after the other)
login;user;name
login;user;name1
login;user
in b.txt i have the text
login;user
login;user
login;user;name2
after comparing it should display in a text file as
login;user;name
login;user;name1
login;user;name2....
How can it be done using python?
A:
for a, b in zip(open('a'), open('b')):
print(a if len(a.split(';')) == 3 else b)
A:
Perhaps the standard-lib difflib module can be of help - check out its documentation. Your question is not clear enough for a more complete answer.
A:
Based on the vague information given, I would try something like the following:
import itertools
def merger(fni1, fni2):
"merge two files ignoring 'login;user\n' lines"
fp1= open(fni1, "r")
fp2= open(fni2, "r")
try:
for line in itertools.chain(fp1, fp2):
if line != "login;user\n":
yield line
finally:
fp1.close()
fp2.close()
def merge_to_file(fni1, fni2, fno):
with open(fno, "w") as fp:
fp.writelines(merger(fni1, fni2))
The merge_to_file is the function you should use.
|
compare two files in python
|
in a.txt i have the text(line one after the other)
login;user;name
login;user;name1
login;user
in b.txt i have the text
login;user
login;user
login;user;name2
after comparing it should display in a text file as
login;user;name
login;user;name1
login;user;name2....
How can it be done using python?
|
[
"for a, b in zip(open('a'), open('b')):\n print(a if len(a.split(';')) == 3 else b)\n\n",
"Perhaps the standard-lib difflib module can be of help - check out its documentation. Your question is not clear enough for a more complete answer.\n",
"Based on the vague information given, I would try something like the following:\nimport itertools\n\ndef merger(fni1, fni2):\n \"merge two files ignoring 'login;user\\n' lines\"\n fp1= open(fni1, \"r\")\n fp2= open(fni2, \"r\")\n try:\n for line in itertools.chain(fp1, fp2):\n if line != \"login;user\\n\":\n yield line\n finally:\n fp1.close()\n fp2.close()\n\ndef merge_to_file(fni1, fni2, fno):\n with open(fno, \"w\") as fp:\n fp.writelines(merger(fni1, fni2))\n\nThe merge_to_file is the function you should use.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002523329_python_string.txt
|
Q:
(interactive) graph as in graph theory on a web page?
Possible Duplicate:
Graph visualization code in javascript?
I have to integrate a graph with nodes and edges on a web page. Ideally, i would like to be able to interact with it (like moving the nodes around).
Actually, i'm beginning by representing trees, so i would appreciate to be able to collapse subtrees.
How can I do that ? I was considering google-visualization api but i wasn't able to find the kind of visualization i'm looking for (org chart doesn't allow to have multiple fathers, if i understood well)
I've got no idea of the kind of technology so my tagging may not be really accurate :-).
thanks
A:
Two other options are:
Prefuse Flare which is in flash
JavaScript InfoVis Toolkit (JIT)
A:
RaphaelJS may be of interest to you. Particularly this example.
A:
http://processingjs.org/ might have what you're looking for.
A:
I'd go for SVG (all 'newer' browsers implement it more or less; older via plugins: e.g. IE6).
If you want to make it interactive javascript manipulation should be doable.
|
(interactive) graph as in graph theory on a web page?
|
Possible Duplicate:
Graph visualization code in javascript?
I have to integrate a graph with nodes and edges on a web page. Ideally, i would like to be able to interact with it (like moving the nodes around).
Actually, i'm beginning by representing trees, so i would appreciate to be able to collapse subtrees.
How can I do that ? I was considering google-visualization api but i wasn't able to find the kind of visualization i'm looking for (org chart doesn't allow to have multiple fathers, if i understood well)
I've got no idea of the kind of technology so my tagging may not be really accurate :-).
thanks
|
[
"Two other options are:\n\nPrefuse Flare which is in flash\nJavaScript InfoVis Toolkit (JIT)\n\n",
"RaphaelJS may be of interest to you. Particularly this example.\n",
"http://processingjs.org/ might have what you're looking for.\n",
"I'd go for SVG (all 'newer' browsers implement it more or less; older via plugins: e.g. IE6).\nIf you want to make it interactive javascript manipulation should be doable.\n"
] |
[
5,
3,
1,
0
] |
[] |
[] |
[
"ajax",
"graph",
"javascript",
"python"
] |
stackoverflow_0002525781_ajax_graph_javascript_python.txt
|
Q:
Speex in Python
How can I use Speex to encode/decode from within python? Are there any wrappers?
I found an old project pySpeex but it is obsolete now (requires Python 2.2).
A:
I think starting from pySpeex (and tweaking any issue that may arise if you're using Python 2.6, say, in lieu of 2.2) is by far the path of least resistance -- there aren't that many backward incompatibilities between 2.2 and 2.6, after all, so the amount of work should be pretty limited (and then you can contribute the patches, if any, back to pySpeex's maintainers to gain some good karma -- why not, after all?).
|
Speex in Python
|
How can I use Speex to encode/decode from within python? Are there any wrappers?
I found an old project pySpeex but it is obsolete now (requires Python 2.2).
|
[
"I think starting from pySpeex (and tweaking any issue that may arise if you're using Python 2.6, say, in lieu of 2.2) is by far the path of least resistance -- there aren't that many backward incompatibilities between 2.2 and 2.6, after all, so the amount of work should be pretty limited (and then you can contribute the patches, if any, back to pySpeex's maintainers to gain some good karma -- why not, after all?).\n"
] |
[
1
] |
[] |
[] |
[
"python",
"speex",
"wrapper"
] |
stackoverflow_0002525494_python_speex_wrapper.txt
|
Q:
Merging contents of two lists based on a if-loop
I have a minor problem while checking for elements in a list:
I have two files with contents something like this
file 1: file2:
47 358 47
48 450 49
49 56 50
I parsed both files into two lists and used the following code to check
for i in file_1:
for j in file_2:
j = j.split()
if i == j[1]:
x=' '.join(j)
print >> write_in, x
I am now trying to get a "0" if the value of file_1 is not there in file_2 for example, value "48" is not there is file_2 so I need to get the output like (with only one space in between the two numbers) Also both the conditions should produce only one output file:
output_file:
358 47
0 48
450 49
56 50
I tried using the dictionary approach but I didn't quite get what I wanted (actually I don't know how to use dictionary in python correctly ;)). Any help will be great.
A:
r1=open('file1').read().split()
r2=open('file2').read().split()
d=dict(zip(r2[1::2],r2[::2]))
output='\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
open('output_file','wb').write(output)
Test
>>> file1='47\n48\n49\n50'
>>> file2='358 47\n450 49\n56 50'
>>>
>>> r1=file1.split()
>>> r2=file2.split()
>>>
>>> d=dict(zip(r2[1::2],r2[::2])) #
>>> d
{'47': '358', '50': '56', '49': '450'}
>>>
>>> print '\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
358 47
0 48
450 49
56 50
>>>
A:
You could modify your code quite easily:
for i in file_1:
x = None
for j in file_2:
j = j.split()
if i == j[1]:
x = ' '.join(j)
if x is None:
x = ' '.join(['0', i])
Depending on your inputs, the whole task might be of course simplified even further. At the moment, your code is 0(n**2) complexity.
A:
Here's a readable solution using a dictionary:
d = {}
for k in file1:
d[k] = 0
for line in file2:
v, k = line.split()
d[k] = v
for k in sorted(d):
print d[k], k
A:
You can try something like:
l1 = open('file1').read().split()
l2 = [line.split() for line in open('file2')]
for x, y in zip(l1, l2):
if x not in y:
print 0, x
print ' '.join(y)
but if you follow your logic, the output should be
358 47
0 48
450 49
0 49
56 50
and not
358 47
0 48
450 49
56 50
A:
def file_process(filename1, filename2):
# read first file with zeroes as values
with open(filename1) as fp:
adict= dict( (line.rstrip(), 0) for line in fp)
# read second file as "value key"
with open(filename2) as fp:
adict.update(
line.rstrip().partition(" ")[2::-2] # tricky, read notes
for line in fp)
for key in sorted(adict):
yield adict[key], key
fp= open("output_file", "w")
fp.writelines("%s %s\n" % items for items in file_process("file1", "file2"))
fp.close()
str.partition(" ") returns a tuple of (pre-space, space, post-space). By slicing the tuple, starting at item 2 (post-space) and moving by a step of -2, we return a tuple of (post-space, pre-space), which are (key, value) for the dictionary that describes the solution.
PS Um :) I just noticed that my answer is essentially the same as Daniel Stutzbach's.
|
Merging contents of two lists based on a if-loop
|
I have a minor problem while checking for elements in a list:
I have two files with contents something like this
file 1: file2:
47 358 47
48 450 49
49 56 50
I parsed both files into two lists and used the following code to check
for i in file_1:
for j in file_2:
j = j.split()
if i == j[1]:
x=' '.join(j)
print >> write_in, x
I am now trying to get a "0" if the value of file_1 is not there in file_2 for example, value "48" is not there is file_2 so I need to get the output like (with only one space in between the two numbers) Also both the conditions should produce only one output file:
output_file:
358 47
0 48
450 49
56 50
I tried using the dictionary approach but I didn't quite get what I wanted (actually I don't know how to use dictionary in python correctly ;)). Any help will be great.
|
[
"r1=open('file1').read().split()\nr2=open('file2').read().split()\n\nd=dict(zip(r2[1::2],r2[::2]))\n\noutput='\\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)\n\nopen('output_file','wb').write(output)\n\nTest\n>>> file1='47\\n48\\n49\\n50'\n>>> file2='358 47\\n450 49\\n56 50'\n>>>\n>>> r1=file1.split()\n>>> r2=file2.split()\n>>>\n>>> d=dict(zip(r2[1::2],r2[::2])) #\n>>> d\n{'47': '358', '50': '56', '49': '450'}\n>>>\n>>> print '\\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)\n358 47\n0 48\n450 49\n56 50\n>>>\n\n",
"You could modify your code quite easily:\nfor i in file_1:\n x = None\n for j in file_2:\n j = j.split()\n if i == j[1]:\n x = ' '.join(j)\n if x is None:\n x = ' '.join(['0', i])\n\nDepending on your inputs, the whole task might be of course simplified even further. At the moment, your code is 0(n**2) complexity.\n",
"Here's a readable solution using a dictionary:\nd = {}\nfor k in file1:\n d[k] = 0\nfor line in file2:\n v, k = line.split()\n d[k] = v\nfor k in sorted(d):\n print d[k], k\n\n",
"You can try something like:\nl1 = open('file1').read().split()\nl2 = [line.split() for line in open('file2')]\n\nfor x, y in zip(l1, l2):\n if x not in y:\n print 0, x\n print ' '.join(y)\n\nbut if you follow your logic, the output should be\n358 47\n0 48\n450 49\n0 49\n56 50\n\nand not\n358 47\n0 48\n450 49\n56 50\n\n",
"def file_process(filename1, filename2):\n\n # read first file with zeroes as values\n with open(filename1) as fp:\n adict= dict( (line.rstrip(), 0) for line in fp)\n\n # read second file as \"value key\"\n with open(filename2) as fp:\n adict.update(\n line.rstrip().partition(\" \")[2::-2] # tricky, read notes\n for line in fp)\n for key in sorted(adict):\n yield adict[key], key\n\nfp= open(\"output_file\", \"w\")\nfp.writelines(\"%s %s\\n\" % items for items in file_process(\"file1\", \"file2\"))\nfp.close()\n\nstr.partition(\" \") returns a tuple of (pre-space, space, post-space). By slicing the tuple, starting at item 2 (post-space) and moving by a step of -2, we return a tuple of (post-space, pre-space), which are (key, value) for the dictionary that describes the solution.\nPS Um :) I just noticed that my answer is essentially the same as Daniel Stutzbach's.\n"
] |
[
2,
1,
1,
0,
0
] |
[] |
[] |
[
"list",
"loops",
"python"
] |
stackoverflow_0002507090_list_loops_python.txt
|
Q:
maintaining a large list in python
I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.
The list should implement all the python-list features, but most of the time I will work sequentially: scan some range in the list and while scanning decide if I want to insert\pop some nodes in the scanning point.
The list can be very large (2-3 GB), and should not be all contained in the RAM at once.
The nodes are small (100-200 bytes) but can contain various types of data.
A good solution for this could be using a BTree, where only the last accessed buckets are loaded in the RAM.
Using SQL tables is not good, since I'll need to implement a complex index-key mechanism.
My data is not a table, its a simple python list, with the feature of adding elements in specific indexes, and popping elements from specific positions.
I tried ZODB and zc.blist, which implement a BTree based list that can be stored in a ZODB database file, but I don't know how to configure it so the above features will run in reasonable time.
I don't need all the multi-threading\transactioning features. No one else will touch the database-file except for my single-thread program.
Can anyone explain me how to configure the ZODB\zc.blist so the above features will run fast, or show me a different large-list implementation?
Some quick&dirty code that I tried:
import time
import random
NODE_JUMP = 50000
NODE_ACCESS = 10000
print 'STARTING'
random_bytes = open('/dev/urandom', 'rb')
my_list = list()
nodes_no = 0
while True:
nodes_no += NODE_JUMP
start = time.time()
my_list.extend(random_bytes.read(100) for i in xrange(NODE_JUMP))
print 'extending to %s nodes took %.2f seconds' % (nodes_no, time.time() - start)
section_start = random.randint(0, nodes_no -NODE_ACCESS -1)
start = time.time()
for index in xrange(section_start, section_start + NODE_ACCESS):
# rotate the string
my_list[index] = my_list[index][1:] + my_list[index][0]
print 'access to %s nodes took %.2f seconds' % (NODE_ACCESS, time.time() - start,)
Print ended with:
extending to 5000000 nodes took 3.49 seconds
access to 10000 nodes took 0.02 seconds
extending to 5050000 nodes took 3.98 seconds
access to 10000 nodes took 0.01 seconds
extending to 5100000 nodes took 2.54 seconds
access to 10000 nodes took 0.01 seconds
extending to 5150000 nodes took 2.19 seconds
access to 10000 nodes took 0.11 seconds
extending to 5200000 nodes took 2.49 seconds
access to 10000 nodes took 0.01 seconds
extending to 5250000 nodes took 3.13 seconds
access to 10000 nodes took 0.05 seconds
Killed (not by me)
A:
Using zc.blist can bring good results after all, and setting the "cache_size" option when creating the DB controls the size of the data that will remain in the RAM. The size of used RAM can grow bigger if you don't do "transaction.commit" often enough. By defining a large cache_size and doing transaction.commit often, the last accessed buckets of the blist will stay in the RAM, giving you fast access to them, and the amount of used RAM won't grow too much.
Packing is very expensive though, but if you have a large harddisk, you don't have to do it that often anyway.
Here is some code to try yourself. Run "top" at the background and change cache_size to see how it affects the amount of used RAM.
import time
import os
import glob
from ZODB import DB
from ZODB.FileStorage import FileStorage
import transaction
from zc.blist import BList
print('STARTING')
random = open('/dev/urandom', 'rb')
def test_list(my_list, loops = 1000, element_size = 100):
print('testing list')
start = time.time()
for loop in xrange(loops):
my_list.append(random.read(element_size))
print('appending %s elements took %.4f seconds' % (loops, time.time() - start))
start = time.time()
length = len(my_list)
print('length calculated in %.4f seconds' % (time.time() - start,))
start = time.time()
for loop in xrange(loops):
my_list.insert(length / 2, random.read(element_size))
print('inserting %s elements took %.4f seconds' % (loops, time.time() - start))
start = time.time()
for loop in xrange(loops):
my_list[loop] = my_list[loop][1:] + my_list[loop][0]
print('modifying %s elements took %.4f seconds' % (loops, time.time() - start))
start = time.time()
for loop in xrange(loops):
del my_list[0]
print('removing %s elements took %.4f seconds' % (loops, time.time() - start))
start = time.time()
transaction.commit()
print('committing all above took %.4f seconds' % (time.time() - start,))
del my_list[:loops]
transaction.commit()
start = time.time()
pack()
print('packing after removing %s elements took %.4f seconds' % (loops, time.time() - start))
for filename in glob.glob('database.db*'):
try:
os.unlink(filename)
except OSError:
pass
db = DB(FileStorage('database.db'),
cache_size = 2000)
def pack():
db.pack()
root = db.open().root()
root['my_list'] = BList()
print('inserting initial data to blist')
for loop in xrange(10):
root['my_list'].extend(random.read(100) for x in xrange(100000))
transaction.commit()
transaction.commit()
test_list(root['my_list'])
A:
I think the ZODB is the tool to use. It will store lots of arbitrary items, it handles memory issues.
Here is a working example, and in this case I included objects that reference each other as well as being stored in a BTree by number.
import random
from collections import deque
import ZODB
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
import transaction
import persistent
import BTrees
def random_string(n=100):
return ''.join([chr(random.randint(0,95)+32) for i in xrange(n)])
class Node(persistent.Persistent):
def __init__(self, value=None):
if not value:
self.value = random_string()
def setNeighbors(self, refs):
self.p1 = refs[0]
self.p2 = refs[1]
self.p3 = refs[2]
self.p4 = refs[3]
def getTree():
storage = FileStorage('c:\\test.zdb')
db = DB(storage)
connection = db.open()
root = connection.root()
if root.has_key('tree'):
tree = root['tree']
else:
tree = BTrees.OOBTree.OOBTree()
root['tree'] = tree
transaction.commit()
return tree
def fillDB():
tree = getTree()
# start with some initial objects.
nodes = deque([Node(), Node(), Node(), Node()])
node = Node()
for n in xrange(20000):
tree[n] = node # store the node based on a numeric ID
node.setNeighbors(nodes) # Make the node refer to more nodes.
node = nodes.popleft() # maintain out list of 4 upcoming nodes.
nodes.append(Node())
if n % 1000 == 0:
transaction.commit() # Must commit for data to make it to disk.
print n
transaction.commit()
return tree
At this point the tree variable basically works like a dictionary and can be accessed by the key. You can also get the keys in a range by using tree.keys(min, max) as described by the ZODB BTrees API documentation.
You can store your 10 lists by putting each one under a different key in the root object returned by the ZODB. The root object serves as the "gateway" to the ZODB object storage.
Thanks to the ZODB, you can also use the inter-object references as well as the Btree index. For example:
tree = getTree()
node1 = tree[1]
print node1.p1.p1.p1.p1.p1.p1.p1.p1.p1.value
A:
How about using Tokyo Cabinet? Very fast and simple, like lists but built for what you want.
http://1978th.net/tokyocabinet/
|
maintaining a large list in python
|
I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.
The list should implement all the python-list features, but most of the time I will work sequentially: scan some range in the list and while scanning decide if I want to insert\pop some nodes in the scanning point.
The list can be very large (2-3 GB), and should not be all contained in the RAM at once.
The nodes are small (100-200 bytes) but can contain various types of data.
A good solution for this could be using a BTree, where only the last accessed buckets are loaded in the RAM.
Using SQL tables is not good, since I'll need to implement a complex index-key mechanism.
My data is not a table, its a simple python list, with the feature of adding elements in specific indexes, and popping elements from specific positions.
I tried ZODB and zc.blist, which implement a BTree based list that can be stored in a ZODB database file, but I don't know how to configure it so the above features will run in reasonable time.
I don't need all the multi-threading\transactioning features. No one else will touch the database-file except for my single-thread program.
Can anyone explain me how to configure the ZODB\zc.blist so the above features will run fast, or show me a different large-list implementation?
Some quick&dirty code that I tried:
import time
import random
NODE_JUMP = 50000
NODE_ACCESS = 10000
print 'STARTING'
random_bytes = open('/dev/urandom', 'rb')
my_list = list()
nodes_no = 0
while True:
nodes_no += NODE_JUMP
start = time.time()
my_list.extend(random_bytes.read(100) for i in xrange(NODE_JUMP))
print 'extending to %s nodes took %.2f seconds' % (nodes_no, time.time() - start)
section_start = random.randint(0, nodes_no -NODE_ACCESS -1)
start = time.time()
for index in xrange(section_start, section_start + NODE_ACCESS):
# rotate the string
my_list[index] = my_list[index][1:] + my_list[index][0]
print 'access to %s nodes took %.2f seconds' % (NODE_ACCESS, time.time() - start,)
Print ended with:
extending to 5000000 nodes took 3.49 seconds
access to 10000 nodes took 0.02 seconds
extending to 5050000 nodes took 3.98 seconds
access to 10000 nodes took 0.01 seconds
extending to 5100000 nodes took 2.54 seconds
access to 10000 nodes took 0.01 seconds
extending to 5150000 nodes took 2.19 seconds
access to 10000 nodes took 0.11 seconds
extending to 5200000 nodes took 2.49 seconds
access to 10000 nodes took 0.01 seconds
extending to 5250000 nodes took 3.13 seconds
access to 10000 nodes took 0.05 seconds
Killed (not by me)
|
[
"Using zc.blist can bring good results after all, and setting the \"cache_size\" option when creating the DB controls the size of the data that will remain in the RAM. The size of used RAM can grow bigger if you don't do \"transaction.commit\" often enough. By defining a large cache_size and doing transaction.commit often, the last accessed buckets of the blist will stay in the RAM, giving you fast access to them, and the amount of used RAM won't grow too much.\nPacking is very expensive though, but if you have a large harddisk, you don't have to do it that often anyway.\nHere is some code to try yourself. Run \"top\" at the background and change cache_size to see how it affects the amount of used RAM.\nimport time\nimport os\nimport glob\nfrom ZODB import DB\nfrom ZODB.FileStorage import FileStorage\nimport transaction\nfrom zc.blist import BList\n\nprint('STARTING')\n\nrandom = open('/dev/urandom', 'rb')\n\n\ndef test_list(my_list, loops = 1000, element_size = 100):\n print('testing list')\n start = time.time()\n for loop in xrange(loops):\n my_list.append(random.read(element_size))\n print('appending %s elements took %.4f seconds' % (loops, time.time() - start))\n\n start = time.time()\n length = len(my_list)\n print('length calculated in %.4f seconds' % (time.time() - start,))\n\n start = time.time()\n for loop in xrange(loops):\n my_list.insert(length / 2, random.read(element_size))\n print('inserting %s elements took %.4f seconds' % (loops, time.time() - start))\n\n start = time.time()\n for loop in xrange(loops):\n my_list[loop] = my_list[loop][1:] + my_list[loop][0]\n print('modifying %s elements took %.4f seconds' % (loops, time.time() - start))\n\n start = time.time()\n for loop in xrange(loops):\n del my_list[0]\n print('removing %s elements took %.4f seconds' % (loops, time.time() - start))\n\n start = time.time()\n transaction.commit()\n print('committing all above took %.4f seconds' % (time.time() - start,))\n\n del my_list[:loops]\n transaction.commit()\n\n start = time.time()\n pack()\n print('packing after removing %s elements took %.4f seconds' % (loops, time.time() - start))\n\nfor filename in glob.glob('database.db*'): \n try:\n os.unlink(filename)\n except OSError:\n pass\n\ndb = DB(FileStorage('database.db'),\n cache_size = 2000)\n\ndef pack():\n db.pack()\n\nroot = db.open().root()\n\nroot['my_list'] = BList()\n\nprint('inserting initial data to blist')\n\nfor loop in xrange(10):\n root['my_list'].extend(random.read(100) for x in xrange(100000))\n transaction.commit()\n\ntransaction.commit()\n\ntest_list(root['my_list'])\n\n",
"I think the ZODB is the tool to use. It will store lots of arbitrary items, it handles memory issues.\nHere is a working example, and in this case I included objects that reference each other as well as being stored in a BTree by number. \nimport random\nfrom collections import deque\n\nimport ZODB\nfrom ZODB.FileStorage import FileStorage\nfrom ZODB.DB import DB\nimport transaction\nimport persistent\nimport BTrees\n\ndef random_string(n=100):\n return ''.join([chr(random.randint(0,95)+32) for i in xrange(n)]) \n\n\nclass Node(persistent.Persistent):\n def __init__(self, value=None):\n if not value:\n self.value = random_string()\n\n def setNeighbors(self, refs):\n self.p1 = refs[0]\n self.p2 = refs[1]\n self.p3 = refs[2]\n self.p4 = refs[3]\n\n\ndef getTree():\n storage = FileStorage('c:\\\\test.zdb')\n db = DB(storage)\n connection = db.open()\n root = connection.root()\n if root.has_key('tree'):\n tree = root['tree']\n else:\n tree = BTrees.OOBTree.OOBTree()\n root['tree'] = tree\n transaction.commit()\n return tree\n\n\ndef fillDB():\n tree = getTree()\n\n # start with some initial objects.\n nodes = deque([Node(), Node(), Node(), Node()])\n node = Node()\n\n for n in xrange(20000):\n tree[n] = node # store the node based on a numeric ID\n node.setNeighbors(nodes) # Make the node refer to more nodes.\n node = nodes.popleft() # maintain out list of 4 upcoming nodes.\n nodes.append(Node())\n if n % 1000 == 0:\n transaction.commit() # Must commit for data to make it to disk.\n print n\n transaction.commit()\n return tree\n\nAt this point the tree variable basically works like a dictionary and can be accessed by the key. You can also get the keys in a range by using tree.keys(min, max) as described by the ZODB BTrees API documentation.\nYou can store your 10 lists by putting each one under a different key in the root object returned by the ZODB. The root object serves as the \"gateway\" to the ZODB object storage.\nThanks to the ZODB, you can also use the inter-object references as well as the Btree index. For example:\ntree = getTree()\n\nnode1 = tree[1]\nprint node1.p1.p1.p1.p1.p1.p1.p1.p1.p1.value\n\n",
"How about using Tokyo Cabinet? Very fast and simple, like lists but built for what you want.\nhttp://1978th.net/tokyocabinet/\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"database",
"python",
"zodb"
] |
stackoverflow_0002510218_database_python_zodb.txt
|
Q:
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
In Python 2.6, I can run the following fine to strip out chars like -()
'(123) 456-7890'.translate(None, '-(), ')
Python2.5 translate does not accept None, how can I do the above in 2.5?
A:
That should be possible with maketrans:
import string
'(123) 456-7890'.translate(string.maketrans('', ''), '-(), ')
But you can also use regular expressions which is more readable.
A:
Use string.maketrans with empty arguments to create the identity translation table:
string.maketrans(from, to)
Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
>>> import string
>>> identity = string.maketrans("", "")
>>> '(123) 456-7890'.translate(identity, '-(), ')
'1234567890'
A:
As an alternative, you can always keep only the digits:
def strip_nondigits(text):
return filter(type(text).isdigit, text)
>>> strip_nondigits('(123) 456-7890')
'1234567890'
This should be more robust against spurious characters. The type(text) makes it work for unicode objects too.
A:
Regular Expressions.
>>> import re
>>> re.sub('\-|\(|\)| ','','(123) 456-7890')
1234567890
|
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
|
In Python 2.6, I can run the following fine to strip out chars like -()
'(123) 456-7890'.translate(None, '-(), ')
Python2.5 translate does not accept None, how can I do the above in 2.5?
|
[
"That should be possible with maketrans:\nimport string\n'(123) 456-7890'.translate(string.maketrans('', ''), '-(), ')\n\nBut you can also use regular expressions which is more readable.\n",
"Use string.maketrans with empty arguments to create the identity translation table:\n\nstring.maketrans(from, to)\nReturn a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.\n\n>>> import string\n>>> identity = string.maketrans(\"\", \"\")\n>>> '(123) 456-7890'.translate(identity, '-(), ')\n'1234567890'\n\n",
"As an alternative, you can always keep only the digits:\ndef strip_nondigits(text):\n return filter(type(text).isdigit, text)\n\n>>> strip_nondigits('(123) 456-7890')\n'1234567890'\n\nThis should be more robust against spurious characters. The type(text) makes it work for unicode objects too.\n",
"Regular Expressions.\n>>> import re\n>>> re.sub('\\-|\\(|\\)| ','','(123) 456-7890')\n1234567890\n\n"
] |
[
3,
3,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002365876_python.txt
|
Q:
Is there a way to create a python object that will be not sortable?
Is there a possibility to create any python object that will be not sortable? So that will be an exception when trying to sort a list of that objects?
I created a very simple class, didn't define any comparison methods, but still instances of this class are comparable and thus sortable. Maybe, my class inherits comparison methods from somewhere. But I don't want this behaviour.
A:
You could define a __cmp__ method on the class and always raise an exception when it is called. That might do the trick.
Out of curiosity, why?
A:
As Will McCutchen has mentioned, you can define a __cmp__ method that raises an exception to prevent garden variety sorting. Something like this:
class Foo(object):
def __cmp__(self, other):
raise Exception()
a = [Foo(), Foo(), Foo()]
a.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __cmp__
Exception
However, you cannot truly prevent a developer from sorting a list of your objects. Using the key or cmp argument with list.sort() or with the built-in standalone sorted() function , anyone can circumvent the __cmp__ method by using a custom comparison function or sorting key.
# continuing from above
>>> a = [Foo(), Foo(), Foo()]
>>> a
[<__main__.Foo object at 0x1004a3350>, <__main__.Foo object at 0x1004a3390>,
<__main__.Foo object at 0x1004a33d0>]
>>> a.sort(key=id, reverse=True)
>>> # or a.sort(cmp=lambda a, b: cmp(id(b), id(a)))
>>> # or sorted(a, key=id)
>>> # etc...
[<__main__.Foo object at 0x1004a33d0>, <__main__.Foo object at 0x1004a3390>,
<__main__.Foo object at 0x1004a3350>]
As others will point out, I'm not sure there's much value in trying to prevent someone from sorting an object. If this isn't just a curious itch you're trying to scratch, what's the use case for this?
A:
The default list sorting uses the built-in cmp() function on its elements. The cmp() function checks if its arguments (2 elements from your list) have a __cmp__() method. If yes, this method is used for comparison. Otherwise, as in your case, the argument object IDs (return value of the built-in function id()) are used for comparison.
To let the sorting fail, you could define a comparison method which throws an Exception:
>>> class X(object):
... def __cmp__(self, other):
... raise StandardError # or whatever Exception you need
...
>>> l = [X(), X(), X()]
>>> l.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in __cmp__
StandardError
A:
For what it's worth, in Python 3 the default will be for new items to not be comparable (and hence not sortable). In Python 2, you have to explicitly create a __cmp__ or __lt__ method, as others have said.
A:
Why don't you just write a class that contains a list object and provides methods to access the data inside? By doing that you would effectively hide the list and therefore prevent them from sorting it.
A:
Sets don't have a total ordering
>>> s=set((1,2,3))
>>> t=set("abc")
>>> s<t
False
>>> t<s
False
>>>
But no exception is raise when you try to sort them
>>> sorted([s,t])
[set([1, 2, 3]), set(['a', 'c', 'b'])]
A:
The python sort algorithms use the __lt__ special method. Keeping in mind that using the cmp and key arguments of the sorting function and methods, it is suggested that your class defines a method:
def __lt__(self, other):
raise NotImplementedError
|
Is there a way to create a python object that will be not sortable?
|
Is there a possibility to create any python object that will be not sortable? So that will be an exception when trying to sort a list of that objects?
I created a very simple class, didn't define any comparison methods, but still instances of this class are comparable and thus sortable. Maybe, my class inherits comparison methods from somewhere. But I don't want this behaviour.
|
[
"You could define a __cmp__ method on the class and always raise an exception when it is called. That might do the trick.\nOut of curiosity, why?\n",
"As Will McCutchen has mentioned, you can define a __cmp__ method that raises an exception to prevent garden variety sorting. Something like this:\nclass Foo(object):\n def __cmp__(self, other):\n raise Exception()\n\na = [Foo(), Foo(), Foo()]\na.sort()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 3, in __cmp__\nException\n\nHowever, you cannot truly prevent a developer from sorting a list of your objects. Using the key or cmp argument with list.sort() or with the built-in standalone sorted() function , anyone can circumvent the __cmp__ method by using a custom comparison function or sorting key.\n# continuing from above\n>>> a = [Foo(), Foo(), Foo()]\n>>> a\n[<__main__.Foo object at 0x1004a3350>, <__main__.Foo object at 0x1004a3390>,\n <__main__.Foo object at 0x1004a33d0>]\n\n>>> a.sort(key=id, reverse=True)\n>>> # or a.sort(cmp=lambda a, b: cmp(id(b), id(a)))\n>>> # or sorted(a, key=id)\n>>> # etc...\n[<__main__.Foo object at 0x1004a33d0>, <__main__.Foo object at 0x1004a3390>,\n <__main__.Foo object at 0x1004a3350>]\n\nAs others will point out, I'm not sure there's much value in trying to prevent someone from sorting an object. If this isn't just a curious itch you're trying to scratch, what's the use case for this?\n",
"The default list sorting uses the built-in cmp() function on its elements. The cmp() function checks if its arguments (2 elements from your list) have a __cmp__() method. If yes, this method is used for comparison. Otherwise, as in your case, the argument object IDs (return value of the built-in function id()) are used for comparison.\nTo let the sorting fail, you could define a comparison method which throws an Exception:\n>>> class X(object):\n... def __cmp__(self, other):\n... raise StandardError # or whatever Exception you need\n...\n>>> l = [X(), X(), X()]\n>>> l.sort()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in __cmp__\nStandardError\n\n",
"For what it's worth, in Python 3 the default will be for new items to not be comparable (and hence not sortable). In Python 2, you have to explicitly create a __cmp__ or __lt__ method, as others have said.\n",
"Why don't you just write a class that contains a list object and provides methods to access the data inside? By doing that you would effectively hide the list and therefore prevent them from sorting it.\n",
"Sets don't have a total ordering\n>>> s=set((1,2,3))\n>>> t=set(\"abc\")\n>>> s<t\nFalse\n>>> t<s\nFalse\n>>> \n\nBut no exception is raise when you try to sort them\n>>> sorted([s,t])\n[set([1, 2, 3]), set(['a', 'c', 'b'])]\n\n",
"The python sort algorithms use the __lt__ special method. Keeping in mind that using the cmp and key arguments of the sorting function and methods, it is suggested that your class defines a method:\ndef __lt__(self, other):\n raise NotImplementedError\n\n"
] |
[
7,
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002367119_python.txt
|
Q:
use proxy in python to fetch a webpage
I am trying to write a function in Python to use a public anonymous proxy and fetch a webpage, but I got a rather strange error.
The code (I have Python 2.4):
import urllib2
def get_source_html_proxy(url, pip, timeout):
# timeout in seconds (maximum number of seconds willing for the code to wait in
# case there is a proxy that is not working, then it gives up)
proxy_handler = urllib2.ProxyHandler({'http': pip})
opener = urllib2.build_opener(proxy_handler)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(opener)
req=urllib2.Request(url)
sock=urllib2.urlopen(req)
timp=0 # a counter that is going to measure the time until the result (webpage) is
# returned
while 1:
data = sock.read(1024)
timp=timp+1
if len(data) < 1024: break
timpLimita=50000000 * timeout
if timp==timpLimita: # 5 millions is about 1 second
break
if timp==timpLimita:
print IPul + ": Connection is working, but the webpage is fetched in more than 50 seconds. This proxy returns the following IP: " + str(data)
return str(data)
else:
print "This proxy " + IPul + "= good proxy. " + "It returns the following IP: " + str(data)
return str(data)
# Now, I call the function to test it for one single proxy (IP:port) that does not support user and password (a public high anonymity proxy)
#(I put a proxy that I know is working - slow, but is working)
rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "93.84.221.248:3128", 50)
print rez
The error:
Traceback (most recent call last):
File "./public_html/cgi-bin/teste5.py", line 43, in ?
rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "xx.yy.zzz.ww:3128", 50)
File "./public_html/cgi-bin/teste5.py", line 18, in get_source_html_proxy
sock=urllib2.urlopen(req)
File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "/usr/lib64/python2.4/urllib2.py", line 358, in open
response = self._open(req, data)
File "/usr/lib64/python2.4/urllib2.py", line 376, in _open
'_open', req)
File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain
result = func(*args)
File "/usr/lib64/python2.4/urllib2.py", line 573, in
lambda r, proxy=url, type=type, meth=self.proxy_open: \
File "/usr/lib64/python2.4/urllib2.py", line 580, in proxy_open
if '@' in host:
TypeError: iterable argument required
I do not know why the character "@" is an issue (I have no such in my code. Should I have?)
Thanks in advance for your valuable help.
A:
urllib2.build_opener takes a list of handlers
opener = urllib2.build_opener([proxy_handler])
A:
The @ itself is a red herring, the traceback comes from the fact that it's trying to execute a x in host operation and, in that context, that means host has to be iterable (such as a string). You'll want to inspect the value of host there, it's something like None or a number, not what you meant.
|
use proxy in python to fetch a webpage
|
I am trying to write a function in Python to use a public anonymous proxy and fetch a webpage, but I got a rather strange error.
The code (I have Python 2.4):
import urllib2
def get_source_html_proxy(url, pip, timeout):
# timeout in seconds (maximum number of seconds willing for the code to wait in
# case there is a proxy that is not working, then it gives up)
proxy_handler = urllib2.ProxyHandler({'http': pip})
opener = urllib2.build_opener(proxy_handler)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(opener)
req=urllib2.Request(url)
sock=urllib2.urlopen(req)
timp=0 # a counter that is going to measure the time until the result (webpage) is
# returned
while 1:
data = sock.read(1024)
timp=timp+1
if len(data) < 1024: break
timpLimita=50000000 * timeout
if timp==timpLimita: # 5 millions is about 1 second
break
if timp==timpLimita:
print IPul + ": Connection is working, but the webpage is fetched in more than 50 seconds. This proxy returns the following IP: " + str(data)
return str(data)
else:
print "This proxy " + IPul + "= good proxy. " + "It returns the following IP: " + str(data)
return str(data)
# Now, I call the function to test it for one single proxy (IP:port) that does not support user and password (a public high anonymity proxy)
#(I put a proxy that I know is working - slow, but is working)
rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "93.84.221.248:3128", 50)
print rez
The error:
Traceback (most recent call last):
File "./public_html/cgi-bin/teste5.py", line 43, in ?
rez=get_source_html_proxy("http://www.whatismyip.com/automation/n09230945.asp", "xx.yy.zzz.ww:3128", 50)
File "./public_html/cgi-bin/teste5.py", line 18, in get_source_html_proxy
sock=urllib2.urlopen(req)
File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "/usr/lib64/python2.4/urllib2.py", line 358, in open
response = self._open(req, data)
File "/usr/lib64/python2.4/urllib2.py", line 376, in _open
'_open', req)
File "/usr/lib64/python2.4/urllib2.py", line 337, in _call_chain
result = func(*args)
File "/usr/lib64/python2.4/urllib2.py", line 573, in
lambda r, proxy=url, type=type, meth=self.proxy_open: \
File "/usr/lib64/python2.4/urllib2.py", line 580, in proxy_open
if '@' in host:
TypeError: iterable argument required
I do not know why the character "@" is an issue (I have no such in my code. Should I have?)
Thanks in advance for your valuable help.
|
[
"urllib2.build_opener takes a list of handlers\nopener = urllib2.build_opener([proxy_handler])\n\n",
"The @ itself is a red herring, the traceback comes from the fact that it's trying to execute a x in host operation and, in that context, that means host has to be iterable (such as a string). You'll want to inspect the value of host there, it's something like None or a number, not what you meant.\n"
] |
[
3,
0
] |
[] |
[] |
[
"proxy",
"python"
] |
stackoverflow_0002527668_proxy_python.txt
|
Q:
Python MySQLdb placeholders syntax
I'd like to use placeholders as seen in this example:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:
query = """UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
cursor.execute(query)
cursor2.execute(query)
cursor3.execute(query)
What would be the proper syntax for doing something like this?
A:
query = """UPDATE animal SET name = %s
WHERE name = %s
"""
values = ("snake", "turtle")
cursor.execute(query, values)
cursor2.execute(query, values)
or if you want group them together...
arglist = [query, values]
cursor.execute(*arglist)
cursor2.execute(*arglist)
but it's probably more readable to do it the first way.
|
Python MySQLdb placeholders syntax
|
I'd like to use placeholders as seen in this example:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:
query = """UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
cursor.execute(query)
cursor2.execute(query)
cursor3.execute(query)
What would be the proper syntax for doing something like this?
|
[
"query = \"\"\"UPDATE animal SET name = %s\n WHERE name = %s\n \"\"\"\nvalues = (\"snake\", \"turtle\")\n\ncursor.execute(query, values)\ncursor2.execute(query, values)\n\nor if you want group them together...\narglist = [query, values]\ncursor.execute(*arglist)\ncursor2.execute(*arglist)\n\nbut it's probably more readable to do it the first way.\n"
] |
[
5
] |
[] |
[] |
[
"mysql",
"pylons",
"python"
] |
stackoverflow_0002527941_mysql_pylons_python.txt
|
Q:
Replace a whole line in a txt file
I'am new to Python 3 and could really use a little help. I have a txt file containing:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
TargetName=D:\new
FriendlyName=Big
Could anyone help me, please? I have tried to search for it, but I didnt find something I could use. The text that should be replaced could have different length.
A:
import fileinput
for line in fileinput.FileInput("file",inplace=1):
sline=line.strip().split("=")
if sline[0].startswith("TargetName"):
sline[1]="new.txt"
elif sline[0].startswith("FriendlyName"):
sline[1]="big"
line='='.join(sline)
print(line)
A:
A very simple solution for what you're doing:
#!/usr/bin/python
import re
import sys
for line in open(sys.argv[1],'r').readlines():
line = re.sub(r'TargetName=.+',r'TargetName=D:\\new', line)
line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line)
print line,
You would invoke this from the command line as ./test.py myfile.txt > output.txt
A:
Writing to a temporary file and the renaming is the best way to make sure you won't get a damaged file if something goes wrong
import os
from tempfile import NamedTemporaryFile
fname = "lines.txt"
with open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout:
for line in fin:
if line.startswith("TargetName="):
line = "TargetName=D:\\new\n"
elif line.startswith("FriendlyName"):
line = "FriendlyName=Big\n"
fout.write(line.encode('utf8'))
os.rename(fout.name, fname)
A:
Is this a config (.ini) file you're trying to parse? The format looks suspiciously similar, except without a header section. You can use configparser, though it may add extra space around the "=" sign (i.e. "TargetName=D:\new" vs. "TargetName = D:\new"), but if those changes don't matter to you, using configparser is way easier and less error-prone than trying to parse it by hand every time.
txt (ini) file:
[section name]
FinishMessage=
TargetName=D:\something
FriendlyName=something
Code:
import sys
from configparser import SafeConfigParser
def main():
cp = SafeConfigParser()
cp.optionxform = str # Preserves case sensitivity
cp.readfp(open(sys.argv[1], 'r'))
section = 'section name'
options = {'TargetName': r'D:\new',
'FriendlyName': 'Big'}
for option, value in options.items():
cp.set(section, option, value)
cp.write(open(sys.argv[1], 'w'))
if __name__ == '__main__':
main()
txt (ini) file (after):
[section name]
FinishMessage =
TargetName = D:\new
FriendlyName = Big
A:
subs_names.py script works both Python 2.6+ and Python 3.x:
#!/usr/bin/env python
from __future__ import print_function
import sys, fileinput
# here goes new values
substitions = dict(TargetName=r"D:\new", FriendlyName="Big")
inplace = '-i' in sys.argv # make substitions inplace
if inplace:
sys.argv.remove('-i')
for line in fileinput.input(inplace=inplace):
name, sep, value = line.partition("=")
if name in substitions:
print(name, sep, substitions[name], sep='')
else:
print(line, end='')
Example:
$ python3.1 subs_names.py input.txt
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\new
FriendlyName=Big
If you are satisfied with the output then add -i parameter to make changes inplace:
$ python3.1 subs_names.py -i input.txt
|
Replace a whole line in a txt file
|
I'am new to Python 3 and could really use a little help. I have a txt file containing:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
TargetName=D:\new
FriendlyName=Big
Could anyone help me, please? I have tried to search for it, but I didnt find something I could use. The text that should be replaced could have different length.
|
[
"import fileinput\nfor line in fileinput.FileInput(\"file\",inplace=1):\n sline=line.strip().split(\"=\")\n if sline[0].startswith(\"TargetName\"):\n sline[1]=\"new.txt\"\n elif sline[0].startswith(\"FriendlyName\"):\n sline[1]=\"big\"\n line='='.join(sline) \n print(line)\n\n",
"A very simple solution for what you're doing:\n#!/usr/bin/python\nimport re\nimport sys\nfor line in open(sys.argv[1],'r').readlines():\n line = re.sub(r'TargetName=.+',r'TargetName=D:\\\\new', line)\n line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line)\n print line,\n\nYou would invoke this from the command line as ./test.py myfile.txt > output.txt\n",
"Writing to a temporary file and the renaming is the best way to make sure you won't get a damaged file if something goes wrong\nimport os\nfrom tempfile import NamedTemporaryFile\nfname = \"lines.txt\"\n\nwith open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout:\n for line in fin:\n if line.startswith(\"TargetName=\"):\n line = \"TargetName=D:\\\\new\\n\"\n elif line.startswith(\"FriendlyName\"):\n line = \"FriendlyName=Big\\n\"\n fout.write(line.encode('utf8'))\n os.rename(fout.name, fname)\n\n",
"Is this a config (.ini) file you're trying to parse? The format looks suspiciously similar, except without a header section. You can use configparser, though it may add extra space around the \"=\" sign (i.e. \"TargetName=D:\\new\" vs. \"TargetName = D:\\new\"), but if those changes don't matter to you, using configparser is way easier and less error-prone than trying to parse it by hand every time.\ntxt (ini) file:\n[section name]\n\nFinishMessage=\n\nTargetName=D:\\something\n\nFriendlyName=something\n\nCode:\nimport sys\nfrom configparser import SafeConfigParser\n\ndef main():\n cp = SafeConfigParser()\n cp.optionxform = str # Preserves case sensitivity\n cp.readfp(open(sys.argv[1], 'r'))\n section = 'section name'\n options = {'TargetName': r'D:\\new',\n 'FriendlyName': 'Big'}\n for option, value in options.items():\n cp.set(section, option, value)\n cp.write(open(sys.argv[1], 'w'))\n\nif __name__ == '__main__':\n main()\n\ntxt (ini) file (after):\n[section name]\n\nFinishMessage = \n\nTargetName = D:\\new\n\nFriendlyName = Big\n\n",
"subs_names.py script works both Python 2.6+ and Python 3.x:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys, fileinput\n\n# here goes new values\nsubstitions = dict(TargetName=r\"D:\\new\", FriendlyName=\"Big\")\n\ninplace = '-i' in sys.argv # make substitions inplace\nif inplace:\n sys.argv.remove('-i')\n\nfor line in fileinput.input(inplace=inplace):\n name, sep, value = line.partition(\"=\")\n if name in substitions:\n print(name, sep, substitions[name], sep='')\n else:\n print(line, end='')\n\nExample:\n$ python3.1 subs_names.py input.txt\nInstallPrompt=\n\nDisplayLicense=\n\nFinishMessage=\n\nTargetName=D:\\new\n\nFriendlyName=Big\n\nIf you are satisfied with the output then add -i parameter to make changes inplace:\n$ python3.1 subs_names.py -i input.txt\n\n"
] |
[
5,
2,
2,
2,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"replace",
"text"
] |
stackoverflow_0002527435_python_python_3.x_replace_text.txt
|
Q:
Simplest way to handle and display errors in a Python Pylons controller without a helper class
I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable.
Is this a correct way of doing it? Is there a better (but still simple) way? I prefer not to use any third party error or form handlers due to the extensive database queries we already have in place in our classes.
Furthermore, how can I "stop" the chain of processing in the class if one of the values is invalid? Is there like a "break" syntax or something?
Thanks.
>>> u = User()
>>> u.name = 'Jason Mendez'
>>> u.password = '1234'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "topic/model/user.py", line 79, in password
return self._password
ValueError: Your password must be greater than 6 characters
In my controller "register," I have:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
try:
u.name = c.name = request.POST['name']
except ValueError, error:
c.errors['name'] = error
try:
u.email = c.email = request.POST['email']
except ValueError, error:
c.errors['email'] = error
try:
u.password = c.password = request.POST['password']
except ValueError, error:
c.errors['password'] = error
try:
u.commit()
except ValueError, error:
pass
return render('/register.mako')
A:
You could remove repetition from the code as a semi-measure:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
for key in "name email password".split():
try:
value = request.POST[key]
for o in (u, c):
setattr(o, key, value)
except ValueError, error:
c.errors[key] = error
u.commit() # allow to propagate (show 500 on error if no middleware)
return render('/register.mako')
Form Handling page from Pylons docs describes several simple approaches to form validating that you could adapt for your project.
class RegisterController(BaseController):
@save(User, commit=True)
# `save` uses filled c.form_result to create User()
@validate(schema=register_schema, form='register')
# `validate` fills c.form_errors, c.form_result dictionaries
def create(self):
return render('/register.mako')
Where validate() is similar to Pylons validate() decorator and save() could be implemented as follows (using decorator module):
def save(klass, commit=False):
def call(action, *args, **kwargs):
obj = klass()
for attr in c.form_result:
if attr in obj.setable_attrs():
setattr(obj, attr, c.form_result[attr])
if commit:
obj.commit()
return action(*args, **kwargs)
return decorator.decorator(call)
|
Simplest way to handle and display errors in a Python Pylons controller without a helper class
|
I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable.
Is this a correct way of doing it? Is there a better (but still simple) way? I prefer not to use any third party error or form handlers due to the extensive database queries we already have in place in our classes.
Furthermore, how can I "stop" the chain of processing in the class if one of the values is invalid? Is there like a "break" syntax or something?
Thanks.
>>> u = User()
>>> u.name = 'Jason Mendez'
>>> u.password = '1234'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "topic/model/user.py", line 79, in password
return self._password
ValueError: Your password must be greater than 6 characters
In my controller "register," I have:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
try:
u.name = c.name = request.POST['name']
except ValueError, error:
c.errors['name'] = error
try:
u.email = c.email = request.POST['email']
except ValueError, error:
c.errors['email'] = error
try:
u.password = c.password = request.POST['password']
except ValueError, error:
c.errors['password'] = error
try:
u.commit()
except ValueError, error:
pass
return render('/register.mako')
|
[
"You could remove repetition from the code as a semi-measure:\nclass RegisterController(BaseController):\n\n def index(self):\n if request.POST:\n c.errors = {}\n u = User()\n for key in \"name email password\".split():\n try:\n value = request.POST[key]\n for o in (u, c):\n setattr(o, key, value)\n except ValueError, error:\n c.errors[key] = error\n\n u.commit() # allow to propagate (show 500 on error if no middleware)\n\n return render('/register.mako')\n\nForm Handling page from Pylons docs describes several simple approaches to form validating that you could adapt for your project.\nclass RegisterController(BaseController):\n\n @save(User, commit=True)\n # `save` uses filled c.form_result to create User() \n @validate(schema=register_schema, form='register')\n # `validate` fills c.form_errors, c.form_result dictionaries\n def create(self):\n return render('/register.mako')\n\nWhere validate() is similar to Pylons validate() decorator and save() could be implemented as follows (using decorator module):\ndef save(klass, commit=False):\n def call(action, *args, **kwargs):\n obj = klass()\n for attr in c.form_result:\n if attr in obj.setable_attrs():\n setattr(obj, attr, c.form_result[attr])\n if commit:\n obj.commit()\n return action(*args, **kwargs)\n return decorator.decorator(call)\n\n"
] |
[
0
] |
[] |
[] |
[
"forms",
"pylons",
"python"
] |
stackoverflow_0002527992_forms_pylons_python.txt
|
Q:
How to customize a modelform widget in Django 1.1?
I'm trying to modify a Django form to use a textarea instead of a normal input for the "address" field in my house form. The docs seem to imply this changed from Django 1.1 (which I'm using) to 1.2. But neither approach is working for me. Here's what I've tried:
class HouseForm(forms.ModelForm):
address = forms.Textarea() # Should work with django 1.1, but doesn't
class Meta:
model = House
#widgets = { 'address': forms.Textarea() } # 1.2 style - doesn't work either.
A:
I think Textarea needs to be assigned as a widget.
Try
class HouseForm(forms.ModelForm):
address = forms.CharField(widget=forms.Textarea)
class Meta:
model = House
|
How to customize a modelform widget in Django 1.1?
|
I'm trying to modify a Django form to use a textarea instead of a normal input for the "address" field in my house form. The docs seem to imply this changed from Django 1.1 (which I'm using) to 1.2. But neither approach is working for me. Here's what I've tried:
class HouseForm(forms.ModelForm):
address = forms.Textarea() # Should work with django 1.1, but doesn't
class Meta:
model = House
#widgets = { 'address': forms.Textarea() } # 1.2 style - doesn't work either.
|
[
"I think Textarea needs to be assigned as a widget.\nTry\nclass HouseForm(forms.ModelForm):\n address = forms.CharField(widget=forms.Textarea)\n\n class Meta:\n model = House\n\n"
] |
[
4
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002528195_django_django_forms_python.txt
|
Q:
Need help parsing HTML with a regex in python
My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None.
How can I get the values and values can be 10.00, 100.00, 1000.00
Thanks
A:
I strongly recommend using a real HTML parser for this, instead of a custom regular-expression.
Here's an example with the BeautifulSoup library:
from BeautifulSoup import BeautifulSoup
str = r'''
<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees) 100.00</span></td></tr>
'''
soup = BeautifulSoup(str)
amount = soup.findAll('span', attrs={'class': 'para'})
amount_tokens = amount[0].text.split()
print amount_tokens[-1]
A:
I second Eli's response - you'll be better off using an HTML parser.
Personally I would highly recommend lxml library for parsing HTML:
http://lxml.de/
It's extremely fast and feature-rich.
from lxml.html import fromstring
s = """
<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>
"""
doc = fromstring(s)
for span in doc.cssselect('span.para'):
print span.text_content().split()[-1]
A:
I agree that a parser is a great way to go, but since you asked how to do it with regex, here's a way:
mystring = """<tr><td><span class='para'><b>Total Amount :
</b>INR (Indian Rupees) 100.00</span></td></tr>"""
test = re.search("\(Indian Rupees\) ([^<]+)", mystring)
Then you'll get the number with:
test.group(1)
|
Need help parsing HTML with a regex in python
|
My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None.
How can I get the values and values can be 10.00, 100.00, 1000.00
Thanks
|
[
"I strongly recommend using a real HTML parser for this, instead of a custom regular-expression.\nHere's an example with the BeautifulSoup library:\nfrom BeautifulSoup import BeautifulSoup\n\nstr = r'''\n<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees) 100.00</span></td></tr>\n'''\n\nsoup = BeautifulSoup(str)\n\namount = soup.findAll('span', attrs={'class': 'para'})\namount_tokens = amount[0].text.split()\nprint amount_tokens[-1]\n\n",
"I second Eli's response - you'll be better off using an HTML parser.\nPersonally I would highly recommend lxml library for parsing HTML: \nhttp://lxml.de/\nIt's extremely fast and feature-rich.\nfrom lxml.html import fromstring\n\ns = \"\"\"\n<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)\n100.00</span></td></tr>\n\"\"\"\n\ndoc = fromstring(s)\nfor span in doc.cssselect('span.para'):\n print span.text_content().split()[-1]\n\n",
"I agree that a parser is a great way to go, but since you asked how to do it with regex, here's a way:\nmystring = \"\"\"<tr><td><span class='para'><b>Total Amount :\n</b>INR (Indian Rupees) 100.00</span></td></tr>\"\"\"\n\ntest = re.search(\"\\(Indian Rupees\\) ([^<]+)\", mystring)\n\nThen you'll get the number with:\ntest.group(1)\n\n"
] |
[
7,
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002528198_python.txt
|
Q:
Modify python USB device driver to only use vendor_id and product_id, excluding BCD
I'm trying to modify the Android device driver for calibre (an e-book management program) so that it identifies devices by only vendor id and product id, and excludes BCD.
The driver is a fairly simply python plugin, and is currently set up to use all three numbers, but apparently, when Android devices use custom Android builds (ie CyanogenMod for the Nexus One), it changes the BCD so calibre stops recognizing it.
The current code looks like this, with a simple list of vendor id's, that then have allowed product id's and BCD's with them:
VENDOR_ID = {
0x0bb4 : { 0x0c02 : [0x100], 0x0c01 : [0x100]},
0x22b8 : { 0x41d9 : [0x216]},
0x18d1 : { 0x4e11 : [0x0100], 0x4e12: [0x0100]},
0x04e8 : { 0x681d : [0x0222]},
}
The line I'm specifically trying to change is:
0x18d1 : { 0x4e11 : [0x0100], 0x4e12: [0x0100]},
Which is, the line for identifying a Nexus One. My N1, running CyanogenMod 5.0.5, has the BCD 0x226, and rather than just adding it to the list, I'd prefer to eliminate the BCD from the recognition process, so that any device with vendor id 0x18d1 and product id 0x4e11 or 0x4e12 would be recognized. The custom Android rom doesn't change enough for the specifics to matter.
The syntax seems to require the BCD in brackets.
How can I edit this so that it matches anything in that field?
A:
That is a data structure, it doesn't "match" anything per se. The change would have to happen in the code that uses that data structure to do the matching. Nothing you could do on the data structure itself would mean "match all" unless there's some kind of flag the matching code recognizes.
|
Modify python USB device driver to only use vendor_id and product_id, excluding BCD
|
I'm trying to modify the Android device driver for calibre (an e-book management program) so that it identifies devices by only vendor id and product id, and excludes BCD.
The driver is a fairly simply python plugin, and is currently set up to use all three numbers, but apparently, when Android devices use custom Android builds (ie CyanogenMod for the Nexus One), it changes the BCD so calibre stops recognizing it.
The current code looks like this, with a simple list of vendor id's, that then have allowed product id's and BCD's with them:
VENDOR_ID = {
0x0bb4 : { 0x0c02 : [0x100], 0x0c01 : [0x100]},
0x22b8 : { 0x41d9 : [0x216]},
0x18d1 : { 0x4e11 : [0x0100], 0x4e12: [0x0100]},
0x04e8 : { 0x681d : [0x0222]},
}
The line I'm specifically trying to change is:
0x18d1 : { 0x4e11 : [0x0100], 0x4e12: [0x0100]},
Which is, the line for identifying a Nexus One. My N1, running CyanogenMod 5.0.5, has the BCD 0x226, and rather than just adding it to the list, I'd prefer to eliminate the BCD from the recognition process, so that any device with vendor id 0x18d1 and product id 0x4e11 or 0x4e12 would be recognized. The custom Android rom doesn't change enough for the specifics to matter.
The syntax seems to require the BCD in brackets.
How can I edit this so that it matches anything in that field?
|
[
"That is a data structure, it doesn't \"match\" anything per se. The change would have to happen in the code that uses that data structure to do the matching. Nothing you could do on the data structure itself would mean \"match all\" unless there's some kind of flag the matching code recognizes.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"calibre",
"python",
"usb"
] |
stackoverflow_0002528359_android_calibre_python_usb.txt
|
Q:
Is Using Python to MapReduce for Cassandra Dumb?
Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?
The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but pretend I'm making Google analytics so I want to keep track of which browsers appear, which pages they went to, and visits vs. pageviews.
I would just atomically update my counters on write, but Cassandra isn't very good at counters either.
May Cassandra just isn't the right choice for this?
Thanks!
A:
Cassandra supports map reduce since version 0.6. (Current stable release is 0.5.1, but go ahead and try the new map reduce functionality in 0.6.0-beta3) To get started I recommend to take a look at the word count map reduce example in 'contrib/word_count'.
A:
MongoDB has update-in-place, so MongoDB should be very good with counters. http://blog.mongodb.org/post/171353301/using-mongodb-for-real-time-analytics
|
Is Using Python to MapReduce for Cassandra Dumb?
|
Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?
The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but pretend I'm making Google analytics so I want to keep track of which browsers appear, which pages they went to, and visits vs. pageviews.
I would just atomically update my counters on write, but Cassandra isn't very good at counters either.
May Cassandra just isn't the right choice for this?
Thanks!
|
[
"Cassandra supports map reduce since version 0.6. (Current stable release is 0.5.1, but go ahead and try the new map reduce functionality in 0.6.0-beta3) To get started I recommend to take a look at the word count map reduce example in 'contrib/word_count'.\n",
"MongoDB has update-in-place, so MongoDB should be very good with counters. http://blog.mongodb.org/post/171353301/using-mongodb-for-real-time-analytics\n"
] |
[
6,
3
] |
[] |
[] |
[
"cassandra",
"couchdb",
"mongodb",
"nosql",
"python"
] |
stackoverflow_0002527173_cassandra_couchdb_mongodb_nosql_python.txt
|
Q:
Django foreign key question
All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
AND IN MY VIEWS I HAVE
p= header(title=name,created_by=id)
p.save()
Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know..
Thanks..
A:
Given your:
p= header(title=name,created_by=id)
p.save()
You can now:
c=criteria(details='some details', headerid=p)
c.save()
o=options(opt_details='more details', headerid=p)
o.save()
Hope this helps.
A:
Take advantage of <related>_set query managers, it's clearer and shorter than constructing and saving objects in separate operations.
h = header.objects.create(title=name,created_by=id)
c = h.criteria_set.create(details='some details')
o = h.options_set.create(opt_details='more details')
And some offtopic: please, start class names from uppercase letter, it really makes code easier to read.
|
Django foreign key question
|
All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
AND IN MY VIEWS I HAVE
p= header(title=name,created_by=id)
p.save()
Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know..
Thanks..
|
[
"Given your:\np= header(title=name,created_by=id)\np.save()\n\nYou can now:\nc=criteria(details='some details', headerid=p)\nc.save()\no=options(opt_details='more details', headerid=p)\no.save()\n\nHope this helps.\n",
"Take advantage of <related>_set query managers, it's clearer and shorter than constructing and saving objects in separate operations.\nh = header.objects.create(title=name,created_by=id)\nc = h.criteria_set.create(details='some details')\no = h.options_set.create(opt_details='more details')\n\nAnd some offtopic: please, start class names from uppercase letter, it really makes code easier to read.\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0002528867_django_django_models_django_templates_django_views_python.txt
|
Q:
why python find not working
i am using python 2.5.2. The following code not working.
def findValue(self, text, findText):
index = text.find(findText)
print index
Although the findText is present in text, but it still returns None.
I have printed the values of text and findText and they are present.
Edit: I have fixed the issue.
The problem was i am calling code like
for i in arr:
self.findValue(i,"someText")
As type of i is instance so this does not work. I have just changed it to:
self.findValue(str(i),"someText")
A:
You aren't returning a value from your function, you are only printing it. This means that the return value for the function will be None.
Try adding return indexat the end of your code.
def myfind(self, text, findText):
index = text.find(findText)
return index
A:
Python doesn't automatically return the last variable, you need to explicitly use return index
And If the .find is failing, it should return -1 instead of None, So most probably, problem is in your return part, not in the .find
A:
I have fixed the issue.
The problem was i am calling code like
for i in arr:
self.findValue(i,"someText")
As type of i is instance so this does not work. I have just changed it to:
self.findValue(str(i),"someText")
|
why python find not working
|
i am using python 2.5.2. The following code not working.
def findValue(self, text, findText):
index = text.find(findText)
print index
Although the findText is present in text, but it still returns None.
I have printed the values of text and findText and they are present.
Edit: I have fixed the issue.
The problem was i am calling code like
for i in arr:
self.findValue(i,"someText")
As type of i is instance so this does not work. I have just changed it to:
self.findValue(str(i),"someText")
|
[
"You aren't returning a value from your function, you are only printing it. This means that the return value for the function will be None.\nTry adding return indexat the end of your code.\ndef myfind(self, text, findText):\n index = text.find(findText)\n return index\n\n",
"Python doesn't automatically return the last variable, you need to explicitly use return index\nAnd If the .find is failing, it should return -1 instead of None, So most probably, problem is in your return part, not in the .find\n",
"I have fixed the issue.\nThe problem was i am calling code like\nfor i in arr: \n self.findValue(i,\"someText\") \n\nAs type of i is instance so this does not work. I have just changed it to:\nself.findValue(str(i),\"someText\") \n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"find",
"python"
] |
stackoverflow_0002513606_find_python.txt
|
Q:
want to add url links to .csv datafeed using python
ive looked through the current related questions but have not managed to find anything similar to my needs.
Im in the process of creating a affiliate store using zencart - now one of the issues is that zencart is not designed for redirects and affiliate stores but it can be done. I will be changing the store so it acts like a showcase store showing prices.
There is a mod called easy populate which allows me to upload datafeeds. This is all well and good however my affiliate link will not be in each product. I can do it manually after uploading the data feed and going to each product and then adding it as an image with a redirect link - However when there are over 500 items its going to be a long repetitive and time consuming job.
I have been told that I can add the links to the data feed before uploading it to zencart and this should be done using python. Ive been reading about python for several days now and feel im looking for the wrong things. I was wondering if someone could please advise the simplest way for me to get this done.
I hope the question makes sense
thanks
abs
A:
You could craft a python script using csv module like this:
>>> import csv
>>> cartWriter = csv.writer(open('yourcart.csv', 'wb'))
>>> cartWriter.writerow(['Product', 'yourinfo', 'yourlink'])
You need to know how link should be formatted hoping that it could be composed using the other parameters present on csv file.
A:
First, use the CSV module as systempuntoout told you, secondly, you will want to change your header to:
mimetype='text/csv'
Content-Disposition = 'attachment; filename=name_of_your_file.csv'
The way to do it depends very much of your website implementation. In pure Python you would probably do that with an HttpResponse object. In django, as well, but there are some shortcuts.
You can find a video demonstrating how to create CSV files with Python on showmedo. It's not free however.
Now, to provide a link to download the CSV, this depends of your Website. What is the technology behinds it : pure Python, Django, Pylons, Tubogear ?
If you can't answer the question, you should ask your boss a training about your infrastructure before trying to make change to it.
|
want to add url links to .csv datafeed using python
|
ive looked through the current related questions but have not managed to find anything similar to my needs.
Im in the process of creating a affiliate store using zencart - now one of the issues is that zencart is not designed for redirects and affiliate stores but it can be done. I will be changing the store so it acts like a showcase store showing prices.
There is a mod called easy populate which allows me to upload datafeeds. This is all well and good however my affiliate link will not be in each product. I can do it manually after uploading the data feed and going to each product and then adding it as an image with a redirect link - However when there are over 500 items its going to be a long repetitive and time consuming job.
I have been told that I can add the links to the data feed before uploading it to zencart and this should be done using python. Ive been reading about python for several days now and feel im looking for the wrong things. I was wondering if someone could please advise the simplest way for me to get this done.
I hope the question makes sense
thanks
abs
|
[
"You could craft a python script using csv module like this:\n>>> import csv\n>>> cartWriter = csv.writer(open('yourcart.csv', 'wb'))\n>>> cartWriter.writerow(['Product', 'yourinfo', 'yourlink'])\n\nYou need to know how link should be formatted hoping that it could be composed using the other parameters present on csv file.\n",
"First, use the CSV module as systempuntoout told you, secondly, you will want to change your header to:\nmimetype='text/csv'\nContent-Disposition = 'attachment; filename=name_of_your_file.csv'\n\nThe way to do it depends very much of your website implementation. In pure Python you would probably do that with an HttpResponse object. In django, as well, but there are some shortcuts.\nYou can find a video demonstrating how to create CSV files with Python on showmedo. It's not free however.\nNow, to provide a link to download the CSV, this depends of your Website. What is the technology behinds it : pure Python, Django, Pylons, Tubogear ?\nIf you can't answer the question, you should ask your boss a training about your infrastructure before trying to make change to it.\n"
] |
[
2,
0
] |
[] |
[] |
[
"add",
"csv",
"datafeed",
"python",
"url"
] |
stackoverflow_0002529238_add_csv_datafeed_python_url.txt
|
Q:
How do I get minidom to ignore namespaces?
I am using minidom in Python and I'd like getElementsByTagName() to match elements purely by tag-name and ignore any namespaces. The documents are being parsed by minidom.parseString(). Is it possible?
A:
getElementsByTagName does match elements purely by tagName.
Do you mean you want to match purely on localName? ie. the part of the tag name after the : (if any)? If so use the DOM Level 2 Core method getElementsByTagNameNS:
els= document.getElementsByTagNameNS('*', 'tag')
|
How do I get minidom to ignore namespaces?
|
I am using minidom in Python and I'd like getElementsByTagName() to match elements purely by tag-name and ignore any namespaces. The documents are being parsed by minidom.parseString(). Is it possible?
|
[
"getElementsByTagName does match elements purely by tagName.\nDo you mean you want to match purely on localName? ie. the part of the tag name after the : (if any)? If so use the DOM Level 2 Core method getElementsByTagNameNS:\nels= document.getElementsByTagNameNS('*', 'tag')\n\n"
] |
[
15
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002528852_python_xml.txt
|
Q:
What is the difference between .get() and .fetch(1)
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
So my app has a query like
data = Paths.all().filter('path =', self.request.path).get()
Which works brilliantly. Now I want to send this to the UI using templates
{% for datum in data %}
{{ datum.title }}
{{ datum.content }}
</div>
{% endfor %}
When I do this I get data is not iterable error. So I updated the Django to {% for datum in data.all %} which now appears to pull more data than I was giving it somehow. It shows all data in the datastore which is not ideal. So I removed the .all from the Django and changed the datastore query to
data = Paths.all().filter('path =', self.request.path).fetch(1)
which now works as I intended. In the documentation it says
The db.get() function fetches an
entity from the datastore for a Key
(or list of Keys).
So my question is why can I iterate over a query when it returns with fetch() but can't with get(). Where has my understanding gone wrong?
A:
You're looking at the docs for the wrong get() - you want the get() method on the Query object. In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.
A:
get() requires (I think) that there be exactly one element, and returns it, while fetch() returns a _list_ of the first _n_ elements, where n happens to be 1 in this case.
|
What is the difference between .get() and .fetch(1)
|
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
So my app has a query like
data = Paths.all().filter('path =', self.request.path).get()
Which works brilliantly. Now I want to send this to the UI using templates
{% for datum in data %}
{{ datum.title }}
{{ datum.content }}
</div>
{% endfor %}
When I do this I get data is not iterable error. So I updated the Django to {% for datum in data.all %} which now appears to pull more data than I was giving it somehow. It shows all data in the datastore which is not ideal. So I removed the .all from the Django and changed the datastore query to
data = Paths.all().filter('path =', self.request.path).fetch(1)
which now works as I intended. In the documentation it says
The db.get() function fetches an
entity from the datastore for a Key
(or list of Keys).
So my question is why can I iterate over a query when it returns with fetch() but can't with get(). Where has my understanding gone wrong?
|
[
"You're looking at the docs for the wrong get() - you want the get() method on the Query object. In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.\n",
"get() requires (I think) that there be exactly one element, and returns it, while fetch() returns a _list_ of the first _n_ elements, where n happens to be 1 in this case.\n"
] |
[
11,
4
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002529198_google_app_engine_google_cloud_datastore_python.txt
|
Q:
importing files in python
I have that file structure-
Blog\DataObjects\User.py
Blog\index.py
I want to import the function(say_hello) at User.py from index.py.
I am trying this code -
from Blog.DataObjects.User import say_hello
say_hello()
And I have that error -
Traceback (most recent call last):
File "index.py", line 1, in <module>
from Blog.DataObjects import User
ImportError: No module named Blog.DataObjects
A:
Python expects in every directory that should be importable, a file __init__.py, which may be empty. So, if you correct your file structure to this:
Blog/__init__.py
Blog/index.py
Blog/DataObjects/User.py
Blog/DataObjects/__init__.py
it should work, if the path to the directory is in your Python path (you can check this with:
import sys
print sys.path
). If not, mind that importing is done relative to the position of the current file. That is, since index.py is already inside Blog, the import should read:
from DataObjects.User import say_hello
A:
from DataObjects.User import say_hello
|
importing files in python
|
I have that file structure-
Blog\DataObjects\User.py
Blog\index.py
I want to import the function(say_hello) at User.py from index.py.
I am trying this code -
from Blog.DataObjects.User import say_hello
say_hello()
And I have that error -
Traceback (most recent call last):
File "index.py", line 1, in <module>
from Blog.DataObjects import User
ImportError: No module named Blog.DataObjects
|
[
"Python expects in every directory that should be importable, a file __init__.py, which may be empty. So, if you correct your file structure to this:\nBlog/__init__.py\nBlog/index.py\nBlog/DataObjects/User.py\nBlog/DataObjects/__init__.py\n\nit should work, if the path to the directory is in your Python path (you can check this with:\nimport sys\nprint sys.path\n\n). If not, mind that importing is done relative to the position of the current file. That is, since index.py is already inside Blog, the import should read:\nfrom DataObjects.User import say_hello\n\n",
"from DataObjects.User import say_hello\n\n"
] |
[
12,
1
] |
[] |
[] |
[
"package",
"python",
"python_2.6"
] |
stackoverflow_0002529466_package_python_python_2.6.txt
|
Q:
Can Django be used for non web apps?
I noticed in the main Django introductin they show a feature that maps python objects to the database. This doesn't strike me as being mutually exclusive with with development, is there any reason why this can't be used for non web apps? Is it easy to separate out?
A:
The part you're mentioning is the ORM and yes, ORMs are useful besides web development. In theory you could use the Django ORM for non-web stuff. However this can be a bit complicated because it is not released separately so you'd have to extract the code yourself (or you have to include the whole django package).
There are a lot of other ORMs in Python that you can use standalone way easier. My favorite is SQLAlchemy (http://www.sqlalchemy.org/), but there are others like storm and SQLObject.
|
Can Django be used for non web apps?
|
I noticed in the main Django introductin they show a feature that maps python objects to the database. This doesn't strike me as being mutually exclusive with with development, is there any reason why this can't be used for non web apps? Is it easy to separate out?
|
[
"The part you're mentioning is the ORM and yes, ORMs are useful besides web development. In theory you could use the Django ORM for non-web stuff. However this can be a bit complicated because it is not released separately so you'd have to extract the code yourself (or you have to include the whole django package).\nThere are a lot of other ORMs in Python that you can use standalone way easier. My favorite is SQLAlchemy (http://www.sqlalchemy.org/), but there are others like storm and SQLObject.\n"
] |
[
8
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002529497_django_django_models_python.txt
|
Q:
Duplicate django query set?
I have a simple django's query set like:
qs = AModel.objects.exclude(state="F").order_by("order")
I'd like to use it as follows:
qs[0:3].update(state='F')
expected = qs[3] # throws error here
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I duplicate the query set?
A:
It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.
update() is meant for bulk updates, resulting in SQL queries like
UPDATE app_model SET state = 'F' WHERE state <> 'F';
You're trying to update the first three items according to "order", but that can't be done with this type of UPDATE--you can't order or limit an SQL UPDATE. It needs to be written differently, eg.
UPDATE app_model SET state = 'F' WHERE id IN (
SELECT id FROM app_model WHERE state <> 'F' ORDER BY order LIMIT 3
) AS sub;
but Django can't do that for you.
A:
You can do this:
qs = AModel.objects.filter(id__in=
AModel.objects.exclude(state="F").order_by("order")[10]).update()
A:
There have been some talks about making it possible to do slices of a queryset and then be able to use update on them before, but AFAIK there have never been made anything. I don't think you can copy a slice of a queryset, but in this case you wont need to. If your order is an unique integer, you would be able to do this:
qs = AModel.objects.exclude(state="F").order_by("order")
if len(qs) > 3:
slice = qs.exclude(order__gt=qs[3])
else:
slice = qs
slice.update(state='F')
I use exclude to remove the unwanted elements, but this will only work if the order is unique, else you wont be able to know how many you update. In case order is not unique it will still be possible using a second and unique arg in order:
qs = AModel.objects.exclude(state="F").order_by("order", "pk")
if len(qs) > 3:
slice = qs.exclude(order__gt=qs[3]).exclude(order=qs[3], pk__gt=qs[3])
...
|
Duplicate django query set?
|
I have a simple django's query set like:
qs = AModel.objects.exclude(state="F").order_by("order")
I'd like to use it as follows:
qs[0:3].update(state='F')
expected = qs[3] # throws error here
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I duplicate the query set?
|
[
"It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.\nupdate() is meant for bulk updates, resulting in SQL queries like\nUPDATE app_model SET state = 'F' WHERE state <> 'F';\n\nYou're trying to update the first three items according to \"order\", but that can't be done with this type of UPDATE--you can't order or limit an SQL UPDATE. It needs to be written differently, eg.\nUPDATE app_model SET state = 'F' WHERE id IN (\n SELECT id FROM app_model WHERE state <> 'F' ORDER BY order LIMIT 3\n) AS sub;\n\nbut Django can't do that for you.\n",
"You can do this:\nqs = AModel.objects.filter(id__in=\nAModel.objects.exclude(state=\"F\").order_by(\"order\")[10]).update()\n",
"There have been some talks about making it possible to do slices of a queryset and then be able to use update on them before, but AFAIK there have never been made anything. I don't think you can copy a slice of a queryset, but in this case you wont need to. If your order is an unique integer, you would be able to do this:\nqs = AModel.objects.exclude(state=\"F\").order_by(\"order\")\nif len(qs) > 3:\n slice = qs.exclude(order__gt=qs[3])\nelse:\n slice = qs\nslice.update(state='F')\n\nI use exclude to remove the unwanted elements, but this will only work if the order is unique, else you wont be able to know how many you update. In case order is not unique it will still be possible using a second and unique arg in order:\nqs = AModel.objects.exclude(state=\"F\").order_by(\"order\", \"pk\")\nif len(qs) > 3:\n slice = qs.exclude(order__gt=qs[3]).exclude(order=qs[3], pk__gt=qs[3])\n...\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001170235_django_django_models_python.txt
|
Q:
google app engine - auto increment
I am new to Google App Engine,
I have this entites User class -
user_id - integer
user_name - string
password - string
I want to do auto increment for the user_id,How I can do this?
A:
You don't need to declare user_id, GAE will create a unique key id every time you insert a new row.
class User(db.Model):
user_name = db.StringProperty()
password = db.StringProperty()
and to store a new user you will do:
user = User()
user.user_name = "Username"
user.password = "Password"
user.put()
to retrieve it:
user = User.get_by_id(<id of the user>)
to retrieve all the ids:
query = datamodel.User().all()
for result in query:
print result.key().id()
See The Model Class for further reference.
A:
Every entity in the AppEngine already has a unique key and id (see the documentation):
user().key().id()
You would be better off using that instead.
To do the converse, use User.get_by_id(id).
|
google app engine - auto increment
|
I am new to Google App Engine,
I have this entites User class -
user_id - integer
user_name - string
password - string
I want to do auto increment for the user_id,How I can do this?
|
[
"You don't need to declare user_id, GAE will create a unique key id every time you insert a new row.\nclass User(db.Model):\nuser_name = db.StringProperty()\npassword = db.StringProperty()\n\nand to store a new user you will do:\nuser = User()\nuser.user_name = \"Username\"\nuser.password = \"Password\"\nuser.put()\n\nto retrieve it:\nuser = User.get_by_id(<id of the user>)\n\nto retrieve all the ids:\nquery = datamodel.User().all()\nfor result in query:\n print result.key().id()\n\nSee The Model Class for further reference.\n",
"Every entity in the AppEngine already has a unique key and id (see the documentation):\nuser().key().id()\n\nYou would be better off using that instead.\nTo do the converse, use User.get_by_id(id).\n"
] |
[
19,
3
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002529620_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Sorting and aligning the contents of a text file in Python
In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an aligned and sorted manner. The contents currently read:
Emily, 6
Sarah, 4
Jess, 7
This is my code where the text file in read and printed:
elif userCommand == 'V':
print "High Scores:"
scoresFile = open("scores1.txt", 'r')
scores = scoresFile.read().split("\n")
for score in scores:
print score
scoresFile.close()
Would I have to convert this information into lists in order to be able to do this? If so, how do I go about doing this?
When writing to the file, I have added a '\n' character to the end, as each record should be printed on a new line.
Thank you
A:
You could use csv module, and then could use sorted to sort.
Let's says, scores1.txt have following
Richard,100
Michael,200
Ricky,150
Chaung,100
Test
import csv
reader=csv.reader(open("scores1.txt"),dialect='excel')
items=sorted(reader)
for x in items:
print x[0],x[1]
...
Emily 6
Jess 7
Sarah 4
A:
Looks like nobody's answered the "aligned" part of your request. Also, it's not clear whether you want the results sorted alphabetically by name, or rather by score. In the first case, alphabetical order (assuming Python 2.6):
with open("scores1.txt", 'r') as scoresFile:
names_scores = [[x.strip() for x in l.split(',', 1)] for l in scoresFile]
# compute column widths
name_width = max(len(name) for name, score in names_scores)
score_width = max(len(score) for name, score in names_scores)
# sort and print
names_scores.sort()
for name, score in names_scores:
print "%*s %*s" % (name_width, name, score_width, score)
If you want descending order by score, just change the names_scores.sort() line to two:
def getscore_int(name_score): return int(name_score[1])
names_scores.sort(key=getscore_int, reverse=True)
A:
to sort stuff in Python, you can use sort()/sorted().
to print, you can use print with format specifiers, str.rjust/str.ljust, pprint etc
|
Sorting and aligning the contents of a text file in Python
|
In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an aligned and sorted manner. The contents currently read:
Emily, 6
Sarah, 4
Jess, 7
This is my code where the text file in read and printed:
elif userCommand == 'V':
print "High Scores:"
scoresFile = open("scores1.txt", 'r')
scores = scoresFile.read().split("\n")
for score in scores:
print score
scoresFile.close()
Would I have to convert this information into lists in order to be able to do this? If so, how do I go about doing this?
When writing to the file, I have added a '\n' character to the end, as each record should be printed on a new line.
Thank you
|
[
"You could use csv module, and then could use sorted to sort.\nLet's says, scores1.txt have following\nRichard,100\nMichael,200\nRicky,150\nChaung,100\n\nTest\nimport csv\n\nreader=csv.reader(open(\"scores1.txt\"),dialect='excel')\nitems=sorted(reader)\nfor x in items:\n print x[0],x[1]\n\n...\nEmily 6\nJess 7\nSarah 4\n\n",
"Looks like nobody's answered the \"aligned\" part of your request. Also, it's not clear whether you want the results sorted alphabetically by name, or rather by score. In the first case, alphabetical order (assuming Python 2.6):\nwith open(\"scores1.txt\", 'r') as scoresFile:\n names_scores = [[x.strip() for x in l.split(',', 1)] for l in scoresFile]\n# compute column widths\nname_width = max(len(name) for name, score in names_scores)\nscore_width = max(len(score) for name, score in names_scores)\n# sort and print\nnames_scores.sort()\nfor name, score in names_scores:\n print \"%*s %*s\" % (name_width, name, score_width, score)\n\nIf you want descending order by score, just change the names_scores.sort() line to two:\ndef getscore_int(name_score): return int(name_score[1])\nnames_scores.sort(key=getscore_int, reverse=True)\n\n",
"\nto sort stuff in Python, you can use sort()/sorted().\nto print, you can use print with format specifiers, str.rjust/str.ljust, pprint etc\n\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002528839_python.txt
|
Q:
Faster or more memory-efficient solution in Python for this Codejam problem
I tried my hand at this Google Codejam Africa problem (the contest is already finished, I just did it to improve my programming skills).
The Problem:
You are hosting a party with G guests
and notice that there is an odd number
of guests! When planning the party you
deliberately invited only couples and
gave each couple a unique number C on
their invitation. You would like to
single out whoever came alone by
asking all of the guests for their
invitation numbers.
The Input:
The first line of input gives the number of cases, N.
N test cases follow. For each test case there will be:
One line containing the value G the
number of guests.
One line containing
a space-separated list of G integers.
Each integer C indicates the
invitation code of a guest. Output
For each test case, output one line
containing "Case #x: " followed by the
number C of the guest who is alone.
The Limits:
1 ≤ N ≤ 50
0 < C ≤ 2147483647
Small dataset
3 ≤ G < 100
Large dataset
3 ≤ G < 1000
Sample Input:
3
3
1 2147483647 2147483647
5
3 4 7 4 3
5
2 10 2 10 5
Sample Output:
Case #1: 1
Case #2: 7
Case #3: 5
This is the solution that I came up with:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
G = int(lines[i])
for guest in range(G):
codes = map(int, lines[i+1].split(' '))
alone = (c for c in codes if codes.count(c)==1)
output.write("Case #%d: %d\n" % (testcase+1, alone.next()))
It runs in 12 seconds on my machine with the large input.
Now, my question is, can this solution be improved in Python to run in a shorter time or use less memory? The analysis of the problem gives some pointers on how to do this in Java and C++ but I can't translate those solutions back to Python.
Edit:
Incorporating the tips from Alex Martelli and IVlad below I now have this solution which runs in 0.079s:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
codes = map(int, lines[i+1].split(' '))
alone = 0
for c in codes: alone ^= c
output.write("Case #%d: %d" % (testcase+1, alone))
A:
I don't know about python, but the problem itself is a classic. Given 2K - 1 numbers, each except one appearing an even number of times, find the one appearing an odd number of times.
Needed formulas:
x xor x == 0 for all x
x xor y == y xor x for all x and y
x xor (y xor z) == (x xor y) xor z (associativity)
x xor 0 == x for all x
So xor all the numbers. The result of xor-ing all the numbers will be your answer. I don't know how you'd do this in python, in the C languages the xor operator is ^.
This is really the most efficient way as you're only doing a simple bitwise operation and you don't even have to store the given numbers.
You can check that:
3 ^ 4 ^ 7 ^ 4 ^ 3 == 7, 2 ^ 10 ^ 2 ^ 10 ^ 5 == 5 etc.
A:
My machine's slower than yours -- your code (put in a main function) took 19 seconds on my machine. The obvious optimization of removing the useless inner for cuts this to 0.46 seconds; changing the heart of the code to
alone = 0
for c in codes: alone ^= c
cuts the time to 0.08 seconds. I'm sure further optimizations are possible, but with the code already 235 times faster I think this may be enough;-).
A:
Consider this:
codes = map(int, lines[i+1].split(' '))
Why resplit the line for each value of guest? The line won't change.
Also, consider this:
for guest in range(G):
codes = map(int, lines[i+1].split(' '))
alone = (c for c in codes if codes.count(c)==1)
None of the code in this loop depends on guest. Why is it in a loop?
A:
This finishes instantly for me with the same results:
src = open('A-large-practice.in')
dst = open('A-large-practice.out', 'w')
n = int(src.readline().rstrip())
for i in xrange(n):
src.readline() # skip g
nums = src.readline().split()
seen = set()
for n in nums:
if n in seen:
seen.remove(n)
else:
seen.add(n)
dst.write("Case #%d: %s\n" % (i+1, tuple(seen)[0]))
src.close()
dst.close()
Damn, I love hash maps!
A:
Yes, as the analysis page explains, you can use constant memory, although any approach will run in O(n) time. Here's how the constant memory solution would work in Python:
numbers = [1, 1, 2, 2, 3, 3, 4, 4, 12345]
missingOne = 0
for number in numbers:
missingOne = missingOne ^ number
assert missingOne == 12345
The key is understanding what the xor operator does. Any number xor'ed with zero is itself. And any number xor'ed with itself is zero. If you look at the truth table for xor, you should be able to convince yourself of both of those facts and then prove that xoring the numbers in a list, starting from zero will produce the non-duplicated number.
|
Faster or more memory-efficient solution in Python for this Codejam problem
|
I tried my hand at this Google Codejam Africa problem (the contest is already finished, I just did it to improve my programming skills).
The Problem:
You are hosting a party with G guests
and notice that there is an odd number
of guests! When planning the party you
deliberately invited only couples and
gave each couple a unique number C on
their invitation. You would like to
single out whoever came alone by
asking all of the guests for their
invitation numbers.
The Input:
The first line of input gives the number of cases, N.
N test cases follow. For each test case there will be:
One line containing the value G the
number of guests.
One line containing
a space-separated list of G integers.
Each integer C indicates the
invitation code of a guest. Output
For each test case, output one line
containing "Case #x: " followed by the
number C of the guest who is alone.
The Limits:
1 ≤ N ≤ 50
0 < C ≤ 2147483647
Small dataset
3 ≤ G < 100
Large dataset
3 ≤ G < 1000
Sample Input:
3
3
1 2147483647 2147483647
5
3 4 7 4 3
5
2 10 2 10 5
Sample Output:
Case #1: 1
Case #2: 7
Case #3: 5
This is the solution that I came up with:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
G = int(lines[i])
for guest in range(G):
codes = map(int, lines[i+1].split(' '))
alone = (c for c in codes if codes.count(c)==1)
output.write("Case #%d: %d\n" % (testcase+1, alone.next()))
It runs in 12 seconds on my machine with the large input.
Now, my question is, can this solution be improved in Python to run in a shorter time or use less memory? The analysis of the problem gives some pointers on how to do this in Java and C++ but I can't translate those solutions back to Python.
Edit:
Incorporating the tips from Alex Martelli and IVlad below I now have this solution which runs in 0.079s:
with open('A-large-practice.in') as f:
lines = f.readlines()
with open('A-large-practice.out', 'w') as output:
N = int(lines[0])
for testcase, i in enumerate(range(1,2*N,2)):
codes = map(int, lines[i+1].split(' '))
alone = 0
for c in codes: alone ^= c
output.write("Case #%d: %d" % (testcase+1, alone))
|
[
"I don't know about python, but the problem itself is a classic. Given 2K - 1 numbers, each except one appearing an even number of times, find the one appearing an odd number of times.\nNeeded formulas:\n\nx xor x == 0 for all x\nx xor y == y xor x for all x and y\nx xor (y xor z) == (x xor y) xor z (associativity)\nx xor 0 == x for all x\n\nSo xor all the numbers. The result of xor-ing all the numbers will be your answer. I don't know how you'd do this in python, in the C languages the xor operator is ^. \nThis is really the most efficient way as you're only doing a simple bitwise operation and you don't even have to store the given numbers.\nYou can check that:\n3 ^ 4 ^ 7 ^ 4 ^ 3 == 7, 2 ^ 10 ^ 2 ^ 10 ^ 5 == 5 etc.\n",
"My machine's slower than yours -- your code (put in a main function) took 19 seconds on my machine. The obvious optimization of removing the useless inner for cuts this to 0.46 seconds; changing the heart of the code to\n alone = 0\n for c in codes: alone ^= c\n\ncuts the time to 0.08 seconds. I'm sure further optimizations are possible, but with the code already 235 times faster I think this may be enough;-).\n",
"Consider this:\ncodes = map(int, lines[i+1].split(' '))\n\nWhy resplit the line for each value of guest? The line won't change.\nAlso, consider this:\nfor guest in range(G):\n codes = map(int, lines[i+1].split(' '))\n alone = (c for c in codes if codes.count(c)==1)\n\nNone of the code in this loop depends on guest. Why is it in a loop?\n",
"This finishes instantly for me with the same results:\nsrc = open('A-large-practice.in')\ndst = open('A-large-practice.out', 'w')\n\nn = int(src.readline().rstrip())\nfor i in xrange(n):\n src.readline() # skip g\n nums = src.readline().split()\n seen = set()\n for n in nums:\n if n in seen:\n seen.remove(n)\n else:\n seen.add(n)\n dst.write(\"Case #%d: %s\\n\" % (i+1, tuple(seen)[0]))\n\nsrc.close()\ndst.close()\n\nDamn, I love hash maps!\n",
"Yes, as the analysis page explains, you can use constant memory, although any approach will run in O(n) time. Here's how the constant memory solution would work in Python:\nnumbers = [1, 1, 2, 2, 3, 3, 4, 4, 12345]\nmissingOne = 0\nfor number in numbers:\n missingOne = missingOne ^ number\nassert missingOne == 12345\n\nThe key is understanding what the xor operator does. Any number xor'ed with zero is itself. And any number xor'ed with itself is zero. If you look at the truth table for xor, you should be able to convince yourself of both of those facts and then prove that xoring the numbers in a list, starting from zero will produce the non-duplicated number.\n"
] |
[
5,
4,
2,
1,
1
] |
[] |
[] |
[
"puzzle",
"python"
] |
stackoverflow_0002529727_puzzle_python.txt
|
Q:
Refresh decorator
I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example:
@auto_refresh
def a():
print "In a"
@auto_refresh
def b():
print "In b"
a()
If a() is called, I want the refresh function to be run after exiting a(). If b() is called, I want the refresh function to be run after exiting b(), but not after a() when called by b(). Here is an example of a class that does this:
class auto_refresh(object):
def __init__(self, f):
print "Initializing decorator"
self.f = f
def __call__(self, *args, **kwargs):
print "Before function"
if 'refresh' in kwargs:
refresh = kwargs.pop('refresh')
else:
refresh = False
self.f(*args, **kwargs)
print "After function"
if refresh:
print "Refreshing"
With this decorator, if I run
b()
print '---'
b(refresh=True)
print '---'
b(refresh=False)
I get the following output:
Initializing decorator
Initializing decorator
Before function
In b
Before function
In a
After function
After function
---
Before function
In b
Before function
In a
After function
After function
Refreshing
---
Before function
In b
Before function
In a
After function
After function
So when written this way, not specifying the refresh argument means that refresh is defaulted to False. Can anyone think of a way to change this so that refresh is True when not specified? Changing the
refresh = False
to
refresh = True
in the decorator does not work:
Initializing decorator
Initializing decorator
Before function
In b
Before function
In a
After function
Refreshing
After function
Refreshing
---
Before function
In b
Before function
In a
After function
Refreshing
After function
Refreshing
---
Before function
In b
Before function
In a
After function
Refreshing
After function
because refresh then gets called multiple times in the first and second case, and once in the last case (when it should be once in the first and second case, and not in the last case).
A:
To count the number of "nestings", in a thread-safe way, is a good example of using thread-local storage:
import threading
mydata = threading.local()
mydata.nesting = 0
class auto_refresh(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
mydata.nesting += 1
try: return self.f(*args, **kwargs)
finally:
mydata.nesting -= 1
if mydata.nesting == 0:
print 'refreshing'
If you don't care about threading, as long as your installation of Python is compiled with threading enabled (and these days just about all of them are), this will still work just fine. If you fear a peculiar Python installation without threading, change the import statement to
try:
import threading
except ImportError:
import dummy_threading as threading
roughly as recommended in the docs (except that the docs use a peculiar "private" name for the import's result, and there's no real reason for that, so I'm using a plain name;-).
A:
I think it might be simpler to maintain a "nested-refresh count" that is incremented before each refresh-decorated call and decremented after (in a finally block so that the count doesn't get messed up); run the refresh routine whenever the count hits zero.
A:
It's not clear to me exactly what you're attempting to use this design for, and because of that, whether it's a good idea or not. Consider whether or not it's the right approach.
However, I think this does what you requested. A common object (named auto_refresh in this case) is shared by all 'decorated' methods, and that object keeps a counter as to how deep the call stack is.
This is not thread-safe.
class AutoRefresh(object):
nesting = 0
def __call__(self, f):
def wrapper(*args, **kwargs):
return self.proxied_call(f, args, kwargs)
return wrapper
def refresh(self):
print 'refresh'
def proxied_call(self, func, args, kwargs):
self.nesting += 1
result = func(*args, **kwargs)
self.nesting -= 1
if self.nesting == 0:
self.refresh()
return result
auto_refresh = AutoRefresh()
Tested with:
@auto_refresh
def a():
print "In a"
@auto_refresh
def b():
print "In b"
a()
a()
print '---'
b()
Resulting in:
In a
refresh
---
In b
In a
refresh
|
Refresh decorator
|
I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example:
@auto_refresh
def a():
print "In a"
@auto_refresh
def b():
print "In b"
a()
If a() is called, I want the refresh function to be run after exiting a(). If b() is called, I want the refresh function to be run after exiting b(), but not after a() when called by b(). Here is an example of a class that does this:
class auto_refresh(object):
def __init__(self, f):
print "Initializing decorator"
self.f = f
def __call__(self, *args, **kwargs):
print "Before function"
if 'refresh' in kwargs:
refresh = kwargs.pop('refresh')
else:
refresh = False
self.f(*args, **kwargs)
print "After function"
if refresh:
print "Refreshing"
With this decorator, if I run
b()
print '---'
b(refresh=True)
print '---'
b(refresh=False)
I get the following output:
Initializing decorator
Initializing decorator
Before function
In b
Before function
In a
After function
After function
---
Before function
In b
Before function
In a
After function
After function
Refreshing
---
Before function
In b
Before function
In a
After function
After function
So when written this way, not specifying the refresh argument means that refresh is defaulted to False. Can anyone think of a way to change this so that refresh is True when not specified? Changing the
refresh = False
to
refresh = True
in the decorator does not work:
Initializing decorator
Initializing decorator
Before function
In b
Before function
In a
After function
Refreshing
After function
Refreshing
---
Before function
In b
Before function
In a
After function
Refreshing
After function
Refreshing
---
Before function
In b
Before function
In a
After function
Refreshing
After function
because refresh then gets called multiple times in the first and second case, and once in the last case (when it should be once in the first and second case, and not in the last case).
|
[
"To count the number of \"nestings\", in a thread-safe way, is a good example of using thread-local storage:\nimport threading\nmydata = threading.local()\nmydata.nesting = 0\n\nclass auto_refresh(object):\n\n def __init__(self, f):\n self.f = f\n\n def __call__(self, *args, **kwargs):\n mydata.nesting += 1\n try: return self.f(*args, **kwargs)\n finally:\n mydata.nesting -= 1\n if mydata.nesting == 0:\n print 'refreshing'\n\nIf you don't care about threading, as long as your installation of Python is compiled with threading enabled (and these days just about all of them are), this will still work just fine. If you fear a peculiar Python installation without threading, change the import statement to\ntry:\n import threading\nexcept ImportError:\n import dummy_threading as threading\n\nroughly as recommended in the docs (except that the docs use a peculiar \"private\" name for the import's result, and there's no real reason for that, so I'm using a plain name;-).\n",
"I think it might be simpler to maintain a \"nested-refresh count\" that is incremented before each refresh-decorated call and decremented after (in a finally block so that the count doesn't get messed up); run the refresh routine whenever the count hits zero.\n",
"It's not clear to me exactly what you're attempting to use this design for, and because of that, whether it's a good idea or not. Consider whether or not it's the right approach.\nHowever, I think this does what you requested. A common object (named auto_refresh in this case) is shared by all 'decorated' methods, and that object keeps a counter as to how deep the call stack is.\nThis is not thread-safe.\nclass AutoRefresh(object):\n nesting = 0\n\n def __call__(self, f):\n def wrapper(*args, **kwargs):\n return self.proxied_call(f, args, kwargs)\n return wrapper\n\n def refresh(self):\n print 'refresh'\n\n def proxied_call(self, func, args, kwargs):\n self.nesting += 1\n result = func(*args, **kwargs)\n self.nesting -= 1\n if self.nesting == 0:\n self.refresh()\n return result\n\nauto_refresh = AutoRefresh()\n\nTested with:\n@auto_refresh\ndef a():\n print \"In a\"\n\n@auto_refresh\ndef b():\n print \"In b\"\n a()\n\na()\nprint '---'\nb()\n\nResulting in:\nIn a\nrefresh\n---\nIn b\nIn a\nrefresh\n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"algorithm",
"decorator",
"python"
] |
stackoverflow_0002529592_algorithm_decorator_python.txt
|
Q:
Python c_types .dll functions (pari library)
Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following:
from ctypes import *
libcyg=CDLL("<path/cygwin1.dll") #It needs cygwin to be loaded. Not sure why.
pari=CDLL("<path>/libpari-gmp-2.4.dll")
print pari.fibo #fibonacci function
#prints something like "<_FuncPtr object at 0x00BA5828>"
So the functions are there and they can potentially be accessed, but I always receive an access violation no matter what I try. For example:
pari.fibo(5) #access violation
pari.fibo(c_int(5)) #access violation
pari.fibo.argtypes = [c_long] #setting arguments manually
pari.fibo.restype = long #set the return type
pari.fibo(byref(c_int(5))) #access violation reading 0x04 consistently
and any variation on that, including setting argtypes to receive pointers.
The Pari .dll is written in C and the fibonacci function's syntax within the library is GEN fibo(long x).
Could it be the return type that's causing these errors, as it is not a standard int or long but a GEN type, which is unique to the PARI library? Any help would be appreciated. If anyone is able to successfully load the library and use ANY function from within python, please tell; I've been at this for hours now.
EDIT: Seems as though I was simply forgetting to initialize the library. After a quick pari.pari_init(4000000,500000) it stopped erroring. Now my problem lies in the in the fact that it returns a GEN object; which is fine, but whenever I try to reference the address to which it points, it's always 33554435, which I presume is still an address. I'm trying further commands and I'll update if I succeed in getting the correct value of something.
A:
You have two problems here, one give fibo the correct return type and two convert the GEN return type to the value you are looking for.
Poking around the source code a bit, you'll find that GEN is defined as a pointer to a long. Also, at looks like the library provides some converting/printing GENs. I focused in on GENtostr since it would probably be safer for all the pari functions.
import cytpes
pari = ctypes.CDLL("./libpari.so.2.3.5") #I did this under linux
pari.fibo.restype = ctypes.POINTER(ctypes.c_long)
pari.GENtostr.restype = ctypes.POINTER(ctypes.c_char)
pari.pari_init(4000000,500000)
x = pari.fibo(100)
y = pari.GENtostr(x)
ctypes.string_at(y)
Results in:
'354224848179261915075'
|
Python c_types .dll functions (pari library)
|
Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following:
from ctypes import *
libcyg=CDLL("<path/cygwin1.dll") #It needs cygwin to be loaded. Not sure why.
pari=CDLL("<path>/libpari-gmp-2.4.dll")
print pari.fibo #fibonacci function
#prints something like "<_FuncPtr object at 0x00BA5828>"
So the functions are there and they can potentially be accessed, but I always receive an access violation no matter what I try. For example:
pari.fibo(5) #access violation
pari.fibo(c_int(5)) #access violation
pari.fibo.argtypes = [c_long] #setting arguments manually
pari.fibo.restype = long #set the return type
pari.fibo(byref(c_int(5))) #access violation reading 0x04 consistently
and any variation on that, including setting argtypes to receive pointers.
The Pari .dll is written in C and the fibonacci function's syntax within the library is GEN fibo(long x).
Could it be the return type that's causing these errors, as it is not a standard int or long but a GEN type, which is unique to the PARI library? Any help would be appreciated. If anyone is able to successfully load the library and use ANY function from within python, please tell; I've been at this for hours now.
EDIT: Seems as though I was simply forgetting to initialize the library. After a quick pari.pari_init(4000000,500000) it stopped erroring. Now my problem lies in the in the fact that it returns a GEN object; which is fine, but whenever I try to reference the address to which it points, it's always 33554435, which I presume is still an address. I'm trying further commands and I'll update if I succeed in getting the correct value of something.
|
[
"You have two problems here, one give fibo the correct return type and two convert the GEN return type to the value you are looking for.\nPoking around the source code a bit, you'll find that GEN is defined as a pointer to a long. Also, at looks like the library provides some converting/printing GENs. I focused in on GENtostr since it would probably be safer for all the pari functions.\nimport cytpes\npari = ctypes.CDLL(\"./libpari.so.2.3.5\") #I did this under linux\npari.fibo.restype = ctypes.POINTER(ctypes.c_long)\npari.GENtostr.restype = ctypes.POINTER(ctypes.c_char) \npari.pari_init(4000000,500000)\nx = pari.fibo(100)\ny = pari.GENtostr(x)\nctypes.string_at(y)\n\nResults in:\n'354224848179261915075'\n\n"
] |
[
3
] |
[] |
[] |
[
"ctypes",
"pari",
"python"
] |
stackoverflow_0002527705_ctypes_pari_python.txt
|
Q:
Get parent function
Is there a way to find what function called the current function? So for example:
def first():
second()
def second():
# print out here what function called this one
Any ideas?
A:
import inspect
def first():
return second()
def second():
return inspect.getouterframes( inspect.currentframe() )[1]
first()[3] # 'first'
A:
These work well for quickly adding minimal where-am-I debugging aids when you don't want to import yet another module. (CPython only, for debugging only.)
def LINE( back = 0 ):
return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
frame = sys._getframe( back + 1 )
return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
frame.f_lineno, frame.f_code.co_name )
Example:
import sys, os # these you almost always have...
def WHERE( back = 0 ):
frame = sys._getframe( back + 1 )
return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
frame.f_lineno, frame.f_code.co_name )
def first():
second()
def second():
print WHERE()
print WHERE(1)
first()
Output:
$ python fs.py
fs.py/12 second()
fs.py/9 first()
A:
You can use the traceback module's extract_stack function.
import traceback
def first():
second()
def second():
print traceback.extract_stack(limit=2)[-2][2]
A:
The inspect module allows for many forms of introspection including this one, but note that it's only recommended to use such information for purposes such as debugging, not as part of your production code's functionality. See the docs for all details.
|
Get parent function
|
Is there a way to find what function called the current function? So for example:
def first():
second()
def second():
# print out here what function called this one
Any ideas?
|
[
"import inspect\n\ndef first():\n return second()\n\ndef second():\n return inspect.getouterframes( inspect.currentframe() )[1]\n\nfirst()[3] # 'first'\n\n",
"These work well for quickly adding minimal where-am-I debugging aids when you don't want to import yet another module. (CPython only, for debugging only.)\ndef LINE( back = 0 ):\n return sys._getframe( back + 1 ).f_lineno\ndef FILE( back = 0 ):\n return sys._getframe( back + 1 ).f_code.co_filename\ndef FUNC( back = 0):\n return sys._getframe( back + 1 ).f_code.co_name\ndef WHERE( back = 0 ):\n frame = sys._getframe( back + 1 )\n return \"%s/%s %s()\" % ( os.path.basename( frame.f_code.co_filename ),\n frame.f_lineno, frame.f_code.co_name )\n\nExample:\nimport sys, os # these you almost always have...\n\ndef WHERE( back = 0 ):\n frame = sys._getframe( back + 1 )\n return \"%s/%s %s()\" % ( os.path.basename( frame.f_code.co_filename ),\n frame.f_lineno, frame.f_code.co_name )\n\ndef first():\n second()\n\ndef second():\n print WHERE()\n print WHERE(1)\n\nfirst()\n\nOutput:\n$ python fs.py\nfs.py/12 second()\nfs.py/9 first()\n\n",
"You can use the traceback module's extract_stack function.\nimport traceback\ndef first():\n second()\n\ndef second():\n print traceback.extract_stack(limit=2)[-2][2]\n\n",
"The inspect module allows for many forms of introspection including this one, but note that it's only recommended to use such information for purposes such as debugging, not as part of your production code's functionality. See the docs for all details.\n"
] |
[
11,
5,
2,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002529859_python.txt
|
Q:
Python beautifulsoup trying to remove html tags 'span'
I am trying to remove
[<span class="street-address">
510 E Airline Way
</span>]
and I have used this clean function to remove the one that is in between < >
def clean(val):
if type(val) is not StringType: val = str(val)
val = re.sub(r'<.*?>', '',val)
val = re.sub("\s+" , " ", val)
return val.strip()
and it produces [ 510 E Airline Way ]
i am trying to add within "clean" function to remove the char '[' and ']' and basically i just want to get the "510 E Airline Way".
anyone has any clue what can i add to clean function?
thank you
A:
Using re:
>>> import re
>>> s='[<span class="street-address">\n 510 E Airline Way\n </span>]'
>>> re.sub(r'\[|\]|\s*<[^>]*>\s*', '', s)
'510 E Airline Way'
Using BeautifulSoup:
>>> from BeautifulSoup import BeautifulSoup
>>> s='[<span class="street-address">\n 510 E Airline Way\n </span>]'
>>> b = BeautifulSoup(s)
>>> b.find('span').getText()
u'510 E Airline Way'
Using lxml:
>>> from lxml import html
>>> s='[<span class="street-address">\n 510 E Airline Way\n </span>]'
>>> h = html.document_fromstring(s)
>>> h.cssselect('span')[0].text.strip()
'510 E Airline Way'
|
Python beautifulsoup trying to remove html tags 'span'
|
I am trying to remove
[<span class="street-address">
510 E Airline Way
</span>]
and I have used this clean function to remove the one that is in between < >
def clean(val):
if type(val) is not StringType: val = str(val)
val = re.sub(r'<.*?>', '',val)
val = re.sub("\s+" , " ", val)
return val.strip()
and it produces [ 510 E Airline Way ]
i am trying to add within "clean" function to remove the char '[' and ']' and basically i just want to get the "510 E Airline Way".
anyone has any clue what can i add to clean function?
thank you
|
[
"Using re:\n>>> import re\n>>> s='[<span class=\"street-address\">\\n 510 E Airline Way\\n </span>]'\n>>> re.sub(r'\\[|\\]|\\s*<[^>]*>\\s*', '', s)\n'510 E Airline Way'\n\nUsing BeautifulSoup:\n>>> from BeautifulSoup import BeautifulSoup\n>>> s='[<span class=\"street-address\">\\n 510 E Airline Way\\n </span>]'\n>>> b = BeautifulSoup(s)\n>>> b.find('span').getText()\nu'510 E Airline Way'\n\nUsing lxml:\n>>> from lxml import html\n>>> s='[<span class=\"street-address\">\\n 510 E Airline Way\\n </span>]'\n>>> h = html.document_fromstring(s)\n>>> h.cssselect('span')[0].text.strip()\n'510 E Airline Way'\n\n"
] |
[
9
] |
[] |
[] |
[
"beautifulsoup",
"python",
"regex"
] |
stackoverflow_0002529978_beautifulsoup_python_regex.txt
|
Q:
How To Collapse Just One Field in Django Admin?
The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. This is good for hiding rarely used or advanced fields to keep the UI clean.
However, I have a situation where I want to hide just one lonesome field on many different apps. This will be a lot of typing to create a full fieldset specification in every admin.py file just to put one field into the collapsed area. It also creates a difficult maintenance situation because I will have to edit the fieldset every time I edit the associated model.
I can easily exclude the field entirely using the exclude option. I want something similar for collapse. Is this possible?
A:
Django doesn't have a built in way of doing this that I'm aware of but I can think of a couple of ways you could do something once, rather than having to manually modify lots of fieldsets.
One approach would be to use javascript to rewrite the page markup. Maybe the javascript could have a list of fieldnames and whenever it finds one of those it hides the field and it's label and adds a button to the page to toggle these invisible fields.
The other approach would just involve python. Normally you just specify the fieldsets attribute in the admin as a tuple. But you could specify it as an imported function which takes the usual tuple as an argument. In your settings file you could specify a list of fieldnames you want to hide. You then need to write a function that returns a modified tuple, moving any fields that match one of your fieldnames into a new fieldset along with the collapse class.
For example in your admin class you could do something like this (you need to write and import hide_fields).
fieldsets = hide_fields(
(None,
{'fields':('title', 'content')}
)
)
This might end up being interpreted as the following, assuming content is in the settings file as something you want to hide:
fieldsets = (
(None,
{'fields':('title',)}
),
('Extra',
{
'fields': ('content',),
'classes':('collapse',),
}
),
)
A:
I do something like this, where I have one or more fields are only required based on the value of another. This is usually a checkbox or select, where true/false or one particular value means that we should show this other set of fields. I've added something like this:
$(document).ready(function(){
function show_hide() {
var is_checked = $('#id_first_field').attr('checked');
$('.second_field')[is_checked ? 'show' : 'hide']();
}
show_hide();
$('#id_first_field').change(show_hide);
});
|
How To Collapse Just One Field in Django Admin?
|
The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. This is good for hiding rarely used or advanced fields to keep the UI clean.
However, I have a situation where I want to hide just one lonesome field on many different apps. This will be a lot of typing to create a full fieldset specification in every admin.py file just to put one field into the collapsed area. It also creates a difficult maintenance situation because I will have to edit the fieldset every time I edit the associated model.
I can easily exclude the field entirely using the exclude option. I want something similar for collapse. Is this possible?
|
[
"Django doesn't have a built in way of doing this that I'm aware of but I can think of a couple of ways you could do something once, rather than having to manually modify lots of fieldsets.\nOne approach would be to use javascript to rewrite the page markup. Maybe the javascript could have a list of fieldnames and whenever it finds one of those it hides the field and it's label and adds a button to the page to toggle these invisible fields.\nThe other approach would just involve python. Normally you just specify the fieldsets attribute in the admin as a tuple. But you could specify it as an imported function which takes the usual tuple as an argument. In your settings file you could specify a list of fieldnames you want to hide. You then need to write a function that returns a modified tuple, moving any fields that match one of your fieldnames into a new fieldset along with the collapse class.\nFor example in your admin class you could do something like this (you need to write and import hide_fields).\nfieldsets = hide_fields(\n (None,\n {'fields':('title', 'content')}\n )\n)\n\nThis might end up being interpreted as the following, assuming content is in the settings file as something you want to hide:\nfieldsets = (\n (None,\n {'fields':('title',)}\n ),\n ('Extra',\n {\n 'fields': ('content',),\n 'classes':('collapse',),\n }\n ),\n)\n\n",
"I do something like this, where I have one or more fields are only required based on the value of another. This is usually a checkbox or select, where true/false or one particular value means that we should show this other set of fields. I've added something like this:\n$(document).ready(function(){\n function show_hide() {\n var is_checked = $('#id_first_field').attr('checked');\n $('.second_field')[is_checked ? 'show' : 'hide']();\n }\n show_hide();\n $('#id_first_field').change(show_hide);\n});\n\n"
] |
[
5,
0
] |
[
"If you want you can use fieldset in your admin.py and the field which you want to collapse use the class as collapse and remaining as foobar.\nRefer to django docs\n"
] |
[
-3
] |
[
"django",
"django_admin",
"python"
] |
stackoverflow_0002420516_django_django_admin_python.txt
|
Q:
Django Foreign key queries
In the following model:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
If there is a row in the database for table header as
Id=1, title=value-mart , createdby=CEO
How do I query criteria and options tables to get all the values related to header table
id=1
Also can some one please suggest a good link for queries examples.
A:
Ironfroggy is right, but there is another more obvious way to get the relevant options and criteria objects. Django automatically creates a 'reverse relation' for every foreign key pointing at a model, and that is usually the name of the related model plus _set. So:
mycriteria.options_set.all()
mycriteria.header_set.all()
will give you all the options and header objects related to a criteria object mycriteria.
Also, a note on style: as ironfroggy pointed out, you shouldn't use id in the foreign key fields, but also you should use Capitalised style for your model classes, so you can see a difference between the class Criteria and a particular instance criteria.
In terms of links, the Django documentation is excellent and explains all of this.
A:
First of all, don't use id in the names, because it is confusing. That field isn't the ID, it is the object itself. (If you have a field ref it automatically creates a field ref_id)
options.objects.filter(header=a_header)
You query it like any value, where some header instance is the value you are filtering on.
A:
Sounds like you are looking for Following relationships "backward".
You can get the header object you want to filter by, and use something like
obj = Header.objects.get(title="value-mart", "createdby=CEO")
obj.criteria_set.all()
Look at the documentation for more detailed info
A:
I would suggest trying to us a coding style and naming convention that is more like you see in the Django documentation for Models. Something more like this:
class Header(models.Model):
...
class Criteria(models.Model):
details = model.CharField(max_length=255)
header = models.ForeignKey(Header)
And then query them as needed:
# find Criteria for a given header
value_mart = Header.objects.get(id=1)
# ... via an instance of Header.
value_mart.criteria_set.all()
# ... or with a filter().
Criteria.objects.filter(header=value_mart)
Criteria.objects.filter(header_id=1)
The documentation for many-to-one relationships also references a usage example.
|
Django Foreign key queries
|
In the following model:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
If there is a row in the database for table header as
Id=1, title=value-mart , createdby=CEO
How do I query criteria and options tables to get all the values related to header table
id=1
Also can some one please suggest a good link for queries examples.
|
[
"Ironfroggy is right, but there is another more obvious way to get the relevant options and criteria objects. Django automatically creates a 'reverse relation' for every foreign key pointing at a model, and that is usually the name of the related model plus _set. So:\nmycriteria.options_set.all()\nmycriteria.header_set.all()\n\nwill give you all the options and header objects related to a criteria object mycriteria.\nAlso, a note on style: as ironfroggy pointed out, you shouldn't use id in the foreign key fields, but also you should use Capitalised style for your model classes, so you can see a difference between the class Criteria and a particular instance criteria.\nIn terms of links, the Django documentation is excellent and explains all of this.\n",
"First of all, don't use id in the names, because it is confusing. That field isn't the ID, it is the object itself. (If you have a field ref it automatically creates a field ref_id)\noptions.objects.filter(header=a_header)\n\nYou query it like any value, where some header instance is the value you are filtering on.\n",
"Sounds like you are looking for Following relationships \"backward\".\nYou can get the header object you want to filter by, and use something like\nobj = Header.objects.get(title=\"value-mart\", \"createdby=CEO\")\nobj.criteria_set.all()\n\nLook at the documentation for more detailed info\n",
"I would suggest trying to us a coding style and naming convention that is more like you see in the Django documentation for Models. Something more like this:\nclass Header(models.Model):\n ...\n\nclass Criteria(models.Model):\n details = model.CharField(max_length=255)\n header = models.ForeignKey(Header)\n\nAnd then query them as needed:\n# find Criteria for a given header\nvalue_mart = Header.objects.get(id=1)\n\n# ... via an instance of Header.\nvalue_mart.criteria_set.all()\n\n# ... or with a filter().\nCriteria.objects.filter(header=value_mart)\nCriteria.objects.filter(header_id=1)\n\nThe documentation for many-to-one relationships also references a usage example. \n"
] |
[
21,
9,
5,
4
] |
[] |
[] |
[
"django",
"django_queryset",
"django_views",
"python"
] |
stackoverflow_0002530158_django_django_queryset_django_views_python.txt
|
Q:
Python idiom for '... if ... else ...' expression
How to write the expression shorter:
return '%.0f' % float_var if float_var else float_var
or
if float_var:
return formatted_string
else:
return None
Thanks!
A:
The expression <value> if <condition> else <other_value> is pretty idiomatic already -- certainly more so than the other example, and is probably preferred whenever <value> is simple. This is Python's ternary operator, so if you were looking for something like <condition> ? <value> : <other_value>, that doesn't exist.
If computing <value> or <other_value> takes a few steps, use the longer if: ... else: ... alternative.
A:
I would use brackets to make the expression more readable:
return ('%.0f' % float_var) if float_var else float_var
When I first saw it I read it as
return '%.0f' % (float_var if float_var else float_var)
which would be silly. I had to try it out to make sure which way it worked.
BTW Your first example not equivalent to your second example
if float_var:
return formatted_string
else:
return None
This will always return either a formatted string or None. Your first example if you pass in anything that evaluates to False (False, 0, 0.0, "", [] etc) will return that unchanged, so your return type could be string, boolean, list, int, float etc. This is probably not what you want, especially if 0.0 is a legitimate value for float_var. I would change your code to:
return ('%.0f' % float_var) if isinstance(float_var, float) else None
alternatively:
try:
return "%.0f" % float_var
except TypeError:
return None
which will work for other integers (and longs) by converting them to float.
A:
It is not clear what exactly you want to do.
The most literal interpretation would have it work like this
>>> float_var = 4.5
>>> '%.0f' % float_var if float_var else float_var
'5' # This is a string
>>> float_var = 0.0
>>> '%.0f' % float_var if float_var else float_var
0.0 # This is a float
which I am almost certain you did not want.
I guess you are wanting to check for None with "if float_var"? If so, you always spell it "if foo is not None", not "if foo", the former being clearer and less bug-prone.
If that is what you intended, I suggest you revise your model. Propagating errors by repeatedly returning None is a bad thing: it is ugly and bug-prone and non-idiomatic. Use exceptions instead.
Shorter is not always better. Your snippets are not painfully long or unwieldly. In fact, you will want to make them a little longer if you use them to avoid a potential bug.
Someone may suggest abusing the short-circuiting behavior of or for this. However, this makes code harder to read and doesn't allow you to specify between None and other false values, which often leads to bugs.
A:
If you are using are already using v if c else u you are already using the most readable and efficient ternary operator.
There are other ways but they suffer in readability.
A:
float_var and "%.0f" % float_vav
Isn't it awesome?
|
Python idiom for '... if ... else ...' expression
|
How to write the expression shorter:
return '%.0f' % float_var if float_var else float_var
or
if float_var:
return formatted_string
else:
return None
Thanks!
|
[
"The expression <value> if <condition> else <other_value> is pretty idiomatic already -- certainly more so than the other example, and is probably preferred whenever <value> is simple. This is Python's ternary operator, so if you were looking for something like <condition> ? <value> : <other_value>, that doesn't exist.\nIf computing <value> or <other_value> takes a few steps, use the longer if: ... else: ... alternative.\n",
"I would use brackets to make the expression more readable:\nreturn ('%.0f' % float_var) if float_var else float_var\n\nWhen I first saw it I read it as\nreturn '%.0f' % (float_var if float_var else float_var)\n\nwhich would be silly. I had to try it out to make sure which way it worked.\nBTW Your first example not equivalent to your second example \nif float_var:\n return formatted_string\nelse:\n return None\n\nThis will always return either a formatted string or None. Your first example if you pass in anything that evaluates to False (False, 0, 0.0, \"\", [] etc) will return that unchanged, so your return type could be string, boolean, list, int, float etc. This is probably not what you want, especially if 0.0 is a legitimate value for float_var. I would change your code to:\nreturn ('%.0f' % float_var) if isinstance(float_var, float) else None\n\nalternatively:\ntry:\n return \"%.0f\" % float_var\nexcept TypeError:\n return None\n\nwhich will work for other integers (and longs) by converting them to float.\n",
"\nIt is not clear what exactly you want to do. \n\nThe most literal interpretation would have it work like this\n>>> float_var = 4.5\n>>> '%.0f' % float_var if float_var else float_var\n'5' # This is a string\n>>> float_var = 0.0\n>>> '%.0f' % float_var if float_var else float_var\n0.0 # This is a float\n\nwhich I am almost certain you did not want. \nI guess you are wanting to check for None with \"if float_var\"? If so, you always spell it \"if foo is not None\", not \"if foo\", the former being clearer and less bug-prone.\nIf that is what you intended, I suggest you revise your model. Propagating errors by repeatedly returning None is a bad thing: it is ugly and bug-prone and non-idiomatic. Use exceptions instead.\n\nShorter is not always better. Your snippets are not painfully long or unwieldly. In fact, you will want to make them a little longer if you use them to avoid a potential bug.\n\nSomeone may suggest abusing the short-circuiting behavior of or for this. However, this makes code harder to read and doesn't allow you to specify between None and other false values, which often leads to bugs.\n\n\n",
"If you are using are already using v if c else u you are already using the most readable and efficient ternary operator.\nThere are other ways but they suffer in readability.\n",
"float_var and \"%.0f\" % float_vav\n\nIsn't it awesome?\n"
] |
[
32,
6,
2,
1,
0
] |
[] |
[] |
[
"idioms",
"python"
] |
stackoverflow_0002529536_idioms_python.txt
|
Q:
Installing Sphinx on App Engine - possible?
Following up on my last year's question on documentation, I now want to get started and try out Python-based Sphinx for putting together the developer documentation for a PHP CMS I've been working on.
Instead of setting up Python locally on my workstation, I would like to run it on a publicly accessible web server from the start. All the web hosting packages I have access to run on the LAMP stack, and I'm reluctant to buy Python-based hosting. I am very interested in the Google App Engine, the free quotas they provide will do for me a hundred times over, and even if not, their pricing looks very reasonable.
Now I have zero knowledge of Python - getting Sphinx to work would be my first contact with it - and very little time. As far as I understand, the platform and python libraries the App Engine provides are very compatible to a standard Python library but not identical.
So my question is:
Can Sphinx run on App Engine at all?
Is installing Sphinx on the App Engine as straightforward as if I would install it on top of a normal Python installation? Or will the App Engine's environment require tweaking of the source code that I can't perform in reasonable time with my current level of Python?
Should I be installing Sphinx on a local server and a "normal" Python stack instead first?
Does anybody know any helpful How-to's, tutorials or other resources for this?
A:
You do not need to install Sphinx on GAE at all.
You use Sphinx to create a directory of static HTML, CSS and JS. When this step is finished, you simply upload the output from Sphinx -- in it's entirety.
The output from Sphinx (HTML, CSS and JS) is simply served from one place. You upload the documentation from where you created it to GAE as static files and serve them. Done.
There's no "install on a web server" aspect to Sphinx at all. Sphinx is not a web application; it does not run on your web server. You run it in development briefly to publish the documentation to HTML, LaTeX or whatever. Once you've created the static HTML files, you no longer need any part of Sphinx anywhere.
Can Sphinx run on App Engine at all?
I suppose it can, but you never need to.
Is installing Sphinx on the App Engine
as straightforward as...
It doesn't matter, because you don't install it there. You install it on your workstation and use it on your workstation.
Should I be installing Sphinx on a
local server and a "normal" Python
stack instead first?
Don't install it on a server. Install it on your workstation.
Does anybody know any helpful
How-to's, tutorials or other resources
for this?
If by "this" you mean "installing on a web server", then then answer is "no". One does not install it on a web server. So there are no how-to's, tutorials or resources for "installing on a web server".
If by "this" you mean "creating documentation with Sphinx", then the answer is "what's wrong with https://www.sphinx-doc.org? What do they lack?
I would like Sphinx's "engine" that
turns the input (consisting of reST
files) into HTML/CSS/JS to be
accessible from anywhere to make me
(and possible other contributors)
independent from a specific
workstation.
Sphinx is like a compiler. Everyone has their own copy on their workstation. They download the document source, make changes, commit the source changes, and upload the resulting document.
serve the generated documentation from
the same place.
Correct. After you download the source, make changes, regenerate the document and commit the changes, you upload the resulting document so it will be served from one -- and only one -- place.
Sphinx is a compiler. It is not a "web engine". It's a simple compiler that simply compiles your documentation into HTML so it can be served.
A:
Interesting project! The main issue you're going to run into is that of filesystem access: The filesystem on App Engine is read-only, and based on looking at the source, Sphinx is fairly hard-coded to use the filesystem for output. It also expects to read the configuration file and input files from the local filesystem, which would make building docs for anything other than projects bundled with the app tricky.
It is possible to work around this, but it would require writing a simple virtual filesystem that uses the App Engine datastore, and using monkeypatching to make it work with the regular Python file interface. That's rather advanced for a "new to Python" project!
One other thing you might want to consider if you were pondering allowing users to upload projects to be documented: The Sphinx configuration file is in Python, so executing it could be dangerous - a user could do nasty things to your app with a malicious configuration file!
A:
The difference between deployment locally via dev_appserver and remotely via appcfg has been - in my experience - limited to which of the two commands I execute. That said, I've no experience with Sphinx.
A:
Sphinx compiles documentation, running it on a webserver makes as much sense as running gcc on a webserver.
|
Installing Sphinx on App Engine - possible?
|
Following up on my last year's question on documentation, I now want to get started and try out Python-based Sphinx for putting together the developer documentation for a PHP CMS I've been working on.
Instead of setting up Python locally on my workstation, I would like to run it on a publicly accessible web server from the start. All the web hosting packages I have access to run on the LAMP stack, and I'm reluctant to buy Python-based hosting. I am very interested in the Google App Engine, the free quotas they provide will do for me a hundred times over, and even if not, their pricing looks very reasonable.
Now I have zero knowledge of Python - getting Sphinx to work would be my first contact with it - and very little time. As far as I understand, the platform and python libraries the App Engine provides are very compatible to a standard Python library but not identical.
So my question is:
Can Sphinx run on App Engine at all?
Is installing Sphinx on the App Engine as straightforward as if I would install it on top of a normal Python installation? Or will the App Engine's environment require tweaking of the source code that I can't perform in reasonable time with my current level of Python?
Should I be installing Sphinx on a local server and a "normal" Python stack instead first?
Does anybody know any helpful How-to's, tutorials or other resources for this?
|
[
"You do not need to install Sphinx on GAE at all.\nYou use Sphinx to create a directory of static HTML, CSS and JS. When this step is finished, you simply upload the output from Sphinx -- in it's entirety.\nThe output from Sphinx (HTML, CSS and JS) is simply served from one place. You upload the documentation from where you created it to GAE as static files and serve them. Done.\nThere's no \"install on a web server\" aspect to Sphinx at all. Sphinx is not a web application; it does not run on your web server. You run it in development briefly to publish the documentation to HTML, LaTeX or whatever. Once you've created the static HTML files, you no longer need any part of Sphinx anywhere.\n\nCan Sphinx run on App Engine at all?\n\nI suppose it can, but you never need to.\n\nIs installing Sphinx on the App Engine\n as straightforward as...\n\nIt doesn't matter, because you don't install it there. You install it on your workstation and use it on your workstation.\n\nShould I be installing Sphinx on a\n local server and a \"normal\" Python\n stack instead first?\n\nDon't install it on a server. Install it on your workstation.\n\nDoes anybody know any helpful\n How-to's, tutorials or other resources\n for this?\n\nIf by \"this\" you mean \"installing on a web server\", then then answer is \"no\". One does not install it on a web server. So there are no how-to's, tutorials or resources for \"installing on a web server\".\nIf by \"this\" you mean \"creating documentation with Sphinx\", then the answer is \"what's wrong with https://www.sphinx-doc.org? What do they lack?\n\n\nI would like Sphinx's \"engine\" that\n turns the input (consisting of reST\n files) into HTML/CSS/JS to be\n accessible from anywhere to make me\n (and possible other contributors)\n independent from a specific\n workstation.\n\nSphinx is like a compiler. Everyone has their own copy on their workstation. They download the document source, make changes, commit the source changes, and upload the resulting document.\n\nserve the generated documentation from\n the same place.\n\nCorrect. After you download the source, make changes, regenerate the document and commit the changes, you upload the resulting document so it will be served from one -- and only one -- place.\nSphinx is a compiler. It is not a \"web engine\". It's a simple compiler that simply compiles your documentation into HTML so it can be served.\n",
"Interesting project! The main issue you're going to run into is that of filesystem access: The filesystem on App Engine is read-only, and based on looking at the source, Sphinx is fairly hard-coded to use the filesystem for output. It also expects to read the configuration file and input files from the local filesystem, which would make building docs for anything other than projects bundled with the app tricky.\nIt is possible to work around this, but it would require writing a simple virtual filesystem that uses the App Engine datastore, and using monkeypatching to make it work with the regular Python file interface. That's rather advanced for a \"new to Python\" project!\nOne other thing you might want to consider if you were pondering allowing users to upload projects to be documented: The Sphinx configuration file is in Python, so executing it could be dangerous - a user could do nasty things to your app with a malicious configuration file!\n",
"The difference between deployment locally via dev_appserver and remotely via appcfg has been - in my experience - limited to which of the two commands I execute. That said, I've no experience with Sphinx.\n",
"Sphinx compiles documentation, running it on a webserver makes as much sense as running gcc on a webserver.\n"
] |
[
6,
3,
1,
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"python_sphinx"
] |
stackoverflow_0002522255_google_app_engine_python_python_sphinx.txt
|
Q:
Why eclipse + pydev print() output look strange with two strings?
hay all, I just did the following:
a = input("give a word: ")
b = input("give another word: ")
c = a + " " + b
print("result is", c)
and get the output as follows:
give a word: name
give another word: word
result is name
word
my question is why the output on pydev or eclipse console in two lines? i expected to output as follows:
give a word: name
give another word: word
result is name word
how and why this happens to me? on cmd its looking fine??!!
also i found that python saves the strings with "\r", i think that is the one making this problem on pydev console, is it?
A:
It seems to me that Eclipse + PyDev is storing the newline character in the string as well. There are a few variants of the newline character depending on the operating system: \n, \r, \r\n.
In any case, I think the following should fix your problem:
a = raw_input("give a word: ").strip()
b = raw_input("give another word: ").strip()
c = a + " " + b
I have tested this code on PyDev for Eclipse Galileo on Windows7 and it works.
Hope this helps
A:
That's very strange.
Are you getting an extra newline after word? (you can check by issuing another print command).
Eclipse is always weird on console input. I would not be surprised if somehow it keeps a CR or a LF (or both) in the string, so that when you print each of them, you would get a line break. But then you should get another line break after word.
|
Why eclipse + pydev print() output look strange with two strings?
|
hay all, I just did the following:
a = input("give a word: ")
b = input("give another word: ")
c = a + " " + b
print("result is", c)
and get the output as follows:
give a word: name
give another word: word
result is name
word
my question is why the output on pydev or eclipse console in two lines? i expected to output as follows:
give a word: name
give another word: word
result is name word
how and why this happens to me? on cmd its looking fine??!!
also i found that python saves the strings with "\r", i think that is the one making this problem on pydev console, is it?
|
[
"It seems to me that Eclipse + PyDev is storing the newline character in the string as well. There are a few variants of the newline character depending on the operating system: \\n, \\r, \\r\\n.\nIn any case, I think the following should fix your problem:\na = raw_input(\"give a word: \").strip()\nb = raw_input(\"give another word: \").strip()\nc = a + \" \" + b\n\nI have tested this code on PyDev for Eclipse Galileo on Windows7 and it works.\nHope this helps\n",
"That's very strange.\nAre you getting an extra newline after word? (you can check by issuing another print command). \nEclipse is always weird on console input. I would not be surprised if somehow it keeps a CR or a LF (or both) in the string, so that when you print each of them, you would get a line break. But then you should get another line break after word.\n"
] |
[
1,
0
] |
[] |
[] |
[
"eclipse_3.5",
"pydev",
"python",
"python_3.x"
] |
stackoverflow_0002530387_eclipse_3.5_pydev_python_python_3.x.txt
|
Q:
Python regex group clarification
I have 0 experience with python, very little with regex and I'm trying to figure out what this small snippet of
python regex would give back from a http response header Set-Cookie entry:
REGEX_COOKIE = '([A-Z]+=[^;]+;)'
resp = urllib2.urlopen(req)
re.search(REGEX_COOKIE, resp.info()['Set-Cookie']).group(1)
Can one give a simple example of a Set-Cookie value and explain what this would match on + return?
Regards
A:
A Set-Cookie is a list of name value pairs, separated with semi-colons:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT
(content of page)
The regular expression matches the name, the equals sign, and the value up to the first semi-colon - in this case: RMID=732423sdfs73242;. In other words, it reads the first name-value pair. Note that it won't work if there is only a single name-value pair which is not followed by a semi-colon.
|
Python regex group clarification
|
I have 0 experience with python, very little with regex and I'm trying to figure out what this small snippet of
python regex would give back from a http response header Set-Cookie entry:
REGEX_COOKIE = '([A-Z]+=[^;]+;)'
resp = urllib2.urlopen(req)
re.search(REGEX_COOKIE, resp.info()['Set-Cookie']).group(1)
Can one give a simple example of a Set-Cookie value and explain what this would match on + return?
Regards
|
[
"A Set-Cookie is a list of name value pairs, separated with semi-colons:\n\nHTTP/1.1 200 OK\nContent-type: text/html\nSet-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT\n\n(content of page)\n\nThe regular expression matches the name, the equals sign, and the value up to the first semi-colon - in this case: RMID=732423sdfs73242;. In other words, it reads the first name-value pair. Note that it won't work if there is only a single name-value pair which is not followed by a semi-colon.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002530794_python_regex.txt
|
Q:
How to get frame rate (fps) up in Python + Pygame?
I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game for Intel's March developer competition, which is squarely aimed at netbooks packing underpowered Atom processors.
Here's a screen from the game:
(source: necessarygames.com)
I am very new to Python and Pygame (this is the first thing I've used them for), and am sadly lacking in formal CS training... which is to say that I think there are probably A LOT of bad practices going on in my code, and A LOT that could be optimized. If some of you older Python hands wouldn't mind taking a look at my code and seeing if you can't find any obvious areas for optimization, I would be extremely grateful.
You can download the full source code here (Python 2.6 + Pygame 1.9):
http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
Compiled exe here:
www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
One thing I am concerned about is my event manager, which I feel may have some performance wholes in it, and another thing is my rendering... I'm pretty much just blitting everything to the screen all the time (see the render routines in my game_components.py below); I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue?
Any thoughts are much appreciated! As usual, I'm happy to "tip" you for your time and energy via PayPal.
Jordan
EDIT:
Thanks to the advice below, I ran cprofile on my code. It would be great if anyone would be willing to look at this output and let me know what is and what is not to be expected.
Here is the output of p.strip_dirs().sort_stats('cumulative').print_stats():
pydev debugger: starting
Sun Mar 28 04:46:16 2010 cprofile
8383715 function calls (8264821 primitive calls) in 157.732 CPU seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 157.732 157.732 <string>:1(<module>)
1 0.000 0.000 157.732 157.732 main.py:47(main)
1 0.074 0.074 157.280 157.280 event_manager.py:101(run)
4911/2414 11.837 0.002 156.984 0.065 event_manager.py:32(post)
4786/4681 0.238 0.000 94.852 0.020 rooms.py:251(notify)
2187 0.523 0.000 51.136 0.023 rooms.py:329(render)
4911/2959 0.220 0.000 35.732 0.012 event_manager.py:54(notify)
2271 33.996 0.015 33.996 0.015 {pygame.display.update}
2271 0.060 0.000 23.664 0.010 app.py:178(paint)
37347/2271 1.580 0.000 23.587 0.010 container.py:83(paint)
70236/2271 3.609 0.000 23.448 0.010 theme.py:275(func)
1078950 16.926 0.000 16.926 0.000 {method 'blit' of 'pygame.Surface' objects}
2187 2.131 0.001 16.875 0.008 game_components.py:666(render)
19635/17756 0.187 0.000 13.852 0.001 game_components.py:641(notify)
733820 7.710 0.000 13.643 0.000 game_components.py:1151(notify)
2271 12.254 0.005 12.254 0.005 {pygame.time.wait}
64112 3.174 0.000 11.252 0.000 game_components.py:1186(render)
9 0.002 0.000 10.151 1.128 game_components.py:286(deal_new_board)
1934 0.095 0.000 8.489 0.004 app.py:144(event)
4359/2146 0.178 0.000 8.375 0.004 container.py:112(event)
2335/2146 0.056 0.000 8.251 0.004 widget.py:346(_event)
2335/2146 0.048 0.000 8.193 0.004 theme.py:320(func)
4883/4691 0.018 0.000 8.049 0.002 widget.py:313(send)
229 0.139 0.001 8.017 0.035 game_components.py:632(refresh_darkness)
7258 0.499 0.000 7.844 0.001 game_components.py:963(test_close_to_trip)
2271 7.378 0.003 7.378 0.003 {pygame.display.set_caption}
19347 3.313 0.000 6.687 0.000 game_components.py:928(get_next_to)
2187 1.529 0.001 6.629 0.003 game_components.py:130(render)
2011729 5.938 0.000 5.938 0.000 {isinstance}
3 0.000 0.000 5.906 1.969 my_gui.py:274(clicked)
219456 3.060 0.000 5.680 0.000 surface.py:5(subsurface)
1290 0.506 0.000 5.416 0.004 game_components.py:683(__init__)
8748 2.891 0.000 5.340 0.001 theme.py:400(render)
70236 2.232 0.000 4.945 0.000 theme.py:186(box)
1357 0.097 0.000 4.391 0.003 game_components.py:742(set_image)
9 0.054 0.006 3.450 0.383 game_components.py:209(deal_connection_matrix)
8748 0.325 0.000 3.318 0.000 theme.py:479(paint)
1051 0.015 0.000 3.262 0.003 game_components.py:1232(__init__)
386467 3.148 0.000 3.148 0.000 {method 'fill' of 'pygame.Surface' objects}
245332 2.470 0.000 3.117 0.000 game_components.py:495(get_card)
55761 3.068 0.000 3.068 0.000 {pygame.draw.aaline}
2271 2.968 0.001 2.968 0.001 {pygame.event.get}
9 0.007 0.001 2.946 0.327 game_components.py:416(clone)
2187 0.089 0.000 2.717 0.001 misc.py:28(paint)
803701 2.483 0.000 2.497 0.000 weakref.py:302(iterkeys)
2739 2.441 0.001 2.441 0.001 {pygame.imageext.load_extended}
1470 1.108 0.001 2.432 0.002 game_components.py:450(set_pos)
29 0.029 0.001 2.270 0.078 game_components.py:433(clear)
2 0.000 0.000 2.158 1.079 main.py:22(set_room)
4911/4862 0.027 0.000 2.141 0.000 main.py:37(notify)
1 0.000 0.000 2.099 2.099 my_gui.py:164(clicked)
1 0.001 0.001 2.099 2.099 rooms.py:117(__init__)
1120 0.039 0.000 1.978 0.002 game_components.py:484(place_card)
27 0.013 0.000 1.963 0.073 game_components.py:339(merge_board_stack)
311 0.018 0.000 1.939 0.006 game_components.py:443(remove)
125 0.007 0.000 1.848 0.015 rooms.py:18(notify)
224 0.003 0.000 1.806 0.008 game_components.py:721(clone)
219456 1.638 0.000 1.638 0.000 {method 'subsurface' of 'pygame.Surface' objects}
183 0.004 0.000 1.313 0.007 game_components.py:1240(__init__)
4374 0.106 0.000 1.224 0.000 button.py:97(paint)
46765 0.967 0.000 1.137 0.000 game_components.py:784(set_pos)
229 0.109 0.000 1.111 0.005 game_components.py:594(refresh_trip)
4076 1.076 0.000 1.076 0.000 {method 'convert_alpha' of 'pygame.Surface' objects}
9 0.015 0.002 1.018 0.113 game_components.py:542(displace_cards)
17496 0.360 0.000 0.953 0.000 basic.py:102(paint)
66299 0.948 0.000 0.948 0.000 {pygame.draw.rect}
1357 0.024 0.000 0.945 0.001 game_components.py:736(set_text)
1357 0.052 0.000 0.917 0.001 game_components.py:841(render_text_rec)
5815 0.455 0.000 0.881 0.000 game_components.py:1108(get_connections)
6610 0.869 0.000 0.869 0.000 {method 'replace' of 'pygame.PixelArray' objects}
56 0.001 0.000 0.861 0.015 game_components.py:1252(__init__)
10 0.001 0.000 0.857 0.086 game_components.py:377(__init__)
540 0.484 0.001 0.828 0.002 game_components.py:613(refresh_connections)
189431 0.730 0.000 0.730 0.000 game_components.py:500(test_index_on_board)
161329 0.632 0.000 0.727 0.000 matrix.py:33(__iter__)
309968 0.710 0.000 0.710 0.000 {method 'get_width' of 'pygame.Surface' objects}
308567 0.675 0.000 0.675 0.000 {method 'get_height' of 'pygame.Surface' objects}
109626 0.646 0.000 0.670 0.000 style.py:18(__getattr__)
241697 0.646 0.000 0.646 0.000 matrix.py:24(getitem)
21084 0.601 0.000 0.601 0.000 {method 'render' of 'pygame.font.Font' objects}
327 0.006 0.000 0.580 0.002 game_components.py:490(place_card_first_time)
26 0.001 0.000 0.561 0.022 game_components.py:1259(__init__)
166 0.002 0.000 0.536 0.003 game_components.py:608(get_longest_trip)
1491/166 0.075 0.000 0.534 0.003 game_components.py:989(get_longest_trip)
5702 0.533 0.000 0.533 0.000 {method 'size' of 'pygame.font.Font' objects}
1 0.000 0.000 0.478 0.478 game_components.py:141(__init__)
1 0.001 0.001 0.478 0.478 game_components.py:165(rebuild)
67 0.005 0.000 0.457 0.007 game_components.py:713(change_size)
1 0.001 0.001 0.420 0.420 game_components.py:347(change_card_size)
1210/166 0.044 0.000 0.412 0.002 game_components.py:982(add_to_trip)
7654 0.275 0.000 0.405 0.000 game_components.py:938(get_bounding_box)
14969 0.101 0.000 0.385 0.000 game_components.py:1305(render)
149709 0.341 0.000 0.341 0.000 {method 'append' of 'list' objects}
87958 0.341 0.000 0.341 0.000 {hasattr}
1362 0.068 0.000 0.336 0.000 textrect.py:12(render_textrect)
30 0.001 0.000 0.301 0.010 game_components.py:1282(__init__)
47795 0.257 0.000 0.257 0.000 game_components.py:1024(test_connection)
14849 0.098 0.000 0.251 0.000 my_gui.py:209(notify)
17498 0.158 0.000 0.242 0.000 basic.py:22(is_color)
87480 0.224 0.000 0.224 0.000 {method 'set_clip' of 'pygame.Surface' objects}
9 0.003 0.000 0.209 0.023 game_components.py:279(deal_to_blank_squares)
1 0.114 0.114 0.208 0.208 {pygame.display.set_mode}
56617 0.206 0.000 0.206 0.000 game_components.py:837(get_center)
84 0.005 0.000 0.206 0.002 rooms.py:110(render)
Here is the output of p.strip_dirs().sort_stats('time').print_stats():
Sun Mar 28 04:46:16 2010 cprofile
8383715 function calls (8264821 primitive calls) in 157.732 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
2271 33.996 0.015 33.996 0.015 {pygame.display.update}
1078950 16.926 0.000 16.926 0.000 {method 'blit' of 'pygame.Surface' objects}
2271 12.254 0.005 12.254 0.005 {pygame.time.wait}
4911/2414 11.837 0.002 156.984 0.065 event_manager.py:32(post)
733820 7.710 0.000 13.643 0.000 game_components.py:1151(notify)
2271 7.378 0.003 7.378 0.003 {pygame.display.set_caption}
2011729 5.938 0.000 5.938 0.000 {isinstance}
70236/2271 3.609 0.000 23.448 0.010 theme.py:275(func)
19347 3.313 0.000 6.687 0.000 game_components.py:928(get_next_to)
64112 3.174 0.000 11.252 0.000 game_components.py:1186(render)
386467 3.148 0.000 3.148 0.000 {method 'fill' of 'pygame.Surface' objects}
55761 3.068 0.000 3.068 0.000 {pygame.draw.aaline}
219456 3.060 0.000 5.680 0.000 surface.py:5(subsurface)
2271 2.968 0.001 2.968 0.001 {pygame.event.get}
8748 2.891 0.000 5.340 0.001 theme.py:400(render)
803701 2.483 0.000 2.497 0.000 weakref.py:302(iterkeys)
245332 2.470 0.000 3.117 0.000 game_components.py:495(get_card)
2739 2.441 0.001 2.441 0.001 {pygame.imageext.load_extended}
70236 2.232 0.000 4.945 0.000 theme.py:186(box)
2187 2.131 0.001 16.875 0.008 game_components.py:666(render)
219456 1.638 0.000 1.638 0.000 {method 'subsurface' of 'pygame.Surface' objects}
37347/2271 1.580 0.000 23.587 0.010 container.py:83(paint)
2187 1.529 0.001 6.629 0.003 game_components.py:130(render)
1470 1.108 0.001 2.432 0.002 game_components.py:450(set_pos)
4076 1.076 0.000 1.076 0.000 {method 'convert_alpha' of 'pygame.Surface' objects}
46765 0.967 0.000 1.137 0.000 game_components.py:784(set_pos)
66299 0.948 0.000 0.948 0.000 {pygame.draw.rect}
6610 0.869 0.000 0.869 0.000 {method 'replace' of 'pygame.PixelArray' objects}
189431 0.730 0.000 0.730 0.000 game_components.py:500(test_index_on_board)
309968 0.710 0.000 0.710 0.000 {method 'get_width' of 'pygame.Surface' objects}
308567 0.675 0.000 0.675 0.000 {method 'get_height' of 'pygame.Surface' objects}
109626 0.646 0.000 0.670 0.000 style.py:18(__getattr__)
241697 0.646 0.000 0.646 0.000 matrix.py:24(getitem)
161329 0.632 0.000 0.727 0.000 matrix.py:33(__iter__)
21084 0.601 0.000 0.601 0.000 {method 'render' of 'pygame.font.Font' objects}
5702 0.533 0.000 0.533 0.000 {method 'size' of 'pygame.font.Font' objects}
2187 0.523 0.000 51.136 0.023 rooms.py:329(render)
1290 0.506 0.000 5.416 0.004 game_components.py:683(__init__)
7258 0.499 0.000 7.844 0.001 game_components.py:963(test_close_to_trip)
540 0.484 0.001 0.828 0.002 game_components.py:613(refresh_connections)
5815 0.455 0.000 0.881 0.000 game_components.py:1108(get_connections)
17496 0.360 0.000 0.953 0.000 basic.py:102(paint)
149709 0.341 0.000 0.341 0.000 {method 'append' of 'list' objects}
87958 0.341 0.000 0.341 0.000 {hasattr}
8748 0.325 0.000 3.318 0.000 theme.py:479(paint)
7654 0.275 0.000 0.405 0.000 game_components.py:938(get_bounding_box)
47795 0.257 0.000 0.257 0.000 game_components.py:1024(test_connection)
4786/4681 0.238 0.000 94.852 0.020 rooms.py:251(notify)
87480 0.224 0.000 0.224 0.000 {method 'set_clip' of 'pygame.Surface' objects}
4911/2959 0.220 0.000 35.732 0.012 event_manager.py:54(notify)
56617 0.206 0.000 0.206 0.000 game_components.py:837(get_center)
1 0.200 0.200 0.200 0.200 {pygame.base.quit}
19635/17756 0.187 0.000 13.852 0.001 game_components.py:641(notify)
1 0.184 0.184 0.184 0.184 {pygame.base.init}
4359/2146 0.178 0.000 8.375 0.004 container.py:112(event)
17498 0.158 0.000 0.242 0.000 basic.py:22(is_color)
1358 0.151 0.000 0.151 0.000 {pygame.transform.smoothscale}
229 0.139 0.001 8.017 0.035 game_components.py:632(refresh_darkness)
1 0.114 0.114 0.208 0.208 {pygame.display.set_mode}
37862 0.112 0.000 0.112 0.000 {method 'set_alpha' of 'pygame.Surface' objects}
6561 0.111 0.000 0.195 0.000 button.py:236(paint)
229 0.109 0.000 1.111 0.005 game_components.py:594(refresh_trip)
4374 0.106 0.000 1.224 0.000 button.py:97(paint)
14969 0.101 0.000 0.385 0.000 game_components.py:1305(render)
14849 0.098 0.000 0.251 0.000 my_gui.py:209(notify)
1357 0.097 0.000 4.391 0.003 game_components.py:742(set_image)
24072 0.096 0.000 0.096 0.000 game_components.py:913(test_pos_on_card)
4926 0.095 0.000 0.132 0.000 game_components.py:1292(__init__)
33286 0.095 0.000 0.095 0.000 {range}
1934 0.095 0.000 8.489 0.004 app.py:144(event)
2187 0.089 0.000 2.717 0.001 misc.py:28(paint)
2135 0.087 0.000 0.091 0.000 matrix.py:21(setitem)
4374 0.076 0.000 0.131 0.000 button.py:182(paint)
1491/166 0.075 0.000 0.534 0.003 game_components.py:989(get_longest_trip)
1 0.074 0.074 157.280 157.280 event_manager.py:101(run)
301 0.069 0.000 0.107 0.000 game_components.py:508(clear_selection)
1362 0.068 0.000 0.336 0.000 textrect.py:12(render_textrect)
2227 0.066 0.000 0.150 0.000 game_components.py:809(move)
5740 0.062 0.000 0.165 0.000 misc.py:34(__setattr__)
2271 0.060 0.000 23.664 0.010 app.py:178(paint)
2335/2146 0.056 0.000 8.251 0.004 widget.py:346(_event)
4786 0.055 0.000 0.099 0.000 game_components.py:97(notify)
9 0.054 0.006 3.450 0.383 game_components.py:209(deal_connection_matrix)
1357 0.052 0.000 0.917 0.001 game_components.py:841(render_text_rec)
5 0.052 0.010 0.052 0.010 {method 'convert' of 'pygame.Surface' objects}
2335/2146 0.048 0.000 8.193 0.004 theme.py:320(func)
1210/166 0.044 0.000 0.412 0.002 game_components.py:982(add_to_trip)
1120 0.039 0.000 1.978 0.002 game_components.py:484(place_card)
2871/465 0.037 0.000 0.070 0.000 container.py:77(reupdate)
11862 0.037 0.000 0.037 0.000 {method 'collidepoint' of 'pygame.Rect' objects}
13602/13558 0.035 0.000 0.035 0.000 {len}
4493 0.035 0.000 0.047 0.000 button.py:71(__setattr__)
Here are some bits of the source:
Main.py
#Remote imports
import pygame
from pygame.locals import *
#Local imports
import config
import rooms
from event_manager import *
from events import *
class RoomController(object):
"""Controls which room is currently active (eg Title Screen)"""
def __init__(self, screen, ev_manager):
self.room = None
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.room = self.set_room(config.room)
def set_room(self, room_const):
#Unregister old room from ev_manager
if self.room:
self.room.ev_manager.unregister_listener(self.room)
self.room = None
#Set new room based on const
if room_const == config.TITLE_SCREEN:
return rooms.TitleScreen(self.screen, self.ev_manager)
elif room_const == config.GAME_MODE_ROOM:
return rooms.GameModeRoom(self.screen, self.ev_manager)
elif room_const == config.GAME_ROOM:
return rooms.GameRoom(self.screen, self.ev_manager)
elif room_const == config.HIGH_SCORES_ROOM:
return rooms.HighScoresRoom(self.screen, self.ev_manager)
def notify(self, event):
if isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
self.room = self.set_room(event.new_room)
def render(self, surface):
self.room.render(surface)
#Run game
def main():
pygame.init()
screen = pygame.display.set_mode(config.screen_size)
ev_manager = EventManager()
spinner = CPUSpinnerController(ev_manager)
room_controller = RoomController(screen, ev_manager)
pygame_event_controller = PyGameEventController(ev_manager)
spinner.run()
# this runs the main function if this script is called to run.
# If it is imported as a module, we don't run the main function.
if __name__ == "__main__":
main()
event_manager.py
#Remote imports
import pygame
from pygame.locals import *
#Local imports
import config
from events import *
def debug( msg ):
print "Debug Message: " + str(msg)
class EventManager:
#This object is responsible for coordinating most communication
#between the Model, View, and Controller.
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
self.eventQueue= []
self.gui_app = None
#----------------------------------------------------------------------
def register_listener(self, listener):
self.listeners[listener] = 1
#----------------------------------------------------------------------
def unregister_listener(self, listener):
if listener in self.listeners:
del self.listeners[listener]
#----------------------------------------------------------------------
def post(self, event):
if isinstance(event, MouseButtonLeftEvent):
debug(event.name)
#NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient,
#but currently has to be done because of how new listeners are added to the queue while it is running
#(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html
#and search for "Watch the iteration"
for listener in list(self.listeners):
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.notify(event)
#------------------------------------------------------------------------------
class PyGameEventController:
"""..."""
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.input_freeze = False
#----------------------------------------------------------------------
def notify(self, incoming_event):
if isinstance(incoming_event, UserInputFreeze):
self.input_freeze = True
elif isinstance(incoming_event, UserInputUnFreeze):
self.input_freeze = False
elif isinstance(incoming_event, TickEvent):
#Share some time with other processes, so we don't hog the cpu
pygame.time.wait(5)
#Handle Pygame Events
for event in pygame.event.get():
#If this event manager has an associated PGU GUI app, notify it of the event
if self.ev_manager.gui_app:
self.ev_manager.gui_app.event(event)
#Standard event handling for everything else
ev = None
if event.type == QUIT:
ev = QuitEvent()
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 1: #Button 1
pos = pygame.mouse.get_pos()
ev = MouseButtonLeftEvent(pos)
elif event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
ev = MouseMoveEvent(pos)
#Post event to event manager
if ev:
self.ev_manager.post(ev)
#------------------------------------------------------------------------------
class CPUSpinnerController:
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.clock = pygame.time.Clock()
self.cumu_time = 0
self.keep_going = True
#----------------------------------------------------------------------
def run(self):
if not self.keep_going:
raise Exception('dead spinner')
while self.keep_going:
time_passed = self.clock.tick()
fps = self.clock.get_fps()
self.cumu_time += time_passed
self.ev_manager.post(TickEvent(time_passed, fps))
if self.cumu_time >= 1000:
self.cumu_time = 0
self.ev_manager.post(SecondEvent())
pygame.quit()
#----------------------------------------------------------------------
def notify(self, event):
if isinstance(event, QuitEvent):
#this will stop the while loop from running
self.keep_going = False
rooms.py
#Remote imports
import pygame
#Local imports
import config
import continents
from game_components import *
from my_gui import *
from pgu import high
class Room(object):
def __init__(self, screen, ev_manager):
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
def notify(self, event):
if isinstance(event, TickEvent):
pygame.display.set_caption('FPS: ' + str(int(event.fps)))
self.render(self.screen)
pygame.display.update()
def get_highs_table(self):
fname = 'high_scores.txt'
highs_table = None
config.all_highs = high.Highs(fname)
if config.game_mode == config.TIME_CHALLENGE:
if config.difficulty == config.EASY:
highs_table = config.all_highs['time_challenge_easy']
if config.difficulty == config.MED_DIF:
highs_table = config.all_highs['time_challenge_med']
if config.difficulty == config.HARD:
highs_table = config.all_highs['time_challenge_hard']
if config.difficulty == config.SUPER:
highs_table = config.all_highs['time_challenge_super']
elif config.game_mode == config.PLAN_AHEAD:
pass
return highs_table
class TitleScreen(Room):
def __init__(self, screen, ev_manager):
Room.__init__(self, screen, ev_manager)
self.background = pygame.image.load('assets/images/interface/background.jpg').convert()
#Initialize
#---------------------------------------
self.gui_form = gui.Form()
self.gui_app = gui.App(config.gui_theme)
self.ev_manager.gui_app = self.gui_app
c = gui.Container(align=0,valign=0)
#Quit Button
#---------------------------------------
b = StartGameButton(ev_manager=self.ev_manager)
c.add(b, 0, 0)
self.gui_app.init(c)
def render(self, surface):
surface.blit(self.background, (0, 0))
#GUI
self.gui_app.paint(surface)
class GameModeRoom(Room):
def __init__(self, screen, ev_manager):
Room.__init__(self, screen, ev_manager)
self.background = pygame.image.load('assets/images/interface/background.jpg').convert()
self.create_gui()
#Create pgu gui elements
def create_gui(self):
#Setup
#---------------------------------------
self.gui_form = gui.Form()
self.gui_app = gui.App(config.gui_theme)
self.ev_manager.gui_app = self.gui_app
c = gui.Container(align=0,valign=-1)
#Mode Relaxed Button
#---------------------------------------
b = GameModeRelaxedButton(ev_manager=self.ev_manager)
self.b = b
print b.rect
A:
Let events come to you with event.wait
Do you really need to do processing every tick? If not, use pygame.event.wait for your event loop to only process when an event comes in, and pygame.time.set_timer if you need periodic events like your SecondEvent.
This means you won't be drawing many frames during seconds when events aren't coming in, but that's okay. Using event.wait will decrease CPU usage and let you still be responsive, and likely removes the need for the time.wait you have in there instead.
Don't re-draw the entire board from scratch every tick
Don't have Room.render blit the background every time, which means then it has to go through and re-draw the entire board and all the cards. Do that once. Then don't have cards re-render themselves unless they changed darkness or they're moving.
When cards are moving, you should be able to restore the background by blitting just a chunk of the background graphic instead of the whole thing.
Pass a rectangle list to display.update
Once you're only updating certain areas, you can pass those areas to display.update so it doesn't have to update the whole screen. For an example, see the Solarwolf code and how it marks dirty rectangles.
A:
On your profile results:
I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue?
Yes. display.update and Surface.blit are at the top of your profile results. You did over a million blits, in about 5000 ticks, which works out to 200 blits every tick.
Also, sixth on your profile results is display.set_caption, which I guess is the display of the FPS counter itself? At 7 seconds of 157, this isn't your major hotspot, but still interesting to know.
|
How to get frame rate (fps) up in Python + Pygame?
|
I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game for Intel's March developer competition, which is squarely aimed at netbooks packing underpowered Atom processors.
Here's a screen from the game:
(source: necessarygames.com)
I am very new to Python and Pygame (this is the first thing I've used them for), and am sadly lacking in formal CS training... which is to say that I think there are probably A LOT of bad practices going on in my code, and A LOT that could be optimized. If some of you older Python hands wouldn't mind taking a look at my code and seeing if you can't find any obvious areas for optimization, I would be extremely grateful.
You can download the full source code here (Python 2.6 + Pygame 1.9):
http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
Compiled exe here:
www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
One thing I am concerned about is my event manager, which I feel may have some performance wholes in it, and another thing is my rendering... I'm pretty much just blitting everything to the screen all the time (see the render routines in my game_components.py below); I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue?
Any thoughts are much appreciated! As usual, I'm happy to "tip" you for your time and energy via PayPal.
Jordan
EDIT:
Thanks to the advice below, I ran cprofile on my code. It would be great if anyone would be willing to look at this output and let me know what is and what is not to be expected.
Here is the output of p.strip_dirs().sort_stats('cumulative').print_stats():
pydev debugger: starting
Sun Mar 28 04:46:16 2010 cprofile
8383715 function calls (8264821 primitive calls) in 157.732 CPU seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 157.732 157.732 <string>:1(<module>)
1 0.000 0.000 157.732 157.732 main.py:47(main)
1 0.074 0.074 157.280 157.280 event_manager.py:101(run)
4911/2414 11.837 0.002 156.984 0.065 event_manager.py:32(post)
4786/4681 0.238 0.000 94.852 0.020 rooms.py:251(notify)
2187 0.523 0.000 51.136 0.023 rooms.py:329(render)
4911/2959 0.220 0.000 35.732 0.012 event_manager.py:54(notify)
2271 33.996 0.015 33.996 0.015 {pygame.display.update}
2271 0.060 0.000 23.664 0.010 app.py:178(paint)
37347/2271 1.580 0.000 23.587 0.010 container.py:83(paint)
70236/2271 3.609 0.000 23.448 0.010 theme.py:275(func)
1078950 16.926 0.000 16.926 0.000 {method 'blit' of 'pygame.Surface' objects}
2187 2.131 0.001 16.875 0.008 game_components.py:666(render)
19635/17756 0.187 0.000 13.852 0.001 game_components.py:641(notify)
733820 7.710 0.000 13.643 0.000 game_components.py:1151(notify)
2271 12.254 0.005 12.254 0.005 {pygame.time.wait}
64112 3.174 0.000 11.252 0.000 game_components.py:1186(render)
9 0.002 0.000 10.151 1.128 game_components.py:286(deal_new_board)
1934 0.095 0.000 8.489 0.004 app.py:144(event)
4359/2146 0.178 0.000 8.375 0.004 container.py:112(event)
2335/2146 0.056 0.000 8.251 0.004 widget.py:346(_event)
2335/2146 0.048 0.000 8.193 0.004 theme.py:320(func)
4883/4691 0.018 0.000 8.049 0.002 widget.py:313(send)
229 0.139 0.001 8.017 0.035 game_components.py:632(refresh_darkness)
7258 0.499 0.000 7.844 0.001 game_components.py:963(test_close_to_trip)
2271 7.378 0.003 7.378 0.003 {pygame.display.set_caption}
19347 3.313 0.000 6.687 0.000 game_components.py:928(get_next_to)
2187 1.529 0.001 6.629 0.003 game_components.py:130(render)
2011729 5.938 0.000 5.938 0.000 {isinstance}
3 0.000 0.000 5.906 1.969 my_gui.py:274(clicked)
219456 3.060 0.000 5.680 0.000 surface.py:5(subsurface)
1290 0.506 0.000 5.416 0.004 game_components.py:683(__init__)
8748 2.891 0.000 5.340 0.001 theme.py:400(render)
70236 2.232 0.000 4.945 0.000 theme.py:186(box)
1357 0.097 0.000 4.391 0.003 game_components.py:742(set_image)
9 0.054 0.006 3.450 0.383 game_components.py:209(deal_connection_matrix)
8748 0.325 0.000 3.318 0.000 theme.py:479(paint)
1051 0.015 0.000 3.262 0.003 game_components.py:1232(__init__)
386467 3.148 0.000 3.148 0.000 {method 'fill' of 'pygame.Surface' objects}
245332 2.470 0.000 3.117 0.000 game_components.py:495(get_card)
55761 3.068 0.000 3.068 0.000 {pygame.draw.aaline}
2271 2.968 0.001 2.968 0.001 {pygame.event.get}
9 0.007 0.001 2.946 0.327 game_components.py:416(clone)
2187 0.089 0.000 2.717 0.001 misc.py:28(paint)
803701 2.483 0.000 2.497 0.000 weakref.py:302(iterkeys)
2739 2.441 0.001 2.441 0.001 {pygame.imageext.load_extended}
1470 1.108 0.001 2.432 0.002 game_components.py:450(set_pos)
29 0.029 0.001 2.270 0.078 game_components.py:433(clear)
2 0.000 0.000 2.158 1.079 main.py:22(set_room)
4911/4862 0.027 0.000 2.141 0.000 main.py:37(notify)
1 0.000 0.000 2.099 2.099 my_gui.py:164(clicked)
1 0.001 0.001 2.099 2.099 rooms.py:117(__init__)
1120 0.039 0.000 1.978 0.002 game_components.py:484(place_card)
27 0.013 0.000 1.963 0.073 game_components.py:339(merge_board_stack)
311 0.018 0.000 1.939 0.006 game_components.py:443(remove)
125 0.007 0.000 1.848 0.015 rooms.py:18(notify)
224 0.003 0.000 1.806 0.008 game_components.py:721(clone)
219456 1.638 0.000 1.638 0.000 {method 'subsurface' of 'pygame.Surface' objects}
183 0.004 0.000 1.313 0.007 game_components.py:1240(__init__)
4374 0.106 0.000 1.224 0.000 button.py:97(paint)
46765 0.967 0.000 1.137 0.000 game_components.py:784(set_pos)
229 0.109 0.000 1.111 0.005 game_components.py:594(refresh_trip)
4076 1.076 0.000 1.076 0.000 {method 'convert_alpha' of 'pygame.Surface' objects}
9 0.015 0.002 1.018 0.113 game_components.py:542(displace_cards)
17496 0.360 0.000 0.953 0.000 basic.py:102(paint)
66299 0.948 0.000 0.948 0.000 {pygame.draw.rect}
1357 0.024 0.000 0.945 0.001 game_components.py:736(set_text)
1357 0.052 0.000 0.917 0.001 game_components.py:841(render_text_rec)
5815 0.455 0.000 0.881 0.000 game_components.py:1108(get_connections)
6610 0.869 0.000 0.869 0.000 {method 'replace' of 'pygame.PixelArray' objects}
56 0.001 0.000 0.861 0.015 game_components.py:1252(__init__)
10 0.001 0.000 0.857 0.086 game_components.py:377(__init__)
540 0.484 0.001 0.828 0.002 game_components.py:613(refresh_connections)
189431 0.730 0.000 0.730 0.000 game_components.py:500(test_index_on_board)
161329 0.632 0.000 0.727 0.000 matrix.py:33(__iter__)
309968 0.710 0.000 0.710 0.000 {method 'get_width' of 'pygame.Surface' objects}
308567 0.675 0.000 0.675 0.000 {method 'get_height' of 'pygame.Surface' objects}
109626 0.646 0.000 0.670 0.000 style.py:18(__getattr__)
241697 0.646 0.000 0.646 0.000 matrix.py:24(getitem)
21084 0.601 0.000 0.601 0.000 {method 'render' of 'pygame.font.Font' objects}
327 0.006 0.000 0.580 0.002 game_components.py:490(place_card_first_time)
26 0.001 0.000 0.561 0.022 game_components.py:1259(__init__)
166 0.002 0.000 0.536 0.003 game_components.py:608(get_longest_trip)
1491/166 0.075 0.000 0.534 0.003 game_components.py:989(get_longest_trip)
5702 0.533 0.000 0.533 0.000 {method 'size' of 'pygame.font.Font' objects}
1 0.000 0.000 0.478 0.478 game_components.py:141(__init__)
1 0.001 0.001 0.478 0.478 game_components.py:165(rebuild)
67 0.005 0.000 0.457 0.007 game_components.py:713(change_size)
1 0.001 0.001 0.420 0.420 game_components.py:347(change_card_size)
1210/166 0.044 0.000 0.412 0.002 game_components.py:982(add_to_trip)
7654 0.275 0.000 0.405 0.000 game_components.py:938(get_bounding_box)
14969 0.101 0.000 0.385 0.000 game_components.py:1305(render)
149709 0.341 0.000 0.341 0.000 {method 'append' of 'list' objects}
87958 0.341 0.000 0.341 0.000 {hasattr}
1362 0.068 0.000 0.336 0.000 textrect.py:12(render_textrect)
30 0.001 0.000 0.301 0.010 game_components.py:1282(__init__)
47795 0.257 0.000 0.257 0.000 game_components.py:1024(test_connection)
14849 0.098 0.000 0.251 0.000 my_gui.py:209(notify)
17498 0.158 0.000 0.242 0.000 basic.py:22(is_color)
87480 0.224 0.000 0.224 0.000 {method 'set_clip' of 'pygame.Surface' objects}
9 0.003 0.000 0.209 0.023 game_components.py:279(deal_to_blank_squares)
1 0.114 0.114 0.208 0.208 {pygame.display.set_mode}
56617 0.206 0.000 0.206 0.000 game_components.py:837(get_center)
84 0.005 0.000 0.206 0.002 rooms.py:110(render)
Here is the output of p.strip_dirs().sort_stats('time').print_stats():
Sun Mar 28 04:46:16 2010 cprofile
8383715 function calls (8264821 primitive calls) in 157.732 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
2271 33.996 0.015 33.996 0.015 {pygame.display.update}
1078950 16.926 0.000 16.926 0.000 {method 'blit' of 'pygame.Surface' objects}
2271 12.254 0.005 12.254 0.005 {pygame.time.wait}
4911/2414 11.837 0.002 156.984 0.065 event_manager.py:32(post)
733820 7.710 0.000 13.643 0.000 game_components.py:1151(notify)
2271 7.378 0.003 7.378 0.003 {pygame.display.set_caption}
2011729 5.938 0.000 5.938 0.000 {isinstance}
70236/2271 3.609 0.000 23.448 0.010 theme.py:275(func)
19347 3.313 0.000 6.687 0.000 game_components.py:928(get_next_to)
64112 3.174 0.000 11.252 0.000 game_components.py:1186(render)
386467 3.148 0.000 3.148 0.000 {method 'fill' of 'pygame.Surface' objects}
55761 3.068 0.000 3.068 0.000 {pygame.draw.aaline}
219456 3.060 0.000 5.680 0.000 surface.py:5(subsurface)
2271 2.968 0.001 2.968 0.001 {pygame.event.get}
8748 2.891 0.000 5.340 0.001 theme.py:400(render)
803701 2.483 0.000 2.497 0.000 weakref.py:302(iterkeys)
245332 2.470 0.000 3.117 0.000 game_components.py:495(get_card)
2739 2.441 0.001 2.441 0.001 {pygame.imageext.load_extended}
70236 2.232 0.000 4.945 0.000 theme.py:186(box)
2187 2.131 0.001 16.875 0.008 game_components.py:666(render)
219456 1.638 0.000 1.638 0.000 {method 'subsurface' of 'pygame.Surface' objects}
37347/2271 1.580 0.000 23.587 0.010 container.py:83(paint)
2187 1.529 0.001 6.629 0.003 game_components.py:130(render)
1470 1.108 0.001 2.432 0.002 game_components.py:450(set_pos)
4076 1.076 0.000 1.076 0.000 {method 'convert_alpha' of 'pygame.Surface' objects}
46765 0.967 0.000 1.137 0.000 game_components.py:784(set_pos)
66299 0.948 0.000 0.948 0.000 {pygame.draw.rect}
6610 0.869 0.000 0.869 0.000 {method 'replace' of 'pygame.PixelArray' objects}
189431 0.730 0.000 0.730 0.000 game_components.py:500(test_index_on_board)
309968 0.710 0.000 0.710 0.000 {method 'get_width' of 'pygame.Surface' objects}
308567 0.675 0.000 0.675 0.000 {method 'get_height' of 'pygame.Surface' objects}
109626 0.646 0.000 0.670 0.000 style.py:18(__getattr__)
241697 0.646 0.000 0.646 0.000 matrix.py:24(getitem)
161329 0.632 0.000 0.727 0.000 matrix.py:33(__iter__)
21084 0.601 0.000 0.601 0.000 {method 'render' of 'pygame.font.Font' objects}
5702 0.533 0.000 0.533 0.000 {method 'size' of 'pygame.font.Font' objects}
2187 0.523 0.000 51.136 0.023 rooms.py:329(render)
1290 0.506 0.000 5.416 0.004 game_components.py:683(__init__)
7258 0.499 0.000 7.844 0.001 game_components.py:963(test_close_to_trip)
540 0.484 0.001 0.828 0.002 game_components.py:613(refresh_connections)
5815 0.455 0.000 0.881 0.000 game_components.py:1108(get_connections)
17496 0.360 0.000 0.953 0.000 basic.py:102(paint)
149709 0.341 0.000 0.341 0.000 {method 'append' of 'list' objects}
87958 0.341 0.000 0.341 0.000 {hasattr}
8748 0.325 0.000 3.318 0.000 theme.py:479(paint)
7654 0.275 0.000 0.405 0.000 game_components.py:938(get_bounding_box)
47795 0.257 0.000 0.257 0.000 game_components.py:1024(test_connection)
4786/4681 0.238 0.000 94.852 0.020 rooms.py:251(notify)
87480 0.224 0.000 0.224 0.000 {method 'set_clip' of 'pygame.Surface' objects}
4911/2959 0.220 0.000 35.732 0.012 event_manager.py:54(notify)
56617 0.206 0.000 0.206 0.000 game_components.py:837(get_center)
1 0.200 0.200 0.200 0.200 {pygame.base.quit}
19635/17756 0.187 0.000 13.852 0.001 game_components.py:641(notify)
1 0.184 0.184 0.184 0.184 {pygame.base.init}
4359/2146 0.178 0.000 8.375 0.004 container.py:112(event)
17498 0.158 0.000 0.242 0.000 basic.py:22(is_color)
1358 0.151 0.000 0.151 0.000 {pygame.transform.smoothscale}
229 0.139 0.001 8.017 0.035 game_components.py:632(refresh_darkness)
1 0.114 0.114 0.208 0.208 {pygame.display.set_mode}
37862 0.112 0.000 0.112 0.000 {method 'set_alpha' of 'pygame.Surface' objects}
6561 0.111 0.000 0.195 0.000 button.py:236(paint)
229 0.109 0.000 1.111 0.005 game_components.py:594(refresh_trip)
4374 0.106 0.000 1.224 0.000 button.py:97(paint)
14969 0.101 0.000 0.385 0.000 game_components.py:1305(render)
14849 0.098 0.000 0.251 0.000 my_gui.py:209(notify)
1357 0.097 0.000 4.391 0.003 game_components.py:742(set_image)
24072 0.096 0.000 0.096 0.000 game_components.py:913(test_pos_on_card)
4926 0.095 0.000 0.132 0.000 game_components.py:1292(__init__)
33286 0.095 0.000 0.095 0.000 {range}
1934 0.095 0.000 8.489 0.004 app.py:144(event)
2187 0.089 0.000 2.717 0.001 misc.py:28(paint)
2135 0.087 0.000 0.091 0.000 matrix.py:21(setitem)
4374 0.076 0.000 0.131 0.000 button.py:182(paint)
1491/166 0.075 0.000 0.534 0.003 game_components.py:989(get_longest_trip)
1 0.074 0.074 157.280 157.280 event_manager.py:101(run)
301 0.069 0.000 0.107 0.000 game_components.py:508(clear_selection)
1362 0.068 0.000 0.336 0.000 textrect.py:12(render_textrect)
2227 0.066 0.000 0.150 0.000 game_components.py:809(move)
5740 0.062 0.000 0.165 0.000 misc.py:34(__setattr__)
2271 0.060 0.000 23.664 0.010 app.py:178(paint)
2335/2146 0.056 0.000 8.251 0.004 widget.py:346(_event)
4786 0.055 0.000 0.099 0.000 game_components.py:97(notify)
9 0.054 0.006 3.450 0.383 game_components.py:209(deal_connection_matrix)
1357 0.052 0.000 0.917 0.001 game_components.py:841(render_text_rec)
5 0.052 0.010 0.052 0.010 {method 'convert' of 'pygame.Surface' objects}
2335/2146 0.048 0.000 8.193 0.004 theme.py:320(func)
1210/166 0.044 0.000 0.412 0.002 game_components.py:982(add_to_trip)
1120 0.039 0.000 1.978 0.002 game_components.py:484(place_card)
2871/465 0.037 0.000 0.070 0.000 container.py:77(reupdate)
11862 0.037 0.000 0.037 0.000 {method 'collidepoint' of 'pygame.Rect' objects}
13602/13558 0.035 0.000 0.035 0.000 {len}
4493 0.035 0.000 0.047 0.000 button.py:71(__setattr__)
Here are some bits of the source:
Main.py
#Remote imports
import pygame
from pygame.locals import *
#Local imports
import config
import rooms
from event_manager import *
from events import *
class RoomController(object):
"""Controls which room is currently active (eg Title Screen)"""
def __init__(self, screen, ev_manager):
self.room = None
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.room = self.set_room(config.room)
def set_room(self, room_const):
#Unregister old room from ev_manager
if self.room:
self.room.ev_manager.unregister_listener(self.room)
self.room = None
#Set new room based on const
if room_const == config.TITLE_SCREEN:
return rooms.TitleScreen(self.screen, self.ev_manager)
elif room_const == config.GAME_MODE_ROOM:
return rooms.GameModeRoom(self.screen, self.ev_manager)
elif room_const == config.GAME_ROOM:
return rooms.GameRoom(self.screen, self.ev_manager)
elif room_const == config.HIGH_SCORES_ROOM:
return rooms.HighScoresRoom(self.screen, self.ev_manager)
def notify(self, event):
if isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
self.room = self.set_room(event.new_room)
def render(self, surface):
self.room.render(surface)
#Run game
def main():
pygame.init()
screen = pygame.display.set_mode(config.screen_size)
ev_manager = EventManager()
spinner = CPUSpinnerController(ev_manager)
room_controller = RoomController(screen, ev_manager)
pygame_event_controller = PyGameEventController(ev_manager)
spinner.run()
# this runs the main function if this script is called to run.
# If it is imported as a module, we don't run the main function.
if __name__ == "__main__":
main()
event_manager.py
#Remote imports
import pygame
from pygame.locals import *
#Local imports
import config
from events import *
def debug( msg ):
print "Debug Message: " + str(msg)
class EventManager:
#This object is responsible for coordinating most communication
#between the Model, View, and Controller.
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
self.eventQueue= []
self.gui_app = None
#----------------------------------------------------------------------
def register_listener(self, listener):
self.listeners[listener] = 1
#----------------------------------------------------------------------
def unregister_listener(self, listener):
if listener in self.listeners:
del self.listeners[listener]
#----------------------------------------------------------------------
def post(self, event):
if isinstance(event, MouseButtonLeftEvent):
debug(event.name)
#NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient,
#but currently has to be done because of how new listeners are added to the queue while it is running
#(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html
#and search for "Watch the iteration"
for listener in list(self.listeners):
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.notify(event)
#------------------------------------------------------------------------------
class PyGameEventController:
"""..."""
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.input_freeze = False
#----------------------------------------------------------------------
def notify(self, incoming_event):
if isinstance(incoming_event, UserInputFreeze):
self.input_freeze = True
elif isinstance(incoming_event, UserInputUnFreeze):
self.input_freeze = False
elif isinstance(incoming_event, TickEvent):
#Share some time with other processes, so we don't hog the cpu
pygame.time.wait(5)
#Handle Pygame Events
for event in pygame.event.get():
#If this event manager has an associated PGU GUI app, notify it of the event
if self.ev_manager.gui_app:
self.ev_manager.gui_app.event(event)
#Standard event handling for everything else
ev = None
if event.type == QUIT:
ev = QuitEvent()
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 1: #Button 1
pos = pygame.mouse.get_pos()
ev = MouseButtonLeftEvent(pos)
elif event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
ev = MouseMoveEvent(pos)
#Post event to event manager
if ev:
self.ev_manager.post(ev)
#------------------------------------------------------------------------------
class CPUSpinnerController:
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.clock = pygame.time.Clock()
self.cumu_time = 0
self.keep_going = True
#----------------------------------------------------------------------
def run(self):
if not self.keep_going:
raise Exception('dead spinner')
while self.keep_going:
time_passed = self.clock.tick()
fps = self.clock.get_fps()
self.cumu_time += time_passed
self.ev_manager.post(TickEvent(time_passed, fps))
if self.cumu_time >= 1000:
self.cumu_time = 0
self.ev_manager.post(SecondEvent())
pygame.quit()
#----------------------------------------------------------------------
def notify(self, event):
if isinstance(event, QuitEvent):
#this will stop the while loop from running
self.keep_going = False
rooms.py
#Remote imports
import pygame
#Local imports
import config
import continents
from game_components import *
from my_gui import *
from pgu import high
class Room(object):
def __init__(self, screen, ev_manager):
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
def notify(self, event):
if isinstance(event, TickEvent):
pygame.display.set_caption('FPS: ' + str(int(event.fps)))
self.render(self.screen)
pygame.display.update()
def get_highs_table(self):
fname = 'high_scores.txt'
highs_table = None
config.all_highs = high.Highs(fname)
if config.game_mode == config.TIME_CHALLENGE:
if config.difficulty == config.EASY:
highs_table = config.all_highs['time_challenge_easy']
if config.difficulty == config.MED_DIF:
highs_table = config.all_highs['time_challenge_med']
if config.difficulty == config.HARD:
highs_table = config.all_highs['time_challenge_hard']
if config.difficulty == config.SUPER:
highs_table = config.all_highs['time_challenge_super']
elif config.game_mode == config.PLAN_AHEAD:
pass
return highs_table
class TitleScreen(Room):
def __init__(self, screen, ev_manager):
Room.__init__(self, screen, ev_manager)
self.background = pygame.image.load('assets/images/interface/background.jpg').convert()
#Initialize
#---------------------------------------
self.gui_form = gui.Form()
self.gui_app = gui.App(config.gui_theme)
self.ev_manager.gui_app = self.gui_app
c = gui.Container(align=0,valign=0)
#Quit Button
#---------------------------------------
b = StartGameButton(ev_manager=self.ev_manager)
c.add(b, 0, 0)
self.gui_app.init(c)
def render(self, surface):
surface.blit(self.background, (0, 0))
#GUI
self.gui_app.paint(surface)
class GameModeRoom(Room):
def __init__(self, screen, ev_manager):
Room.__init__(self, screen, ev_manager)
self.background = pygame.image.load('assets/images/interface/background.jpg').convert()
self.create_gui()
#Create pgu gui elements
def create_gui(self):
#Setup
#---------------------------------------
self.gui_form = gui.Form()
self.gui_app = gui.App(config.gui_theme)
self.ev_manager.gui_app = self.gui_app
c = gui.Container(align=0,valign=-1)
#Mode Relaxed Button
#---------------------------------------
b = GameModeRelaxedButton(ev_manager=self.ev_manager)
self.b = b
print b.rect
|
[
"Let events come to you with event.wait\nDo you really need to do processing every tick? If not, use pygame.event.wait for your event loop to only process when an event comes in, and pygame.time.set_timer if you need periodic events like your SecondEvent.\nThis means you won't be drawing many frames during seconds when events aren't coming in, but that's okay. Using event.wait will decrease CPU usage and let you still be responsive, and likely removes the need for the time.wait you have in there instead.\nDon't re-draw the entire board from scratch every tick\nDon't have Room.render blit the background every time, which means then it has to go through and re-draw the entire board and all the cards. Do that once. Then don't have cards re-render themselves unless they changed darkness or they're moving.\nWhen cards are moving, you should be able to restore the background by blitting just a chunk of the background graphic instead of the whole thing.\nPass a rectangle list to display.update\nOnce you're only updating certain areas, you can pass those areas to display.update so it doesn't have to update the whole screen. For an example, see the Solarwolf code and how it marks dirty rectangles. \n",
"On your profile results:\n\nI recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue?\n\nYes. display.update and Surface.blit are at the top of your profile results. You did over a million blits, in about 5000 ticks, which works out to 200 blits every tick.\nAlso, sixth on your profile results is display.set_caption, which I guess is the display of the FPS counter itself? At 7 seconds of 157, this isn't your major hotspot, but still interesting to know.\n"
] |
[
8,
3
] |
[] |
[] |
[
"frame_rate",
"performance",
"pygame",
"python"
] |
stackoverflow_0002530478_frame_rate_performance_pygame_python.txt
|
Q:
Python unit-testing with nose: Making sequential tests
I am just learning how to do unit-testing. I'm on Python / nose / Wing IDE.
(The project that I'm writing tests for is a simulations framework, and among other things it lets you run simulations both synchronously and asynchronously, and the results of the simulation should be the same in both.)
The thing is, I want some of my tests to use simulation results that were created in other tests. For example, synchronous_test calculates a certain simulation in synchronous mode, but then I want to calculate it in asynchronous mode, and check that the results came out the same.
How do I structure this? Do I put them all in one test function, or make a separate asynchronous_test? Do I pass these objects from one test function to another?
Also, keep in mind that all these tests will run through a test generator, so I can do the tests for each of the simulation packages included with my program.
A:
In general, I'd recommend not making one test depend upon another. Do the synchronous_test, do the asynchronous_test, compare them each to the expected correct output, not to each other.
So something like:
class TestSimulate(TestCase):
def setup(self):
self.simpack = SimpackToTest()
self.initial_state = pickle.load("initial.state")
self.expected_state = pickle.load("known_good.state")
def test_simulate(self):
state = simulate(self.simpack, self.initial_state)
# assert_equal will require State to implement __eq__ in a meaningful
# way. If it doesn't, you'll want to define your own comparison
# function.
self.assert_equal(self.expected_state, state)
def test_other_simulate(self):
foo = OtherThing(self.simpack)
blah = foo.simulate(self.initial_state)
state = blah.state
self.assert_equal(self.expected_state, state)
A:
You can add tests that need to calculate once per class to the "setup" of that class. As an example:
from nose.tools import *
class Test_mysim():
def setup(self):
self.ans = calculate_it_once()
def test_sync(self):
ans=calculate_it_sync()
assert_equal(ans,self.ans)
def test_async(self):
ans=calculate_it_async()
assert_equal(ans,self.ans)
|
Python unit-testing with nose: Making sequential tests
|
I am just learning how to do unit-testing. I'm on Python / nose / Wing IDE.
(The project that I'm writing tests for is a simulations framework, and among other things it lets you run simulations both synchronously and asynchronously, and the results of the simulation should be the same in both.)
The thing is, I want some of my tests to use simulation results that were created in other tests. For example, synchronous_test calculates a certain simulation in synchronous mode, but then I want to calculate it in asynchronous mode, and check that the results came out the same.
How do I structure this? Do I put them all in one test function, or make a separate asynchronous_test? Do I pass these objects from one test function to another?
Also, keep in mind that all these tests will run through a test generator, so I can do the tests for each of the simulation packages included with my program.
|
[
"In general, I'd recommend not making one test depend upon another. Do the synchronous_test, do the asynchronous_test, compare them each to the expected correct output, not to each other.\nSo something like:\nclass TestSimulate(TestCase):\n def setup(self):\n self.simpack = SimpackToTest()\n self.initial_state = pickle.load(\"initial.state\")\n self.expected_state = pickle.load(\"known_good.state\")\n\n def test_simulate(self):\n state = simulate(self.simpack, self.initial_state)\n # assert_equal will require State to implement __eq__ in a meaningful\n # way. If it doesn't, you'll want to define your own comparison \n # function.\n self.assert_equal(self.expected_state, state)\n\n def test_other_simulate(self):\n foo = OtherThing(self.simpack)\n blah = foo.simulate(self.initial_state)\n state = blah.state\n self.assert_equal(self.expected_state, state)\n\n",
"You can add tests that need to calculate once per class to the \"setup\" of that class. As an example:\nfrom nose.tools import *\nclass Test_mysim():\n def setup(self):\n self.ans = calculate_it_once()\n\n def test_sync(self):\n ans=calculate_it_sync()\n assert_equal(ans,self.ans)\n\n def test_async(self):\n ans=calculate_it_async()\n assert_equal(ans,self.ans)\n\n"
] |
[
6,
6
] |
[] |
[] |
[
"nose",
"python",
"unit_testing"
] |
stackoverflow_0002530747_nose_python_unit_testing.txt
|
Q:
Python: How to transfer varrying length arrays over a network connection
I need to transfer an array of varying length in which each element is a tuple of two integers. As an example:
path = [(1,1),(1,2)]
path = [(1,1),(1,2),(2,2)]
I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I was trying to turn it into a single string with delimiters, such as:
msg = 1&1~1&2~
sendMsg = pack("s",msg) or sendMsg = pack("s",str(msg))
on the receiving side:
path = unpack("s",msg)
but that just prints 1 in this case. I was also trying to send 4 integers as well, which send and receive fine, so long as I don't include the extra string representing the path.
sendMsg = pack("hhhh",p.direction[0],p.direction[1],p.id,p.health)
on the receive side:
x,y,id,health = unpack("hhhh",msg)
The first was for illustration as I was trying to send the format "hhhhs", but either way the path doesn't come through properly.
Thank-you for your help. I will also be looking at sending a 2D array of ints, but I can't seem to figure out how to send these more 'complex' structures across the network.
Thank-you for your help.
A:
While you can use pack and unpack, I'd recommend using something like YAML or JSON to transfer your data.
Pack and unpack can lead to difficult to debug errors and incompatibilities if you change your interface and have different versions trying to communicate with each other.
Pickle can give security problems and the pickle format might change between Python versions.
JSON is included in the standard Python distribution since 2.6. For YAML there is PyYAML.
A:
You want some sort of serialization protocol. twisted.spread provides one such (see the Banana specification or Perspective Broker documentation). JSON or protocol buffers would be more verbose examples.
See also Comparison of data serialization formats.
A:
If you include message length as part of the message, then you will know how much data to read. So the entire string should be read across the network.
In any case, perhaps it would help if you posted some of the code you are using to send data across the network, or at least provided more of a description.
A:
Pack and unpack are mandatory?
If not, you could use JSON and YAML.
Don't use pickle because is not secure.
A:
Take a look at xdrlib, it might help. It's part of the standard library, and:
The xdrlib module supports the External Data Representation Standard as described in RFC 1014, written by Sun Microsystems, Inc. June 1987. It supports most of the data types described in the RFC.
|
Python: How to transfer varrying length arrays over a network connection
|
I need to transfer an array of varying length in which each element is a tuple of two integers. As an example:
path = [(1,1),(1,2)]
path = [(1,1),(1,2),(2,2)]
I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I was trying to turn it into a single string with delimiters, such as:
msg = 1&1~1&2~
sendMsg = pack("s",msg) or sendMsg = pack("s",str(msg))
on the receiving side:
path = unpack("s",msg)
but that just prints 1 in this case. I was also trying to send 4 integers as well, which send and receive fine, so long as I don't include the extra string representing the path.
sendMsg = pack("hhhh",p.direction[0],p.direction[1],p.id,p.health)
on the receive side:
x,y,id,health = unpack("hhhh",msg)
The first was for illustration as I was trying to send the format "hhhhs", but either way the path doesn't come through properly.
Thank-you for your help. I will also be looking at sending a 2D array of ints, but I can't seem to figure out how to send these more 'complex' structures across the network.
Thank-you for your help.
|
[
"While you can use pack and unpack, I'd recommend using something like YAML or JSON to transfer your data.\n\nPack and unpack can lead to difficult to debug errors and incompatibilities if you change your interface and have different versions trying to communicate with each other.\nPickle can give security problems and the pickle format might change between Python versions.\n\nJSON is included in the standard Python distribution since 2.6. For YAML there is PyYAML.\n",
"You want some sort of serialization protocol. twisted.spread provides one such (see the Banana specification or Perspective Broker documentation). JSON or protocol buffers would be more verbose examples.\nSee also Comparison of data serialization formats.\n",
"If you include message length as part of the message, then you will know how much data to read. So the entire string should be read across the network.\nIn any case, perhaps it would help if you posted some of the code you are using to send data across the network, or at least provided more of a description.\n",
"Pack and unpack are mandatory?\nIf not, you could use JSON and YAML.\nDon't use pickle because is not secure.\n",
"Take a look at xdrlib, it might help. It's part of the standard library, and:\n\nThe xdrlib module supports the External Data Representation Standard as described in RFC 1014, written by Sun Microsystems, Inc. June 1987. It supports most of the data types described in the RFC.\n\n"
] |
[
7,
1,
0,
0,
0
] |
[] |
[] |
[
"arrays",
"networking",
"pack",
"python",
"unpack"
] |
stackoverflow_0002530865_arrays_networking_pack_python_unpack.txt
|
Q:
How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?
I've read the documentation and I've tried lots of things in the REPL, and Googled, but I can't for the life of me understand how subprocess.Popen works in Python.
Here is some Ruby code I am using:
IO.popen("some-process") do |io|
while(line = io.gets)
# do whatever with line
end
end
How do I translate this into Python using subprocess.Popen?
A:
Probably the simplest "close relative" of your Ruby code in Python:
>>> import subprocess
>>> io = subprocess.Popen('ls', stdout=subprocess.PIPE).stdout
>>> for line in io: print(line.strip())
A:
import subprocess
process = subprocess.Popen(['ls',], stdout=subprocess.PIPE)
print process.communicate()[0]
|
How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?
|
I've read the documentation and I've tried lots of things in the REPL, and Googled, but I can't for the life of me understand how subprocess.Popen works in Python.
Here is some Ruby code I am using:
IO.popen("some-process") do |io|
while(line = io.gets)
# do whatever with line
end
end
How do I translate this into Python using subprocess.Popen?
|
[
"Probably the simplest \"close relative\" of your Ruby code in Python:\n>>> import subprocess\n>>> io = subprocess.Popen('ls', stdout=subprocess.PIPE).stdout\n>>> for line in io: print(line.strip())\n\n",
"import subprocess\n\nprocess = subprocess.Popen(['ls',], stdout=subprocess.PIPE)\nprint process.communicate()[0]\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"io",
"popen",
"python",
"ruby",
"subprocess"
] |
stackoverflow_0002530906_io_popen_python_ruby_subprocess.txt
|
Q:
Matplotlib canvas drawing
Let's say I define a few functions to do certain matplotlib actions, such as
def dostuff(ax):
ax.scatter([0.],[0.])
Now if I launch ipython, I can load these functions and start a new figure:
In [1]: import matplotlib.pyplot as mpl
In [2]: fig = mpl.figure()
In [3]: ax = fig.add_subplot(1,1,1)
In [4]: run functions # run the file with the above defined function
If I now call dostuff, then the figure does not refresh:
In [6]: dostuff(ax)
I have to then explicitly run:
In [7]: fig.canvas.draw()
To get the canvas to draw. Now I can modify dostuff to be
def dostuff(ax):
ax.scatter([0.],[0.])
ax.get_figure().canvas.draw()
This re-draws the canvas automatically. But now, say that I have the following code:
def dostuff1(ax):
ax.scatter([0.],[0.])
ax.get_figure().canvas.draw()
def dostuff2(ax):
ax.scatter([1.],[1.])
ax.get_figure().canvas.draw()
def doboth(ax):
dostuff1(ax)
dostuff2(ax)
ax.get_figure().canvas.draw()
I can call each of these functions, and the canvas will be redrawn, but in the case of doboth(), it will get redrawn multiple times.
My question is: how could I code this, such that the canvas.draw() only gets called once? In the above example it won't change much, but in more complex cases with tens of functions that can be called individually or grouped, the repeated drawing is much more obvious, and it would be nice to be able to avoid it. I thought of using decorators, but it doesn't look as though it would be simple.
Any ideas?
A:
Why doesn't my answer to this SO question of yours about "refresh decorator" make it simple? I showed exactly what to do what you're again requesting here (by keeping a count of nestings -- incidentally, one that's also thread-safe) and you completely ignored my answer... peculiar behavior!-)
|
Matplotlib canvas drawing
|
Let's say I define a few functions to do certain matplotlib actions, such as
def dostuff(ax):
ax.scatter([0.],[0.])
Now if I launch ipython, I can load these functions and start a new figure:
In [1]: import matplotlib.pyplot as mpl
In [2]: fig = mpl.figure()
In [3]: ax = fig.add_subplot(1,1,1)
In [4]: run functions # run the file with the above defined function
If I now call dostuff, then the figure does not refresh:
In [6]: dostuff(ax)
I have to then explicitly run:
In [7]: fig.canvas.draw()
To get the canvas to draw. Now I can modify dostuff to be
def dostuff(ax):
ax.scatter([0.],[0.])
ax.get_figure().canvas.draw()
This re-draws the canvas automatically. But now, say that I have the following code:
def dostuff1(ax):
ax.scatter([0.],[0.])
ax.get_figure().canvas.draw()
def dostuff2(ax):
ax.scatter([1.],[1.])
ax.get_figure().canvas.draw()
def doboth(ax):
dostuff1(ax)
dostuff2(ax)
ax.get_figure().canvas.draw()
I can call each of these functions, and the canvas will be redrawn, but in the case of doboth(), it will get redrawn multiple times.
My question is: how could I code this, such that the canvas.draw() only gets called once? In the above example it won't change much, but in more complex cases with tens of functions that can be called individually or grouped, the repeated drawing is much more obvious, and it would be nice to be able to avoid it. I thought of using decorators, but it doesn't look as though it would be simple.
Any ideas?
|
[
"Why doesn't my answer to this SO question of yours about \"refresh decorator\" make it simple? I showed exactly what to do what you're again requesting here (by keeping a count of nestings -- incidentally, one that's also thread-safe) and you completely ignored my answer... peculiar behavior!-)\n"
] |
[
2
] |
[] |
[] |
[
"algorithm",
"matplotlib",
"python"
] |
stackoverflow_0002531333_algorithm_matplotlib_python.txt
|
Q:
Pointer argument to boost python
What's the best way to make a function that has pointer as argument work with boost python?
I see there are many possibilities for return values in the docs, but I don't know how to do it with arguments.
void Tesuto::testp(std::string* s)
{
if (!s)
cout << " NULL s" << endl;
else
cout << s << endl;
}
>>> t.testp(None)
NULL s
>>>
>>> s='test'
>>> t.testp(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
Tesuto.testp(Tesuto, str)
did not match C++ signature:
testp(Tesuto {lvalue}, std::string*)
>>>
A:
As far as I can tell, after doing a bit of googling on the subject, is that you can't. Python doesn't support pointer argument types by default. If you wanted to, you could probably edit the python interpreter by hand, but this seems to me to be production code of some sort, so that probably isn't an option.
EDIT: You could add a wrapper function like so:
std::string * pointer (std::string& p)
{
return &p
}
Then call your code with:
>>> s = 'hello'
>>> t.testp (pointer (s))
hello
>>>
|
Pointer argument to boost python
|
What's the best way to make a function that has pointer as argument work with boost python?
I see there are many possibilities for return values in the docs, but I don't know how to do it with arguments.
void Tesuto::testp(std::string* s)
{
if (!s)
cout << " NULL s" << endl;
else
cout << s << endl;
}
>>> t.testp(None)
NULL s
>>>
>>> s='test'
>>> t.testp(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
Tesuto.testp(Tesuto, str)
did not match C++ signature:
testp(Tesuto {lvalue}, std::string*)
>>>
|
[
"As far as I can tell, after doing a bit of googling on the subject, is that you can't. Python doesn't support pointer argument types by default. If you wanted to, you could probably edit the python interpreter by hand, but this seems to me to be production code of some sort, so that probably isn't an option.\nEDIT: You could add a wrapper function like so: \n\n \nstd::string * pointer (std::string& p)\n{\n return &p\n}\n\n\nThen call your code with:\n\n\n>>> s = 'hello'\n>>> t.testp (pointer (s))\nhello\n>>>\n\n\n"
] |
[
4
] |
[] |
[] |
[
"argument_passing",
"arguments",
"boost",
"pointers",
"python"
] |
stackoverflow_0002385561_argument_passing_arguments_boost_pointers_python.txt
|
Q:
Apply relative URL to an absolute URL
I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL?
Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"
A:
urlparse.urljoin() does just this.
|
Apply relative URL to an absolute URL
|
I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL?
Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"
|
[
"urlparse.urljoin() does just this.\n"
] |
[
9
] |
[] |
[] |
[
"python",
"url"
] |
stackoverflow_0002531538_python_url.txt
|
Q:
In Python, what are some examples of when decorators greatly simplify a task?
Trying to find examples of when decorators might be really beneficial, and when not so much.
Sample code is appreciated.
A:
Decorators are simple syntax for a specific way to call higher-order functions, so if you're focusing just on the syntax it's unlikely to make a great difference. IOW, wherever you can say
@mydecorator
def f(...):
# body of f
you could identically say
def f(...):
# body of f
f = mydecorator(f)
The decorator syntax's advantage is that it's a wee bit more concise (no repeating f three times;-) and that it comes before the def (or class, for class decorators) statement, thus immediately alerting the reader of the code. It's important, but it just can't be great!
The semantics of decorators (and, identically, of higher-order function calls that match this pattern, if there were no decorators;-). For example,
@classmethod
def f(cls, ...):
lets you make class methods (very useful esp. for alternate constructors), and
@property
def foo(self, ...):
lets you make read-only properties (with other related decorators in 2.6 for non-read-only properties;-), which are extremely useful even when not used (since they save you from writing lot of dumb "boilerplate" accessors for what are essentially attributes... just because access to the attribute might require triggering some computation in the future!-).
Beyond the ones built into Python, your own decorators can be just as important -- depending on what your application is, of course. In general, they make it easy to refactor some part of the code (which would otherwise have to be duplicated in many functions and classes [[or you might have to resort to metaclasses for the class case, but those are richer and more complicated to use correctly]]) into the decorator. Therefore, they help you avoid repetitious, boilerplatey code -- and since DRY, "Don't Repeat Yourself", is a core principle of software development, any help you can get towards it should be heartily welcome.
A:
The usual example is using the @property decorator to make a read-only property:
@property
def count(self):
return self._events
instead of:
def _get_count(self):
return self._events
count = property(_get_count)
A:
The easiest way to understand the usefulness of decorators is to see some examples. Here is one, for instance:
Suppose you are studying some code and wish to
understand when and how a function is called.
You can use a decorator to alter the function
so it prints some debugging information each time the function is called:
import functools
def trace(f):
'''This decorator shows how the function was called'''
@functools.wraps(f)
def wrapper(*arg,**kw):
arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw])
print "%s(%s)" % (f.__name__, arg_str)
return f(*arg, **kw)
return wrapper
@trace
def foo(*args):
pass
for n in range(3):
foo(n)
prints:
# foo(0)
# foo(1)
# foo(2)
If you only wished to trace one function foo, you could of course
add the code more simply to the definition of foo:
def foo(*args):
print('foo({0})'.format(args))
but if you had many functions that you wished to trace, or
did not want to mess with the original code, then the decorator
becomes useful.
For other examples of useful decorators, see the decorator library.
A:
In the AppEngine API, there's the nice @login_required decorator, which can clean up code quite a bit:
class MyPage(webapp.RequestHandler):
@login_required
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("Hello, world!")
As opposed to:
class MyPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(self.request.uri))
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("Hello, world!")
The other ones I find myself using most are @classmethod for class methods, @staticmethod for static methods, and (as Mike DeSimone said) @property for read-only properties. It just reads nicer to have the decorator before the function rather than after it, like in
class Bar(object):
@classmethod
def foo(cls):
return id(cls)
instead of:
class Bar(object):
def foo(cls):
return id(cls)
foo = classmethod(foo)
It just saves boilerplate code.
A:
Decorators are for design choices where you are merging two concepts, like "Logging" and "Inventory Management" or "is registered user" and "View Lastest Messages".
One of those concepts is wrapping the other, controlling how it is called. That concept is the decorator.
The second concept is permanently joined to the first, so much so that it is OK to lose
the ability to call the second concept directly. For example, losing the ability to call "View Latest Messages" without also calling "Is registered user"
When the design choice is correct, the decorator syntax (or syntactic sugar for decorators)
reads cleanly and moves to eliminate errors from misunderstanding.
The usual decorator concepts include:
Logging. This might be joined with a transaction processor to log each successful or
unsuccessful transaction.
Requiring security. This might be coupled with changing price in an inventory.
Caching (or memoizing). This might be coupled with Net Present Value computations or any expensive, static, read only operation.
Language fix-ups like "@classmethod" or "convert error return values to exceptions"
Registration with frameworks, such as "this function gets called when that button is
pressed.
state machine processing, where the decorator decides whch state to process next.
etc. etc.
You might look at http://wiki.python.org/moin/PythonDecoratorLibrary (a dated wiki page) or the dectools (http://pypi.python.org/pypi/dectools) library for more documentation and examples.
|
In Python, what are some examples of when decorators greatly simplify a task?
|
Trying to find examples of when decorators might be really beneficial, and when not so much.
Sample code is appreciated.
|
[
"Decorators are simple syntax for a specific way to call higher-order functions, so if you're focusing just on the syntax it's unlikely to make a great difference. IOW, wherever you can say\n@mydecorator\ndef f(...):\n # body of f\n\nyou could identically say\ndef f(...):\n # body of f\nf = mydecorator(f)\n\nThe decorator syntax's advantage is that it's a wee bit more concise (no repeating f three times;-) and that it comes before the def (or class, for class decorators) statement, thus immediately alerting the reader of the code. It's important, but it just can't be great!\nThe semantics of decorators (and, identically, of higher-order function calls that match this pattern, if there were no decorators;-). For example,\n@classmethod\ndef f(cls, ...):\n\nlets you make class methods (very useful esp. for alternate constructors), and\n@property\ndef foo(self, ...):\n\nlets you make read-only properties (with other related decorators in 2.6 for non-read-only properties;-), which are extremely useful even when not used (since they save you from writing lot of dumb \"boilerplate\" accessors for what are essentially attributes... just because access to the attribute might require triggering some computation in the future!-).\nBeyond the ones built into Python, your own decorators can be just as important -- depending on what your application is, of course. In general, they make it easy to refactor some part of the code (which would otherwise have to be duplicated in many functions and classes [[or you might have to resort to metaclasses for the class case, but those are richer and more complicated to use correctly]]) into the decorator. Therefore, they help you avoid repetitious, boilerplatey code -- and since DRY, \"Don't Repeat Yourself\", is a core principle of software development, any help you can get towards it should be heartily welcome.\n",
"The usual example is using the @property decorator to make a read-only property:\n@property\ndef count(self):\n return self._events\n\ninstead of:\ndef _get_count(self):\n return self._events\n\ncount = property(_get_count)\n\n",
"The easiest way to understand the usefulness of decorators is to see some examples. Here is one, for instance:\nSuppose you are studying some code and wish to \nunderstand when and how a function is called.\nYou can use a decorator to alter the function \nso it prints some debugging information each time the function is called:\nimport functools\ndef trace(f):\n '''This decorator shows how the function was called'''\n @functools.wraps(f)\n def wrapper(*arg,**kw): \n arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw])\n print \"%s(%s)\" % (f.__name__, arg_str)\n return f(*arg, **kw)\n return wrapper\n\n@trace\ndef foo(*args):\n pass\n\n\nfor n in range(3):\n foo(n)\n\nprints:\n# foo(0)\n# foo(1)\n# foo(2)\n\nIf you only wished to trace one function foo, you could of course \nadd the code more simply to the definition of foo:\ndef foo(*args):\n print('foo({0})'.format(args))\n\nbut if you had many functions that you wished to trace, or \ndid not want to mess with the original code, then the decorator \nbecomes useful.\nFor other examples of useful decorators, see the decorator library.\n",
"In the AppEngine API, there's the nice @login_required decorator, which can clean up code quite a bit:\nclass MyPage(webapp.RequestHandler):\n @login_required\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(\"Hello, world!\")\n\nAs opposed to:\nclass MyPage(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if not user:\n return self.redirect(users.create_login_url(self.request.uri))\n\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write(\"Hello, world!\")\n\nThe other ones I find myself using most are @classmethod for class methods, @staticmethod for static methods, and (as Mike DeSimone said) @property for read-only properties. It just reads nicer to have the decorator before the function rather than after it, like in\nclass Bar(object):\n @classmethod\n def foo(cls):\n return id(cls)\n\ninstead of:\nclass Bar(object):\n def foo(cls):\n return id(cls)\n foo = classmethod(foo)\n\nIt just saves boilerplate code.\n",
"Decorators are for design choices where you are merging two concepts, like \"Logging\" and \"Inventory Management\" or \"is registered user\" and \"View Lastest Messages\". \n\nOne of those concepts is wrapping the other, controlling how it is called. That concept is the decorator.\nThe second concept is permanently joined to the first, so much so that it is OK to lose\nthe ability to call the second concept directly. For example, losing the ability to call \"View Latest Messages\" without also calling \"Is registered user\"\n\nWhen the design choice is correct, the decorator syntax (or syntactic sugar for decorators)\nreads cleanly and moves to eliminate errors from misunderstanding.\nThe usual decorator concepts include:\n\nLogging. This might be joined with a transaction processor to log each successful or\n unsuccessful transaction.\nRequiring security. This might be coupled with changing price in an inventory.\nCaching (or memoizing). This might be coupled with Net Present Value computations or any expensive, static, read only operation.\nLanguage fix-ups like \"@classmethod\" or \"convert error return values to exceptions\"\nRegistration with frameworks, such as \"this function gets called when that button is\npressed.\nstate machine processing, where the decorator decides whch state to process next.\netc. etc.\n\nYou might look at http://wiki.python.org/moin/PythonDecoratorLibrary (a dated wiki page) or the dectools (http://pypi.python.org/pypi/dectools) library for more documentation and examples.\n"
] |
[
8,
4,
4,
1,
1
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002531696_decorator_python.txt
|
Q:
Multiple Unpacking Assignment in Python when you don't know the sequence length
The textbook examples of multiple unpacking assignment are something like:
import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.
M = NP.arange(20).reshape(5, 4) # numpy 5x4 array
a, b, c, d, e = M
# here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e)
(My question is not numpy specific. Indeed, I would prefer a pure Python solution.)
For the piece of code I'm looking at now, I see two complications on that straightforward scenario:
I usually won't know the shape of M; and
I want to unpack a certain number of
items (definitely less than all items), and
I want to put the remainder into a single
container
So back to the 5x4 array above, what I would very much like to do is assign the first three rows of M to a, b, and c respectively (exactly as above), and the rest of the rows (I have no idea how many there will be, just some positive integer) to a single container, all_the_rest = [].
A:
Python 3.x can do this easily:
a, b, *c = someseq
Python 2.x needs a bit more work:
(a, b), c = someseq[:2], someseq[2:]
A:
Syntax for this is added to Python 3
>>> # Python 3.x only
>>> a, b, *c = range(10)
>>> a
0
>>> b
1
>>> c
[2, 3, 4, 5, 6, 7, 8, 9]
but no similar solution exists in Python 2.
You can of course do
>>> s = range(10)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> (a, b, c), rest = s[0:3], s[3:]
>>> a
0
>>> b
1
>>> c
2
>>> rest
[3, 4, 5, 6, 7, 8, 9]
or other similar solutions.
|
Multiple Unpacking Assignment in Python when you don't know the sequence length
|
The textbook examples of multiple unpacking assignment are something like:
import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.
M = NP.arange(20).reshape(5, 4) # numpy 5x4 array
a, b, c, d, e = M
# here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e)
(My question is not numpy specific. Indeed, I would prefer a pure Python solution.)
For the piece of code I'm looking at now, I see two complications on that straightforward scenario:
I usually won't know the shape of M; and
I want to unpack a certain number of
items (definitely less than all items), and
I want to put the remainder into a single
container
So back to the 5x4 array above, what I would very much like to do is assign the first three rows of M to a, b, and c respectively (exactly as above), and the rest of the rows (I have no idea how many there will be, just some positive integer) to a single container, all_the_rest = [].
|
[
"Python 3.x can do this easily:\na, b, *c = someseq\n\nPython 2.x needs a bit more work:\n(a, b), c = someseq[:2], someseq[2:]\n\n",
"Syntax for this is added to Python 3\n>>> # Python 3.x only\n>>> a, b, *c = range(10)\n>>> a\n0\n>>> b\n1\n>>> c\n[2, 3, 4, 5, 6, 7, 8, 9]\n\nbut no similar solution exists in Python 2. \nYou can of course do\n>>> s = range(10)\n>>> s\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> (a, b, c), rest = s[0:3], s[3:]\n>>> a\n0\n>>> b\n1\n>>> c\n2\n>>> rest\n[3, 4, 5, 6, 7, 8, 9]\n\nor other similar solutions.\n"
] |
[
35,
11
] |
[] |
[] |
[
"python",
"variable_assignment"
] |
stackoverflow_0002531776_python_variable_assignment.txt
|
Q:
Convert binary information to regular data type without outside modules in python
I'm tasked with reading a poorly formatted binary file and taking in the variables. Although I need to do it in C++ (ROOT, specifically), I've decided to do it in python because python makes sense to me, but my plan is to get it working in python and then tackle re-writing in in C++, so using easy to use python modules won't get me too far later down the road.
Basically, I do this:
In [5]: some_value
Out[5]: '\x00I'
In [6]: ''.join([str(ord(i)) for i in some_value])
Out[6]: '073'
In [7]: int(''.join([str(ord(i)) for i in some_value]))
Out[7]: 73
And I know there has to be a better way. What do you think?
EDIT:
A bit of info on the binary format.
alt text http://grab.by/3njm
alt text http://grab.by/3njv
alt text http://grab.by/3nkL
This is the endian test I am using:
# Read a uint32 for endianess
endian_test = rq1_file.read(uint32)
if endian_test == '\x04\x03\x02\x01':
print "Endian test: \\x04\\x03\\x02\\x01"
swapbits = True
elif endian_test == '\x01\x02\x03\x04':
print "Endian test: \\x01\\x02\\x03\\x04"
swapbits = False
A:
You're basically computing a "number-in-base-256", which is a polynomial, so, by Horner's method:
>>> v = 0
>>> for c in someval: v = v * 256 + ord(c)
More typical would be to use equivalent bit-operations rather than arithmetic -- the following's equivalent:
>>> v = 0
>>> for c in someval: v = v << 8 | ord(c)
A:
import struct
result, = struct.unpack('>H', some_value)
A:
Your int(''.join([str(ord(i)) for i in some_value])) works ONLY when all bytes except the last byte are zero.
Examples:
'\x01I' should be 1 * 256 + 73 == 329; you get 173
'\x01\x02' should be 1 * 256 + 2 == 258; you get 12
'\x01\x00' should be 1 * 256 + 0 == 256; you get 10
It also relies on an assumption that integers are stored in bigendian fashion; have you verified this assumption? Are you sure that '\x00I' represents the integer 73, and not the integer 73 * 256 + 0 == 18688 (or something else)? Please let us help you verify this assumption by telling us what brand and model of computer and what operating system were used to create the data.
How are negative integers represented?
Do you need to deal with floating-point numbers?
Is the requirement to write it in C++ immutable? What does "(ROOT, specifically)" mean?
If the only dictate is common sense, the preferred order would be:
Write it in Python using the struct module.
Write it in C++ but use C++ library routines (especially if floating-point is involved). Don't re-invent the wheel.
Roll your own conversion routines in C++. You could snarf a copy of the C source for the Python struct module.
Update
Comments after the file format details were posted:
The endianness marker is evidently optional, except at the start of a file. This is dodgy; it relies on the fact that if it is not there, the 3rd and 4th bytes of the block are the 1st 2 bytes of the header string, and neither '\x03\x04' nor '\x02\x01' can validly start a header string. The smart thing to do would be to read SIX bytes -- if first 4 are the endian marker, the next two are the header length, and your next read is for the header string; otherwise seek backwards 4 bytes then read the header string.
The above is in the nuisance category. The negative sizes are a real worry, in that they specify a MAXIMUM length, and there is no mention of how the ACTUAL length is determined. It says "The actual size of the entry is then given line by line". How? There is no documentation of what a "line of data" looks like. The description mentions "lines" many times; are these lines terminated by carriage return and/or line feed? If so, how does one tell the difference between say a line feed byte and the first byte of say a uint16 that belongs to the current "line" of data? If no linefeed or whatever, how does one know when the current line of data is finished? Is there a uintNN size in front of every variable or slice thereof?
Then it says that (2) above (negative size) also applies to the header string. The mind boggles. Do you have any examples (in documentation of the file layout, or in actual files) of "negative size" of (a) header string (b) data "line"?
Is this "decided format" publically available e.g. documentation on the web? Does the format have a searchable name? Are you sure you are the first person in the world to want to read that format?
Reading that file format, even with a full specification, is no trivial exercise, even for a binary-format-experienced person who's also experienced with Python (which BTW doesn't have a float128). How many person-hours have you been allocated for the task? What are the penalties for (a) delay (b) failure?
Your original question involved fixing your interesting way of trying to parse a uint16 -- doing much more is way outside the scope/intention of what SO questions are all about.
A:
The equivalent to the Python struct module is a C struct and/or union, so being afraid to use it is silly.
A:
I'm not exactly sure how the format of the data is you want to extract, but maybe you better just write a couple of generic utility functions to extract the different data type you need:
def int1b(data, i):
return ord(data[i])
def int2b(data, i):
return (int1b(data, i) << 8) + int1b(data, i+1)
def int4b(data, i):
return (int2b(data, i) << 16) + int2b(data, i+2)
With such functions you can easily extract values from the data and they also can be translated rather easily to C.
|
Convert binary information to regular data type without outside modules in python
|
I'm tasked with reading a poorly formatted binary file and taking in the variables. Although I need to do it in C++ (ROOT, specifically), I've decided to do it in python because python makes sense to me, but my plan is to get it working in python and then tackle re-writing in in C++, so using easy to use python modules won't get me too far later down the road.
Basically, I do this:
In [5]: some_value
Out[5]: '\x00I'
In [6]: ''.join([str(ord(i)) for i in some_value])
Out[6]: '073'
In [7]: int(''.join([str(ord(i)) for i in some_value]))
Out[7]: 73
And I know there has to be a better way. What do you think?
EDIT:
A bit of info on the binary format.
alt text http://grab.by/3njm
alt text http://grab.by/3njv
alt text http://grab.by/3nkL
This is the endian test I am using:
# Read a uint32 for endianess
endian_test = rq1_file.read(uint32)
if endian_test == '\x04\x03\x02\x01':
print "Endian test: \\x04\\x03\\x02\\x01"
swapbits = True
elif endian_test == '\x01\x02\x03\x04':
print "Endian test: \\x01\\x02\\x03\\x04"
swapbits = False
|
[
"You're basically computing a \"number-in-base-256\", which is a polynomial, so, by Horner's method:\n>>> v = 0\n>>> for c in someval: v = v * 256 + ord(c)\n\nMore typical would be to use equivalent bit-operations rather than arithmetic -- the following's equivalent:\n>>> v = 0\n>>> for c in someval: v = v << 8 | ord(c)\n\n",
"import struct\nresult, = struct.unpack('>H', some_value)\n\n",
"Your int(''.join([str(ord(i)) for i in some_value])) works ONLY when all bytes except the last byte are zero. \nExamples:\n'\\x01I' should be 1 * 256 + 73 == 329; you get 173\n'\\x01\\x02' should be 1 * 256 + 2 == 258; you get 12\n'\\x01\\x00' should be 1 * 256 + 0 == 256; you get 10\nIt also relies on an assumption that integers are stored in bigendian fashion; have you verified this assumption? Are you sure that '\\x00I' represents the integer 73, and not the integer 73 * 256 + 0 == 18688 (or something else)? Please let us help you verify this assumption by telling us what brand and model of computer and what operating system were used to create the data.\nHow are negative integers represented?\nDo you need to deal with floating-point numbers?\nIs the requirement to write it in C++ immutable? What does \"(ROOT, specifically)\" mean?\nIf the only dictate is common sense, the preferred order would be:\n\nWrite it in Python using the struct module.\nWrite it in C++ but use C++ library routines (especially if floating-point is involved). Don't re-invent the wheel.\nRoll your own conversion routines in C++. You could snarf a copy of the C source for the Python struct module.\n\nUpdate\nComments after the file format details were posted:\n\nThe endianness marker is evidently optional, except at the start of a file. This is dodgy; it relies on the fact that if it is not there, the 3rd and 4th bytes of the block are the 1st 2 bytes of the header string, and neither '\\x03\\x04' nor '\\x02\\x01' can validly start a header string. The smart thing to do would be to read SIX bytes -- if first 4 are the endian marker, the next two are the header length, and your next read is for the header string; otherwise seek backwards 4 bytes then read the header string.\nThe above is in the nuisance category. The negative sizes are a real worry, in that they specify a MAXIMUM length, and there is no mention of how the ACTUAL length is determined. It says \"The actual size of the entry is then given line by line\". How? There is no documentation of what a \"line of data\" looks like. The description mentions \"lines\" many times; are these lines terminated by carriage return and/or line feed? If so, how does one tell the difference between say a line feed byte and the first byte of say a uint16 that belongs to the current \"line\" of data? If no linefeed or whatever, how does one know when the current line of data is finished? Is there a uintNN size in front of every variable or slice thereof?\nThen it says that (2) above (negative size) also applies to the header string. The mind boggles. Do you have any examples (in documentation of the file layout, or in actual files) of \"negative size\" of (a) header string (b) data \"line\"?\nIs this \"decided format\" publically available e.g. documentation on the web? Does the format have a searchable name? Are you sure you are the first person in the world to want to read that format?\nReading that file format, even with a full specification, is no trivial exercise, even for a binary-format-experienced person who's also experienced with Python (which BTW doesn't have a float128). How many person-hours have you been allocated for the task? What are the penalties for (a) delay (b) failure?\nYour original question involved fixing your interesting way of trying to parse a uint16 -- doing much more is way outside the scope/intention of what SO questions are all about.\n\n",
"The equivalent to the Python struct module is a C struct and/or union, so being afraid to use it is silly.\n",
"I'm not exactly sure how the format of the data is you want to extract, but maybe you better just write a couple of generic utility functions to extract the different data type you need:\ndef int1b(data, i):\n return ord(data[i])\n\ndef int2b(data, i):\n return (int1b(data, i) << 8) + int1b(data, i+1)\n\ndef int4b(data, i):\n return (int2b(data, i) << 16) + int2b(data, i+2)\n\nWith such functions you can easily extract values from the data and they also can be translated rather easily to C.\n"
] |
[
2,
2,
2,
1,
0
] |
[] |
[] |
[
"binary",
"python"
] |
stackoverflow_0002531439_binary_python.txt
|
Q:
Key word extraction in Python
I'm building a website in django that needs to extract key words from short (twitter-like) messages.
I've looked at packages like topia.textextract and nltk - but both seem to be overkill for what I need to do. All I need to do is filter words like "and", "or", "not" while keeping nouns and verbs that aren't conjunctives or other parts of speech. Are there any "simpler" packages out there that can do this?
EDIT: This needs to be done in near real-time on a production website, so using a keyword extraction service seems out of the question, based on their response times and request throttling.
A:
You can make a set sw of the "stop words" you want to eliminate (maybe copy it once and for all from the stop words corpus of NLTK, depending how familiar you are with the various natural languages you need to support), then apply it very simply.
E.g., if you have a list of words sent that make up the sentence (shorn of punctuation and lowercased, for simplicity), [word for word in sent if word not in sw] is all you need to make a list of non-stopwords -- could hardly be easier, right?
To get the sent list in the first place, using the re module from the standard library, re.findall(r'\w+', sentstring) might suffice if sentstring is the string with the sentence you're dealing with -- it doesn't lowercase, but you can change the list comprehension I suggest above to [word for word in sent if word.lower() not in sw] to compensate for that and (btw) keep the word's original case, which may be useful.
A:
Abbreviations like NO for navigation officer or OR for operations room need a little care lest you cause a SNAFU ;-) One suspects that better results could be obtained from "Find the NO and send her to the OR" by tagging the words with parts of speech using the context ... hint 1: "the OR" should result in "the [noun]" not "the [conjunction]". Hint 2: if in doubt about a word, keep it as a keyword.
|
Key word extraction in Python
|
I'm building a website in django that needs to extract key words from short (twitter-like) messages.
I've looked at packages like topia.textextract and nltk - but both seem to be overkill for what I need to do. All I need to do is filter words like "and", "or", "not" while keeping nouns and verbs that aren't conjunctives or other parts of speech. Are there any "simpler" packages out there that can do this?
EDIT: This needs to be done in near real-time on a production website, so using a keyword extraction service seems out of the question, based on their response times and request throttling.
|
[
"You can make a set sw of the \"stop words\" you want to eliminate (maybe copy it once and for all from the stop words corpus of NLTK, depending how familiar you are with the various natural languages you need to support), then apply it very simply.\nE.g., if you have a list of words sent that make up the sentence (shorn of punctuation and lowercased, for simplicity), [word for word in sent if word not in sw] is all you need to make a list of non-stopwords -- could hardly be easier, right?\nTo get the sent list in the first place, using the re module from the standard library, re.findall(r'\\w+', sentstring) might suffice if sentstring is the string with the sentence you're dealing with -- it doesn't lowercase, but you can change the list comprehension I suggest above to [word for word in sent if word.lower() not in sw] to compensate for that and (btw) keep the word's original case, which may be useful.\n",
"Abbreviations like NO for navigation officer or OR for operations room need a little care lest you cause a SNAFU ;-) One suspects that better results could be obtained from \"Find the NO and send her to the OR\" by tagging the words with parts of speech using the context ... hint 1: \"the OR\" should result in \"the [noun]\" not \"the [conjunction]\". Hint 2: if in doubt about a word, keep it as a keyword.\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"keyword",
"python"
] |
stackoverflow_0002531717_django_keyword_python.txt
|
Q:
I am having issues with django test
I have this test case
def setUp(self):
self.user = User.objects.create(username="tauri", password='gaul')
def test_loginin_student_control_panel(self):
c = Client()
c.login(username="tauri", password="gaul")
response = c.get('/student/')
self.assertEqual(response.status_code, 200)
the view associated with the test case is this
@login_required
def student(request):
return render_to_response('student/controlpanel.html')
so my question is why the above test case redirects user to login
page? should not c.login suppose to take care authenticating user?
A:
The problem is the way you create your User object.
Django does not store your password in plain text in the database, it stores its hash value. But in your code password is set in plain text.
So when you use c.login(...) internally Django will make a call to check_password method which will generate a hash value from the password you passed and will compare it to the password stored in the database and as a result will return False because 'gaul' from DB is not equal to get_hexdigest('gaul')
There are two options:
1) Use a User.objects.create_user method that will take care of password hashing:
def setUp(self):
self.user = User.objects.create_user(username='tauri',
password='gaul',
email='')
2) Or set a password with a set_password method:
def setUp(self):
self.user = user = User.objects.create(username='tauri')
user.set_password('gaul')
user.save()
A:
Did you make sure to create the user entry in your setUp function?
User.objects.create_user(username="tauri", password="gual")
|
I am having issues with django test
|
I have this test case
def setUp(self):
self.user = User.objects.create(username="tauri", password='gaul')
def test_loginin_student_control_panel(self):
c = Client()
c.login(username="tauri", password="gaul")
response = c.get('/student/')
self.assertEqual(response.status_code, 200)
the view associated with the test case is this
@login_required
def student(request):
return render_to_response('student/controlpanel.html')
so my question is why the above test case redirects user to login
page? should not c.login suppose to take care authenticating user?
|
[
"The problem is the way you create your User object.\nDjango does not store your password in plain text in the database, it stores its hash value. But in your code password is set in plain text.\nSo when you use c.login(...) internally Django will make a call to check_password method which will generate a hash value from the password you passed and will compare it to the password stored in the database and as a result will return False because 'gaul' from DB is not equal to get_hexdigest('gaul')\nThere are two options:\n1) Use a User.objects.create_user method that will take care of password hashing:\ndef setUp(self):\n self.user = User.objects.create_user(username='tauri', \n password='gaul', \n email='')\n\n2) Or set a password with a set_password method:\ndef setUp(self):\n self.user = user = User.objects.create(username='tauri')\n user.set_password('gaul')\n user.save()\n\n",
"Did you make sure to create the user entry in your setUp function?\nUser.objects.create_user(username=\"tauri\", password=\"gual\")\n"
] |
[
4,
1
] |
[] |
[] |
[
"django",
"python",
"unit_testing"
] |
stackoverflow_0002531658_django_python_unit_testing.txt
|
Q:
Why won't numpy matrix let me print its rows?
Okay this is probably a really dumb question, however it's really starting to hurt. I have a numpy matrix, and basically I print it out row by row. However I want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Lets say i want to print the first row, and add a '|' between each element:
>>> '|'.join(map(str, arr[0,]))
'[[0 1 2 3 4]]'
Err...
>>> '|'.join(map(lambda x: str(x[0]), arr[0]))
'[[0 1 2 3 4]]'
I am really confused by this behavior why does it do this?
A:
arr is returned as a matrix type, which may not be an iterable object that plays nicely with join.
You could convert arr to a list with tolist() and then perform your join.
>>> a = arr.tolist() # now you can manipulate the list.
>>> for i in a:
'|'.join(map(str,i))
'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'
'0|1|2|3|4'
Or with an array using numpy.asarry for that matter
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> ele = numpy.asarray(arr)
>>> '|'.join(map(str,ele[0,]))
'0|1|2|3|4' # as per your example.
A:
In numpy, slices of matrices are matrices (note the double braces [[ ]] in your example). An easy way around this is to get the array representation using the .A attribute.
'|'.join(map(str, arr.A[0,]))
produces what you want:
0|1|2|3|4
A:
>>> arr[0,]
matrix([[0, 1, 2, 3, 4]])
>>> len(arr[0,])
1
So arr[0,] is not a list or an 1-d array as you expected. On the other hand, your method works for the example matrix from the numpy tutorial:
>>> def f(x,y):
... return 10*x+y
...
>>> b = fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>> len(b[0,])
4
>>> '|'.join(map(str, b[0,]))
'0|1|2|3'
I am not familiar with numpy, so I can tell why this happens. One more observation:
>>> type(arr)
<class 'numpy.matrixlib.defmatrix.matrix'>
>>> type(b)
<type 'numpy.ndarray'>
|
Why won't numpy matrix let me print its rows?
|
Okay this is probably a really dumb question, however it's really starting to hurt. I have a numpy matrix, and basically I print it out row by row. However I want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Lets say i want to print the first row, and add a '|' between each element:
>>> '|'.join(map(str, arr[0,]))
'[[0 1 2 3 4]]'
Err...
>>> '|'.join(map(lambda x: str(x[0]), arr[0]))
'[[0 1 2 3 4]]'
I am really confused by this behavior why does it do this?
|
[
"arr is returned as a matrix type, which may not be an iterable object that plays nicely with join.\nYou could convert arr to a list with tolist() and then perform your join.\n>>> a = arr.tolist() # now you can manipulate the list.\n>>> for i in a:\n '|'.join(map(str,i)) \n\n'0|1|2|3|4'\n'0|1|2|3|4'\n'0|1|2|3|4'\n'0|1|2|3|4'\n'0|1|2|3|4'\n\nOr with an array using numpy.asarry for that matter\n>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])\n>>> ele = numpy.asarray(arr)\n>>> '|'.join(map(str,ele[0,]))\n'0|1|2|3|4' # as per your example.\n\n",
"In numpy, slices of matrices are matrices (note the double braces [[ ]] in your example). An easy way around this is to get the array representation using the .A attribute.\n'|'.join(map(str, arr.A[0,]))\n\nproduces what you want:\n0|1|2|3|4\n\n",
">>> arr[0,]\nmatrix([[0, 1, 2, 3, 4]])\n>>> len(arr[0,])\n1\n\nSo arr[0,] is not a list or an 1-d array as you expected. On the other hand, your method works for the example matrix from the numpy tutorial:\n>>> def f(x,y):\n... return 10*x+y\n...\n>>> b = fromfunction(f,(5,4),dtype=int)\n>>> b\narray([[ 0, 1, 2, 3],\n [10, 11, 12, 13],\n [20, 21, 22, 23],\n [30, 31, 32, 33],\n [40, 41, 42, 43]])\n>>> len(b[0,])\n4\n>>> '|'.join(map(str, b[0,]))\n'0|1|2|3'\n\nI am not familiar with numpy, so I can tell why this happens. One more observation:\n>>> type(arr)\n<class 'numpy.matrixlib.defmatrix.matrix'>\n>>> type(b)\n<type 'numpy.ndarray'>\n\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002532012_numpy_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.