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:
What are your "must-have" Python Packages for Finance?
With the recent SEC proposal requiring that most Asset-Backed Securities issuers file a python computer program to document the flow of funds (or waterfall) provisions of the transaction, I thought it timely to ask what you thought the "Must-Have" Python Packages for Finance would be.
PS: apart from answering here, please also consider answering this survey.
Update: Survey results here.
A:
http://code.google.com/p/pandas/ is also developed with a quantitative finance background.
I guess then the usual suspects:
numpy
scipy
rpy
matplotlib
...
For my quant-development I usual start with pythonxy (http://www.pythonxy.com/) as a basis.
In the past I used also some python bindings for quantlib. (I don't know if they are still developed).
A:
Stefano Taschini's "Interval Arithmetic: Python Implementation and Applications" presented at Scipy 2008 (see here) can be precious, as it can show the range of numerical uncertainty of your computations (so you avoid decisions based on too-fragile input data or equations).
Since Stefano works at Altis Investment Management AG in Zurich, I'm pretty certain he developed and uses his pyinterval package in a finance context, although of course it's just a general-purpose tool, perfectly usable in other fields as well.
A:
While I deal with trading systems, sci-py/num-py have been extremely useful for me.
The built-in CSV reader/writer package in Python is also something that I regularly use.
A:
I will try to restrict for what's relevant to describing securities:
we have some packages that provides market conventions support (day count fractions, adjustment rules, expiration dates, schedule generations, etc.). It would be great to have them officially provided by the SEC? It's absolutely necessary to describe properly any security, and it would be cumbersome to reimplement them in every payoff description script.
some simple pricing-like functions, all very common, were redeveloped (for example: black scholes first order greeks and implied volatility computations) mainly for avoiding the overhead of calling the pricing librairies for such small things. This is used to describe vanilla options, for example, as the market quotes them in volatility points. Same for price-to-yield functions.
Of course, we use lot of other libraries for
communication for other systems
pricing
calibration
model assessment
statistics
production stuff
...
| What are your "must-have" Python Packages for Finance? | With the recent SEC proposal requiring that most Asset-Backed Securities issuers file a python computer program to document the flow of funds (or waterfall) provisions of the transaction, I thought it timely to ask what you thought the "Must-Have" Python Packages for Finance would be.
PS: apart from answering here, please also consider answering this survey.
Update: Survey results here.
| [
"http://code.google.com/p/pandas/ is also developed with a quantitative finance background.\nI guess then the usual suspects:\n\nnumpy\nscipy\nrpy\nmatplotlib\n...\n\nFor my quant-development I usual start with pythonxy (http://www.pythonxy.com/) as a basis.\nIn the past I used also some python bindings for quantlib. (I don't know if they are still developed).\n",
"Stefano Taschini's \"Interval Arithmetic: Python Implementation and Applications\" presented at Scipy 2008 (see here) can be precious, as it can show the range of numerical uncertainty of your computations (so you avoid decisions based on too-fragile input data or equations).\nSince Stefano works at Altis Investment Management AG in Zurich, I'm pretty certain he developed and uses his pyinterval package in a finance context, although of course it's just a general-purpose tool, perfectly usable in other fields as well.\n",
"While I deal with trading systems, sci-py/num-py have been extremely useful for me.\nThe built-in CSV reader/writer package in Python is also something that I regularly use.\n",
"I will try to restrict for what's relevant to describing securities:\n\nwe have some packages that provides market conventions support (day count fractions, adjustment rules, expiration dates, schedule generations, etc.). It would be great to have them officially provided by the SEC? It's absolutely necessary to describe properly any security, and it would be cumbersome to reimplement them in every payoff description script.\nsome simple pricing-like functions, all very common, were redeveloped (for example: black scholes first order greeks and implied volatility computations) mainly for avoiding the overhead of calling the pricing librairies for such small things. This is used to describe vanilla options, for example, as the market quotes them in volatility points. Same for price-to-yield functions.\n\nOf course, we use lot of other libraries for\n\ncommunication for other systems\npricing\ncalibration\nmodel assessment\nstatistics\nproduction stuff\n...\n\n"
] | [
7,
6,
3,
3
] | [] | [] | [
"finance",
"python",
"scientific_computing"
] | stackoverflow_0002870661_finance_python_scientific_computing.txt |
Q:
Need to get the uploaded file to my local PC
I have created a test form which will ask users to enter a name and upload the image file:
<html lang="en">
<head>
<title>Testing image upload</title>
</head>
<body>
<form action="/services/upload" method="POST" enctype="multipart/form-data">
File Description: <input name='fdesc' type='text'><br>
File name: <input type="file" name="fname"><br>
<div><input type="submit"></div>
</form>
</body>
</html>
i need to get the file uploaded by the user and store it on my local PC. can this be done in python ? please let me know.
A:
mod_python includes the FieldStorage class which allows you access to uploaded form data. In order to use it, you'd put something like the following in your Python script:
req.form = FieldStorage(req)
description = req.form['fdesc']
Since fdesc is a text input, description will be a string (more precisely, a StringField, which you can treat as a string).
file_field = req.form['fname']
Since fname is a file input, file_field will not be a string (or StringField), but rather a Field object which allows you access to the file data. The attribute file_field.file is a file-like object which you can use to read the file's contents, for example like so:
for line in file_field.file:
# process the line
You could use this to copy the file's data somewhere of your choosing, for example.
file_field.filename is the name of the file as provided by the client. Other useful attributes are listed in the documentation I linked to.
A:
Maybie the minimal http cgi upload recipe and it's comments are helpful for you.
A:
Hey David i got it working, i did it this way:
filename = request.FILES['fname']
destination = open('%s/%s'%(/tmp/,fileName), 'wb+')
for chunk in filename.chunks():
destination.write(chunk)
destination.close()
file = open('%s/%s'%(/tmp/,fileName),"rb").read()
Thanks for the help guys.
| Need to get the uploaded file to my local PC | I have created a test form which will ask users to enter a name and upload the image file:
<html lang="en">
<head>
<title>Testing image upload</title>
</head>
<body>
<form action="/services/upload" method="POST" enctype="multipart/form-data">
File Description: <input name='fdesc' type='text'><br>
File name: <input type="file" name="fname"><br>
<div><input type="submit"></div>
</form>
</body>
</html>
i need to get the file uploaded by the user and store it on my local PC. can this be done in python ? please let me know.
| [
"mod_python includes the FieldStorage class which allows you access to uploaded form data. In order to use it, you'd put something like the following in your Python script:\nreq.form = FieldStorage(req)\ndescription = req.form['fdesc']\n\nSince fdesc is a text input, description will be a string (more precisely, a StringField, which you can treat as a string).\nfile_field = req.form['fname']\n\nSince fname is a file input, file_field will not be a string (or StringField), but rather a Field object which allows you access to the file data. The attribute file_field.file is a file-like object which you can use to read the file's contents, for example like so:\nfor line in file_field.file:\n # process the line\n\nYou could use this to copy the file's data somewhere of your choosing, for example.\nfile_field.filename is the name of the file as provided by the client. Other useful attributes are listed in the documentation I linked to.\n",
"Maybie the minimal http cgi upload recipe and it's comments are helpful for you.\n",
"Hey David i got it working, i did it this way:\nfilename = request.FILES['fname']\ndestination = open('%s/%s'%(/tmp/,fileName), 'wb+')\nfor chunk in filename.chunks():\n destination.write(chunk)\ndestination.close()\n\nfile = open('%s/%s'%(/tmp/,fileName),\"rb\").read()\n\nThanks for the help guys.\n"
] | [
1,
0,
0
] | [] | [] | [
"file",
"file_upload",
"python",
"upload"
] | stackoverflow_0002880475_file_file_upload_python_upload.txt |
Q:
How to think in Python after working in C++?
I'm brand new to Python and trying to learn it by replicating the following C++ function into python
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <string> words, ofstream & outFile) {
outFile << "Equivalent words\n";
// checkedWord is parallel to the words vector. It is
// used to make sure each word is only displayed once.
vector <bool> checkedWord (words.size(), false);
for(int i = 0; i < words.size(); i++) {
if (!checkedWord[i]){
outFile << " ";
for(int j = i; j < words.size(); j++){
if(equivalentWords(words[i], words[j], outFile)) {
outFile << words[j] << " ";
checkedWord[j] = true;
}
}
outFile << "\n";
}
}
}
In my python code (below), rather than having a second vector, I have a list ("words") of lists of a string, a sorted list of the chars in the former string (because strings are immutable), and a bool (that tells if the word has been checked yet). However, I can't figure out how to change a value as you iterate through a list.
for word, s_word, checked in words:
if not checked:
for word1, s_word1, checked1 in words:
if s_word1 == s_word:
checked1 = True # this doesn't work
print word1,
print ""
Any help on doing this or thinking more "Pythony" is appreciated.
A:
Keeping things simple, this is O(N) complexity and should be sufficient if you don't have GBs of word data. Note that set() and dict() basically is a hashed index (free and builtin!).
index = {}
for word, s_word in words:
index[s_word] = index.get(s_word, []) + [word]
for similar_words in index.values():
print ' '.join(similar_words)
Don't know what you are using it for, but it might be of interest to you that in python 2.7 a Counter class was introduced in the collections module.
If you really want to keep your algorithm and update a boolean list (which you don't because that algorithm would do inefficient double loops), you would do it like this:
checked = [False] * len(words)
for i, (word, word_s) in enumerate(words):
if checked[i]:
continue
for j, (other, other_s) in enumerate(words[i:]):
if word_s == other_s:
print other,
checked[i+j] = True
print
A:
I generally like catchmeifyoutry's answer, but I would personally tighten it up a bit further as
for word in set(words):
print word
Edit: My answer is a shorter but functionally equivalent form of catchmeifyoutry's original, pre-edited answer.
A:
I think the word you're looking for is Pythonic, here's a pythonic code sample for what you're tying to do, determine words that are equivalent, where equivalence is determined by having the same set of letters
import collections
def print_equivalent_words(words):
eq_words = defaultdict(list)
for word in words:
eq_words["".join(sorted(set(word)))].append(word)
for k,v in eq_words.items():
print(v)
A:
This is not the best algorithm to solve this problem (it's O(N^2) instead of O(N)), but here's a pythonic version of it. The method I've used is to replace your array of bits with a set that contains words you've already seen.
checked = set()
for i, word in enumerate(words):
if word in checked:
continue
to_output = [word]
for word2 in words[i + 1:]:
if equivalentWords(word, word2):
to_output.append(word2)
checked.add(word2)
print ' '.join(to_output)
A:
Make words a list of objects:
class Word(object):
def __init__(self, word, s_word, checked=False):
self.word = word
self.s_word = s_word
self.checked = checked
....
for word1 in words:
if word1.s_word == word.s_word:
word1.checked = True
print word1.word
print
A:
Based on the comment:
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
I'm not quite sure that the original code works, and even if it does, I can't say I like it much. First of all, based on the loop nesting, it looks like the complexity is O(N2). Second, I can't figure out what it's doing well enough to be sure it really does what's stated above (it uses a three-parameter overload of equivalentWords, which seems to be missing, which makes it hard to say though).
Some of the Python solutions are a lot shorter and simpler -- to the point that I feel reasonably certain they simply don't work. A couple seem to simply print out unique words, which (at least as I interpret it) is not the intent at all.
Here's a version in C++ that does what I interpret the requirements to be:
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <iostream>
#include <map>
std::string
sort_word(std::string word) {
std::sort(word.begin(), word.end());
return word;
}
namespace std {
std::ostream &
operator<<(std::ostream &os,
std::pair<std::string, std::set<std::string> >const &words)
{
std::copy(words.second.begin(), words.second.end(),
std::ostream_iterator<std::string>(os, "\t"));
return os;
}
}
void
equivalentWords(std::vector<std::string> const &words, std::ostream &os) {
typedef std::map<std::string, std::set<std::string> > word_list_t;
word_list_t word_list;
for (int i=0; i<words.size(); i++)
word_list[sort_word(words[i])].insert(words[i]);
std::copy(word_list.begin(), word_list.end(),
std::ostream_iterator<word_list_t::value_type>(os, "\n"));
}
int
main() {
std::vector<std::string> input;
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(input));
equivalentWords(input, std::cout);
return 0;
}
I think using that as a starting point for a Python version is more likely to produce a clean, working result.
A:
I wouldn't say this is pythonic, but I'm quite proud of it.
import itertools
for _, to_output in itertools.groupby(sorted(words, key=sorted), sorted):
print ' '.join(to_output)
| How to think in Python after working in C++? | I'm brand new to Python and trying to learn it by replicating the following C++ function into python
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <string> words, ofstream & outFile) {
outFile << "Equivalent words\n";
// checkedWord is parallel to the words vector. It is
// used to make sure each word is only displayed once.
vector <bool> checkedWord (words.size(), false);
for(int i = 0; i < words.size(); i++) {
if (!checkedWord[i]){
outFile << " ";
for(int j = i; j < words.size(); j++){
if(equivalentWords(words[i], words[j], outFile)) {
outFile << words[j] << " ";
checkedWord[j] = true;
}
}
outFile << "\n";
}
}
}
In my python code (below), rather than having a second vector, I have a list ("words") of lists of a string, a sorted list of the chars in the former string (because strings are immutable), and a bool (that tells if the word has been checked yet). However, I can't figure out how to change a value as you iterate through a list.
for word, s_word, checked in words:
if not checked:
for word1, s_word1, checked1 in words:
if s_word1 == s_word:
checked1 = True # this doesn't work
print word1,
print ""
Any help on doing this or thinking more "Pythony" is appreciated.
| [
"Keeping things simple, this is O(N) complexity and should be sufficient if you don't have GBs of word data. Note that set() and dict() basically is a hashed index (free and builtin!).\nindex = {}\nfor word, s_word in words:\n index[s_word] = index.get(s_word, []) + [word]\n\nfor similar_words in index.values():\n print ' '.join(similar_words) \n\nDon't know what you are using it for, but it might be of interest to you that in python 2.7 a Counter class was introduced in the collections module.\nIf you really want to keep your algorithm and update a boolean list (which you don't because that algorithm would do inefficient double loops), you would do it like this:\nchecked = [False] * len(words)\nfor i, (word, word_s) in enumerate(words):\n if checked[i]:\n continue\n for j, (other, other_s) in enumerate(words[i:]):\n if word_s == other_s:\n print other,\n checked[i+j] = True\n print\n\n",
"I generally like catchmeifyoutry's answer, but I would personally tighten it up a bit further as\nfor word in set(words):\n print word\n\nEdit: My answer is a shorter but functionally equivalent form of catchmeifyoutry's original, pre-edited answer.\n",
"I think the word you're looking for is Pythonic, here's a pythonic code sample for what you're tying to do, determine words that are equivalent, where equivalence is determined by having the same set of letters \nimport collections\n\ndef print_equivalent_words(words):\n eq_words = defaultdict(list)\n for word in words:\n eq_words[\"\".join(sorted(set(word)))].append(word)\n\n for k,v in eq_words.items():\n print(v)\n\n",
"This is not the best algorithm to solve this problem (it's O(N^2) instead of O(N)), but here's a pythonic version of it. The method I've used is to replace your array of bits with a set that contains words you've already seen.\nchecked = set()\nfor i, word in enumerate(words):\n if word in checked:\n continue\n to_output = [word]\n for word2 in words[i + 1:]:\n if equivalentWords(word, word2):\n to_output.append(word2)\n checked.add(word2)\n print ' '.join(to_output)\n\n",
"Make words a list of objects:\nclass Word(object):\n def __init__(self, word, s_word, checked=False):\n self.word = word\n self.s_word = s_word\n self.checked = checked\n\n ....\n for word1 in words:\n if word1.s_word == word.s_word:\n word1.checked = True\n print word1.word\n print\n\n",
"Based on the comment:\n// determines which words in a vector consist of the same letters\n// outputs the words with the same letters on the same line\n\nI'm not quite sure that the original code works, and even if it does, I can't say I like it much. First of all, based on the loop nesting, it looks like the complexity is O(N2). Second, I can't figure out what it's doing well enough to be sure it really does what's stated above (it uses a three-parameter overload of equivalentWords, which seems to be missing, which makes it hard to say though).\nSome of the Python solutions are a lot shorter and simpler -- to the point that I feel reasonably certain they simply don't work. A couple seem to simply print out unique words, which (at least as I interpret it) is not the intent at all.\nHere's a version in C++ that does what I interpret the requirements to be:\n#include <string>\n#include <set>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <map>\n\nstd::string \nsort_word(std::string word) { \n std::sort(word.begin(), word.end());\n return word;\n}\n\nnamespace std { \n std::ostream &\n operator<<(std::ostream &os, \n std::pair<std::string, std::set<std::string> >const &words) \n { \n std::copy(words.second.begin(), words.second.end(), \n std::ostream_iterator<std::string>(os, \"\\t\"));\n return os;\n }\n}\n\nvoid \nequivalentWords(std::vector<std::string> const &words, std::ostream &os) { \n typedef std::map<std::string, std::set<std::string> > word_list_t;\n word_list_t word_list;\n\n for (int i=0; i<words.size(); i++)\n word_list[sort_word(words[i])].insert(words[i]);\n\n std::copy(word_list.begin(), word_list.end(),\n std::ostream_iterator<word_list_t::value_type>(os, \"\\n\"));\n}\n\nint \nmain() { \n std::vector<std::string> input;\n\n std::copy(std::istream_iterator<std::string>(std::cin),\n std::istream_iterator<std::string>(),\n std::back_inserter(input));\n equivalentWords(input, std::cout);\n return 0;\n}\n\nI think using that as a starting point for a Python version is more likely to produce a clean, working result.\n",
"I wouldn't say this is pythonic, but I'm quite proud of it.\nimport itertools\n\nfor _, to_output in itertools.groupby(sorted(words, key=sorted), sorted):\n print ' '.join(to_output)\n\n"
] | [
5,
3,
3,
1,
0,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002879055_c++_python.txt |
Q:
Python: When passing variables between methods, is it necessary to assign it a new name?
I'm thinking that the answer is probably 'no' if the program is small and there are a lot of methods, but what about in a larger program? If I am going to be using one variable in multiple methods throughout the program, is it smarter to:
Come up with a different phrasing for each method (to eliminate naming conflicts).
Use the same name for each method (to eliminate confusion)
Just use a global variable (to eliminate both)
This is more of a stylistic question than anything else. What naming convention do YOU use when passing variables?
A:
When passing variables between methods ... there are no naming conflicts, since the variable is local in each method, the same name in both methods eliminates confusion.
def printIt(num):
print(num)
def f():
num = 2
printIt(num)
A:
I tend to reuse variable names in local functions a lot, as long as they are mid-process. Usually 'result' for a db lookup or a calculation that is used intermediary and is needed to generate or construct the end-result of the method.
Only rarely have I used global variables, in fact only if I must.
A:
Python's scoping rules pretty much free you from the need to use different or identical names for variables just to satisfy language needs.
Variable name choice should be driven primarily by readability and maintainability concerns. In general, it is good to use just one name to identify a particular kind of thing throughout the code. This kind of consistency is helpful to readers. Naming variables, methods, and classes is one of the biggest tools you have to make your intent clear---to both yourself and others.
There is a large (and not entirely consistent) literature about naming things. A couple of things to consider:
Names with small scopes can be short names that do not necessarily tell the whole story about the variable, since the entire context for the variable is easily visible. i,j,k as counters in loops are maybe the classic example---but you don't see that much in Python with its dandy for item in collection loop construct.
The flip side of this is that names with larger scopes (instance variables in a class, maybe) should have more completely descriptive names, since they show up in places where the initialization/modification context is not visible.
Try not to put 'noise' pieces into your names. frequencyInfo---what, exactly does the Info part add to things?
Don't include the data structure type in the name---the dict in urldict doesn't really help you much.
Use names from the domain you are working in when you can, but don't force it.
Python style leans towards terse names. Careful thinking and choices often result in a name that is brief, but apt.
A:
Don't go inventing ways of indicating which method the name belongs to. If you are coding correctly you will won't be treating other methods variables as local. If you have a hanle on method foobar and want its foo value use foobar.foo.
Variable names should indicate contents of the variable and aid in understanding the code. Referring to a foo by a lot of different names because a lot of methods use foos won't help. Your time may be better spent clarifying cases where a foo here is not a foo there. For those cases you problably need to use different terminology in at least one case. Document the case in your code.
Using the same name for the variable will help tracing where you use key objects in your code. You will also have a lot of generic variables which make code easier to understand: i, j, and k for interators; result for result for intermediate results; etc.
A:
You should use the same name when it means the same thing. For example, if you have a database of "cars", you might want to use the name "car" to refer to a single car in every method or function that accepts a car as an argument or works with car objects internally. Doing this, someone reading the code will begin to say to themselves "ok, this is a car" rather than "hmmm, I wonder what type of thing 'foo' is ...".
So, be consistent in using variable names, and that means you can use the same name many times as long as it has the same meaning. If at all possible, never use the same name to mean two different things. For example, don't use "item" to mean a car in one context and a random item from a list in another.
A:
There's no such requirement to give variables different names in different methods or function arguments. In fact, it would greatly hurt readability and go against common sense -- when two things are the same, one tries to give them the same name, not different ones.
| Python: When passing variables between methods, is it necessary to assign it a new name? | I'm thinking that the answer is probably 'no' if the program is small and there are a lot of methods, but what about in a larger program? If I am going to be using one variable in multiple methods throughout the program, is it smarter to:
Come up with a different phrasing for each method (to eliminate naming conflicts).
Use the same name for each method (to eliminate confusion)
Just use a global variable (to eliminate both)
This is more of a stylistic question than anything else. What naming convention do YOU use when passing variables?
| [
"When passing variables between methods ... there are no naming conflicts, since the variable is local in each method, the same name in both methods eliminates confusion.\ndef printIt(num):\n print(num)\n\ndef f():\n num = 2\n printIt(num)\n\n",
"I tend to reuse variable names in local functions a lot, as long as they are mid-process. Usually 'result' for a db lookup or a calculation that is used intermediary and is needed to generate or construct the end-result of the method.\nOnly rarely have I used global variables, in fact only if I must.\n",
"Python's scoping rules pretty much free you from the need to use different or identical names for variables just to satisfy language needs.\nVariable name choice should be driven primarily by readability and maintainability concerns. In general, it is good to use just one name to identify a particular kind of thing throughout the code. This kind of consistency is helpful to readers. Naming variables, methods, and classes is one of the biggest tools you have to make your intent clear---to both yourself and others.\nThere is a large (and not entirely consistent) literature about naming things. A couple of things to consider:\n\nNames with small scopes can be short names that do not necessarily tell the whole story about the variable, since the entire context for the variable is easily visible. i,j,k as counters in loops are maybe the classic example---but you don't see that much in Python with its dandy for item in collection loop construct.\nThe flip side of this is that names with larger scopes (instance variables in a class, maybe) should have more completely descriptive names, since they show up in places where the initialization/modification context is not visible.\nTry not to put 'noise' pieces into your names. frequencyInfo---what, exactly does the Info part add to things?\nDon't include the data structure type in the name---the dict in urldict doesn't really help you much.\nUse names from the domain you are working in when you can, but don't force it.\nPython style leans towards terse names. Careful thinking and choices often result in a name that is brief, but apt.\n\n",
"Don't go inventing ways of indicating which method the name belongs to. If you are coding correctly you will won't be treating other methods variables as local. If you have a hanle on method foobar and want its foo value use foobar.foo. \nVariable names should indicate contents of the variable and aid in understanding the code. Referring to a foo by a lot of different names because a lot of methods use foos won't help. Your time may be better spent clarifying cases where a foo here is not a foo there. For those cases you problably need to use different terminology in at least one case. Document the case in your code.\nUsing the same name for the variable will help tracing where you use key objects in your code. You will also have a lot of generic variables which make code easier to understand: i, j, and k for interators; result for result for intermediate results; etc. \n",
"You should use the same name when it means the same thing. For example, if you have a database of \"cars\", you might want to use the name \"car\" to refer to a single car in every method or function that accepts a car as an argument or works with car objects internally. Doing this, someone reading the code will begin to say to themselves \"ok, this is a car\" rather than \"hmmm, I wonder what type of thing 'foo' is ...\".\nSo, be consistent in using variable names, and that means you can use the same name many times as long as it has the same meaning. If at all possible, never use the same name to mean two different things. For example, don't use \"item\" to mean a car in one context and a random item from a list in another.\n",
"There's no such requirement to give variables different names in different methods or function arguments. In fact, it would greatly hurt readability and go against common sense -- when two things are the same, one tries to give them the same name, not different ones.\n"
] | [
4,
3,
2,
1,
1,
1
] | [] | [] | [
"coding_style",
"methods",
"python"
] | stackoverflow_0002886048_coding_style_methods_python.txt |
Q:
Testing Django Inline ModelForms: How to arrange POST data?
I have a Django 'add business' view which adds a new business with an inline 'business_contact' form.
The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL, postdata)
I've inspected the fields in my browser and tried adding post data with corresponding names, but I still get a 'ManagementForm data is missing or has been tampered with' error when run.
Anyone know of any resources for figuring out how to post inline data?
Relevant models, views & forms below if it helps. Lotsa thanks.
MODEL:
class Contact(models.Model):
""" Contact details for the representatives of each business """
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
business = models.ForeignKey('Business')
slug = models.SlugField(max_length=150, unique=True, help_text=settings.SLUG_HELPER_TEXT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
phone = models.CharField(max_length=100, null=True, blank=True)
mobile_phone = models.CharField(max_length=100, null=True, blank=True)
email = models.EmailField(null=True)
deleted = models.BooleanField(default=False)
class Meta:
db_table='business_contact'
def __unicode__(self):
return '%s %s' % (self.first_name, self.surname)
@models.permalink
def get_absolute_url(self):
return('business_contact', (), {'contact_slug': self.slug })
class Business(models.Model):
""" The business clients who you are selling products/services to """
business = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=100, unique=True, help_text=settings.SLUG_HELPER_TEXT)
description = models.TextField(null=True, blank=True)
primary_contact = models.ForeignKey('Contact', null=True, blank=True, related_name='primary_contact')
business_type = models.ForeignKey('BusinessType')
deleted = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
address_1 = models.CharField(max_length=255, null=True, blank=True)
address_2 = models.CharField(max_length=255, null=True, blank=True)
suburb = models.CharField(max_length=255, null=True, blank=True)
city = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=40, null=True, blank=True)
website = models.URLField(null=True, blank=True)
class Meta:
db_table = 'business'
def __unicode__(self):
return self.business
def get_absolute_url(self):
return '%s%s/' % (settings.BUSINESS_URL, self.slug)
VIEWS:
def business_add(request):
template_name = 'business/business_add.html'
if request.method == 'POST':
form = AddBusinessForm(request.POST)
if form.is_valid():
business = form.save(commit=False)
contact_formset = AddBusinessFormSet(request.POST, instance=business)
if contact_formset.is_valid():
business.save()
contact_formset.save()
contact = Contact.objects.get(id=business.id)
business.primary_contact = contact
business.save()
#return HttpResponse(help(contact))
#business.primary = contact.id
return HttpResponseRedirect(settings.BUSINESS_URL)
else:
contact_formset = AddBusinessFormSet(request.POST)
else:
form = AddBusinessForm()
contact_formset = AddBusinessFormSet(instance=Business())
return render_to_response(
template_name,
{
'form': form,
'contact_formset': contact_formset,
},
context_instance=RequestContext(request)
)
FORMS:
class AddBusinessForm(ModelForm):
class Meta:
model = Business
exclude = ['deleted','primary_contact',]
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ['deleted',]
AddBusinessFormSet = inlineformset_factory(Business,
Contact,
can_delete=False,
extra=1,
form=AddBusinessForm,
)
A:
The problem is you have not included the management form in your data. You need to include form-TOTAL_FORMS (total number of forms in the formset, default is 2), form-INITIAL_FORMS (the initial number of forms in the formset, default is 0) and form-MAX_NUM_FORMS (the maximum number of forms in the formset, default is '').
See the Formset documentation for more information on the management form.
| Testing Django Inline ModelForms: How to arrange POST data? | I have a Django 'add business' view which adds a new business with an inline 'business_contact' form.
The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL, postdata)
I've inspected the fields in my browser and tried adding post data with corresponding names, but I still get a 'ManagementForm data is missing or has been tampered with' error when run.
Anyone know of any resources for figuring out how to post inline data?
Relevant models, views & forms below if it helps. Lotsa thanks.
MODEL:
class Contact(models.Model):
""" Contact details for the representatives of each business """
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
business = models.ForeignKey('Business')
slug = models.SlugField(max_length=150, unique=True, help_text=settings.SLUG_HELPER_TEXT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
phone = models.CharField(max_length=100, null=True, blank=True)
mobile_phone = models.CharField(max_length=100, null=True, blank=True)
email = models.EmailField(null=True)
deleted = models.BooleanField(default=False)
class Meta:
db_table='business_contact'
def __unicode__(self):
return '%s %s' % (self.first_name, self.surname)
@models.permalink
def get_absolute_url(self):
return('business_contact', (), {'contact_slug': self.slug })
class Business(models.Model):
""" The business clients who you are selling products/services to """
business = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=100, unique=True, help_text=settings.SLUG_HELPER_TEXT)
description = models.TextField(null=True, blank=True)
primary_contact = models.ForeignKey('Contact', null=True, blank=True, related_name='primary_contact')
business_type = models.ForeignKey('BusinessType')
deleted = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
address_1 = models.CharField(max_length=255, null=True, blank=True)
address_2 = models.CharField(max_length=255, null=True, blank=True)
suburb = models.CharField(max_length=255, null=True, blank=True)
city = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=40, null=True, blank=True)
website = models.URLField(null=True, blank=True)
class Meta:
db_table = 'business'
def __unicode__(self):
return self.business
def get_absolute_url(self):
return '%s%s/' % (settings.BUSINESS_URL, self.slug)
VIEWS:
def business_add(request):
template_name = 'business/business_add.html'
if request.method == 'POST':
form = AddBusinessForm(request.POST)
if form.is_valid():
business = form.save(commit=False)
contact_formset = AddBusinessFormSet(request.POST, instance=business)
if contact_formset.is_valid():
business.save()
contact_formset.save()
contact = Contact.objects.get(id=business.id)
business.primary_contact = contact
business.save()
#return HttpResponse(help(contact))
#business.primary = contact.id
return HttpResponseRedirect(settings.BUSINESS_URL)
else:
contact_formset = AddBusinessFormSet(request.POST)
else:
form = AddBusinessForm()
contact_formset = AddBusinessFormSet(instance=Business())
return render_to_response(
template_name,
{
'form': form,
'contact_formset': contact_formset,
},
context_instance=RequestContext(request)
)
FORMS:
class AddBusinessForm(ModelForm):
class Meta:
model = Business
exclude = ['deleted','primary_contact',]
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ['deleted',]
AddBusinessFormSet = inlineformset_factory(Business,
Contact,
can_delete=False,
extra=1,
form=AddBusinessForm,
)
| [
"The problem is you have not included the management form in your data. You need to include form-TOTAL_FORMS (total number of forms in the formset, default is 2), form-INITIAL_FORMS (the initial number of forms in the formset, default is 0) and form-MAX_NUM_FORMS (the maximum number of forms in the formset, default is '').\nSee the Formset documentation for more information on the management form.\n"
] | [
3
] | [] | [] | [
"django",
"inline",
"python",
"testing"
] | stackoverflow_0002887464_django_inline_python_testing.txt |
Q:
combine lines from 2 prints to single line and insert into mysql database
Hello everyone i currently have this:
import feedparser
d = feedparser.parse('http://store.steampowered.com/feeds/news.xml')
for i in range(10):
print d.entries[i].title
print d.entries[i].date
How would i go about making it so that the title and date are on the same line? Also it doesn't need to print i just have that in there for testing, i would like to dump this output into a mysql db with the title and date, any help is greatly appreciated!
A:
If you want to print on the same line, just add a comma:
print d.entries[i].title, # <- comma here
print d.entries[i].date
To insert to MySQL, you'd do something like this:
to_db = []
for i in range(10):
to_db.append((d.entries[i].title, d.entries[i].date))
import MySQLdb
conn = MySQLdb.connect(host="localhost",user="me",passwd="pw",db="mydb")
c = conn.cursor()
c.executemany("INSERT INTO mytable (title, date) VALUES (%s, %s)", to_db)
A:
Regarding your actual question: if you want to join two strings with a comma you can use something like this:
print d.entries[i].title + ', ' + str(d.entries[i].date)
Note that I have converted the date to a string using str.
You can also use string formatting instead:
print '%s, %s' % (d.entries[i].title, str(d.entries[i].date))
Or in Python 2.6 or newer use str.format.
But if you want to store this in a database it might be better to use two separate columns instead of combining both values into a single string. You might want to consider adjusting your schema to allow this.
| combine lines from 2 prints to single line and insert into mysql database | Hello everyone i currently have this:
import feedparser
d = feedparser.parse('http://store.steampowered.com/feeds/news.xml')
for i in range(10):
print d.entries[i].title
print d.entries[i].date
How would i go about making it so that the title and date are on the same line? Also it doesn't need to print i just have that in there for testing, i would like to dump this output into a mysql db with the title and date, any help is greatly appreciated!
| [
"If you want to print on the same line, just add a comma:\nprint d.entries[i].title, # <- comma here\nprint d.entries[i].date\n\nTo insert to MySQL, you'd do something like this:\nto_db = []\nfor i in range(10):\n to_db.append((d.entries[i].title, d.entries[i].date))\n\nimport MySQLdb\nconn = MySQLdb.connect(host=\"localhost\",user=\"me\",passwd=\"pw\",db=\"mydb\")\nc = conn.cursor()\nc.executemany(\"INSERT INTO mytable (title, date) VALUES (%s, %s)\", to_db)\n\n",
"Regarding your actual question: if you want to join two strings with a comma you can use something like this:\nprint d.entries[i].title + ', ' + str(d.entries[i].date)\n\nNote that I have converted the date to a string using str.\nYou can also use string formatting instead:\nprint '%s, %s' % (d.entries[i].title, str(d.entries[i].date))\n\nOr in Python 2.6 or newer use str.format.\nBut if you want to store this in a database it might be better to use two separate columns instead of combining both values into a single string. You might want to consider adjusting your schema to allow this.\n"
] | [
2,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002887688_mysql_python.txt |
Q:
Python regex on list
I am trying to build a parser and save the results as an xml file but i have problems..
Would you experts please have a look at my code ?
Traceback :TypeError: expected string or buffer
import urllib2, re
from xml.dom.minidom import Document
from BeautifulSoup import BeautifulSoup as bs
osc = open('OSCTEST.html','r')
oscread = osc.read()
soup=bs(oscread)
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
countries = doc.createElement('countries')
root.appendChild(countries)
findtags1 = re.compile ('<h1 class="title metadata_title content_perceived_text(.*?)`</h1>', re.DOTALL | re.IGNORECASE).findall(soup)
findtags2 = re.compile ('<span class="content_text">(.*?)</span>', re.DOTALL | re.IGNORECASE).findall(soup)
for header in findtags1:
title_elem = doc.createElement('title')
countries.appendChild(title_elem)
header_elem = doc.createTextNode(header)
title_elem.appendChild(header_elem)
for item in findtags2:
art_elem = doc.createElement('artikel')
countries.appendChild(art_elem)
s = item.replace('<P>','')
t = s.replace('</P>','')
text_elem = doc.createTextNode(t)
art_elem.appendChild(text_elem)
print doc.toprettyxml()
A:
It's good that you're trying to using BeautifulSoup to parse HTML but this won't work:
re.compile('<h1 class="title metadata_title content_perceived_text(.*?)`</h1>',
re.DOTALL | re.IGNORECASE).findall(soup)
You're trying to parse a BeautifulSoup object using a regular expression. Instead you should be using the findAll method on the soup, like this:
regex = re.compile('^title metadata_title content_perceived_text', re.IGNORECASE)
for tag in soup.findAll('h1', attrs = { 'class' : regex }):
print tag.contents
If you do actually want to parse the document as text with a regular expression then don't use BeautifulSoup - just read the document into a string and parse that. But I'd suggest you take the time to learn how BeautifulSoup works as this is the preferred way to do it. See the documentation for more details.
| Python regex on list | I am trying to build a parser and save the results as an xml file but i have problems..
Would you experts please have a look at my code ?
Traceback :TypeError: expected string or buffer
import urllib2, re
from xml.dom.minidom import Document
from BeautifulSoup import BeautifulSoup as bs
osc = open('OSCTEST.html','r')
oscread = osc.read()
soup=bs(oscread)
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
countries = doc.createElement('countries')
root.appendChild(countries)
findtags1 = re.compile ('<h1 class="title metadata_title content_perceived_text(.*?)`</h1>', re.DOTALL | re.IGNORECASE).findall(soup)
findtags2 = re.compile ('<span class="content_text">(.*?)</span>', re.DOTALL | re.IGNORECASE).findall(soup)
for header in findtags1:
title_elem = doc.createElement('title')
countries.appendChild(title_elem)
header_elem = doc.createTextNode(header)
title_elem.appendChild(header_elem)
for item in findtags2:
art_elem = doc.createElement('artikel')
countries.appendChild(art_elem)
s = item.replace('<P>','')
t = s.replace('</P>','')
text_elem = doc.createTextNode(t)
art_elem.appendChild(text_elem)
print doc.toprettyxml()
| [
"It's good that you're trying to using BeautifulSoup to parse HTML but this won't work:\nre.compile('<h1 class=\"title metadata_title content_perceived_text(.*?)`</h1>',\n re.DOTALL | re.IGNORECASE).findall(soup)\n\nYou're trying to parse a BeautifulSoup object using a regular expression. Instead you should be using the findAll method on the soup, like this:\nregex = re.compile('^title metadata_title content_perceived_text', re.IGNORECASE)\nfor tag in soup.findAll('h1', attrs = { 'class' : regex }):\n print tag.contents\n\nIf you do actually want to parse the document as text with a regular expression then don't use BeautifulSoup - just read the document into a string and parse that. But I'd suggest you take the time to learn how BeautifulSoup works as this is the preferred way to do it. See the documentation for more details.\n"
] | [
5
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0002887769_parsing_python_xml.txt |
Q:
Random function in Python
How can I use the random function (in Python) to choose a string from a txt list?
i want random from a list :
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
is this code ok ?
A:
> import random
> list_of_strings = open(sys.argv[1]).readlines()
> randomly_chosen_string = random.choice(list_of_strings)
> help(random.choice)
Help on method choice in module random:
choice(self, seq) method of random.Random instance
Choose a random element from a non-empty sequence.
A:
import random
file = open("file.txt", "r")
list = file.readlines()
def getline ():
return list[random.randint(0,(len(list) - 1))]
getline()
| Random function in Python | How can I use the random function (in Python) to choose a string from a txt list?
i want random from a list :
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
is this code ok ?
| [
"> import random\n> list_of_strings = open(sys.argv[1]).readlines()\n> randomly_chosen_string = random.choice(list_of_strings)\n> help(random.choice)\nHelp on method choice in module random:\n\nchoice(self, seq) method of random.Random instance\nChoose a random element from a non-empty sequence.\n\n",
"import random\n\nfile = open(\"file.txt\", \"r\")\nlist = file.readlines()\ndef getline ():\n return list[random.randint(0,(len(list) - 1))]\n\ngetline()\n\n"
] | [
3,
1
] | [] | [] | [
"function",
"python",
"random"
] | stackoverflow_0002886716_function_python_random.txt |
Q:
Object-oriented GUI development in python
Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong...
Basically, what I have is this:
class Lesson(Frame):
def __init__ (self, parent=None):
Frame.__init__(self, parent)
self.pack()
Lesson.make_widgets(self)
def make_widgets(self):
Label(self, text="").pack(side=TOP)
ent = Entry(self)
self.a = randrange(1,10)
self.b = randrange(1,10)
self.expr = choice(["+","-"])
ent.insert(END, str(self.a) + str(self.expr) + str(self.a))
I've broken this down into many little steps and basically, what I'm trying to do right now is insert a default random expression into the first entry widget. When I run this code, I just get a blank Label. Why is that? How can I put a something like "7+7" into the box? If you absolutely need background to the problem, it's question #3 on this link.
http://reed.cs.depaul.edu/lperkovic/csc242/homeworks/Homework8.html
-Thanks for all help in advance.
A:
Do you want to change the Label or the contents of the Entry? I'll assume the latter. The short answer is
ent.delete(0, END)
ent.insert(END, 'stringy thing')
but nothing is going to change in the interface until the Tk() instance mainloop() method is called.
A:
Change the
text=""
in the Label object instantiation to
text="Label Text"
or what ever you want to show as the label.
Next add
ent.pack()
after your ent.insert in your make_widgets method.
| Object-oriented GUI development in python | Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong...
Basically, what I have is this:
class Lesson(Frame):
def __init__ (self, parent=None):
Frame.__init__(self, parent)
self.pack()
Lesson.make_widgets(self)
def make_widgets(self):
Label(self, text="").pack(side=TOP)
ent = Entry(self)
self.a = randrange(1,10)
self.b = randrange(1,10)
self.expr = choice(["+","-"])
ent.insert(END, str(self.a) + str(self.expr) + str(self.a))
I've broken this down into many little steps and basically, what I'm trying to do right now is insert a default random expression into the first entry widget. When I run this code, I just get a blank Label. Why is that? How can I put a something like "7+7" into the box? If you absolutely need background to the problem, it's question #3 on this link.
http://reed.cs.depaul.edu/lperkovic/csc242/homeworks/Homework8.html
-Thanks for all help in advance.
| [
"Do you want to change the Label or the contents of the Entry? I'll assume the latter. The short answer is\nent.delete(0, END)\nent.insert(END, 'stringy thing')\n\nbut nothing is going to change in the interface until the Tk() instance mainloop() method is called.\n",
"Change the \ntext=\"\"\n\nin the Label object instantiation to\ntext=\"Label Text\"\n\nor what ever you want to show as the label. \nNext add\nent.pack()\n\nafter your ent.insert in your make_widgets method.\n"
] | [
0,
0
] | [] | [] | [
"oop",
"python",
"user_interface"
] | stackoverflow_0002886938_oop_python_user_interface.txt |
Q:
Need help/guidance about creating a desktop application with gui
I'm planning to do an Desktop application using Python, to learn some Desktop concepts. I'm going to use GTK or Qt, I still haven't decided which one.
Fact is: I would like to create an application with the possibility to be called from command line, AND using a GUI. So it would be useful for cmd fans, and GUI users as well.
It would be interesting to create a web interface too in the future, so it could be run in a server somewhere using an html interface created with a template language.
I'm thinking about two approaches:
- Creating a "model" (core module, where all the functionality resides) with a simple interface which is called from a desktop/web implementation;
- Creating a "model" with an html interface, and embeb a browser component so I could reuse all the code in both desktop/web scenarios.
My question is: which exactly concepts are involved in this project? What advantages/disadvantages each approach has? Are they possible?
By naming "interface", I'm planning to just do some interfaces.py files with def calls. Is this a bad approach?
I would like to know some book recommendations, or resources to both options - or source code from projects which share the same GUI/cmd/web goals I'm after.
Thanks in advance!
A:
Decoupling the presentation layer from application logic makes it possible!.
You can divide your application into layers, a layer is a reusable portion of code that performs a specific function.
For example, you can divide the application into two or more layers, one layer with the presentation of the application and the other with the model. This allows reuse of the entire model of the application with different implementations of the presentation layer.
The presentation layer contains the components that implement and display the user interface and manage user interaction. This layer includes controls for user input and display, in addition to components that organize user interaction. Can have multiple implementations of the presentation layer technologies such as PyQt4, PyGtk, Html, console, etc.
Why Separating Model Is Useful?
You may wonder why it is important to move as much logic outside the presentation layer and into the model layer. The biggest reason is reuse: logic placed in a model increases the reusability of an application. As applications grow, applications often grow into other realms. Applications may start out as a web application, but some of the functionality may later be moved to a smart client application. Portions of an application may be split between a web site and a web or windows service that runs on a server. In addition, keeping logic helps aid in developing a good design (sometimes code can get sloppier in the UI).
However, there are some caveats to this: it takes a little longer to develop applications when most of the logic resides in the business layer. The reason is this often involves creating several sets of objects (data layer and access code, plus business objects) rather than embedding it in the application. The extra time that it takes to do this can be a turnoff for some managers and project leads, especially because it often requires you to be knowledgeable about object-oriented programming, more than most people are comfortable with.
You can search about N-Layered architectural style on the Internet.
This is a sample application that implements several types of user interfaces, but based on. NET framework, for python is similar.
http://microsoftnlayerapp.codeplex.com/
I am working on a big project based on PyQt4 presentation framework. one of the styles of architecture applied is N-Layers. If you want a simple example based on PyQt4, send me a email.
A:
What about a link to the source?
Having a CLI command and a GUI front-end is really common on unix platforms... The TransmissionBT bit torrent client is a good example of what you plan to do.
| Need help/guidance about creating a desktop application with gui | I'm planning to do an Desktop application using Python, to learn some Desktop concepts. I'm going to use GTK or Qt, I still haven't decided which one.
Fact is: I would like to create an application with the possibility to be called from command line, AND using a GUI. So it would be useful for cmd fans, and GUI users as well.
It would be interesting to create a web interface too in the future, so it could be run in a server somewhere using an html interface created with a template language.
I'm thinking about two approaches:
- Creating a "model" (core module, where all the functionality resides) with a simple interface which is called from a desktop/web implementation;
- Creating a "model" with an html interface, and embeb a browser component so I could reuse all the code in both desktop/web scenarios.
My question is: which exactly concepts are involved in this project? What advantages/disadvantages each approach has? Are they possible?
By naming "interface", I'm planning to just do some interfaces.py files with def calls. Is this a bad approach?
I would like to know some book recommendations, or resources to both options - or source code from projects which share the same GUI/cmd/web goals I'm after.
Thanks in advance!
| [
"Decoupling the presentation layer from application logic makes it possible!.\nYou can divide your application into layers, a layer is a reusable portion of code that performs a specific function.\nFor example, you can divide the application into two or more layers, one layer with the presentation of the application and the other with the model. This allows reuse of the entire model of the application with different implementations of the presentation layer.\nThe presentation layer contains the components that implement and display the user interface and manage user interaction. This layer includes controls for user input and display, in addition to components that organize user interaction. Can have multiple implementations of the presentation layer technologies such as PyQt4, PyGtk, Html, console, etc. \nWhy Separating Model Is Useful?\nYou may wonder why it is important to move as much logic outside the presentation layer and into the model layer. The biggest reason is reuse: logic placed in a model increases the reusability of an application. As applications grow, applications often grow into other realms. Applications may start out as a web application, but some of the functionality may later be moved to a smart client application. Portions of an application may be split between a web site and a web or windows service that runs on a server. In addition, keeping logic helps aid in developing a good design (sometimes code can get sloppier in the UI).\nHowever, there are some caveats to this: it takes a little longer to develop applications when most of the logic resides in the business layer. The reason is this often involves creating several sets of objects (data layer and access code, plus business objects) rather than embedding it in the application. The extra time that it takes to do this can be a turnoff for some managers and project leads, especially because it often requires you to be knowledgeable about object-oriented programming, more than most people are comfortable with.\nYou can search about N-Layered architectural style on the Internet.\nThis is a sample application that implements several types of user interfaces, but based on. NET framework, for python is similar.\nhttp://microsoftnlayerapp.codeplex.com/\nI am working on a big project based on PyQt4 presentation framework. one of the styles of architecture applied is N-Layers. If you want a simple example based on PyQt4, send me a email.\n",
"What about a link to the source?\nHaving a CLI command and a GUI front-end is really common on unix platforms... The TransmissionBT bit torrent client is a good example of what you plan to do.\n"
] | [
1,
1
] | [] | [] | [
"cross_platform",
"gtk",
"python",
"qt"
] | stackoverflow_0002860835_cross_platform_gtk_python_qt.txt |
Q:
Reading a series of input / output in Python
For my app, I need to print out a series of outputs and then accepts inputs from the user. What would be the best way of doing this?
Like:
print '1'
x = raw_input()
print '2'
y = raw_input()
Something like this, but it would go on for at least 10 times. My only concern with doing the above is that it would make up for poor code readability.
How should I do it? Should I create a function like this:
def printOut(string):
print string
Or is there a better way?
A:
First one note: raw_input() takes an optional argument ... a prompt string.
Regarding the broader question, a simplistic approach would be to create a class which defines the elements of your form and provides the functions for their input, validation, and later manipulations or output.
With such a class instances can be created (instantiated), and collected, stored, etc.
Such an approach need not any more complicated than something like:
#!/usr/bin/python
# I use /usr/bin/env python; but making SO's syntax highlighter happy.
class generic_form:
def __init__(self, element_list):
self.form_elements = element_list
self.contents= dict()
def fill_it_in(self):
for prompt in self.form_elements:
self.contents[prompt] = raw_input(prompt)
def get(self, item):
return self.contents[item]
def print_it(self):
for each in self.form_elements:
print each, self.contents[each]
if __name__ == '__main__':
sample_fields = ("Given Name: ",
"Surname: ",
"Date of Birth: ",
"Notes: ")
example = generic_form(sample_fields)
print "Fill in my form:"
example.fill_it_in()
print
print "Please review your input:"
example.print_it()
# store(:%s, %s: %s" % (example.get('Surname: '), \
# example.get('Given Name: '), example.get('Notes: '))
The main code is only a dozen lines long to define a generic form class with input
and output functionality (and a simple get() method for further illustrative purposes).
The rest of this example simply creates an instance and shows how it could be used.
Because my generic_form class is generic, we have to supply a list of field names which are to be filled in. The names are used as both the names of the fields for later access (see the get() method for an example). Personally I wouldn't do it this way, I'd provide a list of short field names and prompts similar to Marcelo's example. However, I wanted this particular example to be a short as possible to get the main point across.
(The comment at the end would be a call to a hypothetical "store()" function to store this for posterity, by the way).
This is the most minimal approach. However, you'd rapidly find that it's far more useful to have a richer class with validation for each field, and separate classes which format and output instances of that in different ways, and different classes for input. "teletype" input (as provided by the Python raw_input() built-in function) is the crudest form (primarily useful for simplicity and for the ability to process files using shell redirection). One could also support input with the GNU readline support (already included as a standard library in Python), curses support (also included), and one could imagine writing some HTML wrapper and CGI code for handling web-based input.
Coupling "raw_input()" and "print" into our class would mean more work if we ever needed or wanted to support any forms of input or output other than "dumb terminal."
If we create a class which only concerns itself with the data to be collected, then it could provide an interface for any other input class to get the list of the prompts with references to "setter" functions (and perhaps a "required" or "optional" flag). Then any instance of any input class could request the list of desired/required inputs for any form ... present the prompts, call the "setter" methods (which return a boolean to indicate if the data supplied was valid), loop over bad inputs on "required" fields, offer to skip "optional" fields, and so on.
Notice that the logic for displaying prompts, accepting responses, relaying those back to the data object via their setter methods, and handling invalid inputs and be the same for many types of forms. All we need is a way for the form to provide the list of prompts and their corresponding validation functions (and we need to ensure that all these validation functions have the same semantics --- taking the same parameters and so on).
Here's an example of separating the input behavior from the storage and validation of the data fields:
#!/usr/bin/env python
class generic_form:
def __init__(self, element_list):
self.hints = list()
for each in element_list:
self.hints.append((each, each, self.store))
self.contents= dict()
def store(self, key, data):
'''Called by client instances
'''
self.contents[key] = data
return True
def get_hints(self):
return self.hints
def get(self, item):
return self.contents[item]
def form_input(form):
for each, key, fn in form.get_hints():
while True:
if fn(key,raw_input(each)):
break
else:
keep_trying = raw_input("Try again:")
if keep_trying.lower() in ['n', 'no', 'naw']:
break
if __name__ == '__main__':
sample_fields = ("Given Name: ",
"Surname: ",
"Date of Birth: ",
"etc: ")
example = generic_form(sample_fields)
print "Fill in my form:"
form_input(example)
print
print "Please review your input:"
for i, x, x in example.get_hints():
print example.get(i),
In this case the extra complication is not doing anything useful. Our generic_form performs no validation. However, this same input function could be used with any data/form class that provided the same interface. That interface, in this example, only requires a get_hints() method providing tuples of "prompt string", storage key, and storage function references, and a store() method which must return "True" or "False" and take arguments for the key and data to be stored.
The fact that our storage key is passed to our input "client" as an opaque item that must be passed back through its calls to our store() method is a bit subtle; but it allows us to use any single validation function for multiple form elements ... all names can be any string, all dates must pass some call to time.strftime() or some third party parser ... and so on.
The main point is that I can create better forms classes which implement data validation methods as appropriate to the data being gathered and stored. The input example will work for our original dumb forms, but it will work better with forms that return meaningful results from our calls to store() (A better interface between forms and input handling might supply "error" and "help" prompts as well as the simple short "input" prompt we show here. A more complex system might pass "datum" objects through the get_hints() methods. That would require that the forms class instantiate such objects and store a list of them instead of the tuples I'm showing here).
Another benefit is that I can also write other input functions (or classes which implement such functions) that can also use this same interface to any form. Thus I could write some HTML rendering and CGI processing which could use all of the forms that had developed with no changes to my data validation semantics.
(In this example I'm using the get_hints() method as hints for my crude output function as well as my inputs. I'm only doing this to keep the example simple. In practice I'd want to separate input hinting from output handling).
A:
If you are reading in several fields, you might want to do something like this:
field_defs = [
('name', 'Name'),
('dob' , 'Date of Birth'),
('sex' , 'Gender'),
#...
]
# Figure out the widest description.
maxlen = max(len(descr) for (name, descr) in field_defs)
fields = {}
for (name, descr) in field_defs:
# Pad to the widest description.
print '%-*s:' % (maxlen, descr),
fields[name] = raw_input()
# You should access the fields directly from the fields variable.
# But if you really want to access the fields as local variables...
locals().update(fields)
print name, dob, sex
A:
"10 times... poor code readability"
Not really. You'll have to provide something more complex than that.
20 lines of code is hardly a problem. You can easily write more than 20 lines of code trying to save yourself from simply writing 20 lines of code.
You should, also, read the description of raw_input. http://docs.python.org/library/functions.html#raw_input
It writes a prompt. Your four lines of code is really
x = raw_input( '1' )
y = raw_input( '2' )
You can't simplify this much more.
| Reading a series of input / output in Python | For my app, I need to print out a series of outputs and then accepts inputs from the user. What would be the best way of doing this?
Like:
print '1'
x = raw_input()
print '2'
y = raw_input()
Something like this, but it would go on for at least 10 times. My only concern with doing the above is that it would make up for poor code readability.
How should I do it? Should I create a function like this:
def printOut(string):
print string
Or is there a better way?
| [
"First one note: raw_input() takes an optional argument ... a prompt string.\nRegarding the broader question, a simplistic approach would be to create a class which defines the elements of your form and provides the functions for their input, validation, and later manipulations or output.\nWith such a class instances can be created (instantiated), and collected, stored, etc.\nSuch an approach need not any more complicated than something like:\n#!/usr/bin/python\n# I use /usr/bin/env python; but making SO's syntax highlighter happy.\n\nclass generic_form:\n def __init__(self, element_list):\n self.form_elements = element_list\n self.contents= dict()\n\n def fill_it_in(self):\n for prompt in self.form_elements:\n self.contents[prompt] = raw_input(prompt)\n\n def get(self, item):\n return self.contents[item]\n\n def print_it(self):\n for each in self.form_elements:\n print each, self.contents[each]\n\nif __name__ == '__main__':\n sample_fields = (\"Given Name: \",\n \"Surname: \",\n \"Date of Birth: \",\n \"Notes: \")\n\n example = generic_form(sample_fields)\n\n print \"Fill in my form:\"\n example.fill_it_in()\n\n print\n print \"Please review your input:\"\n example.print_it()\n\n # store(:%s, %s: %s\" % (example.get('Surname: '), \\\n # example.get('Given Name: '), example.get('Notes: '))\n\nThe main code is only a dozen lines long to define a generic form class with input\nand output functionality (and a simple get() method for further illustrative purposes).\nThe rest of this example simply creates an instance and shows how it could be used.\nBecause my generic_form class is generic, we have to supply a list of field names which are to be filled in. The names are used as both the names of the fields for later access (see the get() method for an example). Personally I wouldn't do it this way, I'd provide a list of short field names and prompts similar to Marcelo's example. However, I wanted this particular example to be a short as possible to get the main point across.\n(The comment at the end would be a call to a hypothetical \"store()\" function to store this for posterity, by the way).\nThis is the most minimal approach. However, you'd rapidly find that it's far more useful to have a richer class with validation for each field, and separate classes which format and output instances of that in different ways, and different classes for input. \"teletype\" input (as provided by the Python raw_input() built-in function) is the crudest form (primarily useful for simplicity and for the ability to process files using shell redirection). One could also support input with the GNU readline support (already included as a standard library in Python), curses support (also included), and one could imagine writing some HTML wrapper and CGI code for handling web-based input.\nCoupling \"raw_input()\" and \"print\" into our class would mean more work if we ever needed or wanted to support any forms of input or output other than \"dumb terminal.\"\nIf we create a class which only concerns itself with the data to be collected, then it could provide an interface for any other input class to get the list of the prompts with references to \"setter\" functions (and perhaps a \"required\" or \"optional\" flag). Then any instance of any input class could request the list of desired/required inputs for any form ... present the prompts, call the \"setter\" methods (which return a boolean to indicate if the data supplied was valid), loop over bad inputs on \"required\" fields, offer to skip \"optional\" fields, and so on.\nNotice that the logic for displaying prompts, accepting responses, relaying those back to the data object via their setter methods, and handling invalid inputs and be the same for many types of forms. All we need is a way for the form to provide the list of prompts and their corresponding validation functions (and we need to ensure that all these validation functions have the same semantics --- taking the same parameters and so on).\nHere's an example of separating the input behavior from the storage and validation of the data fields:\n #!/usr/bin/env python\n\n class generic_form:\n def __init__(self, element_list):\n self.hints = list()\n for each in element_list:\n self.hints.append((each, each, self.store))\n self.contents= dict()\n def store(self, key, data):\n '''Called by client instances\n '''\n self.contents[key] = data\n return True\n\n def get_hints(self):\n return self.hints\n\n def get(self, item):\n return self.contents[item]\n\n\n def form_input(form):\n for each, key, fn in form.get_hints():\n while True:\n if fn(key,raw_input(each)):\n break\n else:\n keep_trying = raw_input(\"Try again:\")\n if keep_trying.lower() in ['n', 'no', 'naw']:\n break\n\n if __name__ == '__main__':\n sample_fields = (\"Given Name: \",\n \"Surname: \",\n \"Date of Birth: \",\n \"etc: \")\n\n example = generic_form(sample_fields)\n\n print \"Fill in my form:\"\n form_input(example)\n\n print\n print \"Please review your input:\"\n for i, x, x in example.get_hints():\n print example.get(i),\n\nIn this case the extra complication is not doing anything useful. Our generic_form performs no validation. However, this same input function could be used with any data/form class that provided the same interface. That interface, in this example, only requires a get_hints() method providing tuples of \"prompt string\", storage key, and storage function references, and a store() method which must return \"True\" or \"False\" and take arguments for the key and data to be stored.\nThe fact that our storage key is passed to our input \"client\" as an opaque item that must be passed back through its calls to our store() method is a bit subtle; but it allows us to use any single validation function for multiple form elements ... all names can be any string, all dates must pass some call to time.strftime() or some third party parser ... and so on.\nThe main point is that I can create better forms classes which implement data validation methods as appropriate to the data being gathered and stored. The input example will work for our original dumb forms, but it will work better with forms that return meaningful results from our calls to store() (A better interface between forms and input handling might supply \"error\" and \"help\" prompts as well as the simple short \"input\" prompt we show here. A more complex system might pass \"datum\" objects through the get_hints() methods. That would require that the forms class instantiate such objects and store a list of them instead of the tuples I'm showing here).\nAnother benefit is that I can also write other input functions (or classes which implement such functions) that can also use this same interface to any form. Thus I could write some HTML rendering and CGI processing which could use all of the forms that had developed with no changes to my data validation semantics.\n(In this example I'm using the get_hints() method as hints for my crude output function as well as my inputs. I'm only doing this to keep the example simple. In practice I'd want to separate input hinting from output handling).\n",
"If you are reading in several fields, you might want to do something like this:\nfield_defs = [\n ('name', 'Name'),\n ('dob' , 'Date of Birth'),\n ('sex' , 'Gender'),\n #...\n ]\n\n# Figure out the widest description. \nmaxlen = max(len(descr) for (name, descr) in field_defs)\n\nfields = {}\nfor (name, descr) in field_defs:\n # Pad to the widest description.\n print '%-*s:' % (maxlen, descr),\n fields[name] = raw_input()\n\n# You should access the fields directly from the fields variable.\n# But if you really want to access the fields as local variables...\nlocals().update(fields)\n\nprint name, dob, sex\n\n",
"\n\"10 times... poor code readability\" \n\nNot really. You'll have to provide something more complex than that. \n20 lines of code is hardly a problem. You can easily write more than 20 lines of code trying to save yourself from simply writing 20 lines of code.\nYou should, also, read the description of raw_input. http://docs.python.org/library/functions.html#raw_input\nIt writes a prompt. Your four lines of code is really\nx = raw_input( '1' )\ny = raw_input( '2' )\n\nYou can't simplify this much more.\n"
] | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002887767_python.txt |
Q:
Where is a good place/way to store Windows config files for Python scripts?
I have a script/program I am working on that requires a configuration file (I am using ConfigParser). On linux, I will default to store these variables in ~/.myscript using the os.getenv('HOME') function.
With Windows, I know I can use os.getenv('USERPROFILE') to find the User's "home" directory, however, is it a good idea to save a hidden file that way (ie, with the name .myscript)?
I don't use Windows, obviously, but wanted to be smart about it for those who do.
Is there a standard place/way to store these config variables on Windows?
A:
os.environ['AppData']
It's usual to create a folder inside with your organisation name and put any files inside that. There's no need to ‘hide’ the files, and . at the start of a filename isn't valid in Windows.
Or put the settings in the registry.
| Where is a good place/way to store Windows config files for Python scripts? | I have a script/program I am working on that requires a configuration file (I am using ConfigParser). On linux, I will default to store these variables in ~/.myscript using the os.getenv('HOME') function.
With Windows, I know I can use os.getenv('USERPROFILE') to find the User's "home" directory, however, is it a good idea to save a hidden file that way (ie, with the name .myscript)?
I don't use Windows, obviously, but wanted to be smart about it for those who do.
Is there a standard place/way to store these config variables on Windows?
| [
"os.environ['AppData']\n\nIt's usual to create a folder inside with your organisation name and put any files inside that. There's no need to ‘hide’ the files, and . at the start of a filename isn't valid in Windows.\nOr put the settings in the registry.\n"
] | [
2
] | [] | [] | [
"configparser",
"configuration",
"python",
"windows"
] | stackoverflow_0002888100_configparser_configuration_python_windows.txt |
Q:
Django Import Error with URLS and ROOT_URLCONF confusion
In httpd conf,
<VirtualHost *:8080>
ServerName tweet_search_engine
DocumentRoot /var/www/microblogsearchengine/twingle
</VirtualHost>
<Directory /var/www/microblogsearchengine/twingle>
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /var/www/microbloggingsearchengine/twingle
PythonDebug On
</Directory>
Running python manage.py runserver and visiting localhost:8000 returns a splash page telling me everything is okay. However when I visit this site through apache, I get an import error with urls.
In my settings.py file I have a line,
ROOT_URLCONF = 'twingle.urls'
I'm assuming this is the cause of the error. The project folder contains only 4 files:
__init__.py manage.py settings.py urls.py
I tried replacing twingle.urls with urls.py but then it gave me a different error. What is it I can do to get this working?
A:
Typo in your PythonOption line:
django.rooti instead of django.root
Furthermore you might have to add something like this inside your Directory section:
PythonPath "['/var/www/microbloggingsearchengine','/var/www/microbloggingsearchengine/twingle'] + sys.path"
| Django Import Error with URLS and ROOT_URLCONF confusion | In httpd conf,
<VirtualHost *:8080>
ServerName tweet_search_engine
DocumentRoot /var/www/microblogsearchengine/twingle
</VirtualHost>
<Directory /var/www/microblogsearchengine/twingle>
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /var/www/microbloggingsearchengine/twingle
PythonDebug On
</Directory>
Running python manage.py runserver and visiting localhost:8000 returns a splash page telling me everything is okay. However when I visit this site through apache, I get an import error with urls.
In my settings.py file I have a line,
ROOT_URLCONF = 'twingle.urls'
I'm assuming this is the cause of the error. The project folder contains only 4 files:
__init__.py manage.py settings.py urls.py
I tried replacing twingle.urls with urls.py but then it gave me a different error. What is it I can do to get this working?
| [
"Typo in your PythonOption line:\ndjango.rooti instead of django.root\nFurthermore you might have to add something like this inside your Directory section:\nPythonPath \"['/var/www/microbloggingsearchengine','/var/www/microbloggingsearchengine/twingle'] + sys.path\"\n\n"
] | [
3
] | [] | [] | [
"django",
"python",
"url"
] | stackoverflow_0002888179_django_python_url.txt |
Q:
Django - markup parser in template or view?
I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python.
Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like:
return render_to_response( 'blog/post.html', {'post': post,
'content': parseMyMarkup(post.content) })
Is this the usual convention, or should I do something different?
A:
The general rule for deciding whether or not to place your code in the view or the template is this:
If your code is going to modify the
data, put it into the view. If your
code will only effect the display of
the data, put it into the template.
I'm not very familiar with the markup formatting, but if you are going to be performing substitution (eg: **word** becomes <b>word</b>), then I'd put it into the view as it will be modifying your data.
Hope that helps!
| Django - markup parser in template or view? | I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python.
Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like:
return render_to_response( 'blog/post.html', {'post': post,
'content': parseMyMarkup(post.content) })
Is this the usual convention, or should I do something different?
| [
"The general rule for deciding whether or not to place your code in the view or the template is this:\n\nIf your code is going to modify the\n data, put it into the view. If your\n code will only effect the display of\n the data, put it into the template.\n\nI'm not very familiar with the markup formatting, but if you are going to be performing substitution (eg: **word** becomes <b>word</b>), then I'd put it into the view as it will be modifying your data.\nHope that helps!\n"
] | [
3
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0002888142_django_django_templates_django_views_python.txt |
Q:
Getting two characters from string in python
how to get in python from string not one character, but two?
I have:
long_str = 'abcd'
for c in long_str:
print c
and it gives me like
a
b
c
d
but i need to get
ab
cd
I'm new in python.. is there any way?
A:
You can use slice notation. long_str[x:y] will give you characters in the range [x, y) (where x is included and y is not).
>>> for i in range(0, len(long_str) - 1, 2):
... print long_str[i:i+2]
...
ab
cd
Here I am using the three-argument range operator to denote start, end, and step (see http://docs.python.org/library/functions.html).
Note that for a string of odd length, this will not take the last character. If you want the last character by itself, change the second argument of range to len(long_str).
A:
for i, j in zip(long_str[::2], long_str[1::2]):
print (i+j)
or
import operator
for s in map(operator.add, long_str[::2], long_str[1::2]):
print (s)
itertools also provide a generalized implementation of this:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
| Getting two characters from string in python | how to get in python from string not one character, but two?
I have:
long_str = 'abcd'
for c in long_str:
print c
and it gives me like
a
b
c
d
but i need to get
ab
cd
I'm new in python.. is there any way?
| [
"You can use slice notation. long_str[x:y] will give you characters in the range [x, y) (where x is included and y is not).\n>>> for i in range(0, len(long_str) - 1, 2):\n... print long_str[i:i+2]\n... \nab\ncd\n\nHere I am using the three-argument range operator to denote start, end, and step (see http://docs.python.org/library/functions.html).\nNote that for a string of odd length, this will not take the last character. If you want the last character by itself, change the second argument of range to len(long_str).\n",
"for i, j in zip(long_str[::2], long_str[1::2]):\n print (i+j)\n\nor\nimport operator\nfor s in map(operator.add, long_str[::2], long_str[1::2]):\n print (s)\n\n\nitertools also provide a generalized implementation of this:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\n"
] | [
13,
7
] | [] | [] | [
"character",
"for_loop",
"loops",
"python"
] | stackoverflow_0002888281_character_for_loop_loops_python.txt |
Q:
information hiding in python
in python tutorial added that python cannot hide its attributes from other classes. some thing such as private data in C++ or java..But also i know that we can use _ or __ to set some variables as privated one but it is not enogh. I think it is a weak if it is not any thing to do it.
A:
Data encapsulation in Python is enforced by convention and peer review. Surprisingly, having every attribute effectively be public hasn't caused a problem for the majority of Python programmers.
A:
Using an underscore at the start of the name for an element or a method signals to the reader that what they're looking at is "internal implementation details". If they want to use that, they can, but it is very likely that a new version of the class will not preserve the API for internal-only method or elements (eh, "slots", I guess, the instance variables).
By having compiler-enforced guarantees as to what is and isn't visible, you are more sure that external parties are not looking at the internal bits, but even in C++ it is not that hard to access private things.
In practice, as long as you trust people not to do stupid things there's no problem having "this is internal, don't touch" as a polite reminder rather than enforced.
A:
This is part of Python's philosophy. It basically trusts you to be sensible and exercise caution with anything that starts with an underscore. If you really want to hide state so no one can touch it, you can do this:
def fort_knox():
# A very private variable
gold = [0]
class impl(object):
def add_gold(self, amt):
gold[0] += amt
def remove_gold(self, amt):
raise Exception('No withdrawals!')
def count_gold(self):
return gold[0]
return impl()
A:
You are right that the _foo convention isn't sufficient to make data private; it's not supposed to be! Information hiding is not part of the design of Python. When writing programs in Python, you depend on the caller's good manners to leave your internals alone based on the naming convention and your documentation. Don't try to exert more control than this; we're all consenting adults.
There is a convention of naming internal-use methods like _foo with a single leading underscore; this serves more documentation purposes than anything else. Python name-mangles __foo attributes. Some people think this makes them more private, but it doesn't make them at all private, though it does make your classes harder to use, extend, and test. I never use them.
| information hiding in python | in python tutorial added that python cannot hide its attributes from other classes. some thing such as private data in C++ or java..But also i know that we can use _ or __ to set some variables as privated one but it is not enogh. I think it is a weak if it is not any thing to do it.
| [
"Data encapsulation in Python is enforced by convention and peer review. Surprisingly, having every attribute effectively be public hasn't caused a problem for the majority of Python programmers.\n",
"Using an underscore at the start of the name for an element or a method signals to the reader that what they're looking at is \"internal implementation details\". If they want to use that, they can, but it is very likely that a new version of the class will not preserve the API for internal-only method or elements (eh, \"slots\", I guess, the instance variables).\nBy having compiler-enforced guarantees as to what is and isn't visible, you are more sure that external parties are not looking at the internal bits, but even in C++ it is not that hard to access private things.\nIn practice, as long as you trust people not to do stupid things there's no problem having \"this is internal, don't touch\" as a polite reminder rather than enforced.\n",
"This is part of Python's philosophy. It basically trusts you to be sensible and exercise caution with anything that starts with an underscore. If you really want to hide state so no one can touch it, you can do this:\ndef fort_knox():\n # A very private variable\n gold = [0]\n\n class impl(object):\n def add_gold(self, amt):\n gold[0] += amt\n\n def remove_gold(self, amt):\n raise Exception('No withdrawals!')\n\n def count_gold(self):\n return gold[0]\n\n return impl()\n\n",
"You are right that the _foo convention isn't sufficient to make data private; it's not supposed to be! Information hiding is not part of the design of Python. When writing programs in Python, you depend on the caller's good manners to leave your internals alone based on the naming convention and your documentation. Don't try to exert more control than this; we're all consenting adults.\nThere is a convention of naming internal-use methods like _foo with a single leading underscore; this serves more documentation purposes than anything else. Python name-mangles __foo attributes. Some people think this makes them more private, but it doesn't make them at all private, though it does make your classes harder to use, extend, and test. I never use them.\n"
] | [
4,
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002888035_python.txt |
Q:
Huffman coding two characters as one
I need huffman code(best in python or in java), which could encode text not by one character (a = 10, b = 11), but by two (ab = 11, ag = 10). Is it possible and if yes, where could i find it, maybe it's somewhere in the internet and i just can'd find it?
A:
Huffman code doesn't care about characters, it cares about symbols. Generally, it is used to encode the alphabet / other single characters, but can very easily be generalized to encode strings of characters. Basically, you would just take an existing implementation and allow symbols to be strings rather than characters. A leaf node would then correspond to a list of strings.
A:
There's a Huffman encoder example distributed with the Python bitarray module, if that's any use to you.
A:
There is probably some code somewhere. But this sounds like a parsing and tokenising question. One of the first questions I would be answering is how many unique pairs are you dealing with. Huffman encoding works best with small numbers of tokens. For example, the 101 characters on your keyboard. But if your two characters can be anything, you are now expanding the maximum number of characters massively.
| Huffman coding two characters as one | I need huffman code(best in python or in java), which could encode text not by one character (a = 10, b = 11), but by two (ab = 11, ag = 10). Is it possible and if yes, where could i find it, maybe it's somewhere in the internet and i just can'd find it?
| [
"Huffman code doesn't care about characters, it cares about symbols. Generally, it is used to encode the alphabet / other single characters, but can very easily be generalized to encode strings of characters. Basically, you would just take an existing implementation and allow symbols to be strings rather than characters. A leaf node would then correspond to a list of strings.\n",
"There's a Huffman encoder example distributed with the Python bitarray module, if that's any use to you.\n",
"There is probably some code somewhere. But this sounds like a parsing and tokenising question. One of the first questions I would be answering is how many unique pairs are you dealing with. Huffman encoding works best with small numbers of tokens. For example, the 101 characters on your keyboard. But if your two characters can be anything, you are now expanding the maximum number of characters massively.\n"
] | [
6,
1,
0
] | [] | [] | [
"huffman_code",
"java",
"python"
] | stackoverflow_0002888468_huffman_code_java_python.txt |
Q:
sqlite3.OperationalError
The "python manage.py syncdb" command is giving me the following error:
sqlite3.OperationalError: unable to open database file
I'm following the step by step instructions in Practical Django Projects, so I think this has to do something with the Windows Operating system acting quirky!
Things I've checkde:
1.The path is updated in settings.py is absolutely correcto!
2. Path is : C:\Documents and Settings\fixavier\Desktop\Django\Database\cms\cms.txt
So the entire folder - Database, has sharing and security permissions.
I'm pretty much at the bottom of the ocean for not being able to follow and successfully execute simple instructions, so could you please help me out here!
A:
You haven't shown exactly how the path is represented in your settings.py file. But if you've done it how you show here, it won't work. You need to use forward slashes (/) or double backwards slashes (\\).
This is because in Python a backslash usually means to escape the following character.
| sqlite3.OperationalError | The "python manage.py syncdb" command is giving me the following error:
sqlite3.OperationalError: unable to open database file
I'm following the step by step instructions in Practical Django Projects, so I think this has to do something with the Windows Operating system acting quirky!
Things I've checkde:
1.The path is updated in settings.py is absolutely correcto!
2. Path is : C:\Documents and Settings\fixavier\Desktop\Django\Database\cms\cms.txt
So the entire folder - Database, has sharing and security permissions.
I'm pretty much at the bottom of the ocean for not being able to follow and successfully execute simple instructions, so could you please help me out here!
| [
"You haven't shown exactly how the path is represented in your settings.py file. But if you've done it how you show here, it won't work. You need to use forward slashes (/) or double backwards slashes (\\\\).\nThis is because in Python a backslash usually means to escape the following character.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002888326_django_python.txt |
Q:
Do something every 3 loops in django-templates?
I wanna make change in css class every 3 loops. In the first three I want to use the CSS class A, in the next three I want to use the CSS class B, in the next three I want to use the CSS class A again and so on.
can anyone help? Thanks
A:
{% cycle "A" "A" "A" "B" "B" "B" %}
| Do something every 3 loops in django-templates? | I wanna make change in css class every 3 loops. In the first three I want to use the CSS class A, in the next three I want to use the CSS class B, in the next three I want to use the CSS class A again and so on.
can anyone help? Thanks
| [
"{% cycle \"A\" \"A\" \"A\" \"B\" \"B\" \"B\" %}\n\n"
] | [
3
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002888598_django_django_templates_python.txt |
Q:
how to pass in dynamic data to decorators
I am trying to write a base crud controller class that does the
following:
class BaseCrudController:
model = ""
field_validation = {}
template_dir = ""
@expose(self.template_dir)
def new(self, *args, **kwargs)
....
@validate(self.field_validation, error_handler=new)
@expose()
def post(self, *args, **kwargs):
...
My intent is to have my controllers extend this base class, set the
model, field_validation, and template locations, and am ready to go.
Unfortunately, decorators (to my understanding), are interpreted when
the function is defined. Hence it won't have access to instance's
value. Is there a way to pass in dynamic data or values from the sub
class?
For example:
class AddressController(BaseCrudController):
model = Address
template_dir = "addressbook.templates.addresses"
When I try to load AddressController, it says "self is not defined". I am assuming that the base class is evaluating the decorator before the sub class is initialized.
Thanks,
Steve
A:
Perhaps using a factory to create the class would be better than subclassing:
def CrudControllerFactory(model, field_validation, template_dir):
class BaseCrudController:
@expose(template_dir)
def new(self, *args, **kwargs)
....
@validate(field_validation, error_handler=new)
@expose()
def post(self, *args, **kwargs):
....
return BaseCrudController
A:
Unfortunately, decorators (to my
understanding), are interpreted when
the function is defined. Hence it
won't have access to instance's value.
Is there a way to pass in dynamic data
or values from the sub class?
The template needs to be called with the name of the relevant attribute; the wrapper can then get that attribute's value dynamically. For example:
import functools
def expose(attname=None):
if attname:
def makewrapper(f):
@functools.wraps(f)
def wrapper(self, *a, **k):
attvalue = getattr(self, attname, None)
...use attvalue as needed...
return wrapper
return makewrapper
else:
...same but without the getattr...
Note that the complication is only because, judging from the code snippets in your Q, you want to allow the expose decorator to be used both with and without an argument (you could move the if attname guard to live within wrapper, but then you'd uselessly repeat the check at each call -- the code within wrapper may also need to be pretty different in the two cases, I imagine -- so, shoehorning two different control flows into one wrapper may be even more complicated). BTW, this is a dubious design decision, IMHO. But, it's quite separate from your actual Q about "dynamic data".
The point is, by using the attribute name as the argument, you empower your decorator to fetch the value dynamically "just in time" when it's needed. Think of it as "an extra level of indirection", that well-known panacea for all difficulties in programming!-)
| how to pass in dynamic data to decorators | I am trying to write a base crud controller class that does the
following:
class BaseCrudController:
model = ""
field_validation = {}
template_dir = ""
@expose(self.template_dir)
def new(self, *args, **kwargs)
....
@validate(self.field_validation, error_handler=new)
@expose()
def post(self, *args, **kwargs):
...
My intent is to have my controllers extend this base class, set the
model, field_validation, and template locations, and am ready to go.
Unfortunately, decorators (to my understanding), are interpreted when
the function is defined. Hence it won't have access to instance's
value. Is there a way to pass in dynamic data or values from the sub
class?
For example:
class AddressController(BaseCrudController):
model = Address
template_dir = "addressbook.templates.addresses"
When I try to load AddressController, it says "self is not defined". I am assuming that the base class is evaluating the decorator before the sub class is initialized.
Thanks,
Steve
| [
"Perhaps using a factory to create the class would be better than subclassing:\ndef CrudControllerFactory(model, field_validation, template_dir):\n class BaseCrudController:\n @expose(template_dir)\n def new(self, *args, **kwargs)\n ....\n\n @validate(field_validation, error_handler=new)\n @expose()\n def post(self, *args, **kwargs):\n ....\n\n return BaseCrudController\n\n",
"\nUnfortunately, decorators (to my\n understanding), are interpreted when\n the function is defined. Hence it\n won't have access to instance's value.\n Is there a way to pass in dynamic data\n or values from the sub class?\n\nThe template needs to be called with the name of the relevant attribute; the wrapper can then get that attribute's value dynamically. For example:\nimport functools\n\ndef expose(attname=None):\n if attname:\n def makewrapper(f):\n @functools.wraps(f)\n def wrapper(self, *a, **k):\n attvalue = getattr(self, attname, None)\n ...use attvalue as needed...\n return wrapper\n return makewrapper\n else:\n ...same but without the getattr...\n\nNote that the complication is only because, judging from the code snippets in your Q, you want to allow the expose decorator to be used both with and without an argument (you could move the if attname guard to live within wrapper, but then you'd uselessly repeat the check at each call -- the code within wrapper may also need to be pretty different in the two cases, I imagine -- so, shoehorning two different control flows into one wrapper may be even more complicated). BTW, this is a dubious design decision, IMHO. But, it's quite separate from your actual Q about \"dynamic data\".\nThe point is, by using the attribute name as the argument, you empower your decorator to fetch the value dynamically \"just in time\" when it's needed. Think of it as \"an extra level of indirection\", that well-known panacea for all difficulties in programming!-)\n"
] | [
1,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002884771_decorator_python.txt |
Q:
How to Redirect a Python Console output to a QTextBox
I'm working on developing a GUI for the recompilation of Linux kernel. For this I need to implement 4-5 Linux commands from Python. I use Qt as GUI designer. I have successfully implemented the commands using os.system() call. But the output is obtained at the console. The real problem is the output of command is a listing that takes almost 20-25 min continuous printing. How we can transfer this console output to a text box designed in Qt. Can any one help me to implement the setSource() operation in Qt using source as the live console outputs.
A:
self.process = QProcess()
self.connect(self.process, SIGNAL("readyReadStdout()"), self.readOutput)
self.connect(self.process, SIGNAL("readyReadStderr()"), self.readErrors)
tarsourcepath="sudo tar xvpf "+ self.path1
self.process.setArguments(QStringList.split(" ",tarsourcepath))
self.process.start()
def readOutput(self):
self.textBrowser2.append(QString(self.process.readStdout()))
if self.process.isRunning()==False:
self.textBrowser2.append("\n Completed Successfully")
def readErrors(self):
self.textBrowser2.append("error: " + QString(self.process.readLineStderr()))
This did the work quite good for me. thank you all.
A:
I mostly deal with wxPython, but is http://diotavelli.net/PyQtWiki/Capturing_Output_from_a_Process a solution that would work?
From the page:
Problem: You want to run a process
that prints lots of information to the
console and display the output in a
text editor or browser, but the result
is a GUI that freezes until the
process is finished.
Solution (one of many possible):
Create a QProcess object, connect its
signals to some slots in your class,
pass it the required arguments and
start it. Data on the process's stdout
and stderr is delivered to your slots.
continued...
A:
Using a pipe comes to mind. You could use a background thread that reads the output of the program (and sends events to the GUI whenever a new line is added).
So the basic idea is this:
os.chdir("/usr/src/linux-2.6.34")
p = os.popen("make", "r")
try:
while True:
line = p.readline()
if not line:
break
# Replace this with a GUI update event (don't know anything about Qt, sorry)
print line
finally:
# Cf. http://docs.python.org/library/os.html#os.popen
programReturnValue = p.close() or 0
| How to Redirect a Python Console output to a QTextBox | I'm working on developing a GUI for the recompilation of Linux kernel. For this I need to implement 4-5 Linux commands from Python. I use Qt as GUI designer. I have successfully implemented the commands using os.system() call. But the output is obtained at the console. The real problem is the output of command is a listing that takes almost 20-25 min continuous printing. How we can transfer this console output to a text box designed in Qt. Can any one help me to implement the setSource() operation in Qt using source as the live console outputs.
| [
"self.process = QProcess()\nself.connect(self.process, SIGNAL(\"readyReadStdout()\"), self.readOutput)\nself.connect(self.process, SIGNAL(\"readyReadStderr()\"), self.readErrors)\ntarsourcepath=\"sudo tar xvpf \"+ self.path1\nself.process.setArguments(QStringList.split(\" \",tarsourcepath))\nself.process.start()\n\n\n\ndef readOutput(self):\n\n self.textBrowser2.append(QString(self.process.readStdout()))\n if self.process.isRunning()==False:\n self.textBrowser2.append(\"\\n Completed Successfully\")\n\n\n\n\ndef readErrors(self):\n self.textBrowser2.append(\"error: \" + QString(self.process.readLineStderr()))\n\nThis did the work quite good for me. thank you all.\n",
"I mostly deal with wxPython, but is http://diotavelli.net/PyQtWiki/Capturing_Output_from_a_Process a solution that would work?\nFrom the page:\n\nProblem: You want to run a process\n that prints lots of information to the\n console and display the output in a\n text editor or browser, but the result\n is a GUI that freezes until the\n process is finished.\nSolution (one of many possible):\n Create a QProcess object, connect its\n signals to some slots in your class,\n pass it the required arguments and\n start it. Data on the process's stdout\n and stderr is delivered to your slots.\ncontinued...\n\n",
"Using a pipe comes to mind. You could use a background thread that reads the output of the program (and sends events to the GUI whenever a new line is added).\nSo the basic idea is this:\nos.chdir(\"/usr/src/linux-2.6.34\")\n\np = os.popen(\"make\", \"r\")\ntry:\n while True:\n line = p.readline()\n if not line:\n break\n\n # Replace this with a GUI update event (don't know anything about Qt, sorry)\n print line\nfinally:\n # Cf. http://docs.python.org/library/os.html#os.popen\n programReturnValue = p.close() or 0\n\n"
] | [
7,
1,
0
] | [] | [] | [
"console",
"python",
"qwidget",
"redirect"
] | stackoverflow_0002859256_console_python_qwidget_redirect.txt |
Q:
Python handwriting recognition software?
Is there a Python handwriting recognition library? What are the inputs to hand writing recognition packages, .jpg images? .pdf images?
A:
Zinnia is a C/C++ library with SWIG generated wrappers for Perl/Python/Ruby. It has a BSD license and converts user pen strokes provided as coordinates into character best matches. It also has a training module.
It looks like it performs single character recognition, so you might need to build something on top of it to improve the results.
PenCommander from PhatWare is a commercial, non-Python, Windows-only SDK. If you can live with all of those limitations, PhatWare products are the best handwriting recognition products that I've found so far, although I haven't been looking that hard since the Microsoft's digital ink for the Tablet PC came out. I'm still saving for the Tablet PC though :-(
| Python handwriting recognition software? | Is there a Python handwriting recognition library? What are the inputs to hand writing recognition packages, .jpg images? .pdf images?
| [
"Zinnia is a C/C++ library with SWIG generated wrappers for Perl/Python/Ruby. It has a BSD license and converts user pen strokes provided as coordinates into character best matches. It also has a training module.\nIt looks like it performs single character recognition, so you might need to build something on top of it to improve the results.\nPenCommander from PhatWare is a commercial, non-Python, Windows-only SDK. If you can live with all of those limitations, PhatWare products are the best handwriting recognition products that I've found so far, although I haven't been looking that hard since the Microsoft's digital ink for the Tablet PC came out. I'm still saving for the Tablet PC though :-(\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002888613_python.txt |
Q:
Help Me: Loading Qt dialogs from python Scripts
im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window)
from qt import *
from dialogselectkernelfile import *
from formcopyextract import *
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = DialogSelectKernelFile()
f.show()
app.setMainWidget(f)
app.exec_loop()
main dialog opens on running. i have a set of back,Next,Cancel buttons pusing on each should open the next or previous dialogs. i use the pyuic compiler to source translation.how can i do this from python. please reply i`m running out of time.i dont know how to load another dialog from a signal of push button in another dialog. Help me pls
Thanks a Lot
A:
Are you connecting the button click signals to handler functions?
If you are able to get one dialog to open, getting the other dialogs to open should be as simple as instantiating the new dialog and calling the .show() method in the first dialog's button handler.
Maybe you could upload your code somewhere so we can see more of it. What you have above doesn't really help much.
A:
def displayNextForm(self):
self.close()
self.extr=FormMakeImage(self,"FormMakeImage",1,Qt.WStyle_DialogBorder)
self.extr.exec_loop()
def displayPrevForm(self):
from DialogSelectFile import *
self.close()
self.ext=DialogSelectKernelFile(self,"SelectKernel",1,Qt.WStyle_DialogBorder)
self.ext.exec_loop()
This did work smooth. I was able to implement the Next back feature. Possible warnings are occuring on Imports. but no problem on running.
Thanks all
| Help Me: Loading Qt dialogs from python Scripts | im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window)
from qt import *
from dialogselectkernelfile import *
from formcopyextract import *
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = DialogSelectKernelFile()
f.show()
app.setMainWidget(f)
app.exec_loop()
main dialog opens on running. i have a set of back,Next,Cancel buttons pusing on each should open the next or previous dialogs. i use the pyuic compiler to source translation.how can i do this from python. please reply i`m running out of time.i dont know how to load another dialog from a signal of push button in another dialog. Help me pls
Thanks a Lot
| [
"Are you connecting the button click signals to handler functions?\nIf you are able to get one dialog to open, getting the other dialogs to open should be as simple as instantiating the new dialog and calling the .show() method in the first dialog's button handler.\nMaybe you could upload your code somewhere so we can see more of it. What you have above doesn't really help much.\n",
"def displayNextForm(self): \n self.close()\n self.extr=FormMakeImage(self,\"FormMakeImage\",1,Qt.WStyle_DialogBorder)\n self.extr.exec_loop()\ndef displayPrevForm(self):\n from DialogSelectFile import *\n self.close()\n self.ext=DialogSelectKernelFile(self,\"SelectKernel\",1,Qt.WStyle_DialogBorder)\n self.ext.exec_loop()\n\nThis did work smooth. I was able to implement the Next back feature. Possible warnings are occuring on Imports. but no problem on running.\n Thanks all\n"
] | [
0,
0
] | [] | [] | [
"dialog",
"editing",
"python",
"qt",
"signals"
] | stackoverflow_0002844365_dialog_editing_python_qt_signals.txt |
Q:
What framework is trac based on?
I just downloaded this tracking system and curious what framework this great system uses?
A:
Trac does not use any overarching external "framework". You can see its complete list of external dependencies (beyond a Python interpreter itself) in the setup.py file from the distribution:
install_requires = [
'setuptools>=0.6b1',
'Genshi>=0.6',
],
extras_require = {
'Babel': ['Babel>=0.9.5'],
'Pygments': ['Pygments>=0.6'],
'reST': ['docutils>=0.3'],
'SilverCity': ['SilverCity>=0.9.4'],
'Textile': ['textile>=2.0'],
},
If you're particularly interested in the HTTP side of things, take a look at the source to the trac.web module.
| What framework is trac based on? | I just downloaded this tracking system and curious what framework this great system uses?
| [
"Trac does not use any overarching external \"framework\". You can see its complete list of external dependencies (beyond a Python interpreter itself) in the setup.py file from the distribution:\n install_requires = [\n 'setuptools>=0.6b1',\n 'Genshi>=0.6',\n ],\n extras_require = {\n 'Babel': ['Babel>=0.9.5'],\n 'Pygments': ['Pygments>=0.6'],\n 'reST': ['docutils>=0.3'],\n 'SilverCity': ['SilverCity>=0.9.4'],\n 'Textile': ['textile>=2.0'],\n },\n\nIf you're particularly interested in the HTTP side of things, take a look at the source to the trac.web module.\n"
] | [
9
] | [] | [] | [
"frameworks",
"python",
"trac"
] | stackoverflow_0002888879_frameworks_python_trac.txt |
Q:
Nested navigation menu using a recursive Python function
I want to render this data structure as an unordered list.
menu = [
[1, 0],
[2, 1],
[3, 1],
[4, 3],
[5, 3],
[6, 5],
[7,1]
]
[n][0] is the key
[n][1] references the parent key
The desired output is:
<ul>
<li>Node 1</li>
<ul>
<li>Node 2</li>
<li>Node 3</li>
<ul>
<li>Node 4</li>
<li>Node 5</li>
<ul>
<li>Node 6</li>
</ul>
</ul>
<li>Node 7</li>
</ul>
</ul>
I could probably do this without recursion but that would be no fun. What is the most efficient way to solve this problem with recursion?
Thanks!
A:
def render(nodes, parent = 0):
if parent not in nodes:
return
print('<ul>')
for n in nodes[parent]:
print('<li>Node %d</li>' % n)
render(nodes, n)
print('</ul>')
Here is the output
>>> nodes = {}
>>> for n in menu:
if n[1] not in nodes:
nodes[n[1]] = []
nodes[n[1]].append(n[0])
>>> render(nodes)
<ul>
<li>Node 1</li>
<ul>
<li>Node 2</li>
<li>Node 3</li>
<ul>
<li>Node 4</li>
<li>Node 5</li>
<ul>
<li>Node 6</li>
</ul>
</ul>
<li>Node 7</li>
</ul>
</ul>
A:
I would not use two-element lists, even if your structure is that simple. Use some TreeNode class, and give it an appropriate __str__ method, e.g.
class TreeNode(object):
# ...
# methods for adding children (instances of TreeNode again) etc.
def __str__(self):
ret = "<li>%s" % self.value
if self.children:
children = "".join([str(c) for c in self.children])
ret += "<ul>%s</ul>" % children
ret += "</li>"
return ret
... or something like that. Didn't test it, though. Enclose the whole tree's representation in an <ul> tag.
| Nested navigation menu using a recursive Python function | I want to render this data structure as an unordered list.
menu = [
[1, 0],
[2, 1],
[3, 1],
[4, 3],
[5, 3],
[6, 5],
[7,1]
]
[n][0] is the key
[n][1] references the parent key
The desired output is:
<ul>
<li>Node 1</li>
<ul>
<li>Node 2</li>
<li>Node 3</li>
<ul>
<li>Node 4</li>
<li>Node 5</li>
<ul>
<li>Node 6</li>
</ul>
</ul>
<li>Node 7</li>
</ul>
</ul>
I could probably do this without recursion but that would be no fun. What is the most efficient way to solve this problem with recursion?
Thanks!
| [
"def render(nodes, parent = 0):\n if parent not in nodes:\n return\n print('<ul>')\n for n in nodes[parent]:\n print('<li>Node %d</li>' % n)\n render(nodes, n)\n print('</ul>')\n\nHere is the output\n>>> nodes = {}\n>>> for n in menu:\n if n[1] not in nodes:\n nodes[n[1]] = []\n nodes[n[1]].append(n[0])\n>>> render(nodes)\n<ul>\n<li>Node 1</li>\n<ul>\n<li>Node 2</li>\n<li>Node 3</li>\n<ul>\n<li>Node 4</li>\n<li>Node 5</li>\n<ul>\n<li>Node 6</li>\n</ul>\n</ul>\n<li>Node 7</li>\n</ul>\n</ul>\n\n",
"I would not use two-element lists, even if your structure is that simple. Use some TreeNode class, and give it an appropriate __str__ method, e.g.\nclass TreeNode(object):\n # ...\n # methods for adding children (instances of TreeNode again) etc.\n\n def __str__(self):\n ret = \"<li>%s\" % self.value\n\n if self.children:\n children = \"\".join([str(c) for c in self.children])\n ret += \"<ul>%s</ul>\" % children \n ret += \"</li>\"\n\n return ret\n\n... or something like that. Didn't test it, though. Enclose the whole tree's representation in an <ul> tag.\n"
] | [
3,
2
] | [] | [] | [
"menu",
"navigation",
"python",
"recursion"
] | stackoverflow_0002888810_menu_navigation_python_recursion.txt |
Q:
What exactly is a web application framework?
I'm getting into python for cgi and came across Django. I'm not quite sure I understand it very much. Is it something I have to install inside apache or is it just something I can use with my cgi?
Wanted to know because I'd love to learn it but my server I'm using doesn't give me a lot of privileges.
thanks
A:
While you could run a Python web framework on top of CGI, I don't think you want to: a web framework provides you with lots of extra functionality to make your coding easier, but part of the price you pay for that is that the framework has lots of extra code to supply that functionality -- that code needs to get loaded, and its initialization parts executed, every time your web application process starts.
CGI starts a fresh process for your code every time the corresponding URL gets visited, and that process terminates when it's done responding to that single visit. So, you really want to do as little initialization work as possible, to avoid responding very slowly to user requests.
So, if all your hosting provider allows you is CGI, you probably want to program "down to the bare CGI interface", in order to minimize the start-up/shut-down overhead.
You can get a good overview of the issues and possibilities in Marek Kubica's howto "HOWTO Use Python in the web". WSGI (among many other ways it can interface to the underlying web server) can run on top of CGI, so in theory you can use any Python web framework which supports WSGI (which means just about all modern ones) -- the point is, unless you're doing nothing more than just learning and "playing around", you don't want to incur that startup overhead over and over again on pages you're actually serving. (If you are just learning and playing around, you can run a web server on your own machine for your own exclusive use, so your hosting provider's limitations are irrelevant;-).
If you do decide to program at "bare CGI" level, you can start at this page -- make sure you follow the various links from it to useful tutorials and to the voidspace collection of useful and interesting examples of Python CGI scripts.
For a survey of some of the many available Python web app frameworks, you can start here
where for each framework covered you'll find some information and links.
Last but not least, you should not ignore the possibility of developing web apps on Google App Engine -- albeit with its own peculiarities and limitations, it does offer a WSGI-compliant environment that is free of charge for even pretty intense usage. There are interesting lightweight frameworks developed specifically to take advantage of App Engine, such as the excellent tipfy (this page from the tipfy wiki also links to others), but in particular you can run the popular django framework there (with peculiarities and limitations, as I said -- in particular, no relational database underneath -- but it's still the most popular choice despite that).
In App Engine's early days some people were worried that using it could lead to "lock in" -- since it's different from other hosting environments, wouldn't web apps developed for it be hard to port elsewhere if and when one wanted to? Fortunately, open-source software like appscale and typhoonae has dispelled any such worries.
A:
A web application framework like Django replaces CGI by spawning its own processes and handling requests from a web server. They also provide tools for simplifying html by creating templates, partial templates, helpers etc.
If you don't have full control over your server, your host will need to install it for you.
A:
A web application framework is independent of the actual HTTP server in use. The server passes an application written using it the requests, and it cranks some gears and spits out a response, which is sent back to the HTTP server.
Django has 3 popular connectors to the HTTP server: WSGI, FastCGI, and mod_python. These are all explained... somewhere here, so I'll not repeat information that can easily be discovered.
A:
Basically the functions of any framework are:-
make sure that you do not have to do the repetitive tasks.
make it easy for you to re-use and modularize
they provide a layer of abstraction(which in most cases, makes you more productive)
So, Django is a web application framework; naturally it satisfies all three conditions above.
If you are interested in cgi programming using Python you should`nt be looking at Django.
On the other hand, if you are looking for options for web-development, then django certainly is a good option while manual cgi programming is not.
| What exactly is a web application framework? | I'm getting into python for cgi and came across Django. I'm not quite sure I understand it very much. Is it something I have to install inside apache or is it just something I can use with my cgi?
Wanted to know because I'd love to learn it but my server I'm using doesn't give me a lot of privileges.
thanks
| [
"While you could run a Python web framework on top of CGI, I don't think you want to: a web framework provides you with lots of extra functionality to make your coding easier, but part of the price you pay for that is that the framework has lots of extra code to supply that functionality -- that code needs to get loaded, and its initialization parts executed, every time your web application process starts.\nCGI starts a fresh process for your code every time the corresponding URL gets visited, and that process terminates when it's done responding to that single visit. So, you really want to do as little initialization work as possible, to avoid responding very slowly to user requests.\nSo, if all your hosting provider allows you is CGI, you probably want to program \"down to the bare CGI interface\", in order to minimize the start-up/shut-down overhead.\nYou can get a good overview of the issues and possibilities in Marek Kubica's howto \"HOWTO Use Python in the web\". WSGI (among many other ways it can interface to the underlying web server) can run on top of CGI, so in theory you can use any Python web framework which supports WSGI (which means just about all modern ones) -- the point is, unless you're doing nothing more than just learning and \"playing around\", you don't want to incur that startup overhead over and over again on pages you're actually serving. (If you are just learning and playing around, you can run a web server on your own machine for your own exclusive use, so your hosting provider's limitations are irrelevant;-).\nIf you do decide to program at \"bare CGI\" level, you can start at this page -- make sure you follow the various links from it to useful tutorials and to the voidspace collection of useful and interesting examples of Python CGI scripts.\nFor a survey of some of the many available Python web app frameworks, you can start here\nwhere for each framework covered you'll find some information and links.\nLast but not least, you should not ignore the possibility of developing web apps on Google App Engine -- albeit with its own peculiarities and limitations, it does offer a WSGI-compliant environment that is free of charge for even pretty intense usage. There are interesting lightweight frameworks developed specifically to take advantage of App Engine, such as the excellent tipfy (this page from the tipfy wiki also links to others), but in particular you can run the popular django framework there (with peculiarities and limitations, as I said -- in particular, no relational database underneath -- but it's still the most popular choice despite that).\nIn App Engine's early days some people were worried that using it could lead to \"lock in\" -- since it's different from other hosting environments, wouldn't web apps developed for it be hard to port elsewhere if and when one wanted to? Fortunately, open-source software like appscale and typhoonae has dispelled any such worries.\n",
"A web application framework like Django replaces CGI by spawning its own processes and handling requests from a web server. They also provide tools for simplifying html by creating templates, partial templates, helpers etc.\nIf you don't have full control over your server, your host will need to install it for you.\n",
"A web application framework is independent of the actual HTTP server in use. The server passes an application written using it the requests, and it cranks some gears and spits out a response, which is sent back to the HTTP server.\nDjango has 3 popular connectors to the HTTP server: WSGI, FastCGI, and mod_python. These are all explained... somewhere here, so I'll not repeat information that can easily be discovered.\n",
"Basically the functions of any framework are:-\n\nmake sure that you do not have to do the repetitive tasks.\nmake it easy for you to re-use and modularize\nthey provide a layer of abstraction(which in most cases, makes you more productive)\n\nSo, Django is a web application framework; naturally it satisfies all three conditions above.\nIf you are interested in cgi programming using Python you should`nt be looking at Django.\nOn the other hand, if you are looking for options for web-development, then django certainly is a good option while manual cgi programming is not.\n"
] | [
4,
0,
0,
0
] | [] | [] | [
"cgi",
"django",
"python",
"web_frameworks"
] | stackoverflow_0002886466_cgi_django_python_web_frameworks.txt |
Q:
Errno socket error in python
i wrote this code :
import random
import sys
import urllib
openfile = open(sys.argv[1]).readlines()
c = random.choice(openfile)
i = 0
while i < 5:
i=i+1
c = random.choice(openfile)
proxies = {'http': c}
opener = urllib.FancyURLopener(proxies).open("http://whatismyip.com.au/").read()
::: I put 3 proxy in a txt file . :
http://211.161.159.74:8080
http://119.70.40.101:8080
http://124.42.10.119:8080
but when execute it i get this error :
IOError: [Errno socket error] (10054, 'Connection reset by peer')
what am i going to do ?
please help me .
A:
The first proxy you list is giving my telnet an ECONNRESET too. What makes you think these are valid proxies?
Incidentally, if you are trying to find out their DNS names, they don't have any.
$ dig -x 211.161.159.74
;; connection timed out; no servers could be reached
| Errno socket error in python | i wrote this code :
import random
import sys
import urllib
openfile = open(sys.argv[1]).readlines()
c = random.choice(openfile)
i = 0
while i < 5:
i=i+1
c = random.choice(openfile)
proxies = {'http': c}
opener = urllib.FancyURLopener(proxies).open("http://whatismyip.com.au/").read()
::: I put 3 proxy in a txt file . :
http://211.161.159.74:8080
http://119.70.40.101:8080
http://124.42.10.119:8080
but when execute it i get this error :
IOError: [Errno socket error] (10054, 'Connection reset by peer')
what am i going to do ?
please help me .
| [
"The first proxy you list is giving my telnet an ECONNRESET too. What makes you think these are valid proxies?\nIncidentally, if you are trying to find out their DNS names, they don't have any.\n$ dig -x 211.161.159.74 \n;; connection timed out; no servers could be reached\n\n"
] | [
2
] | [] | [] | [
"proxy",
"python",
"sockets",
"urllib"
] | stackoverflow_0002888973_proxy_python_sockets_urllib.txt |
Q:
Mutate an object into an instance of one its subclasses
Is it possible to mutate an object into an instance of a derived class of the initial's object class?
Something like:
class Base():
def __init__(self):
self.a = 1
def mutate(self):
self = Derived()
class Derived(Base):
def __init__(self):
self.b = 2
But that doesn't work.
>>> obj = Base()
>>> obj.mutate()
>>> obj.a
1
>>> obj.b
AttributeError...
If this isn't possible, how should I do otherwise?
My problem is the following:
My Base class is like a "summary", and the Derived class is the "whole thing". Of course getting the "whole thing" is a bit expensive so working on summaries as long as it is possible is the point of having these two classes. But you should be able to get it if you want, and then there's no point in having the summary anymore, so every reference to the summary should now be (or contain, at least) the whole thing. I guess I would have to create a class that can hold both, right?
class Thing():
def __init__(self):
self.summary = Summary()
self.whole = None
def get_whole_thing(self):
self.whole = Whole()
A:
Responding to the original question as posed, changing the mutate method to:
def mutate(self):
self.__class__ = Derived
will do exactly what was requested -- change self's class to be Derived instead of Base. This does not automatically execute Derived.__init__, but if that's desired it can be explicitly called (e.g. as self.__init__() as the second statement in the method).
Whether this is a good approach for the OP's actual problem is a completely different question than the original question, which was
Is it possible to mutate an object
into an instance of a derived class of
the initial's object class?
The answer to this is "yes, it's possible" (and it's done the way I just showed). "Is it the best approach for my specific application problem" is a different question than "is it possible";-)
A:
A general OOP approach would be to make the summary object be a Façade that Delegates the expensive operations to a (dynamically constructed) back-end object. You could even make it totally transparent so that callers of the object don't see that there is anything going on (well, not unless they start timing things of course).
A:
I forgot to say that I also wanted to be able to create a "whole thing" from the start and not a summary if it wasn't needed.
I've finally done it like that:
class Thing():
def __init__(self, summary=False):
if summary:
self.summary = "summary"
self._whole = None
else:
self._whole = "wholething"
@property
def whole(self):
if self._whole: return self._whole
else:
self.__init__()
return self._whole
Works like a charm :)
A:
You cannot assign to self to do what you want, but you can change the class of an object by assigning to self.__class__ in your mutate method.
However this is really bad practice - for your situation delegation is better than inheritance.
| Mutate an object into an instance of one its subclasses | Is it possible to mutate an object into an instance of a derived class of the initial's object class?
Something like:
class Base():
def __init__(self):
self.a = 1
def mutate(self):
self = Derived()
class Derived(Base):
def __init__(self):
self.b = 2
But that doesn't work.
>>> obj = Base()
>>> obj.mutate()
>>> obj.a
1
>>> obj.b
AttributeError...
If this isn't possible, how should I do otherwise?
My problem is the following:
My Base class is like a "summary", and the Derived class is the "whole thing". Of course getting the "whole thing" is a bit expensive so working on summaries as long as it is possible is the point of having these two classes. But you should be able to get it if you want, and then there's no point in having the summary anymore, so every reference to the summary should now be (or contain, at least) the whole thing. I guess I would have to create a class that can hold both, right?
class Thing():
def __init__(self):
self.summary = Summary()
self.whole = None
def get_whole_thing(self):
self.whole = Whole()
| [
"Responding to the original question as posed, changing the mutate method to:\ndef mutate(self):\n self.__class__ = Derived\n\nwill do exactly what was requested -- change self's class to be Derived instead of Base. This does not automatically execute Derived.__init__, but if that's desired it can be explicitly called (e.g. as self.__init__() as the second statement in the method).\nWhether this is a good approach for the OP's actual problem is a completely different question than the original question, which was\n\nIs it possible to mutate an object\n into an instance of a derived class of\n the initial's object class?\n\nThe answer to this is \"yes, it's possible\" (and it's done the way I just showed). \"Is it the best approach for my specific application problem\" is a different question than \"is it possible\";-)\n",
"A general OOP approach would be to make the summary object be a Façade that Delegates the expensive operations to a (dynamically constructed) back-end object. You could even make it totally transparent so that callers of the object don't see that there is anything going on (well, not unless they start timing things of course).\n",
"I forgot to say that I also wanted to be able to create a \"whole thing\" from the start and not a summary if it wasn't needed.\nI've finally done it like that:\nclass Thing():\n def __init__(self, summary=False):\n if summary:\n self.summary = \"summary\"\n self._whole = None\n else:\n self._whole = \"wholething\"\n\n @property\n def whole(self):\n if self._whole: return self._whole\n else:\n self.__init__()\n return self._whole\n\nWorks like a charm :)\n",
"You cannot assign to self to do what you want, but you can change the class of an object by assigning to self.__class__ in your mutate method.\nHowever this is really bad practice - for your situation delegation is better than inheritance. \n"
] | [
7,
6,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002887643_oop_python.txt |
Q:
Why is my code shown as messy while it isn't?
class sss(webapp.RequestHandler):
def get(self):
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
self.response.out.write(result.content)
When I change code to this:
if result.status_code == 200:
self.response.out.write(result.content.decode('utf-8').encode('gb2312'))
It shows something strange. What should I do?
When I use this:
self.response.out.write(result.content.decode('big5'))
The page is different with the one I saw Google.com.
How to get Google.com that I saw?
A:
Google is probably serving you ISO-8859-1. At least, that is what they serve me for the User-Agent "AppEngine-Google; (+http://code.google.com/appengine)" (which urlfetch uses). The Content-Type header value is:
text/html; charset=ISO-8859-1
So you would use:
result.content.decode('ISO-8859-1')
If you check result.headers["Content-Type"], your code can adapt to changes on the other end. You can generally pass the charset (ISO-8859-1 in this case) directly to the Python decode method.
A:
how to get google.com that i saw ?
It's probably using relative URLs to images, javascript, CSS, etc, that you're not changing into absolute URLs into google's site. To confirm this: your logs should be showing 404 errors ("page not found") as the browser to which you're serving "just the HTML" tries locating the relative-addressed resources that you're not supplying.
| Why is my code shown as messy while it isn't? | class sss(webapp.RequestHandler):
def get(self):
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
self.response.out.write(result.content)
When I change code to this:
if result.status_code == 200:
self.response.out.write(result.content.decode('utf-8').encode('gb2312'))
It shows something strange. What should I do?
When I use this:
self.response.out.write(result.content.decode('big5'))
The page is different with the one I saw Google.com.
How to get Google.com that I saw?
| [
"Google is probably serving you ISO-8859-1. At least, that is what they serve me for the User-Agent \"AppEngine-Google; (+http://code.google.com/appengine)\" (which urlfetch uses). The Content-Type header value is:\ntext/html; charset=ISO-8859-1\n\nSo you would use:\nresult.content.decode('ISO-8859-1')\n\nIf you check result.headers[\"Content-Type\"], your code can adapt to changes on the other end. You can generally pass the charset (ISO-8859-1 in this case) directly to the Python decode method.\n",
"\nhow to get google.com that i saw ?\n\nIt's probably using relative URLs to images, javascript, CSS, etc, that you're not changing into absolute URLs into google's site. To confirm this: your logs should be showing 404 errors (\"page not found\") as the browser to which you're serving \"just the HTML\" tries locating the relative-addressed resources that you're not supplying.\n"
] | [
3,
1
] | [] | [] | [
"encode",
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0002887734_encode_google_app_engine_python_urlfetch.txt |
Q:
finding a solution to a giving maze txt.file
how can i fix this program, the problem is when it print out the coordinate it give me a 7 for the start and finish, i would appreciated you help, thanks
start = (len(data))
finish = (len(data))
pos= []
for i in range(len(pos)):
for j in range(len(pos[i])):
if pos[i][j] == "S":
start=(i,j)
elif pos[i][j] == "F":
finish=(i,j)
print "S found in",start,
print "\nF found in",finish,"\n"
A:
Look at the start of your code:
start = (len(data))
finish = (len(data))
pos= []
for i in range(len(pos)):
len(pos) is zero, of course (you've just assigned the empty list to pos, so what else could that length possibly be but 0?!), so the loop executes zero times, start and finish never change, and what you print for them after the loop is exactly what you assigned to them here -- and despite all the redundant parentheses that's just the same integer for both (which you tell us is 7, so presumably whatever data is, it has a length of 7).
| finding a solution to a giving maze txt.file | how can i fix this program, the problem is when it print out the coordinate it give me a 7 for the start and finish, i would appreciated you help, thanks
start = (len(data))
finish = (len(data))
pos= []
for i in range(len(pos)):
for j in range(len(pos[i])):
if pos[i][j] == "S":
start=(i,j)
elif pos[i][j] == "F":
finish=(i,j)
print "S found in",start,
print "\nF found in",finish,"\n"
| [
"Look at the start of your code:\nstart = (len(data))\nfinish = (len(data))\npos= []\nfor i in range(len(pos)):\n\nlen(pos) is zero, of course (you've just assigned the empty list to pos, so what else could that length possibly be but 0?!), so the loop executes zero times, start and finish never change, and what you print for them after the loop is exactly what you assigned to them here -- and despite all the redundant parentheses that's just the same integer for both (which you tell us is 7, so presumably whatever data is, it has a length of 7).\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002889073_python.txt |
Q:
How to verify object creation in Django?
I want to verify that the object I created was really created, and return True or False according to that:
obj = object(name='plop')
try:
obj.save()
return True
except ???:
return False
How can object creation be verified?
A:
First of all - that's a not good practice that you are doing
2nd the only case when exception can happen is database connection fail or some constrains or required required fields not set.. in that case db-backend.OperationalError is raised
Update: on constrains fail there is a IntegrityError exception
A:
save() can also raise other exceptions, such as ValidationError in django 1.2, or any arbitrary exception if the save() method has been overridden.
I don't see anything particularly wrong with attempting a save() and catching the exception. If for some reason you prefer to check a boolean return value than just catch the exception (not usually how it's done in python), then you have the right idea. Just change except ???: to except Exception:
After all you want to return False on any expected failure.
| How to verify object creation in Django? | I want to verify that the object I created was really created, and return True or False according to that:
obj = object(name='plop')
try:
obj.save()
return True
except ???:
return False
How can object creation be verified?
| [
"First of all - that's a not good practice that you are doing\n2nd the only case when exception can happen is database connection fail or some constrains or required required fields not set.. in that case db-backend.OperationalError is raised\nUpdate: on constrains fail there is a IntegrityError exception\n",
"save() can also raise other exceptions, such as ValidationError in django 1.2, or any arbitrary exception if the save() method has been overridden.\nI don't see anything particularly wrong with attempting a save() and catching the exception. If for some reason you prefer to check a boolean return value than just catch the exception (not usually how it's done in python), then you have the right idea. Just change except ???: to except Exception:\nAfter all you want to return False on any expected failure.\n"
] | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002889523_django_python.txt |
Q:
Creating collaborative whiteboard drawing application
I have my own drawing program in place, with a variety of "drawing tools" such as Pen, Eraser, Rectangle, Circle, Select, Text etc.
It's made with Python and wxPython. Each tool mentioned above is a class, which all have polymorphic methods, such as left_down(), mouse_motion(), hit_test() etc. The program manages a list of all drawn shapes -- when a user has drawn a shape, it's added to the list. This is used to manage undo/redo operations too.
So, I have a decent codebase that I can hook collaborative drawing into. Each shape could be changed to know its owner -- the user who drew it, and to only allow delete/move/rescale operations to be performed on shapes owned by one person.
I'm just wondering the best way to develop this. One person in the "session" will have to act as the server, I have no money to offer free central servers. Somehow users will need a way to connect to servers, meaning some kind of "discover servers" browser...or something. How do I broadcast changes made to the application? Drawing in realtime and broadcasting a message on each mouse motion event would be costly in terms of performance and things get worse the more users there are at a given time.
Any ideas are welcome, I'm not too sure where to begin with developing this (or even how to test it)
A:
Making any real-time collaborative tool/game boils down to efficiently synchronizing changes on a minimal shared data structure between clients. Network bandwidth is the bottleneck. Send only information absolutely needed to synchronize the shared data. You are on the right track by storing shapes instead of individual pixels. However, the shapes should not handle mouse events. As you noted, broadcasting mouse events will quickly saturate the network bandwidth! Instead, pass deltas of how the shapes are altered by the mouse events. For example, instead of sending mouse_motion() send the final position [x,y] after a shape has been moved.
I suggest splitting your drawing program into a server part and client part. The server keeps the authoritative version of the shared data. A client never manipulates the shared data structure directly; it only sends network messages to the server. This may seem silly when both the client and server are in the same process/PC, but there are some good reasons:
Shared code path for both single-user and multi-user
The network overhead between a client and server in the same process is next to zero when using local sockets
In addition, editing does not have to be limited to the owner of that shape. Since the server is the final authority, it resolves any conflicts when two people grab the same shape simultaneously and send the results back to the clients. (Undo gets a little tricky, though.)
Although a centralized server is best for network discovery, clients can use other methods to find a server:
Send or listen for network broadcast packets.
Connect directly via an IP address. (The server IP address will have to be communicated via other means: chat, cell phone, shouting across the room, carrier pigeon, ...)
Finally, look at how other multi-user applications are designed. Here are some examples:
Zoidcom Multi-player game programming libary (C++). Much of this answer is based on information from Zoidcom documentation. There are even sample programs that demonstrate server discovery via network broadcast.
Operational Transformation algorithm behind Wave, Google Docs. (article discussion on Hacker News)
Etherpad Open-source real-time collaborative text editor.
Source Multiplayer Networking Explains how an FPS like HAlf-life is designed. Gets into tricks for reducing lag/latency.
Google Wave (Apparently the documentation is stil pretty poor...)
| Creating collaborative whiteboard drawing application | I have my own drawing program in place, with a variety of "drawing tools" such as Pen, Eraser, Rectangle, Circle, Select, Text etc.
It's made with Python and wxPython. Each tool mentioned above is a class, which all have polymorphic methods, such as left_down(), mouse_motion(), hit_test() etc. The program manages a list of all drawn shapes -- when a user has drawn a shape, it's added to the list. This is used to manage undo/redo operations too.
So, I have a decent codebase that I can hook collaborative drawing into. Each shape could be changed to know its owner -- the user who drew it, and to only allow delete/move/rescale operations to be performed on shapes owned by one person.
I'm just wondering the best way to develop this. One person in the "session" will have to act as the server, I have no money to offer free central servers. Somehow users will need a way to connect to servers, meaning some kind of "discover servers" browser...or something. How do I broadcast changes made to the application? Drawing in realtime and broadcasting a message on each mouse motion event would be costly in terms of performance and things get worse the more users there are at a given time.
Any ideas are welcome, I'm not too sure where to begin with developing this (or even how to test it)
| [
"Making any real-time collaborative tool/game boils down to efficiently synchronizing changes on a minimal shared data structure between clients. Network bandwidth is the bottleneck. Send only information absolutely needed to synchronize the shared data. You are on the right track by storing shapes instead of individual pixels. However, the shapes should not handle mouse events. As you noted, broadcasting mouse events will quickly saturate the network bandwidth! Instead, pass deltas of how the shapes are altered by the mouse events. For example, instead of sending mouse_motion() send the final position [x,y] after a shape has been moved.\nI suggest splitting your drawing program into a server part and client part. The server keeps the authoritative version of the shared data. A client never manipulates the shared data structure directly; it only sends network messages to the server. This may seem silly when both the client and server are in the same process/PC, but there are some good reasons:\n\nShared code path for both single-user and multi-user\nThe network overhead between a client and server in the same process is next to zero when using local sockets\n\nIn addition, editing does not have to be limited to the owner of that shape. Since the server is the final authority, it resolves any conflicts when two people grab the same shape simultaneously and send the results back to the clients. (Undo gets a little tricky, though.)\nAlthough a centralized server is best for network discovery, clients can use other methods to find a server:\n\nSend or listen for network broadcast packets.\nConnect directly via an IP address. (The server IP address will have to be communicated via other means: chat, cell phone, shouting across the room, carrier pigeon, ...)\n\nFinally, look at how other multi-user applications are designed. Here are some examples:\n\nZoidcom Multi-player game programming libary (C++). Much of this answer is based on information from Zoidcom documentation. There are even sample programs that demonstrate server discovery via network broadcast.\nOperational Transformation algorithm behind Wave, Google Docs. (article discussion on Hacker News)\nEtherpad Open-source real-time collaborative text editor.\nSource Multiplayer Networking Explains how an FPS like HAlf-life is designed. Gets into tricks for reducing lag/latency.\nGoogle Wave (Apparently the documentation is stil pretty poor...)\n\n"
] | [
14
] | [] | [] | [
"paint",
"python",
"twisted",
"whiteboard",
"wxpython"
] | stackoverflow_0002889363_paint_python_twisted_whiteboard_wxpython.txt |
Q:
Python: How can I subclass a class I'm nesting in?
I am trying to do the following in a bit of python code:
class Parent:
class Child(Parent):
pass
And it does not work. Is there any python syntax I can use to achieve the same result?
Thanks.
A:
You can't do that because at the point where Child is being defined, Parent is not defined yet (definition in progress). Nested classes are not usually used in Python, you can just declare different classes in the same module. However, if you absolutely need to achieve the outlined setup, you can do this:
class Parent: pass
class Child (Parent): pass
Parent.Child = Child
del Child
A:
Inner classes have no special relationship with their outer classes in Python, so there's really no reason to use them. Also, having a class as a class attribute of another class is not usually an optimal design. By restructuring a bit, I bet you could come up with a solution that doesn't require or desire this behavior and that is better and more idiomatic.
A:
I strongly recommend against doing anything like the following; there really isn't any reason I can think of to do it, and it's overly complicated. But for educational purposes...
It is possible to have a metaclass (or a class decorator, I suppose) replace some object that came from a class definition with an actual subclass, after the enclosing (Parent) class has been created.
For example in the following, we check for the presence of a special marker (a class called ReplaceMe) in the __bases__ attribute of each of our class attributes. If we find it, we assume that what we found was a stand in for what is supposed to be a subclass. We make a new (sub-)class dynamically, replacing the ReplaceMe class with ourself.
class ReplaceMe(object): pass
class DerivedInnerChildren(type):
def __init__(cls, name, bases, attrs):
for k, v in attrs.items():
if ReplaceMe in getattr(v, '__bases__', ()):
child_name = v.__name__
child_bases = tuple([
base if base is not ReplaceMe else cls
for base in v.__bases__])
child_attrs = dict(v.__dict__)
setattr(cls, k, type(child_name, child_bases, child_attrs))
class Parent(object):
__metaclass__ = DerivedInnerChildren
class Child(ReplaceMe):
pass
print Parent
print Parent.Child
print 'Parent in Child mro?', Parent in Parent.Child.__mro__
print Parent.Child.__mro__
This prints:
<class '__main__.Parent'>
<class '__main__.Child'>
Parent in Child mro? True
(<class '__main__.Child'>, <class '__main__.Parent'>, <type 'object'>)
| Python: How can I subclass a class I'm nesting in? | I am trying to do the following in a bit of python code:
class Parent:
class Child(Parent):
pass
And it does not work. Is there any python syntax I can use to achieve the same result?
Thanks.
| [
"You can't do that because at the point where Child is being defined, Parent is not defined yet (definition in progress). Nested classes are not usually used in Python, you can just declare different classes in the same module. However, if you absolutely need to achieve the outlined setup, you can do this:\nclass Parent: pass\nclass Child (Parent): pass\n\nParent.Child = Child\ndel Child\n\n",
"Inner classes have no special relationship with their outer classes in Python, so there's really no reason to use them. Also, having a class as a class attribute of another class is not usually an optimal design. By restructuring a bit, I bet you could come up with a solution that doesn't require or desire this behavior and that is better and more idiomatic.\n",
"I strongly recommend against doing anything like the following; there really isn't any reason I can think of to do it, and it's overly complicated. But for educational purposes...\nIt is possible to have a metaclass (or a class decorator, I suppose) replace some object that came from a class definition with an actual subclass, after the enclosing (Parent) class has been created.\nFor example in the following, we check for the presence of a special marker (a class called ReplaceMe) in the __bases__ attribute of each of our class attributes. If we find it, we assume that what we found was a stand in for what is supposed to be a subclass. We make a new (sub-)class dynamically, replacing the ReplaceMe class with ourself.\nclass ReplaceMe(object): pass\n\nclass DerivedInnerChildren(type):\n def __init__(cls, name, bases, attrs):\n for k, v in attrs.items():\n if ReplaceMe in getattr(v, '__bases__', ()):\n child_name = v.__name__\n child_bases = tuple([\n base if base is not ReplaceMe else cls\n for base in v.__bases__])\n child_attrs = dict(v.__dict__)\n setattr(cls, k, type(child_name, child_bases, child_attrs))\n\nclass Parent(object):\n __metaclass__ = DerivedInnerChildren\n class Child(ReplaceMe): \n pass\n\nprint Parent\nprint Parent.Child\nprint 'Parent in Child mro?', Parent in Parent.Child.__mro__\nprint Parent.Child.__mro__\n\nThis prints:\n<class '__main__.Parent'>\n<class '__main__.Child'>\nParent in Child mro? True\n(<class '__main__.Child'>, <class '__main__.Parent'>, <type 'object'>)\n\n"
] | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002889739_python.txt |
Q:
Returning JSON from JavaScript to Python
I'm writing a simple App Engine app.
I have a simple page that allows a user to move a marker on a Google map instance. Each time the user drops the marker, I want to return the long/lat to my Python app.
function initialize() {
... // Init map
var marker = new GMarker(center, {draggable: true});
GEvent.addListener(marker, "dragend", function() {
// I want to return the marker.x/y to my app when this function is called ..
});
}
To my (admittedly limited) knowledge, I should be:
1). Returning a JSON structure with my required data in the listener callback above
2). In my webapp.RequestHandler Handler class, trying to retrieve the JSON structure during the post method.
I would very much like to pass this JSOn data back to the app without causing a page reload (which is what has happened when I've used various post/form.submit methods so far).
Can anyone provide me with some psuedo code or an example on how I might achieve what I'm after?
Thanks.
A:
The way to prevent a page reload is to handle this with AJAX on the web page side.
Using jquery, you might do something like this:
$("#testform").submit(function() {
// post the form values via AJAX...
var postdata = {lat: $("#lat").val(), long: $("#long").val()} ;
$.post('/submit', postdata, function(data) {
// and set the location with the result
$("#location").html(data['location']) ;
});
return false ;
});
Assuming you have a web page something like this:
<p>Enter lat and long:</p>
<form id="testform" action="#" method="post">
<p>
<label for="lat">Lat:</label>
<input type="text" id="lat" /> <br />
<label for="long">Long:</label>
<input type="text" id="long" /> <br />
<input type="submit" value="Get Location" />
</p>
</form>
<p>The location is:</p><p id="location">(enter lat and long above)</p>
and then have the python code return the location in a JSON dict.
Finally, I would recommend having a graceful fallback: if the user has JavaScript disabled, do a regular post to e.g. /getlocation and reload, and then have JavaScript override this to submit to a special URL that returns json, like /getlocationajax
A:
If you don't want the page to update, then you need to use a XMLHttpRequest. In this example, i'm using the client-side function Request(function_name, opt_argv) and server-side RPCHandler from this Google App Engine example. I haven't tested this, but it would look like:
Client-side Javascript
function initialize() {
... // Init map
var marker = new GMarker(center, {draggable: true});
GEvent.addListener(marker, "dragend", function(position) {
Request('update_marker_position', [ unique_identifier, position.lat(), position.lng() ] );
});
}
Server-side Python
# Create database model for LatLng position
class LatLng(db.Model):
lat = db.IntegerProperty()
lng = db.IntegerProperty()
...
class RPCMethods:
""" Defines the methods that can be RPCed.
NOTE: Do not allow remote callers access to private/protected "_*" methods.
"""
def update_marker_position(self, *args):
# args[0] - unique identifier, say GAE db key
# args[1] - lat
# args[2] - lng
# Note: need to do some checking that lat and lng are valid
# Retrieve key and update position
position = LatLng.get(db.Key(args[0])
if position:
position.lat = args[1]
position.lng = args[2]
else:
position = LatLng(
lat= args[1],
lng= args[2]
)
position.put()
payload = {
'lat': args[1],
'lng': args[2],
}
return payload
You'll need to create the db entry when you serve up the page, and store the db key client side. You could also use some other unique identifier. In this case, I assumed you stored it as a global variable 'unique_identifier'.
As well, you'll need to add a callback function to handle the returning payload (with members 'lat' and 'lng'). From the example, I believe you just add your callback function as the zeroth parameter in the opt_argv array of Request. I hope this helps.
| Returning JSON from JavaScript to Python | I'm writing a simple App Engine app.
I have a simple page that allows a user to move a marker on a Google map instance. Each time the user drops the marker, I want to return the long/lat to my Python app.
function initialize() {
... // Init map
var marker = new GMarker(center, {draggable: true});
GEvent.addListener(marker, "dragend", function() {
// I want to return the marker.x/y to my app when this function is called ..
});
}
To my (admittedly limited) knowledge, I should be:
1). Returning a JSON structure with my required data in the listener callback above
2). In my webapp.RequestHandler Handler class, trying to retrieve the JSON structure during the post method.
I would very much like to pass this JSOn data back to the app without causing a page reload (which is what has happened when I've used various post/form.submit methods so far).
Can anyone provide me with some psuedo code or an example on how I might achieve what I'm after?
Thanks.
| [
"The way to prevent a page reload is to handle this with AJAX on the web page side.\nUsing jquery, you might do something like this:\n$(\"#testform\").submit(function() {\n // post the form values via AJAX...\n var postdata = {lat: $(\"#lat\").val(), long: $(\"#long\").val()} ;\n $.post('/submit', postdata, function(data) {\n // and set the location with the result\n $(\"#location\").html(data['location']) ;\n });\n return false ;\n });\n\nAssuming you have a web page something like this:\n<p>Enter lat and long:</p>\n<form id=\"testform\" action=\"#\" method=\"post\">\n <p>\n <label for=\"lat\">Lat:</label>\n <input type=\"text\" id=\"lat\" /> <br />\n <label for=\"long\">Long:</label>\n <input type=\"text\" id=\"long\" /> <br />\n\n <input type=\"submit\" value=\"Get Location\" />\n </p>\n</form>\n\n<p>The location is:</p><p id=\"location\">(enter lat and long above)</p>\n\nand then have the python code return the location in a JSON dict.\nFinally, I would recommend having a graceful fallback: if the user has JavaScript disabled, do a regular post to e.g. /getlocation and reload, and then have JavaScript override this to submit to a special URL that returns json, like /getlocationajax\n",
"If you don't want the page to update, then you need to use a XMLHttpRequest. In this example, i'm using the client-side function Request(function_name, opt_argv) and server-side RPCHandler from this Google App Engine example. I haven't tested this, but it would look like:\nClient-side Javascript\nfunction initialize() {\n\n ... // Init map\n\n var marker = new GMarker(center, {draggable: true});\n GEvent.addListener(marker, \"dragend\", function(position) {\n Request('update_marker_position', [ unique_identifier, position.lat(), position.lng() ] );\n });\n\n}\n\nServer-side Python\n# Create database model for LatLng position\nclass LatLng(db.Model):\n lat = db.IntegerProperty()\n lng = db.IntegerProperty()\n\n...\n\nclass RPCMethods:\n \"\"\" Defines the methods that can be RPCed.\n NOTE: Do not allow remote callers access to private/protected \"_*\" methods.\n \"\"\"\n\n def update_marker_position(self, *args):\n # args[0] - unique identifier, say GAE db key\n # args[1] - lat\n # args[2] - lng\n # Note: need to do some checking that lat and lng are valid\n \n # Retrieve key and update position\n position = LatLng.get(db.Key(args[0])\n if position:\n position.lat = args[1]\n position.lng = args[2]\n else:\n position = LatLng(\n lat= args[1], \n lng= args[2]\n )\n position.put()\n \n payload = {\n 'lat': args[1],\n 'lng': args[2],\n }\n return payload\n\nYou'll need to create the db entry when you serve up the page, and store the db key client side. You could also use some other unique identifier. In this case, I assumed you stored it as a global variable 'unique_identifier'.\nAs well, you'll need to add a callback function to handle the returning payload (with members 'lat' and 'lng'). From the example, I believe you just add your callback function as the zeroth parameter in the opt_argv array of Request. I hope this helps.\n"
] | [
7,
1
] | [] | [] | [
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0002796736_google_app_engine_javascript_python.txt |
Q:
How to extract comment out of header file using python, perl, or sed?
I have a header file like this:
/*
* APP 180-2 ALG-254/258/772 implementation
* Last update: 03/01/2006
* Issue date: 08/22/2004
*
* Copyright (C) 2006 Somebody's Name here
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef HEADER_H
#define HEADER_H
/* More comments and C++ code here. */
#endif /* End of file. */
And I wish to extract out the contents of the first C style comment only and drop the " *" at the start of each line to get a file with the following contents:
APP 180-2 ALG-254/258/772 implementation
Last update: 03/01/2006
Issue date: 08/22/2004
Copyright (C) 2006 Somebody's Name here
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please suggest an easy way to do this with Python, Perl, sed, or some other way on Unix. Preferably as a one-liner.
A:
This should work for you:
sed -n '/\*\//q; /^\/\*/d; s/^ \* \?//p' <file.h >comment.txt
Here's an explanation: sed (as you may know) is a command that goes through a file applying a list of rules to each line. Each rule consists of a "selector" and commands that are applied to that line only if the selector matches.
The first rule has the selector /\*\//. This is a regular expression selector; it matches any line that contains the characters */. Both of these need to be backslash-escaped since they have special meanings in a regexp. (I've assumed that this will only match the closing line of the comment in your case and that this entire line should be deleted.) The command is q which means "quit." sed just stops. Ordinarily it would print out the line, but I provided the -n option which means "don't print unless explicitly instructed to."
The second rule has the selector /^\/\*/ which is again a regexp selector that matches the characters /* at the start of the line. Again, I've assumed this line will not contain part of the comment. The d command tells sed to delete this line and move on.
The final rule has no selector, so it applies to all lines (unless a previous command prevented processing from reaching the final rule). The command in this last rule is a substitution command, s/PATTERN/REPLACEMENT/, which finds text in the line that matches some pattern and replaces it with a replacement text. The pattern here is ^ \* \?, which matches a space, an asterisk, and either 0 or 1 spaces, but only at the beginning of the line. And the replacement is nothing. So sed simply deletes the leading space-asterisk-(space)? sequence. The p is actually a flag to the substitution command that tells sed to print out the result of the substitution. It's needed because of the -n option.
A:
Pyparsing includes a built-in pattern for matching comment formats from various languages. Using cStyleComment and scanString to find the first comment in the source file makes the rest just string functions:
c_src = open(c_source_file).read()
from pyparsing import cStyleComment
cmt = cStyleComment.scanString(c_src).next()[0][0]
lines = [l[3:] for l in cmt.splitlines()]
print '\n'.join(lines)
scanString is a generator that returns each match before going to the next instance, so only the first comment gets processed. With your sample code, this returns:
APP 180-2 ALG-254/258/772 implementation
Last update: 03/01/2006
Issue date: 08/22/2004
Copyright (C) 2006 Somebody's Name here
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
| How to extract comment out of header file using python, perl, or sed? | I have a header file like this:
/*
* APP 180-2 ALG-254/258/772 implementation
* Last update: 03/01/2006
* Issue date: 08/22/2004
*
* Copyright (C) 2006 Somebody's Name here
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef HEADER_H
#define HEADER_H
/* More comments and C++ code here. */
#endif /* End of file. */
And I wish to extract out the contents of the first C style comment only and drop the " *" at the start of each line to get a file with the following contents:
APP 180-2 ALG-254/258/772 implementation
Last update: 03/01/2006
Issue date: 08/22/2004
Copyright (C) 2006 Somebody's Name here
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please suggest an easy way to do this with Python, Perl, sed, or some other way on Unix. Preferably as a one-liner.
| [
"This should work for you:\nsed -n '/\\*\\//q; /^\\/\\*/d; s/^ \\* \\?//p' <file.h >comment.txt\n\nHere's an explanation: sed (as you may know) is a command that goes through a file applying a list of rules to each line. Each rule consists of a \"selector\" and commands that are applied to that line only if the selector matches.\nThe first rule has the selector /\\*\\//. This is a regular expression selector; it matches any line that contains the characters */. Both of these need to be backslash-escaped since they have special meanings in a regexp. (I've assumed that this will only match the closing line of the comment in your case and that this entire line should be deleted.) The command is q which means \"quit.\" sed just stops. Ordinarily it would print out the line, but I provided the -n option which means \"don't print unless explicitly instructed to.\"\nThe second rule has the selector /^\\/\\*/ which is again a regexp selector that matches the characters /* at the start of the line. Again, I've assumed this line will not contain part of the comment. The d command tells sed to delete this line and move on.\nThe final rule has no selector, so it applies to all lines (unless a previous command prevented processing from reaching the final rule). The command in this last rule is a substitution command, s/PATTERN/REPLACEMENT/, which finds text in the line that matches some pattern and replaces it with a replacement text. The pattern here is ^ \\* \\?, which matches a space, an asterisk, and either 0 or 1 spaces, but only at the beginning of the line. And the replacement is nothing. So sed simply deletes the leading space-asterisk-(space)? sequence. The p is actually a flag to the substitution command that tells sed to print out the result of the substitution. It's needed because of the -n option.\n",
"Pyparsing includes a built-in pattern for matching comment formats from various languages. Using cStyleComment and scanString to find the first comment in the source file makes the rest just string functions:\nc_src = open(c_source_file).read()\n\nfrom pyparsing import cStyleComment\ncmt = cStyleComment.scanString(c_src).next()[0][0]\nlines = [l[3:] for l in cmt.splitlines()]\nprint '\\n'.join(lines)\n\nscanString is a generator that returns each match before going to the next instance, so only the first comment gets processed. With your sample code, this returns:\nAPP 180-2 ALG-254/258/772 implementation \nLast update: 03/01/2006 \nIssue date: 08/22/2004 \n\nCopyright (C) 2006 Somebody's Name here \nAll rights reserved. \n\nRedistribution and use in source and binary forms, with or without \nmodification, are permitted provided that the following conditions \nare met: \n1. Redistributions of source code must retain the above copyright \n notice, this list of conditions and the following disclaimer. \n2. Redistributions in binary form must reproduce the above copyright \n notice, this list of conditions and the following disclaimer in the \n documentation and/or other materials provided with the distribution. \n3. Neither the name of the project nor the names of its contributors \n may be used to endorse or promote products derived from this software \n without specific prior written permission. \n\nTHIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \nARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE \nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS \nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT \nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY \nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF \nSUCH DAMAGE. \n\n"
] | [
5,
4
] | [
"sed -i -r \"s/[\\/\\ ]{1}\\*[\\/\\ ]?//g\" YOURFILENAME\n\nThis replaces trims comments from your file, keeping the content. This will modify YOURFILENAME file though. If you don't want that remove -i from the line\n"
] | [
-1
] | [
"c++",
"extraction",
"perl",
"python",
"sed"
] | stackoverflow_0002889771_c++_extraction_perl_python_sed.txt |
Q:
How Can I: Generate 40/64 Bit WEP Key In Python?
So, I've been beating my head against the wall of this issue for several months now, partly because it's a side interest and partly because I suck at programming. I've searched and researched all across the web, but have not had any luck (except one small bit of success; see below), so I thought I might try asking the experts.
What I am trying to do is, as the title suggests, generate a 40/64 bit WEP key from a passphrase, according to the "de facto" standard. (A site such as http://www.powerdog.com/wepkey.cgi produces the expected outputs.) I have already written portions of the script that take inputs and write them to a file; one of the inputs would be the passphrase, sanitized to lower case.
For the longest time I had no idea what the defacto standard was, much less how to even go about implementing it. I finally stumbled across a paper (http://www.lava.net/~newsham/wlan/WEP_password_cracker.pdf) that sheds as much light as I've had yet on the issue (page 18 has the relevant bits). Apparently, the passphrase is "mapped to a 32-bit value with XOR," the result of which is then used as the seed for a "linear congruential PRNG (which one of the several PRNGs Python has would fit this description, I don't know), and then from that result several bits of the result are taken. I have no idea how to go about implementing this, since the description is rather vague.
What I need is help in writing the generator in Python, and also in understanding how exactly the key is generated. In other words, I need code to turn "jackson" into "09F38AF593". (And please don't tell me jackson = 09F38AF593; print (jackson))
I'm not much of a programmer, so explanations are appreciated as well.
(Yes, I know that WEP isn't secure.)
A:
That C code you linked to would have been awfully helpful to include in the question ;-) Anyway, I went ahead and translated it into Python. Before you read it, let me say that I highly encourage you to try it yourself and only use my transcription as a guide. Translating algorithms from one programming language to another is generally great practice when you want to boost your skills in one or both languages. Even if you don't know C, as long as you're familiar enough with Python to write programs in it, you should be able to get the gist of the C code, since there are many similarities.
Anyway, on to the code.
import itertools, operator
First, the pseudorandom number generator, which was identified in the presentation as a linear congruential generator. This type of PRNG is a general algorithm which can be "customized" by choosing specific values of a, c, and m (the variables mentioned in the Wikipedia article). Here is an implementation of a generic linear congruential generator:
def prng(x, a, c, m):
while True:
x = (a * x + c) % m
yield x
(hopefully you could have come up with that on your own)
Now for the actual function:
def pass_to_key(passphrase):
The first step in the process is to hash (or "map") the passphrase provided to a 32-bit number. The WEP algorithm does this by creating a set of 4 bytes (thus 4*8=32 bits) which are initialized to zero.
bits = [0,0,0,0]
It goes through the string and XORs each character with one of the bytes; specifically, character i is XOR'd into byte i % 4.
for i, c in enumerate(passphrase):
bits[i & 3] ^= ord(c)
These four bytes are then concatenated together, in order, to form a single 32-bit value. (Alternatively, I could have written the code to store them as a 32-bit number from the beginning)
val = reduce(operator.__or__, (b << 8*i for (i,b) in enumerate(bits)))
This 32-bit value is used as the seed for a linear congruential generator with certain specific values which you can see in the code. How the original developer figured out these numbers, I have no idea.
keys = []
The linear congruential generator can produce up to 32 bits of output at a time. (In C this is a limitation of the data type; in Python I had to artificially enforce it.) I need 20 bytes to generate 4 40-bit (5-byte) WEP keys, so I'll iterate the PRNG 20 times,
for i, b in enumerate(itertools.islice(prng(val, 0x343fd, 0x269ec3, 1<<32), 20)):
and from each number, take only the 3rd byte from the right (bits 16-23):
keys.append((b >> 16) & 0xff)
Why the third? Well, the bits at the high end (4th from the right) tend not to change much, and those at the low end can be predictable for many values of the PRNG constants.
Afterwards, all that's left is to print out the generated bytes in groups of 5.
print ('%02x:%02x:%02x:%02x:%02x\n'*4) % tuple(keys)
A:
I'm not sure what "de facto standard" that website is talking about, but I'm fairly sure router manufacturers all implement their own methods. It doesn't matter how you do it, as long as the same input always results in the same output; it's a convenience so WEP users can remember a passphrase instead of the actual hex key. Even the method in the PDF you posted is largely ambiguous; it uses an undefined PRNG (and every type of PRNG is going to give a different result), and takes "one byte" from each result without specifying which. If you're trying to reverse engineer a particular router's method, mention that in the post and we might be able to find out how that one works, but there isn't a standard method
| How Can I: Generate 40/64 Bit WEP Key In Python? | So, I've been beating my head against the wall of this issue for several months now, partly because it's a side interest and partly because I suck at programming. I've searched and researched all across the web, but have not had any luck (except one small bit of success; see below), so I thought I might try asking the experts.
What I am trying to do is, as the title suggests, generate a 40/64 bit WEP key from a passphrase, according to the "de facto" standard. (A site such as http://www.powerdog.com/wepkey.cgi produces the expected outputs.) I have already written portions of the script that take inputs and write them to a file; one of the inputs would be the passphrase, sanitized to lower case.
For the longest time I had no idea what the defacto standard was, much less how to even go about implementing it. I finally stumbled across a paper (http://www.lava.net/~newsham/wlan/WEP_password_cracker.pdf) that sheds as much light as I've had yet on the issue (page 18 has the relevant bits). Apparently, the passphrase is "mapped to a 32-bit value with XOR," the result of which is then used as the seed for a "linear congruential PRNG (which one of the several PRNGs Python has would fit this description, I don't know), and then from that result several bits of the result are taken. I have no idea how to go about implementing this, since the description is rather vague.
What I need is help in writing the generator in Python, and also in understanding how exactly the key is generated. In other words, I need code to turn "jackson" into "09F38AF593". (And please don't tell me jackson = 09F38AF593; print (jackson))
I'm not much of a programmer, so explanations are appreciated as well.
(Yes, I know that WEP isn't secure.)
| [
"That C code you linked to would have been awfully helpful to include in the question ;-) Anyway, I went ahead and translated it into Python. Before you read it, let me say that I highly encourage you to try it yourself and only use my transcription as a guide. Translating algorithms from one programming language to another is generally great practice when you want to boost your skills in one or both languages. Even if you don't know C, as long as you're familiar enough with Python to write programs in it, you should be able to get the gist of the C code, since there are many similarities.\nAnyway, on to the code.\nimport itertools, operator\n\nFirst, the pseudorandom number generator, which was identified in the presentation as a linear congruential generator. This type of PRNG is a general algorithm which can be \"customized\" by choosing specific values of a, c, and m (the variables mentioned in the Wikipedia article). Here is an implementation of a generic linear congruential generator:\ndef prng(x, a, c, m):\n while True:\n x = (a * x + c) % m\n yield x\n\n(hopefully you could have come up with that on your own)\nNow for the actual function:\ndef pass_to_key(passphrase):\n\nThe first step in the process is to hash (or \"map\") the passphrase provided to a 32-bit number. The WEP algorithm does this by creating a set of 4 bytes (thus 4*8=32 bits) which are initialized to zero.\n bits = [0,0,0,0]\n\nIt goes through the string and XORs each character with one of the bytes; specifically, character i is XOR'd into byte i % 4.\n for i, c in enumerate(passphrase):\n bits[i & 3] ^= ord(c)\n\nThese four bytes are then concatenated together, in order, to form a single 32-bit value. (Alternatively, I could have written the code to store them as a 32-bit number from the beginning)\n val = reduce(operator.__or__, (b << 8*i for (i,b) in enumerate(bits)))\n\nThis 32-bit value is used as the seed for a linear congruential generator with certain specific values which you can see in the code. How the original developer figured out these numbers, I have no idea.\n keys = []\n\nThe linear congruential generator can produce up to 32 bits of output at a time. (In C this is a limitation of the data type; in Python I had to artificially enforce it.) I need 20 bytes to generate 4 40-bit (5-byte) WEP keys, so I'll iterate the PRNG 20 times,\n for i, b in enumerate(itertools.islice(prng(val, 0x343fd, 0x269ec3, 1<<32), 20)):\n\nand from each number, take only the 3rd byte from the right (bits 16-23):\n keys.append((b >> 16) & 0xff)\n\nWhy the third? Well, the bits at the high end (4th from the right) tend not to change much, and those at the low end can be predictable for many values of the PRNG constants.\nAfterwards, all that's left is to print out the generated bytes in groups of 5.\n print ('%02x:%02x:%02x:%02x:%02x\\n'*4) % tuple(keys)\n\n",
"I'm not sure what \"de facto standard\" that website is talking about, but I'm fairly sure router manufacturers all implement their own methods. It doesn't matter how you do it, as long as the same input always results in the same output; it's a convenience so WEP users can remember a passphrase instead of the actual hex key. Even the method in the PDF you posted is largely ambiguous; it uses an undefined PRNG (and every type of PRNG is going to give a different result), and takes \"one byte\" from each result without specifying which. If you're trying to reverse engineer a particular router's method, mention that in the post and we might be able to find out how that one works, but there isn't a standard method\n"
] | [
5,
1
] | [] | [] | [
"python",
"wep",
"xor"
] | stackoverflow_0002890438_python_wep_xor.txt |
Q:
How to map one class against multiple tables with SQLAlchemy?
Lets say that I have a database structure with three tables that look like this:
items
- item_id
- item_handle
attributes
- attribute_id
- attribute_name
item_attributes
- item_attribute_id
- item_id
- attribute_id
- attribute_value
I would like to be able to do this in SQLAlchemy:
item = Item('item1')
item.foo = 'bar'
session.add(item)
session.commit()
item1 = session.query(Item).filter_by(handle='item1').one()
print item1.foo # => 'bar'
I'm new to SQLAlchemy and I found this in the documentation (http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables):
j = join(items, item_attributes, items.c.item_id == item_attributes.c.item_id). \
join(attributes, item_attributes.c.attribute_id == attributes.c.attribute_id)
mapper(Item, j, properties={
'item_id': [items.c.item_id, item_attributes.c.item_id],
'attribute_id': [item_attributes.c.attribute_id, attributes.c.attribute_id],
})
It only adds item_id and attribute_id to Item and its not possible to add attributes to Item object.
Is what I'm trying to achieve possible with SQLAlchemy? Is there a better way to structure the database to get the same behaviour of "dynamic columns"?
A:
This is called the entity-attribute-value pattern. There is an example about this under the SQLAlchemy examples directory: vertical/.
If you are using PostgreSQL, then there is also the hstore contrib module that can store a string to string mapping. If you are interested then I have some code for a custom type that makes it possible to use that to store extended attributes via SQLAlchemy.
Another option to store custom attributes is to serialize them to a text field. In that case you will lose the ability to filter by attributes.
A:
The link to vertical/vertical.py is broken. The example had been renamed to dictlike-polymorphic.py and dictlike.py.
I am pasting in the contents of dictlike.py:
"""Mapping a vertical table as a dictionary.
This example illustrates accessing and modifying a "vertical" (or
"properties", or pivoted) table via a dict-like interface. These are tables
that store free-form object properties as rows instead of columns. For
example, instead of::
# A regular ("horizontal") table has columns for 'species' and 'size'
Table('animal', metadata,
Column('id', Integer, primary_key=True),
Column('species', Unicode),
Column('size', Unicode))
A vertical table models this as two tables: one table for the base or parent
entity, and another related table holding key/value pairs::
Table('animal', metadata,
Column('id', Integer, primary_key=True))
# The properties table will have one row for a 'species' value, and
# another row for the 'size' value.
Table('properties', metadata
Column('animal_id', Integer, ForeignKey('animal.id'),
primary_key=True),
Column('key', UnicodeText),
Column('value', UnicodeText))
Because the key/value pairs in a vertical scheme are not fixed in advance,
accessing them like a Python dict can be very convenient. The example below
can be used with many common vertical schemas as-is or with minor adaptations.
"""
class VerticalProperty(object):
"""A key/value pair.
This class models rows in the vertical table.
"""
def __init__(self, key, value):
self.key = key
self.value = value
def __repr__(self):
return '<%s %r=%r>' % (self.__class__.__name__, self.key, self.value)
class VerticalPropertyDictMixin(object):
"""Adds obj[key] access to a mapped class.
This is a mixin class. It can be inherited from directly, or included
with multiple inheritence.
Classes using this mixin must define two class properties::
_property_type:
The mapped type of the vertical key/value pair instances. Will be
invoked with two positional arugments: key, value
_property_mapping:
A string, the name of the Python attribute holding a dict-based
relationship of _property_type instances.
Using the VerticalProperty class above as an example,::
class MyObj(VerticalPropertyDictMixin):
_property_type = VerticalProperty
_property_mapping = 'props'
mapper(MyObj, sometable, properties={
'props': relationship(VerticalProperty,
collection_class=attribute_mapped_collection('key'))})
Dict-like access to MyObj is proxied through to the 'props' relationship::
myobj['key'] = 'value'
# ...is shorthand for:
myobj.props['key'] = VerticalProperty('key', 'value')
myobj['key'] = 'updated value']
# ...is shorthand for:
myobj.props['key'].value = 'updated value'
print myobj['key']
# ...is shorthand for:
print myobj.props['key'].value
"""
_property_type = VerticalProperty
_property_mapping = None
__map = property(lambda self: getattr(self, self._property_mapping))
def __getitem__(self, key):
return self.__map[key].value
def __setitem__(self, key, value):
property = self.__map.get(key, None)
if property is None:
self.__map[key] = self._property_type(key, value)
else:
property.value = value
def __delitem__(self, key):
del self.__map[key]
def __contains__(self, key):
return key in self.__map
# Implement other dict methods to taste. Here are some examples:
def keys(self):
return self.__map.keys()
def values(self):
return [prop.value for prop in self.__map.values()]
def items(self):
return [(key, prop.value) for key, prop in self.__map.items()]
def __iter__(self):
return iter(self.keys())
if __name__ == '__main__':
from sqlalchemy import (MetaData, Table, Column, Integer, Unicode,
ForeignKey, UnicodeText, and_, not_)
from sqlalchemy.orm import mapper, relationship, create_session
from sqlalchemy.orm.collections import attribute_mapped_collection
metadata = MetaData()
# Here we have named animals, and a collection of facts about them.
animals = Table('animal', metadata,
Column('id', Integer, primary_key=True),
Column('name', Unicode(100)))
facts = Table('facts', metadata,
Column('animal_id', Integer, ForeignKey('animal.id'),
primary_key=True),
Column('key', Unicode(64), primary_key=True),
Column('value', UnicodeText, default=None),)
class AnimalFact(VerticalProperty):
"""A fact about an animal."""
class Animal(VerticalPropertyDictMixin):
"""An animal.
Animal facts are available via the 'facts' property or by using
dict-like accessors on an Animal instance::
cat['color'] = 'calico'
# or, equivalently:
cat.facts['color'] = AnimalFact('color', 'calico')
"""
_property_type = AnimalFact
_property_mapping = 'facts'
def __init__(self, name):
self.name = name
def __repr__(self):
return '<%s %r>' % (self.__class__.__name__, self.name)
mapper(Animal, animals, properties={
'facts': relationship(
AnimalFact, backref='animal',
collection_class=attribute_mapped_collection('key')),
})
mapper(AnimalFact, facts)
metadata.bind = 'sqlite:///'
metadata.create_all()
session = create_session()
stoat = Animal(u'stoat')
stoat[u'color'] = u'reddish'
stoat[u'cuteness'] = u'somewhat'
# dict-like assignment transparently creates entries in the
# stoat.facts collection:
print stoat.facts[u'color']
session.add(stoat)
session.flush()
session.expunge_all()
critter = session.query(Animal).filter(Animal.name == u'stoat').one()
print critter[u'color']
print critter[u'cuteness']
critter[u'cuteness'] = u'very'
print 'changing cuteness:'
metadata.bind.echo = True
session.flush()
metadata.bind.echo = False
marten = Animal(u'marten')
marten[u'color'] = u'brown'
marten[u'cuteness'] = u'somewhat'
session.add(marten)
shrew = Animal(u'shrew')
shrew[u'cuteness'] = u'somewhat'
shrew[u'poisonous-part'] = u'saliva'
session.add(shrew)
loris = Animal(u'slow loris')
loris[u'cuteness'] = u'fairly'
loris[u'poisonous-part'] = u'elbows'
session.add(loris)
session.flush()
q = (session.query(Animal).
filter(Animal.facts.any(
and_(AnimalFact.key == u'color',
AnimalFact.value == u'reddish'))))
print 'reddish animals', q.all()
# Save some typing by wrapping that up in a function:
with_characteristic = lambda key, value: and_(AnimalFact.key == key,
AnimalFact.value == value)
q = (session.query(Animal).
filter(Animal.facts.any(
with_characteristic(u'color', u'brown'))))
print 'brown animals', q.all()
q = (session.query(Animal).
filter(not_(Animal.facts.any(
with_characteristic(u'poisonous-part', u'elbows')))))
print 'animals without poisonous-part == elbows', q.all()
q = (session.query(Animal).
filter(Animal.facts.any(AnimalFact.value == u'somewhat')))
print 'any animal with any .value of "somewhat"', q.all()
# Facts can be queried as well.
q = (session.query(AnimalFact).
filter(with_characteristic(u'cuteness', u'very')))
print 'just the facts', q.all()
metadata.drop_all()
| How to map one class against multiple tables with SQLAlchemy? | Lets say that I have a database structure with three tables that look like this:
items
- item_id
- item_handle
attributes
- attribute_id
- attribute_name
item_attributes
- item_attribute_id
- item_id
- attribute_id
- attribute_value
I would like to be able to do this in SQLAlchemy:
item = Item('item1')
item.foo = 'bar'
session.add(item)
session.commit()
item1 = session.query(Item).filter_by(handle='item1').one()
print item1.foo # => 'bar'
I'm new to SQLAlchemy and I found this in the documentation (http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables):
j = join(items, item_attributes, items.c.item_id == item_attributes.c.item_id). \
join(attributes, item_attributes.c.attribute_id == attributes.c.attribute_id)
mapper(Item, j, properties={
'item_id': [items.c.item_id, item_attributes.c.item_id],
'attribute_id': [item_attributes.c.attribute_id, attributes.c.attribute_id],
})
It only adds item_id and attribute_id to Item and its not possible to add attributes to Item object.
Is what I'm trying to achieve possible with SQLAlchemy? Is there a better way to structure the database to get the same behaviour of "dynamic columns"?
| [
"This is called the entity-attribute-value pattern. There is an example about this under the SQLAlchemy examples directory: vertical/.\nIf you are using PostgreSQL, then there is also the hstore contrib module that can store a string to string mapping. If you are interested then I have some code for a custom type that makes it possible to use that to store extended attributes via SQLAlchemy.\nAnother option to store custom attributes is to serialize them to a text field. In that case you will lose the ability to filter by attributes.\n",
"The link to vertical/vertical.py is broken. The example had been renamed to dictlike-polymorphic.py and dictlike.py.\nI am pasting in the contents of dictlike.py:\n\"\"\"Mapping a vertical table as a dictionary.\n\nThis example illustrates accessing and modifying a \"vertical\" (or\n\"properties\", or pivoted) table via a dict-like interface. These are tables\nthat store free-form object properties as rows instead of columns. For\nexample, instead of::\n\n # A regular (\"horizontal\") table has columns for 'species' and 'size'\n Table('animal', metadata,\n Column('id', Integer, primary_key=True),\n Column('species', Unicode),\n Column('size', Unicode))\n\nA vertical table models this as two tables: one table for the base or parent\nentity, and another related table holding key/value pairs::\n\n Table('animal', metadata,\n Column('id', Integer, primary_key=True))\n\n # The properties table will have one row for a 'species' value, and\n # another row for the 'size' value.\n Table('properties', metadata\n Column('animal_id', Integer, ForeignKey('animal.id'),\n primary_key=True),\n Column('key', UnicodeText),\n Column('value', UnicodeText))\n\nBecause the key/value pairs in a vertical scheme are not fixed in advance,\naccessing them like a Python dict can be very convenient. The example below\ncan be used with many common vertical schemas as-is or with minor adaptations.\n\n\"\"\"\n\nclass VerticalProperty(object):\n \"\"\"A key/value pair.\n\n This class models rows in the vertical table.\n \"\"\"\n\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n def __repr__(self):\n return '<%s %r=%r>' % (self.__class__.__name__, self.key, self.value)\n\n\nclass VerticalPropertyDictMixin(object):\n \"\"\"Adds obj[key] access to a mapped class.\n\n This is a mixin class. It can be inherited from directly, or included\n with multiple inheritence.\n\n Classes using this mixin must define two class properties::\n\n _property_type:\n The mapped type of the vertical key/value pair instances. Will be\n invoked with two positional arugments: key, value\n\n _property_mapping:\n A string, the name of the Python attribute holding a dict-based\n relationship of _property_type instances.\n\n Using the VerticalProperty class above as an example,::\n\n class MyObj(VerticalPropertyDictMixin):\n _property_type = VerticalProperty\n _property_mapping = 'props'\n\n mapper(MyObj, sometable, properties={\n 'props': relationship(VerticalProperty,\n collection_class=attribute_mapped_collection('key'))})\n\n Dict-like access to MyObj is proxied through to the 'props' relationship::\n\n myobj['key'] = 'value'\n # ...is shorthand for:\n myobj.props['key'] = VerticalProperty('key', 'value')\n\n myobj['key'] = 'updated value']\n # ...is shorthand for:\n myobj.props['key'].value = 'updated value'\n\n print myobj['key']\n # ...is shorthand for:\n print myobj.props['key'].value\n\n \"\"\"\n\n _property_type = VerticalProperty\n _property_mapping = None\n\n __map = property(lambda self: getattr(self, self._property_mapping))\n\n def __getitem__(self, key):\n return self.__map[key].value\n\n def __setitem__(self, key, value):\n property = self.__map.get(key, None)\n if property is None:\n self.__map[key] = self._property_type(key, value)\n else:\n property.value = value\n\n def __delitem__(self, key):\n del self.__map[key]\n\n def __contains__(self, key):\n return key in self.__map\n\n # Implement other dict methods to taste. Here are some examples:\n def keys(self):\n return self.__map.keys()\n\n def values(self):\n return [prop.value for prop in self.__map.values()]\n\n def items(self):\n return [(key, prop.value) for key, prop in self.__map.items()]\n\n def __iter__(self):\n return iter(self.keys())\n\n\nif __name__ == '__main__':\n from sqlalchemy import (MetaData, Table, Column, Integer, Unicode,\n ForeignKey, UnicodeText, and_, not_)\n from sqlalchemy.orm import mapper, relationship, create_session\n from sqlalchemy.orm.collections import attribute_mapped_collection\n\n metadata = MetaData()\n\n # Here we have named animals, and a collection of facts about them.\n animals = Table('animal', metadata,\n Column('id', Integer, primary_key=True),\n Column('name', Unicode(100)))\n\n facts = Table('facts', metadata,\n Column('animal_id', Integer, ForeignKey('animal.id'),\n primary_key=True),\n Column('key', Unicode(64), primary_key=True),\n Column('value', UnicodeText, default=None),)\n\n class AnimalFact(VerticalProperty):\n \"\"\"A fact about an animal.\"\"\"\n\n class Animal(VerticalPropertyDictMixin):\n \"\"\"An animal.\n\n Animal facts are available via the 'facts' property or by using\n dict-like accessors on an Animal instance::\n\n cat['color'] = 'calico'\n # or, equivalently:\n cat.facts['color'] = AnimalFact('color', 'calico')\n \"\"\"\n\n _property_type = AnimalFact\n _property_mapping = 'facts'\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return '<%s %r>' % (self.__class__.__name__, self.name)\n\n\n mapper(Animal, animals, properties={\n 'facts': relationship(\n AnimalFact, backref='animal',\n collection_class=attribute_mapped_collection('key')),\n })\n mapper(AnimalFact, facts)\n\n\n metadata.bind = 'sqlite:///'\n metadata.create_all()\n session = create_session()\n\n stoat = Animal(u'stoat')\n stoat[u'color'] = u'reddish'\n stoat[u'cuteness'] = u'somewhat'\n\n # dict-like assignment transparently creates entries in the\n # stoat.facts collection:\n print stoat.facts[u'color']\n\n session.add(stoat)\n session.flush()\n session.expunge_all()\n\n critter = session.query(Animal).filter(Animal.name == u'stoat').one()\n print critter[u'color']\n print critter[u'cuteness']\n\n critter[u'cuteness'] = u'very'\n\n print 'changing cuteness:'\n metadata.bind.echo = True\n session.flush()\n metadata.bind.echo = False\n\n marten = Animal(u'marten')\n marten[u'color'] = u'brown'\n marten[u'cuteness'] = u'somewhat'\n session.add(marten)\n\n shrew = Animal(u'shrew')\n shrew[u'cuteness'] = u'somewhat'\n shrew[u'poisonous-part'] = u'saliva'\n session.add(shrew)\n\n loris = Animal(u'slow loris')\n loris[u'cuteness'] = u'fairly'\n loris[u'poisonous-part'] = u'elbows'\n session.add(loris)\n session.flush()\n\n q = (session.query(Animal).\n filter(Animal.facts.any(\n and_(AnimalFact.key == u'color',\n AnimalFact.value == u'reddish'))))\n print 'reddish animals', q.all()\n\n # Save some typing by wrapping that up in a function:\n with_characteristic = lambda key, value: and_(AnimalFact.key == key,\n AnimalFact.value == value)\n\n q = (session.query(Animal).\n filter(Animal.facts.any(\n with_characteristic(u'color', u'brown'))))\n print 'brown animals', q.all()\n\n q = (session.query(Animal).\n filter(not_(Animal.facts.any(\n with_characteristic(u'poisonous-part', u'elbows')))))\n print 'animals without poisonous-part == elbows', q.all()\n\n q = (session.query(Animal).\n filter(Animal.facts.any(AnimalFact.value == u'somewhat')))\n print 'any animal with any .value of \"somewhat\"', q.all()\n\n # Facts can be queried as well.\n q = (session.query(AnimalFact).\n filter(with_characteristic(u'cuteness', u'very')))\n print 'just the facts', q.all()\n\n\n metadata.drop_all()\n\n"
] | [
8,
6
] | [] | [] | [
"database",
"database_design",
"python",
"sqlalchemy"
] | stackoverflow_0001300433_database_database_design_python_sqlalchemy.txt |
Q:
AppEngine dev_appserver.py aborts with no error message
I have an app which works well live on AppEngine.
However, when I try to run it locally with the dev_appserver.py, it aborts within ~1 second with:
~/ dev_appserver.py --debug_imports myapp
/opt/local/share/google_appengine/google/appengine/api/datastore_file_stub.py:40: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
/opt/local/share/google_appengine/google/appengine/api/memcache/__init__.py:31: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
import sha
I'm on OS X 10.6.3, Python 2.6.4 + Django 1.1.1 + appengine 1.3.1 (all installed via macports)
Any ideas?
Thanks!
A:
Edit: the answer below is potentially no longer relevant depending on individual use-case as Python 2.7 is now supported on App Engine.
App Engine only works with Python 2.5.x
Install 2.5, and run explicitly.
For example:
python2.5 /path/to/dev_appserver.py myapp
A:
I had the same problem, it seems that after I installed py26-googleappengine using macports and adding its subdirs to my PATH the first dev_appserver.py found was at
/opt/local/share/google_appengine/google/appengine/tools/dev_appserver.py
When I changed it to be the other copy found at
/opt/local/share/google_appengine/dev_appserver.py
all started working normally.
The two files are vastly different...
Unlike what Adam said, it works fine for me with Python 2.6.
| AppEngine dev_appserver.py aborts with no error message | I have an app which works well live on AppEngine.
However, when I try to run it locally with the dev_appserver.py, it aborts within ~1 second with:
~/ dev_appserver.py --debug_imports myapp
/opt/local/share/google_appengine/google/appengine/api/datastore_file_stub.py:40: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
/opt/local/share/google_appengine/google/appengine/api/memcache/__init__.py:31: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
import sha
I'm on OS X 10.6.3, Python 2.6.4 + Django 1.1.1 + appengine 1.3.1 (all installed via macports)
Any ideas?
Thanks!
| [
"Edit: the answer below is potentially no longer relevant depending on individual use-case as Python 2.7 is now supported on App Engine.\n\nApp Engine only works with Python 2.5.x\nInstall 2.5, and run explicitly.\nFor example:\n\npython2.5 /path/to/dev_appserver.py myapp\n\n",
"I had the same problem, it seems that after I installed py26-googleappengine using macports and adding its subdirs to my PATH the first dev_appserver.py found was at\n\n/opt/local/share/google_appengine/google/appengine/tools/dev_appserver.py\n\nWhen I changed it to be the other copy found at\n/opt/local/share/google_appengine/dev_appserver.py\n\nall started working normally.\nThe two files are vastly different...\nUnlike what Adam said, it works fine for me with Python 2.6.\n"
] | [
4,
1
] | [] | [] | [
"django",
"google_app_engine",
"macos",
"python"
] | stackoverflow_0002624686_django_google_app_engine_macos_python.txt |
Q:
In Ruby or Python can the very concept of Class be rewritten?
first time at stack overflow.
I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of Class. This doesn't mean that I want to rewrite a specific class during run time, but rather I want to make my own conceptualization of what a Class is. To be a smidge more specific here, I want to make something that is like what people normally call a Class, but I want to follow an "open world" assumption. In the "closed world" of normal Classes, if I declare Poodle to be a subclass of Dog to be a subclass of Animal, then I know that Poodle is not going to also be a type of FurCoat. However, in an open world Class, then the Poodle object I've defined may or may not be and object of type FurCoat and we won't know for sure until I explain that I can wear the poodle. (Poor poodle.) This all has to do with a study I'm doing concerning OWL ontologies.
Just so you know, I've tried to find information online, but due to the overloading of terms here I haven't found anything helpful.
Super thanks,
John
UPDATE: I just thought of a good use case for my open-world concept of Class. Perhaps this will provide a better understanding of what I really wish to do. I want to be able to "describe" a Class rather than define it. For instance, I want to be able to say that a Dog is anything that a) has four legs b) barks. Then I want to be able to create an object of unspecified Class, and describe that this object has four legs. At this point the object is still of unspecified type. Then I want to say that the object barks. At this point, the object will be known to be (possibly among other things) a Dog.
A:
Sounds like duck typing to me. Just declare the methods you want and remember that it's easier to ask forgiveness than permission:
try:
poodle.wear()
except (AttributeError, TypeError):
pass
A:
I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object really 'is' you only need bother with what an object can 'do'. This is true in both Ruby and Python.
However if you really are checking the types of classes and you really do need to have a Poodle object optionally also be a FurCoat at runtime, then the way to do this in Ruby is to mixin a FurCoat module into the Poodle object, as follows:
class Poodle; end
module FurCoat; def wear; end; end
my_poodle = Poodle.new
my_poodle.is_a?(Poodle) #=> true
my_poodle.is_a?(FurCoat) #=> false
my_poodle.wear #=> NoMethodError
# now we mix in the FurCoat module
my_poodle.extend(FurCoat)
# my_poodle is now also a FurCoat
my_poodle.is_a?(Poodle) #=> true (still)
my_poodle.is_a?(FurCoat) #=> true
my_poodle.wear #=> the wear method now works
EDIT (due to your updated question):
You still do not need to rewrite Class to achieve what you want, you just need to monkey-patch the kind_of? and is_a? (and potentially instance_of?) methods on Ruby's Kernel module. Since Ruby has open classes this is easily done:
class Module
def obj_implements_interface?(obj)
false
end
end
module Kernel
alias_method :orig_is_a?, :is_a?
def is_a?(klass)
orig_is_a?(klass) || klass.obj_implements_interface?(self)
end
end
And then define for each class (or module) what it means for an object to implement its interface:
class Dog
def self.obj_implements_interface?(obj)
obj.respond_to?(:bark) && obj.respond_to?(:num_legs) && obj.num_legs == 4
end
end
module FurCoat
def self.obj_implements_interface?(obj)
obj.respond_to?(:wear)
end
end
Now test it:
my_poodle = Poodle.new
my_poodle.is_a?(FurCoat) #=> false
# now define a wear method on my_poodle
def my_poodle.wear; end
my_poodle.is_a?(FurCoat) #=> true
A:
No, you cannot do that in Ruby. In Ruby, the object model is baked into the language specification and is not accessible (and certainly not modifiable) from within the program. Even in Rubinius, which is a Ruby implementation written mostly in Ruby, and with amazing metaprogramming capabilities that extend far beyond what the Ruby specification offers, some of the fundamental primitives are hardwired in C++.
I am not that intimately familiar with Python, but I'm pretty sure it's the same way, even in PyPy.
You might be able to do that in Smalltalk, by modifying (or subclassing) the Behavior class, which is the superclass of Class and defines the behavior of both classes and metaclasses.
You can certainly do that in CLOS, or more precisely using CLOS's MOP (Meta-Object Protocol). After all, that's what a MOP is for: defining the object model.
The closest OO concept to what you are describing seems to be that of Predicate Classes. A predicate class is a class whose instances are not defined statically, but by a set of predicates: all objects that satisfy the set of predicates are instances of the class, as soon as and for as long as the predicate holds. In a language with mutable state, this obviously means that objects can "move" in and out of predicate classes as their state changes. It also means that at any given time an object can be an instance of many or no predicate classes.
The only mainstream language (for a rather broad definition of "mainstream") I know of that has predicate classes is Factor.
However, please note that even here, the predicates are defined and an object either fulfils them or it doesn't. There is no concept of discovering whether or not an object fulfils a predicate at runtime.
You might also be interested in Clojure's idea of ad-hoc taxonomy.
Last, but certainly not least, you might take a look at Mikel Evins's object system called Categories. The best description of Categories, is to simply follow the blog entries in chronological order:
Protocols
Categories
A peek at Categories
No Kings in Rome
Up pops a reasonable facsimile thereof
Different Categories of Categories
Categories Bugs
Flat Cat in a C3 Vat
Categories 0.2
Bard
Bard intricacies
In the future, most of the development on Categories is going to be done in Mikel's new language Bard and you can follow their progress by following the Categories tag and the Bard tag on Mikel's new blog.
However, in general, I would say that the fact that Knowledge Management and Object-Orientation both use the word class is mainly a historic accident. I don't think that modeling one with the other is a good fit.
A:
In Python you can change the inheritence of a class at runtime, but at every given time a class is not a subclass of another one unless declared otherwise. There is no "may or may not" - that would need ternary logic which Python doesn't support. But of course you can write your own "Is-a" and "Has-a" functions to map OWL ontologies to Python classes.
A:
I think relying on a class structure, no matter how dynamic, is a step backwards when representing information with an open word assumption.
Classes serving as templates and objects serving as instances give absolutely no advantage when used with an OWA. Consider a Person class where we encode the knowledge that a person has 2 legs. However, we cannot deduce that a instance of Person will have two legs, as the person may have a disability.
If class properties don't mean anything as in the above example, there seems little point in using them or any other hierarchical structure to encode information.
| In Ruby or Python can the very concept of Class be rewritten? | first time at stack overflow.
I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of Class. This doesn't mean that I want to rewrite a specific class during run time, but rather I want to make my own conceptualization of what a Class is. To be a smidge more specific here, I want to make something that is like what people normally call a Class, but I want to follow an "open world" assumption. In the "closed world" of normal Classes, if I declare Poodle to be a subclass of Dog to be a subclass of Animal, then I know that Poodle is not going to also be a type of FurCoat. However, in an open world Class, then the Poodle object I've defined may or may not be and object of type FurCoat and we won't know for sure until I explain that I can wear the poodle. (Poor poodle.) This all has to do with a study I'm doing concerning OWL ontologies.
Just so you know, I've tried to find information online, but due to the overloading of terms here I haven't found anything helpful.
Super thanks,
John
UPDATE: I just thought of a good use case for my open-world concept of Class. Perhaps this will provide a better understanding of what I really wish to do. I want to be able to "describe" a Class rather than define it. For instance, I want to be able to say that a Dog is anything that a) has four legs b) barks. Then I want to be able to create an object of unspecified Class, and describe that this object has four legs. At this point the object is still of unspecified type. Then I want to say that the object barks. At this point, the object will be known to be (possibly among other things) a Dog.
| [
"Sounds like duck typing to me. Just declare the methods you want and remember that it's easier to ask forgiveness than permission:\ntry:\n poodle.wear()\nexcept (AttributeError, TypeError):\n pass\n\n",
"I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object really 'is' you only need bother with what an object can 'do'. This is true in both Ruby and Python.\nHowever if you really are checking the types of classes and you really do need to have a Poodle object optionally also be a FurCoat at runtime, then the way to do this in Ruby is to mixin a FurCoat module into the Poodle object, as follows:\nclass Poodle; end\nmodule FurCoat; def wear; end; end\n\nmy_poodle = Poodle.new\nmy_poodle.is_a?(Poodle) #=> true\nmy_poodle.is_a?(FurCoat) #=> false\nmy_poodle.wear #=> NoMethodError\n\n# now we mix in the FurCoat module\nmy_poodle.extend(FurCoat)\n\n# my_poodle is now also a FurCoat\nmy_poodle.is_a?(Poodle) #=> true (still)\nmy_poodle.is_a?(FurCoat) #=> true\nmy_poodle.wear #=> the wear method now works\n\nEDIT (due to your updated question):\nYou still do not need to rewrite Class to achieve what you want, you just need to monkey-patch the kind_of? and is_a? (and potentially instance_of?) methods on Ruby's Kernel module. Since Ruby has open classes this is easily done:\nclass Module\n def obj_implements_interface?(obj)\n false\n end\nend\n\nmodule Kernel\n alias_method :orig_is_a?, :is_a?\n\n def is_a?(klass)\n orig_is_a?(klass) || klass.obj_implements_interface?(self)\n end\nend\n\nAnd then define for each class (or module) what it means for an object to implement its interface:\nclass Dog\n def self.obj_implements_interface?(obj)\n obj.respond_to?(:bark) && obj.respond_to?(:num_legs) && obj.num_legs == 4\n end\nend\n\nmodule FurCoat\n def self.obj_implements_interface?(obj)\n obj.respond_to?(:wear)\n end\nend\n\nNow test it:\nmy_poodle = Poodle.new\nmy_poodle.is_a?(FurCoat) #=> false\n\n# now define a wear method on my_poodle\ndef my_poodle.wear; end\nmy_poodle.is_a?(FurCoat) #=> true\n\n",
"No, you cannot do that in Ruby. In Ruby, the object model is baked into the language specification and is not accessible (and certainly not modifiable) from within the program. Even in Rubinius, which is a Ruby implementation written mostly in Ruby, and with amazing metaprogramming capabilities that extend far beyond what the Ruby specification offers, some of the fundamental primitives are hardwired in C++.\nI am not that intimately familiar with Python, but I'm pretty sure it's the same way, even in PyPy.\nYou might be able to do that in Smalltalk, by modifying (or subclassing) the Behavior class, which is the superclass of Class and defines the behavior of both classes and metaclasses.\nYou can certainly do that in CLOS, or more precisely using CLOS's MOP (Meta-Object Protocol). After all, that's what a MOP is for: defining the object model.\nThe closest OO concept to what you are describing seems to be that of Predicate Classes. A predicate class is a class whose instances are not defined statically, but by a set of predicates: all objects that satisfy the set of predicates are instances of the class, as soon as and for as long as the predicate holds. In a language with mutable state, this obviously means that objects can \"move\" in and out of predicate classes as their state changes. It also means that at any given time an object can be an instance of many or no predicate classes.\nThe only mainstream language (for a rather broad definition of \"mainstream\") I know of that has predicate classes is Factor.\nHowever, please note that even here, the predicates are defined and an object either fulfils them or it doesn't. There is no concept of discovering whether or not an object fulfils a predicate at runtime.\nYou might also be interested in Clojure's idea of ad-hoc taxonomy.\nLast, but certainly not least, you might take a look at Mikel Evins's object system called Categories. The best description of Categories, is to simply follow the blog entries in chronological order:\n\nProtocols\nCategories\nA peek at Categories\nNo Kings in Rome\nUp pops a reasonable facsimile thereof\nDifferent Categories of Categories\nCategories Bugs\nFlat Cat in a C3 Vat\nCategories 0.2\nBard\nBard intricacies\n\nIn the future, most of the development on Categories is going to be done in Mikel's new language Bard and you can follow their progress by following the Categories tag and the Bard tag on Mikel's new blog.\nHowever, in general, I would say that the fact that Knowledge Management and Object-Orientation both use the word class is mainly a historic accident. I don't think that modeling one with the other is a good fit.\n",
"In Python you can change the inheritence of a class at runtime, but at every given time a class is not a subclass of another one unless declared otherwise. There is no \"may or may not\" - that would need ternary logic which Python doesn't support. But of course you can write your own \"Is-a\" and \"Has-a\" functions to map OWL ontologies to Python classes.\n",
"I think relying on a class structure, no matter how dynamic, is a step backwards when representing information with an open word assumption.\nClasses serving as templates and objects serving as instances give absolutely no advantage when used with an OWA. Consider a Person class where we encode the knowledge that a person has 2 legs. However, we cannot deduce that a instance of Person will have two legs, as the person may have a disability. \nIf class properties don't mean anything as in the above example, there seems little point in using them or any other hierarchical structure to encode information.\n"
] | [
8,
7,
6,
2,
1
] | [] | [] | [
"class",
"metaprogramming",
"ontology",
"python",
"ruby"
] | stackoverflow_0002890229_class_metaprogramming_ontology_python_ruby.txt |
Q:
Is there really no binary distribution of MySQLdb for Windows?
You have to build it yourself? Or am I missing something.
A:
There are, however, oursql binaries for Windows. Read about oursql here.
A:
There's no "official" binary, but I found some on this site (for 2.6 32 or 64 bit, or 2.5 64 bit) via the MySQLdb page on Pypi. Also, this blog has instructions on how to build MySQLdb on Windows if you're feeling up to the task.
| Is there really no binary distribution of MySQLdb for Windows? | You have to build it yourself? Or am I missing something.
| [
"There are, however, oursql binaries for Windows. Read about oursql here.\n",
"There's no \"official\" binary, but I found some on this site (for 2.6 32 or 64 bit, or 2.5 64 bit) via the MySQLdb page on Pypi. Also, this blog has instructions on how to build MySQLdb on Windows if you're feeling up to the task.\n"
] | [
2,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002890551_mysql_python.txt |
Q:
How to generate graphs and statistics from SQLAlchemy tables?
After running a bunch of simulations I'm going to be outputting the results into a table created using SQLAlchemy. I plan to use this data to generate statistics - mean and variance being key. These, in turn, will be used to generate some graphs - histograms/line graphs, pie-charts and box-and-whisker plots specifically.
I'm aware of the Python graphing libraries like matplotlib. The thing is, I'm not sure how to have this integrate with the information contained within the database tables.
Any suggestions on how to make these two play with each other?
The main problem is that I'm not sure how to supply the information as "data sets" to the graphing library.
A:
It looks like matplotlib takes simple python data types -- lists of numbers, etc, so you'll be need to write custom code to massage what you pull out of mysql/sqlalchemy for input into the graphing functions...
| How to generate graphs and statistics from SQLAlchemy tables? | After running a bunch of simulations I'm going to be outputting the results into a table created using SQLAlchemy. I plan to use this data to generate statistics - mean and variance being key. These, in turn, will be used to generate some graphs - histograms/line graphs, pie-charts and box-and-whisker plots specifically.
I'm aware of the Python graphing libraries like matplotlib. The thing is, I'm not sure how to have this integrate with the information contained within the database tables.
Any suggestions on how to make these two play with each other?
The main problem is that I'm not sure how to supply the information as "data sets" to the graphing library.
| [
"It looks like matplotlib takes simple python data types -- lists of numbers, etc, so you'll be need to write custom code to massage what you pull out of mysql/sqlalchemy for input into the graphing functions...\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python",
"sqlalchemy"
] | stackoverflow_0002890564_matplotlib_python_sqlalchemy.txt |
Q:
Why program with php frameworks if it can be done better with ruby on rails, python or java?
We have discussion in my job place about question (We use 1 of the php frameworks):
Why program with php frameworks big web application if it can be done better with ruby on rails, python or java?
Please say our opinion
thanks
A:
If you only know PHP and you don't feel like learning Ruby/Python/Java. Seriously, if it can be done better with another tool, it should be done with another tool. Of course, this assumes the other tools are actually better. That part is arguable. Some people are so stuck up on their "my way is the best way" that they leave out the "because it's the only way I know" part.
A:
"Better" is subjective. Does Rails have such a strong background & community full of tools like opcode cachers, memcache libs, PINBA, PHPFpm and many many more?
| Why program with php frameworks if it can be done better with ruby on rails, python or java? | We have discussion in my job place about question (We use 1 of the php frameworks):
Why program with php frameworks big web application if it can be done better with ruby on rails, python or java?
Please say our opinion
thanks
| [
"If you only know PHP and you don't feel like learning Ruby/Python/Java. Seriously, if it can be done better with another tool, it should be done with another tool. Of course, this assumes the other tools are actually better. That part is arguable. Some people are so stuck up on their \"my way is the best way\" that they leave out the \"because it's the only way I know\" part.\n",
"\"Better\" is subjective. Does Rails have such a strong background & community full of tools like opcode cachers, memcache libs, PINBA, PHPFpm and many many more?\n"
] | [
3,
2
] | [] | [] | [
"django",
"java",
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0002891017_django_java_php_python_ruby_on_rails.txt |
Q:
Reading lines including space
I want to read file including spaces in each lines
My current code
def data():
f = open("save.aln")
for line in f.readlines():
print "</br>"
print line
I am using python and output embedded in html
File to be read - http://pastebin.com/EaeKsyvg
Thanks
A:
It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets
def data():
print "<pre>"
f = open("save.aln")
for line in f.readlines():
print line
print "</pre>"
Note that in this case you don't need the <br> elements either, since the newline characters are also preserved.
A:
The problem that you are faced with is that HTML ignores multiple whitespaces. @itsadok's solution is great. I upvoted it. But, it's not the only way to do this either.
If you want to explicitly turn those whitespaces into HTML whitespace characters, you could to this:
def data():
f = open("save.aln")
for line in f.readlines():
print "<br />"
print line.replace(" ", " ")
Cheers
A:
import cgi
with open('save.aln') as f:
for line in f:
print cgi.escape(line) # escape <, >, &
print '<br/>'
| Reading lines including space | I want to read file including spaces in each lines
My current code
def data():
f = open("save.aln")
for line in f.readlines():
print "</br>"
print line
I am using python and output embedded in html
File to be read - http://pastebin.com/EaeKsyvg
Thanks
| [
"It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets\ndef data(): \n print \"<pre>\"\n f = open(\"save.aln\") \n for line in f.readlines(): \n print line\n print \"</pre>\"\n\nNote that in this case you don't need the <br> elements either, since the newline characters are also preserved.\n",
"The problem that you are faced with is that HTML ignores multiple whitespaces. @itsadok's solution is great. I upvoted it. But, it's not the only way to do this either.\nIf you want to explicitly turn those whitespaces into HTML whitespace characters, you could to this:\ndef data():\n f = open(\"save.aln\")\n for line in f.readlines():\n print \"<br />\"\n print line.replace(\" \", \" \")\n\nCheers\n",
"import cgi\nwith open('save.aln') as f:\n for line in f:\n print cgi.escape(line) # escape <, >, &\n print '<br/>'\n\n"
] | [
2,
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002890988_file_io_python.txt |
Q:
Using a dictionary to assign misspelled words to its line number
This is the code I currently have:
from collections import defaultdict
goodwords = set()
with open("soccer.txt", "rt") as f:
for word in f.readlines():
goodwords.add(word.strip())
badwords = defaultdict(list)
with open("soccer.txt", "rt") as f:
for line_no, line in enumerate(f):
for word in line.split():
if word not in text:
badwords[word].append(line_no)
print(badwords)
How can I fix my code so that it prints the incorrect words stored inside the words list and the line number?
For example if the word togeher was misspelled on lines 5 and 7, it would print something like:
togeher 5 7
A:
When you insert the new counter into d, you check first word is contained in words. Probably you wanted to check if word is already contained in d:
if word not in d:
d[word] = [counter]
else:
d[word].append(counter)
The check if the word is contained in words or line should be a separate if.
You could also simplify this logic with the dicts setdefault() method:
d.setdefault(word, []).append(counter)
Or you make d a defaultdict, which simplifies the assignment even more:
from collections import defaultdict
d = defaultdict(list)
...
d[word].append(counter)
About the general algorithm note that at the moment you first iterate over all lines to increment the counter and then, when the counter has already reached it's maximum value, start checking for misspelled words. Probably you should do the checking for each line in the loop where you increment the counter.
A:
Form what you are doing, I suspect that the following would suit you near perfectly:
from collections import defaultdict
text = ( "cat", "dog", "rat", "bat", "rat", "dog",
"man", "woman", "child", "child") #
d = defaultdict(list)
for lineno, word in enumerate(text):
d[word].append(lineno)
print d
This gives you an output of:
defaultdict(<type 'list'>, {'bat': [3], 'woman': [7], 'dog': [1, 5],
'cat': [0], 'rat': [2, 4], 'child': [8, 9],
'man': [6]})
This simply sets up an empty default dictionary containing a list for each item you access, so that you don't need to worry about creating the entry, and then enumerates it's way over the list of words, so you don't need to keep track of the line number.
As you don't have a list of correct spellings, this doesn't actually check if the words are correctly spelled, just builds a dictionary of all the words in the text file.
To convert the dictionary to a set of words, try:
all_words = set(d.keys())
print all_words
Which produces:
set(['bat', 'woman', 'dog', 'cat', 'rat', 'child', 'man'])
Or, just to print the words:
for word in d.keys():
print word
Edit 3:
I think this might be the final version:
It's a (deliberately) very crude, but almost complete spell checker.
from collections import defaultdict
# Build a set of all the words we know, assuming they're one word per line
good_words = set() # Use a set, as this will have the fastest look-up time.
with open("words.txt", "rt") as f:
for word in f.readlines():
good_words.add(word.strip())
bad_words = defaultdict(list)
with open("text_to_check.txt", "rt") as f:
# For every line of text, get the line number, and the text.
for line_no, line in enumerate(f):
# Split into seperate words - note there is an issue with punctuation,
# case sensitivitey, etc..
for word in line.split():
# If the word is not recognised, record the line where it occurred.
if word not in good_words:
bad_words[word].append(line_no)
At the end, bad_words will be a dictionary with the unrecognised words as the key, and the line numbers where the words were as the matching value entry.
| Using a dictionary to assign misspelled words to its line number | This is the code I currently have:
from collections import defaultdict
goodwords = set()
with open("soccer.txt", "rt") as f:
for word in f.readlines():
goodwords.add(word.strip())
badwords = defaultdict(list)
with open("soccer.txt", "rt") as f:
for line_no, line in enumerate(f):
for word in line.split():
if word not in text:
badwords[word].append(line_no)
print(badwords)
How can I fix my code so that it prints the incorrect words stored inside the words list and the line number?
For example if the word togeher was misspelled on lines 5 and 7, it would print something like:
togeher 5 7
| [
"When you insert the new counter into d, you check first word is contained in words. Probably you wanted to check if word is already contained in d:\nif word not in d:\n d[word] = [counter]\nelse:\n d[word].append(counter)\n\nThe check if the word is contained in words or line should be a separate if.\nYou could also simplify this logic with the dicts setdefault() method:\nd.setdefault(word, []).append(counter)\n\nOr you make d a defaultdict, which simplifies the assignment even more:\nfrom collections import defaultdict\nd = defaultdict(list)\n...\nd[word].append(counter)\n\nAbout the general algorithm note that at the moment you first iterate over all lines to increment the counter and then, when the counter has already reached it's maximum value, start checking for misspelled words. Probably you should do the checking for each line in the loop where you increment the counter.\n",
"Form what you are doing, I suspect that the following would suit you near perfectly:\nfrom collections import defaultdict\n\ntext = ( \"cat\", \"dog\", \"rat\", \"bat\", \"rat\", \"dog\",\n \"man\", \"woman\", \"child\", \"child\") #\n\nd = defaultdict(list)\n\nfor lineno, word in enumerate(text):\n d[word].append(lineno)\n\nprint d\n\nThis gives you an output of:\ndefaultdict(<type 'list'>, {'bat': [3], 'woman': [7], 'dog': [1, 5],\n 'cat': [0], 'rat': [2, 4], 'child': [8, 9],\n 'man': [6]})\n\nThis simply sets up an empty default dictionary containing a list for each item you access, so that you don't need to worry about creating the entry, and then enumerates it's way over the list of words, so you don't need to keep track of the line number.\nAs you don't have a list of correct spellings, this doesn't actually check if the words are correctly spelled, just builds a dictionary of all the words in the text file.\nTo convert the dictionary to a set of words, try:\nall_words = set(d.keys())\nprint all_words\n\nWhich produces:\nset(['bat', 'woman', 'dog', 'cat', 'rat', 'child', 'man'])\n\nOr, just to print the words:\nfor word in d.keys():\n print word\n\nEdit 3:\nI think this might be the final version:\nIt's a (deliberately) very crude, but almost complete spell checker.\nfrom collections import defaultdict\n\n# Build a set of all the words we know, assuming they're one word per line\ngood_words = set() # Use a set, as this will have the fastest look-up time.\nwith open(\"words.txt\", \"rt\") as f:\n for word in f.readlines():\n good_words.add(word.strip())\n\nbad_words = defaultdict(list)\n\nwith open(\"text_to_check.txt\", \"rt\") as f:\n # For every line of text, get the line number, and the text.\n for line_no, line in enumerate(f):\n # Split into seperate words - note there is an issue with punctuation,\n # case sensitivitey, etc..\n for word in line.split():\n # If the word is not recognised, record the line where it occurred.\n if word not in good_words:\n bad_words[word].append(line_no)\n\nAt the end, bad_words will be a dictionary with the unrecognised words as the key, and the line numbers where the words were as the matching value entry.\n"
] | [
1,
0
] | [] | [] | [
"dictionary",
"python",
"spell_checking"
] | stackoverflow_0002891632_dictionary_python_spell_checking.txt |
Q:
psycopg2 can't find my python26 installation
I believe it's because I installed python using SciPy, so apparently it's not in the registry where the psycopg2 installer is looking. Anyway to fix this without installing python26 over the existing install? I'm not sure if that will corrupt it.
EDIT: My PYTHONPATH looks like the following:
'C:\\Python26\\scripts',
'C:\\Python26\\lib\\site-packages\\apptools-3.3.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\blockcanvas-3.1.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\chaco-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\codetools-3.1.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\configobj-4.6.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\enable-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\enthoughtbase-3.0.3-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\envisagecore-3.1.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\envisageplugins-3.1.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\ets-3.3.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\etsdevtools-3.0.3-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\etsprojecttools-0.5.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\mayavi-3.3.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\scimath-3.0.4-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\setupdocs-1.0.3-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traits-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\traitsbackendqt-3.2.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traitsbackendwx-3.2.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traitsgui-3.1.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\python_twitter-0.6-py2.6.egg',
'C:\\Program Files (x86)\\OpenLibraries\\python',
'C:\\Python26\\python26.zip',
'C:\\Python26\\DLLs',
'C:\\Python26\\lib',
'C:\\Python26\\lib\\plat-win',
'C:\\Python26\\lib\\lib-tk',
'C:\\Python26',
'C:\\Python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\PIL',
'C:\\Python26\\lib\\site-packages\\win32',
'C:\\Python26\\lib\\site-packages\\win32\\lib',
'C:\\Python26\\lib\\site-packages\\Pythonwin',
'c:\\python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Python26\\lib\\site-packages\\IPython/Extensions',
A:
I found this script which can fix it:
http://effbot.org/zone/python-register.htm
| psycopg2 can't find my python26 installation | I believe it's because I installed python using SciPy, so apparently it's not in the registry where the psycopg2 installer is looking. Anyway to fix this without installing python26 over the existing install? I'm not sure if that will corrupt it.
EDIT: My PYTHONPATH looks like the following:
'C:\\Python26\\scripts',
'C:\\Python26\\lib\\site-packages\\apptools-3.3.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\blockcanvas-3.1.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\chaco-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\codetools-3.1.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\configobj-4.6.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\enable-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\enthoughtbase-3.0.3-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\envisagecore-3.1.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\envisageplugins-3.1.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\ets-3.3.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\etsdevtools-3.0.3-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\etsprojecttools-0.5.1-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\mayavi-3.3.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\scimath-3.0.4-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\setupdocs-1.0.3-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traits-3.2.0-py2.6-win32.egg',
'C:\\Python26\\lib\\site-packages\\traitsbackendqt-3.2.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traitsbackendwx-3.2.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\traitsgui-3.1.0-py2.6.egg',
'C:\\Python26\\lib\\site-packages\\python_twitter-0.6-py2.6.egg',
'C:\\Program Files (x86)\\OpenLibraries\\python',
'C:\\Python26\\python26.zip',
'C:\\Python26\\DLLs',
'C:\\Python26\\lib',
'C:\\Python26\\lib\\plat-win',
'C:\\Python26\\lib\\lib-tk',
'C:\\Python26',
'C:\\Python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\PIL',
'C:\\Python26\\lib\\site-packages\\win32',
'C:\\Python26\\lib\\site-packages\\win32\\lib',
'C:\\Python26\\lib\\site-packages\\Pythonwin',
'c:\\python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Python26\\lib\\site-packages\\IPython/Extensions',
| [
"I found this script which can fix it:\nhttp://effbot.org/zone/python-register.htm\n"
] | [
1
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0002890749_postgresql_psycopg2_python.txt |
Q:
File management
I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have it automatically.
Workflow goes like this.
----If submit is not true then display only header and form part
--- if submit is true then call execute() and get file name from form input
--- Then displaying result file name is same as executed file name but only change in extension
My raw code is here -- http://pastebin.com/FPUgZSSe
Any suggestions, changes and algorithm is appreciated
Thanks
A:
You need to read the uploaded file out of the cgi.FieldStorage() and save it onto the server. Ususally a temp directory (/tmp on Linux) is used for this. You should remove these files after processing or on some schedule to clean up the drive.
def main():
import cgi
import cgitb; cgitb.enable()
f1 = cgi.FieldStorage()
if "dfile" in f1:
fileitem = f1["dfile"]
pathtoTmpFile = os.path.join("path/to/temp/directory", fileitem.filename)
fout = file(pathtoTmpFile, 'wb')
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
execute(pathtoTmpFile)
os.remove(pathtoTmpFile)
else:
header()
form()
This modified the execute to take the path to the newly saved file.
cline = ClustalwCommandline("clustalw", infile=pathToFile)
For the result file, you could also stream it back so the user gets a "Save as..." dialog. That might be a little more usable than displaying it in HTML.
| File management | I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have it automatically.
Workflow goes like this.
----If submit is not true then display only header and form part
--- if submit is true then call execute() and get file name from form input
--- Then displaying result file name is same as executed file name but only change in extension
My raw code is here -- http://pastebin.com/FPUgZSSe
Any suggestions, changes and algorithm is appreciated
Thanks
| [
"You need to read the uploaded file out of the cgi.FieldStorage() and save it onto the server. Ususally a temp directory (/tmp on Linux) is used for this. You should remove these files after processing or on some schedule to clean up the drive.\ndef main():\n import cgi\n import cgitb; cgitb.enable()\n f1 = cgi.FieldStorage()\n if \"dfile\" in f1:\n fileitem = f1[\"dfile\"]\n pathtoTmpFile = os.path.join(\"path/to/temp/directory\", fileitem.filename)\n fout = file(pathtoTmpFile, 'wb')\n while 1:\n chunk = fileitem.file.read(100000)\n if not chunk: break\n fout.write (chunk)\n fout.close()\n execute(pathtoTmpFile)\n os.remove(pathtoTmpFile)\n else:\n header()\n form()\n\nThis modified the execute to take the path to the newly saved file.\ncline = ClustalwCommandline(\"clustalw\", infile=pathToFile)\n\nFor the result file, you could also stream it back so the user gets a \"Save as...\" dialog. That might be a little more usable than displaying it in HTML.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002891998_python.txt |
Q:
Bypassing import in Python so that I don't have to upload multiple libraries and classes?
For example, I have a few python scripts, that link together and some libraries for it that need to be imported. I'm trying to reduce it to only one script.
So instead of:
import library.py
Can I just take the coding from library.py and put into the main script?
A:
There are no limits to the size of a .py file, so you can certainly perform the copy and paste (and edit) operations you have in mind.
Some caveats:
import library.py
is unlikely to do what you want: it imports a module named py from a package named library. Thus it requires the existence of a directory library with an __init__.py and a py.py in it (or .pyc, etc). I suspect you mean import library.
Merging all the needed modules into one large .py file only works for modules for which you have Python sources (.py) -- you need different techniques if all you have for a module is bytecode .pyc or .pyo, and if any of the modules are native-code binary Python extensions (.pyd or .so or .dylib etc etc, depending on your system) that just won't work.
You may have to do some renaming, e.g. when you import two modules that both define name foo you'll have to alter one or both of those names foo. That's because, via imports, you get qualified names (so there's no problem if a.foo and b.foo both exist), but without imports you get bare names so you'll need to disambiguate them "manually".
A:
Yes you can do this, but probably it won't increase readability or maintainability.
Anyway be careful if you use functions like this:
import library
library.functionA()
If you copy the content of library.py, you have to rename the function call to just functionA().
| Bypassing import in Python so that I don't have to upload multiple libraries and classes? | For example, I have a few python scripts, that link together and some libraries for it that need to be imported. I'm trying to reduce it to only one script.
So instead of:
import library.py
Can I just take the coding from library.py and put into the main script?
| [
"There are no limits to the size of a .py file, so you can certainly perform the copy and paste (and edit) operations you have in mind.\nSome caveats:\nimport library.py\n\nis unlikely to do what you want: it imports a module named py from a package named library. Thus it requires the existence of a directory library with an __init__.py and a py.py in it (or .pyc, etc). I suspect you mean import library.\nMerging all the needed modules into one large .py file only works for modules for which you have Python sources (.py) -- you need different techniques if all you have for a module is bytecode .pyc or .pyo, and if any of the modules are native-code binary Python extensions (.pyd or .so or .dylib etc etc, depending on your system) that just won't work.\nYou may have to do some renaming, e.g. when you import two modules that both define name foo you'll have to alter one or both of those names foo. That's because, via imports, you get qualified names (so there's no problem if a.foo and b.foo both exist), but without imports you get bare names so you'll need to disambiguate them \"manually\".\n",
"Yes you can do this, but probably it won't increase readability or maintainability.\nAnyway be careful if you use functions like this:\nimport library \nlibrary.functionA()\n\nIf you copy the content of library.py, you have to rename the function call to just functionA().\n"
] | [
1,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002892128_import_python.txt |
Q:
how to print the linenumber of incorrectwords located in a txt file?
i have this piece of code which only prints the line number of the incorrect words.
i want it to print the linenumbers of the incorrect words from the txt file.
Am i able to modify this code to do that?
# text1 is my incorrect words
# words is my text file where my incorrect word are in
from collections import defaultdict
d = defaultdict(list)
for lineno, word in enumerate(text1):
d[word].append(lineno)
print(d)
ive now done this but this prints the character its located like the place of the word rather then the line.
this is the code
import sys
import string
text = []
infile = open(sys.argv[1], 'r').read()
for punct in string.punctuation:
infile = infile.replace(punct, "")
text = infile.split()
dict = open(sys.argv[2], 'r').read()
dictset = []
dictset = dict.split()
words = []
words = list(set(text) - set(dictset))
words = [text.lower() for text in words]
words.sort()
def allwords(line):
return line.split()
def iswrong(word):
return word in words
for i, line in enumerate(text):
for word in allwords(line):
if iswrong(word):
print(word, i))
the output of that code is
millwal 342
this is printing where the character is located not which line its located
i want it to print the line number so what do i change in my code?????
A:
You could completely rewrite this code to do what you mention -- this code's structure has no relation whatsoever to what you require.
Since you need "line numbers from a text file", you'll need an object representing the text file (either as a list of lines in memory, or as an open file object). You say you have one called words (it's not clear if that's a filename or a Python variable identifier): having the text in a file called (say, as a variable) words and the (incorrect) words in a (collection of some kind) named text1 is a truly horrible choice of names, possibly the worst I've seen in many decades -- positively misleading. Use variable names that are a better match for the variables' meaning, unless you're trying to confuse yourself and everybody else.
Given a sensibly named variable for the input text, e.g. text = open('thefile.txt'), and a decent way to determine whether a word is incorrect, say a function def iswrong(word):..., the way to code what you require becomes clear:
for i, line in enumerate(text):
for word in allwords(line):
if iswrong(word):
print word, i
The allwords function could be just:
def allwords(line):
return line.split()
if you have no punctuation (words just separated by whitespace), or
import re
def allwords(line):
return re.findall(r'\w+', line)
using regular expressions.
If e.g. badwords is a set of incorrect words,
def iswrong(word):
return word in badwords
or viceversa if goodwords is the set of all correct words,
def iswrong(word):
return word not in goodwords
The details of iswrong and allwords are secondary -- as is the choice of whether to keep them as functions or just embed their code inline in the main stream of control.
| how to print the linenumber of incorrectwords located in a txt file? | i have this piece of code which only prints the line number of the incorrect words.
i want it to print the linenumbers of the incorrect words from the txt file.
Am i able to modify this code to do that?
# text1 is my incorrect words
# words is my text file where my incorrect word are in
from collections import defaultdict
d = defaultdict(list)
for lineno, word in enumerate(text1):
d[word].append(lineno)
print(d)
ive now done this but this prints the character its located like the place of the word rather then the line.
this is the code
import sys
import string
text = []
infile = open(sys.argv[1], 'r').read()
for punct in string.punctuation:
infile = infile.replace(punct, "")
text = infile.split()
dict = open(sys.argv[2], 'r').read()
dictset = []
dictset = dict.split()
words = []
words = list(set(text) - set(dictset))
words = [text.lower() for text in words]
words.sort()
def allwords(line):
return line.split()
def iswrong(word):
return word in words
for i, line in enumerate(text):
for word in allwords(line):
if iswrong(word):
print(word, i))
the output of that code is
millwal 342
this is printing where the character is located not which line its located
i want it to print the line number so what do i change in my code?????
| [
"You could completely rewrite this code to do what you mention -- this code's structure has no relation whatsoever to what you require.\nSince you need \"line numbers from a text file\", you'll need an object representing the text file (either as a list of lines in memory, or as an open file object). You say you have one called words (it's not clear if that's a filename or a Python variable identifier): having the text in a file called (say, as a variable) words and the (incorrect) words in a (collection of some kind) named text1 is a truly horrible choice of names, possibly the worst I've seen in many decades -- positively misleading. Use variable names that are a better match for the variables' meaning, unless you're trying to confuse yourself and everybody else.\nGiven a sensibly named variable for the input text, e.g. text = open('thefile.txt'), and a decent way to determine whether a word is incorrect, say a function def iswrong(word):..., the way to code what you require becomes clear:\nfor i, line in enumerate(text):\n for word in allwords(line):\n if iswrong(word):\n print word, i\n\nThe allwords function could be just:\ndef allwords(line):\n return line.split()\n\nif you have no punctuation (words just separated by whitespace), or\nimport re\n\ndef allwords(line):\n return re.findall(r'\\w+', line)\n\nusing regular expressions.\nIf e.g. badwords is a set of incorrect words,\ndef iswrong(word):\n return word in badwords\n\nor viceversa if goodwords is the set of all correct words,\ndef iswrong(word):\n return word not in goodwords\n\nThe details of iswrong and allwords are secondary -- as is the choice of whether to keep them as functions or just embed their code inline in the main stream of control.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0002892161_python.txt |
Q:
Making only a part of model field available in Django
I have a such model:
GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') )
class Profile(models.Model):
user = models.ForeignKey(User)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
class FrontPage(models.Model):
female = models.ForeignKey(User,related_name="female")
male = models.ForeignKey(User,related_name="male")
Once I attempt to add a new FrontPage object via the Admin page, I can select "Female" profiles for the male field of FrontPage, how can I restrict that?
Thanks
A:
ForeignKey's limit_choices_to argument will allow you to limit the choices available via the admin interface.
| Making only a part of model field available in Django | I have a such model:
GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') )
class Profile(models.Model):
user = models.ForeignKey(User)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
class FrontPage(models.Model):
female = models.ForeignKey(User,related_name="female")
male = models.ForeignKey(User,related_name="male")
Once I attempt to add a new FrontPage object via the Admin page, I can select "Female" profiles for the male field of FrontPage, how can I restrict that?
Thanks
| [
"ForeignKey's limit_choices_to argument will allow you to limit the choices available via the admin interface.\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0002892581_django_django_admin_django_models_python.txt |
Q:
Confused as to use a class or a function: Writing XML files using lxml and Python
I need to write XML files using lxml and Python.
However, I can't figure out whether to use a class to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious.
I will illustrate my point.
For example, consider the following function based code I wrote for adding a subelement to a etree root.
from lxml import etree
root = etree.Element('document')
def createSubElement(text, tagText = ""):
etree.SubElement(root, text)
# How do I do this: element.text = tagText
createSubElement('firstChild')
createSubElement('SecondChild')
As expected, the output of this is:
<document>
<firstChild/>
<SecondChild/>
</document>
However as you can notice the comment, I have no idea how to do set the text variable using this approach.
Is using a class the only way to solve this? And if yes, can you give me some pointers on how to achieve this?
A:
The following code works:
def createSubElement(text, tagText = ""):
elem = etree.SubElement(root, text)
elem.text = tagText
createSubElement('firstChild', 'first one')
createSubElement('SecondChild', 'second one')
print etree.tostring(root)
Using a class rather than a function has mostly to do with keeping state in the class's instances (in very few use cases will a class make sense if there's no state-keeping required), which has nothing to do with your problem -- as the code shows, your problem was simply that you were not binding any name to the element returned from the SubElement call, and therefore of course you were unable to further manipulate that element (e.g. by setting its text attribute) in the rest of your function.
| Confused as to use a class or a function: Writing XML files using lxml and Python | I need to write XML files using lxml and Python.
However, I can't figure out whether to use a class to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious.
I will illustrate my point.
For example, consider the following function based code I wrote for adding a subelement to a etree root.
from lxml import etree
root = etree.Element('document')
def createSubElement(text, tagText = ""):
etree.SubElement(root, text)
# How do I do this: element.text = tagText
createSubElement('firstChild')
createSubElement('SecondChild')
As expected, the output of this is:
<document>
<firstChild/>
<SecondChild/>
</document>
However as you can notice the comment, I have no idea how to do set the text variable using this approach.
Is using a class the only way to solve this? And if yes, can you give me some pointers on how to achieve this?
| [
"The following code works:\ndef createSubElement(text, tagText = \"\"):\n elem = etree.SubElement(root, text)\n elem.text = tagText\n\ncreateSubElement('firstChild', 'first one')\ncreateSubElement('SecondChild', 'second one')\n\nprint etree.tostring(root)\n\nUsing a class rather than a function has mostly to do with keeping state in the class's instances (in very few use cases will a class make sense if there's no state-keeping required), which has nothing to do with your problem -- as the code shows, your problem was simply that you were not binding any name to the element returned from the SubElement call, and therefore of course you were unable to further manipulate that element (e.g. by setting its text attribute) in the rest of your function.\n"
] | [
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0002892528_lxml_python.txt |
Q:
Web framework recommendation for python (webservices, auth, cache, ...)
Googling for the past week, but cannot finally decide which python web framework would be right for me. The web app I'm about to develop would be almost completely "pure" html with js (jQuery). Server side would have to do the following:
authentication
session management
caching
web services (almost all the on page data would be pulled with jQuery
through web services)
secured web services (through some form of authentication; this is for
remote accessing some of the web
services though other web apps,
desktop/mobile applications)
If there is a good tutorial/guide/idea for how to do this in Django I would be most thankfull if someone could share it as I already have experience with it. The thing that made me start thinking about other frameworks is Django's built in ORM. I know I could swap it with SQLAlchemy, but wouldn't go down that road if I'm not sure all the rest of the requirements is supported.
Thanks all in advance.
A:
The best way to do web services in Django, if you choose that route, is to use piston. The combination of Django and Piston can certainly fulfil all the requirements you specify.
A:
For me - there are two choices:
Django - I find it much, much easier to learn and to work with than Pylons. Most of the time it just does what it is expected from it and doesn't stay on my way. Plus - there is django-piston that is designed for quick API making.
Make your own stack - Using Werkzeug + SQLAlchemy + Jinja can yield some very nice results.
Bots options have very good documentation, communities and are easy to learn. If you prefer more modular approach - go for 2. If you can give up some freedom for better integration - go with Django.
A:
Have a look at pylons the idea behind this framework is flexibility of components, and it comes with caching, sessions middleware (Beaker). You can also do RESTful web services using this. If you want to swap out components, no problem...it was designed for that.
| Web framework recommendation for python (webservices, auth, cache, ...) | Googling for the past week, but cannot finally decide which python web framework would be right for me. The web app I'm about to develop would be almost completely "pure" html with js (jQuery). Server side would have to do the following:
authentication
session management
caching
web services (almost all the on page data would be pulled with jQuery
through web services)
secured web services (through some form of authentication; this is for
remote accessing some of the web
services though other web apps,
desktop/mobile applications)
If there is a good tutorial/guide/idea for how to do this in Django I would be most thankfull if someone could share it as I already have experience with it. The thing that made me start thinking about other frameworks is Django's built in ORM. I know I could swap it with SQLAlchemy, but wouldn't go down that road if I'm not sure all the rest of the requirements is supported.
Thanks all in advance.
| [
"The best way to do web services in Django, if you choose that route, is to use piston. The combination of Django and Piston can certainly fulfil all the requirements you specify.\n",
"For me - there are two choices:\n\nDjango - I find it much, much easier to learn and to work with than Pylons. Most of the time it just does what it is expected from it and doesn't stay on my way. Plus - there is django-piston that is designed for quick API making.\nMake your own stack - Using Werkzeug + SQLAlchemy + Jinja can yield some very nice results.\n\nBots options have very good documentation, communities and are easy to learn. If you prefer more modular approach - go for 2. If you can give up some freedom for better integration - go with Django.\n",
"Have a look at pylons the idea behind this framework is flexibility of components, and it comes with caching, sessions middleware (Beaker). You can also do RESTful web services using this. If you want to swap out components, no problem...it was designed for that.\n"
] | [
3,
2,
1
] | [] | [] | [
"frameworks",
"jquery",
"python",
"security",
"web_services"
] | stackoverflow_0002892720_frameworks_jquery_python_security_web_services.txt |
Q:
Stepping over a yield statement
When in the Python debugger (pdb) I want to step over a yield statement, but hitting (n) for next brings me to the destination of the yield i.e. the consumer of the generator. I want to go to the next line that is executed within the generator. Is there any way to do this?
I'm using Python 2.6
| Stepping over a yield statement | When in the Python debugger (pdb) I want to step over a yield statement, but hitting (n) for next brings me to the destination of the yield i.e. the consumer of the generator. I want to go to the next line that is executed within the generator. Is there any way to do this?
I'm using Python 2.6
| [] | [] | [
"If your debugger allows you to use breakpoints and change variable values when you're there, it's as simple as [in pseudo code]\nSet Boolean yieldValue to true;\n[breakpoint after that line is executed, you can set yieldValue to false here]\nif yieldValue, yield value;\n\nin other words:\n\nbool yieldValue = true;\n[breakpoint here]\nif(yieldValue) yield value;\n\nNote that you usually can't stick a breakpoint on an empty line. You'll have to stick it before the if statement, though.\n",
"In debuggers, generally you want to \"step\" (s) into a function in this case, rather than \"next\" (n).\n\"Next\" executes the next line in the scope you're looking at; \"step\" brings you into the next scope down, the generator in this case, which sounds like what you want to do.\n"
] | [
-2,
-2
] | [
"generator",
"pdb",
"python"
] | stackoverflow_0002892746_generator_pdb_python.txt |
Q:
verbose_name for a model's method
How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form?
example:
class Article(models.Model):
title = models.CharField(max_length=64)
created_date = models.DateTimeField(....)
def created_weekday(self):
return self.created_date.strftime("%A")
in admin.py:
class ArticleAdmin(admin.ModelAdmin):
readonly_fields = ('created_weekday',)
fields = ('title', 'created_weekday')
Now the label for created_weekday is "Created Weekday", but I'd like it to have a different label which should be i18nable using ugettext_lazy as well.
I've tried
created_weekday.verbose_name=...
after the method, but that did not show any result. Is there a decorator or something I can use, so I could make my own "verbose_name" / "label" / whateverthename is?
A:
list_display
created_weekday.short_description = 'Foo'
This solution requires the method to be defined in the ModelAdmin class. You can call a Model method (eg: get_created_weekday) from ModelAdmin like:
def created_weekday(self, obj):
return obj.get_created_weekday()
| verbose_name for a model's method | How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form?
example:
class Article(models.Model):
title = models.CharField(max_length=64)
created_date = models.DateTimeField(....)
def created_weekday(self):
return self.created_date.strftime("%A")
in admin.py:
class ArticleAdmin(admin.ModelAdmin):
readonly_fields = ('created_weekday',)
fields = ('title', 'created_weekday')
Now the label for created_weekday is "Created Weekday", but I'd like it to have a different label which should be i18nable using ugettext_lazy as well.
I've tried
created_weekday.verbose_name=...
after the method, but that did not show any result. Is there a decorator or something I can use, so I could make my own "verbose_name" / "label" / whateverthename is?
| [
"list_display\ncreated_weekday.short_description = 'Foo'\n\nThis solution requires the method to be defined in the ModelAdmin class. You can call a Model method (eg: get_created_weekday) from ModelAdmin like: \ndef created_weekday(self, obj):\n return obj.get_created_weekday()\n\n"
] | [
23
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0002892999_django_django_admin_django_models_python.txt |
Q:
Python modules import error
Very strange for me:
# uname -a
Linux localhost.localdomain 2.6.18-194.3.1.el5 #1 SMP Thu May 13 13:09:10 EDT 2010 i686 i686 i386 GNU/Linux
# pwd
/root
# python
Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
>>>
[3]+ Stopped python
# cd /home/user/dev/dns
[root@localhost dns]# python
Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
Traceback (most recent call last):
File "", line 1, in
File "dns.py", line 1, in
import dns.resolver
ImportError: No module named resolver
>>>
[4]+ Stopped python
#
Summary: I can't import same python module from different path.
Any ideas? 0_o
P.S. SELINUX=disabled
A:
What's dns.__file__ in the first case? I suspect it's not coming from the directory you cded into the second time (the current directory when you start Python goes at the front of sys.path) but rather from a package containing that crucial resolver module which the second one appears to be lacking.
| Python modules import error | Very strange for me:
# uname -a
Linux localhost.localdomain 2.6.18-194.3.1.el5 #1 SMP Thu May 13 13:09:10 EDT 2010 i686 i686 i386 GNU/Linux
# pwd
/root
# python
Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
>>>
[3]+ Stopped python
# cd /home/user/dev/dns
[root@localhost dns]# python
Python 2.6.5 (r265:79063, Apr 11 2010, 22:34:44)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
Traceback (most recent call last):
File "", line 1, in
File "dns.py", line 1, in
import dns.resolver
ImportError: No module named resolver
>>>
[4]+ Stopped python
#
Summary: I can't import same python module from different path.
Any ideas? 0_o
P.S. SELINUX=disabled
| [
"What's dns.__file__ in the first case? I suspect it's not coming from the directory you cded into the second time (the current directory when you start Python goes at the front of sys.path) but rather from a package containing that crucial resolver module which the second one appears to be lacking.\n"
] | [
4
] | [] | [] | [
"centos",
"linux",
"python"
] | stackoverflow_0002893033_centos_linux_python.txt |
Q:
404 not found in telnet, works fine in browser
i am having a very irritating problem, when i open a url ( http://celebs.widewallpapers.net/md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg ) in browser, it works fine.. but when i try to access it by telnet on bash, i get 404 not found!!
my exact terminal:
$ telnet celebs.widewallpapers.net 80
HEAD /md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg HTTP/1.0
[enter]
[enter]
HTTP/1.1 404 Not Found
Server: nginx
Date: Sun, 23 May 2010 21:36:05 GMT
Content-Type: text/html; charset=windows-1251
Content-Length: 166
Connection: close
please help me with this as i m trying to make a C batch-downloader, which is almost working as same as the telnet.
A:
You aren't passing a host header. As per HTTP/1.1 you need to tell the web server which virtual host you are expecting to talk to. And 99% of servers today will only talk HTTP/1.1 even if you specify HTTP/1.0 in the request.
jb@apto % telnet celebs.widewallpapers.net 80
...
HEAD /md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg HTTP/1.1
Host: celebs.widewallpapers.net
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 23 May 2010 22:08:36 GMT
Content-Type: image/jpeg
Connection: close
Last-Modified: Sun, 27 Apr 2008 14:30:17 GMT
ETag: "4784e0-264b0-48148df9"
Accept-Ranges: bytes
Content-Length: 156848
Connection closed by foreign host.
| 404 not found in telnet, works fine in browser | i am having a very irritating problem, when i open a url ( http://celebs.widewallpapers.net/md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg ) in browser, it works fine.. but when i try to access it by telnet on bash, i get 404 not found!!
my exact terminal:
$ telnet celebs.widewallpapers.net 80
HEAD /md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg HTTP/1.0
[enter]
[enter]
HTTP/1.1 404 Not Found
Server: nginx
Date: Sun, 23 May 2010 21:36:05 GMT
Content-Type: text/html; charset=windows-1251
Content-Length: 166
Connection: close
please help me with this as i m trying to make a C batch-downloader, which is almost working as same as the telnet.
| [
"You aren't passing a host header. As per HTTP/1.1 you need to tell the web server which virtual host you are expecting to talk to. And 99% of servers today will only talk HTTP/1.1 even if you specify HTTP/1.0 in the request.\njb@apto % telnet celebs.widewallpapers.net 80\n...\nHEAD /md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg HTTP/1.1\nHost: celebs.widewallpapers.net\n\nHTTP/1.1 200 OK\nServer: nginx\nDate: Sun, 23 May 2010 22:08:36 GMT\nContent-Type: image/jpeg\nConnection: close\nLast-Modified: Sun, 27 Apr 2008 14:30:17 GMT\nETag: \"4784e0-264b0-48148df9\"\nAccept-Ranges: bytes\nContent-Length: 156848\n\nConnection closed by foreign host.\n\n"
] | [
10
] | [] | [] | [
"c",
"http",
"python",
"telnet"
] | stackoverflow_0002893063_c_http_python_telnet.txt |
Q:
How should I go about learning Python?
I am currently learning PHP and want to learn about OOP.
I know Python is a well-organized and is all OOP, so would learning Python be a wise choose to learn OOP?
The thing is I am more towards web development then just general programming, and I know Python is just a general purpose language, but there is Django.
So how should I go about learning Python if I am lending towards web development?
Is there any good books/websites that help me learn Python for web development?
Is there any free webhosting companies that allow Python? I never used Python before, only PHP, and not sure how it works? Is there like a "xampp" for python?
A:
I would pick up a good O'Reilly book on Python and build a strong understanding of the fundamentals before delving into more web specific ventures. Once you've got the essentials then I'd branch out to things like Django.
Here's a good starting page:
O'Reilly - Python
And here's a good tutorial if you'd rather do your research on the web:
Python Tutorial
A:
I learned Python reading the book Learning Python. I read almost the whole thing on a plane trip, and when I got home I was able to start building applications immediately. There are newer versions out since I read it (and it's longer), but I found it very easy to follow.
As mentioned by others, Django is definitely the place to start for Web development.
A:
Work through the examples on www.pythonchallenge.com. Refer to the language documentation when you get stuck.
A:
As long as you stay within their quota Google Apps Engine provides free hosting for Python.
Django is a great framework when you want to do webdevelopment with Python. Django also has great documention with http://www.djangobook.com/ and the official Django website.
A:
If you want to learn about Object Oriented Programming in general, you may want to look at the answers to this question, although many of the books are higher level (and some are aimed at Java/C# like languages instead of Python-like languages).
A:
Here's some answers to your questions:
Python is an excellent language for beginners looking to learn OO design/programming.
As far as books and websites, the best python book I've read is available free online Mark Pilgrim's Dive into Python.
For web programming there are many many options. You mention Django which is the most popular although I like Turbogears, Cherrypy and web.py. All of these have their own webserver built-in (Based on paste or cherrypy)
For hosting, it's usually based on fastcgi or Apache's mod_python.
I've heard really good reports of webfaction for python based hosting.
Hope this helps, but if you are learning php why not go for Apress's PHP Objects, Patterns, and Practice that's a good book.
A:
If it is your basics in OOPS that you wish to strengthen, Java is a good option(provided you know c++ or any other non-web-based language which supports OOPS). However, if you are looking towards web-development, Python should be your best option.
Yes, Python is a good option
Yes, Django is a very good web application framework(and they have awesome documentation and tutorials put up at their site)
To learn Python I definitely recommend reading "The Python Cookbook" cover-to-cover. Its fun, and covers some very important concepts. However, there really is no substitute for the standard python documentation. Its well written, but it might take a while through a major portion of it. Using it as just reference material is also a fine idea.
Well I have seen domains which allow Django to be hosted; also you should try out the GAE(google app engine) once you are comfortable with django. Its a great place to host your apps.
A:
You could learn using books, but nothing beats practical hands-on approach - so make sure you have Python installed in a computer to help you learn. If you decide to buy a Python book, I strongly suggest you DO NOT buy a copy of Vernon Ceder's Python Book, it has very bad reviews. I bought a copy and was also disappointed.
If you'd like to join a mailing list, we have a good community at Python Tutor. Sign up and post your questions there as well.
Good luck
A:
Get ipython. Use it as your shell. This means move, copy, view, change, edit files from ipython. Day to day shell stuff anywhere has enough little problems that one ordinarily solves by piping, but are just as easily solvable by python. The real bonus is that your eye for syntax and simple solutions will develop quickly.
Need to find files? use os.walk,
Running grep? try to 'open' the file instead, try some regex while you are there. Those uses of the language will serve you in any type of python programming.
( Good news, PHP and python use the same underlying regex lib PCRE, so although there are some additions, it'll be familiar to you, )
The nice thing about having this in the language , which is not really the case in PHP or Perl, is that you can just mess around with functions, not full programs.
Why ipython and not the standard REPL or bpython? Easier to use as a shell out of the box. That's all.
A:
I recently learnt Python and had very little programming experience before. I found that doing a little bit of Python first then diving into Django worked for me. USing Django, looking through its reference material and Googling individual problems when I needed the help was really good.
Django has a built in Development server for you to use a bit like xampp, however, to make things like installing Django, installing Python, installing plugins etc a lot easier, use a unix based OS. I am developing on Mac OS and I have had no problems. Most Linux distributions will be the same. I wouldn't want to try Django development on Windows, there are just too many hacks you need to do to get it working, plus, it is more difficult for when you then publish the site (on a unix server).
Learn some Python, there are some good books suggested here, but don't get too deeply stuck into it if your focus will be Django. Go and do the official Django tutorial and then Google around for one or two more.
I use a book called 'The Definitive Guide to Django'. It is great for learning Django in the first place, but after the first few chapters, I stopped following it and started my own projects instead. Now it is a really good reference book to have.
It takes a while, but its worth it. I started working at a company as a Django developer recently and it is great.
Good Luck!
| How should I go about learning Python? | I am currently learning PHP and want to learn about OOP.
I know Python is a well-organized and is all OOP, so would learning Python be a wise choose to learn OOP?
The thing is I am more towards web development then just general programming, and I know Python is just a general purpose language, but there is Django.
So how should I go about learning Python if I am lending towards web development?
Is there any good books/websites that help me learn Python for web development?
Is there any free webhosting companies that allow Python? I never used Python before, only PHP, and not sure how it works? Is there like a "xampp" for python?
| [
"I would pick up a good O'Reilly book on Python and build a strong understanding of the fundamentals before delving into more web specific ventures. Once you've got the essentials then I'd branch out to things like Django. \nHere's a good starting page:\nO'Reilly - Python\nAnd here's a good tutorial if you'd rather do your research on the web:\nPython Tutorial\n",
"I learned Python reading the book Learning Python. I read almost the whole thing on a plane trip, and when I got home I was able to start building applications immediately. There are newer versions out since I read it (and it's longer), but I found it very easy to follow.\nAs mentioned by others, Django is definitely the place to start for Web development.\n",
"Work through the examples on www.pythonchallenge.com. Refer to the language documentation when you get stuck.\n",
"As long as you stay within their quota Google Apps Engine provides free hosting for Python.\nDjango is a great framework when you want to do webdevelopment with Python. Django also has great documention with http://www.djangobook.com/ and the official Django website.\n",
"If you want to learn about Object Oriented Programming in general, you may want to look at the answers to this question, although many of the books are higher level (and some are aimed at Java/C# like languages instead of Python-like languages).\n",
"Here's some answers to your questions:\n\nPython is an excellent language for beginners looking to learn OO design/programming. \nAs far as books and websites, the best python book I've read is available free online Mark Pilgrim's Dive into Python.\nFor web programming there are many many options. You mention Django which is the most popular although I like Turbogears, Cherrypy and web.py. All of these have their own webserver built-in (Based on paste or cherrypy)\nFor hosting, it's usually based on fastcgi or Apache's mod_python.\nI've heard really good reports of webfaction for python based hosting.\nHope this helps, but if you are learning php why not go for Apress's PHP Objects, Patterns, and Practice that's a good book.\n",
"\nIf it is your basics in OOPS that you wish to strengthen, Java is a good option(provided you know c++ or any other non-web-based language which supports OOPS). However, if you are looking towards web-development, Python should be your best option.\nYes, Python is a good option\nYes, Django is a very good web application framework(and they have awesome documentation and tutorials put up at their site)\nTo learn Python I definitely recommend reading \"The Python Cookbook\" cover-to-cover. Its fun, and covers some very important concepts. However, there really is no substitute for the standard python documentation. Its well written, but it might take a while through a major portion of it. Using it as just reference material is also a fine idea.\nWell I have seen domains which allow Django to be hosted; also you should try out the GAE(google app engine) once you are comfortable with django. Its a great place to host your apps.\n\n",
"You could learn using books, but nothing beats practical hands-on approach - so make sure you have Python installed in a computer to help you learn. If you decide to buy a Python book, I strongly suggest you DO NOT buy a copy of Vernon Ceder's Python Book, it has very bad reviews. I bought a copy and was also disappointed. \nIf you'd like to join a mailing list, we have a good community at Python Tutor. Sign up and post your questions there as well.\nGood luck\n",
"Get ipython. Use it as your shell. This means move, copy, view, change, edit files from ipython. Day to day shell stuff anywhere has enough little problems that one ordinarily solves by piping, but are just as easily solvable by python. The real bonus is that your eye for syntax and simple solutions will develop quickly.\nNeed to find files? use os.walk, \nRunning grep? try to 'open' the file instead, try some regex while you are there. Those uses of the language will serve you in any type of python programming.\n( Good news, PHP and python use the same underlying regex lib PCRE, so although there are some additions, it'll be familiar to you, )\nThe nice thing about having this in the language , which is not really the case in PHP or Perl, is that you can just mess around with functions, not full programs.\nWhy ipython and not the standard REPL or bpython? Easier to use as a shell out of the box. That's all.\n",
"I recently learnt Python and had very little programming experience before. I found that doing a little bit of Python first then diving into Django worked for me. USing Django, looking through its reference material and Googling individual problems when I needed the help was really good. \nDjango has a built in Development server for you to use a bit like xampp, however, to make things like installing Django, installing Python, installing plugins etc a lot easier, use a unix based OS. I am developing on Mac OS and I have had no problems. Most Linux distributions will be the same. I wouldn't want to try Django development on Windows, there are just too many hacks you need to do to get it working, plus, it is more difficult for when you then publish the site (on a unix server).\nLearn some Python, there are some good books suggested here, but don't get too deeply stuck into it if your focus will be Django. Go and do the official Django tutorial and then Google around for one or two more.\nI use a book called 'The Definitive Guide to Django'. It is great for learning Django in the first place, but after the first few chapters, I stopped following it and started my own projects instead. Now it is a really good reference book to have.\nIt takes a while, but its worth it. I started working at a company as a Django developer recently and it is great.\nGood Luck!\n"
] | [
4,
4,
2,
2,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002876337_django_python.txt |
Q:
Building a balanced binary search tree
Is there a method to build a balanced binary search tree?
Example:
1 2 3 4 5 6 7 8 9
5
/ \
3 etc
/ \
2 4
/
1
I'm thinking there is a method to do this, without using the more complex self-balancing trees. Otherwise I can do it on my own, but someone probably have done this already :)
Thanks for the answers! This is the final python code:
def _buildTree(self, keys):
if not keys:
return None
middle = len(keys) // 2
return Node(
key=keys[middle],
left=self._buildTree(keys[:middle]),
right=self._buildTree(keys[middle + 1:])
)
A:
For each subtree:
Find the middle element of the subtree and put that at the top of the tree.
Find all the elements before the middle element and use this algorithm recursively to get the left subtree.
Find all the elements after the middle element and use this algorithm recursively to get the right subtree.
If you sort your elements first (as in your example) finding the middle element of a subtree can be done in constant time.
This is a simple algorithm for constructing a one-off balanced tree. It is not an algorithm for a self-balancing tree.
Here is some source code in C# that you can try for yourself:
public class Program
{
class TreeNode
{
public int Value;
public TreeNode Left;
public TreeNode Right;
}
TreeNode constructBalancedTree(List<int> values, int min, int max)
{
if (min == max)
return null;
int median = min + (max - min) / 2;
return new TreeNode
{
Value = values[median],
Left = constructBalancedTree(values, min, median),
Right = constructBalancedTree(values, median + 1, max)
};
}
TreeNode constructBalancedTree(IEnumerable<int> values)
{
return constructBalancedTree(
values.OrderBy(x => x).ToList(), 0, values.Count());
}
void Run()
{
TreeNode balancedTree = constructBalancedTree(Enumerable.Range(1, 9));
// displayTree(balancedTree); // TODO: implement this!
}
static void Main(string[] args)
{
new Program().Run();
}
}
A:
This paper explains in detail:
Tree Rebalancing in Optimal Time and Space
http://www.eecs.umich.edu/~qstout/abs/CACM86.html
Also here:
One-Time Binary Search Tree Balancing:
The Day/Stout/Warren (DSW) Algorithm
http://penguin.ewu.edu/~trolfe/DSWpaper/
If you really want to do it on-the-fly, you need a self-balancing tree.
If you just want to build a simple tree, without having to go to the trouble of balancing it, just randomize the elements before inserting them into the tree.
A:
Make the median of your data (or more precisely, the nearest element in your array to the median) the root of the tree. And so on recursively.
| Building a balanced binary search tree | Is there a method to build a balanced binary search tree?
Example:
1 2 3 4 5 6 7 8 9
5
/ \
3 etc
/ \
2 4
/
1
I'm thinking there is a method to do this, without using the more complex self-balancing trees. Otherwise I can do it on my own, but someone probably have done this already :)
Thanks for the answers! This is the final python code:
def _buildTree(self, keys):
if not keys:
return None
middle = len(keys) // 2
return Node(
key=keys[middle],
left=self._buildTree(keys[:middle]),
right=self._buildTree(keys[middle + 1:])
)
| [
"For each subtree:\n\nFind the middle element of the subtree and put that at the top of the tree.\nFind all the elements before the middle element and use this algorithm recursively to get the left subtree.\nFind all the elements after the middle element and use this algorithm recursively to get the right subtree.\n\nIf you sort your elements first (as in your example) finding the middle element of a subtree can be done in constant time.\nThis is a simple algorithm for constructing a one-off balanced tree. It is not an algorithm for a self-balancing tree.\nHere is some source code in C# that you can try for yourself:\npublic class Program\n{\n class TreeNode\n {\n public int Value;\n public TreeNode Left;\n public TreeNode Right;\n }\n\n TreeNode constructBalancedTree(List<int> values, int min, int max)\n {\n if (min == max)\n return null;\n\n int median = min + (max - min) / 2;\n return new TreeNode\n {\n Value = values[median],\n Left = constructBalancedTree(values, min, median),\n Right = constructBalancedTree(values, median + 1, max)\n };\n }\n\n TreeNode constructBalancedTree(IEnumerable<int> values)\n {\n return constructBalancedTree(\n values.OrderBy(x => x).ToList(), 0, values.Count());\n }\n\n void Run()\n {\n TreeNode balancedTree = constructBalancedTree(Enumerable.Range(1, 9));\n // displayTree(balancedTree); // TODO: implement this!\n }\n\n static void Main(string[] args)\n {\n new Program().Run();\n }\n}\n\n",
"This paper explains in detail:\nTree Rebalancing in Optimal Time and Space\nhttp://www.eecs.umich.edu/~qstout/abs/CACM86.html\nAlso here:\nOne-Time Binary Search Tree Balancing:\nThe Day/Stout/Warren (DSW) Algorithm\nhttp://penguin.ewu.edu/~trolfe/DSWpaper/\nIf you really want to do it on-the-fly, you need a self-balancing tree.\nIf you just want to build a simple tree, without having to go to the trouble of balancing it, just randomize the elements before inserting them into the tree.\n",
"Make the median of your data (or more precisely, the nearest element in your array to the median) the root of the tree. And so on recursively.\n"
] | [
10,
5,
2
] | [] | [] | [
"binary_tree",
"c#",
"python"
] | stackoverflow_0002893318_binary_tree_c#_python.txt |
Q:
Dealing with external processes
I've been working on a gui app that needs to manage external processes. Working with external processes leads to a lot of issues that can make a programmer's life difficult. I feel like maintenence on this app is taking an unacceptably long time. I've been trying to list the things that make working with external processes difficult so that I can come up with ways of mitigating the pain. This kind of turned into a rant which I thought I'd post here in order to get some feedback and to provide some guidance to anybody thinking about sailing into these very murky waters. Here's what I've got so far:
Output from the child can get mixed up with output from the parent. This can make both outputs misleading and hard to read. It can be hard to tell what came from where. It becomes harder to figure out what's going on when things are asynchronous. Here's a contrived example:
import textwrap, os, time
from subprocess import Popen
test_path = 'test_file.py'
with open(test_path, 'w') as file:
file.write(textwrap.dedent('''
import time
for i in range(3):
print 'Hello %i' % i
time.sleep(1)'''))
proc = Popen('python -B "%s"' % test_path)
for i in range(3):
print 'Hello %i' % i
time.sleep(1)
os.remove(test_path)
Output:
Hello 0
Hello 0
Hello 1
Hello 1
Hello 2
Hello 2
I guess I could have the child process write its output to a file. But it can be annoying to have to open up a file every time I want to see the result of a print statement.
If I have code for the child process I could add a label, something like print 'child: Hello %i', but it can be annoying to do that for every print. And it adds some noise to the output. And of course I can't do it if I don't have access to the code.
I could manually manage the process output. But then you open up a huge can of worms with threads and polling and stuff like that.
A simple solution is to treat processes like synchronous functions, that is, no further code executes until the process completes. In other words, make the process block. But that doesn't work if you're building a gui app. Which brings me to the next problem...
Blocking processes cause the gui to become unresponsive.
import textwrap, sys, os
from subprocess import Popen
from PyQt4.QtGui import *
from PyQt4.QtCore import *
test_path = 'test_file.py'
with open(test_path, 'w') as file:
file.write(textwrap.dedent('''
import time
for i in range(3):
print 'Hello %i' % i
time.sleep(1)'''))
app = QApplication(sys.argv)
button = QPushButton('Launch process')
def launch_proc():
# Can't move the window until process completes
proc = Popen('python -B "%s"' % test_path)
proc.communicate()
button.connect(button, SIGNAL('clicked()'), launch_proc)
button.show()
app.exec_()
os.remove(test_path)
Qt provides a process wrapper of its own called QProcess which can help with this. You can connect functions to signals to capture output relatively easily. This is what I'm currently using. But I'm finding that all these signals behave suspiciously like goto statements and can lead to spaghetti code. I think I want to get sort-of blocking behavior by having the 'finished' signal from QProcess call a function containing all the code that comes after the process call. I think that should work but I'm still a bit fuzzy on the details...
Stack traces get interrupted when you go from the child process back to the parent process. If a normal function screws up, you get a nice complete stack trace with filenames and line numbers. If a subprocess screws up, you'll be lucky if you get any output at all. You end up having to do a lot more detective work everytime something goes wrong.
Speaking of which, output has a way of disappearing when dealing external processes. Like if you run something via the windows 'cmd' command, the console will pop up, execute the code, and then disappear before you have a chance to see the output. You have to pass the /k flag to make it stick around. Similar issues seem to crop up all the time.
I suppose both problems 3 and 4 have the same root cause: no exception handling. Exception handling is meant to be used with functions, it doesn't work with processes. Maybe there's some way to get something like exception handling for processes? I guess that's what stderr is for? But dealing with two different streams can be annoying in itself. Maybe I should look into this more...
Processes can hang and stick around in the background without you realizing it. So you end up yelling at your computer cuz it's going so slow until you finally bring up your task manager and see 30 instances of the same process hanging out in the background.
Also, hanging background processes can interefere with other instances of the process in various fun ways, such as causing permissions errors by holding a handle to a file or someting like that.
It seems like an easy solution to this would be to have the parent process kill the child process on exit if the child process didn't close itself. But if the parent process crashes, cleanup code might not get called and the child can be left hanging.
Also, if the parent waits for the child to complete, and the child is in an infinite loop or something, you can end up with two hanging processes.
This problem can tie in to problem 2 for extra fun, causing your gui to stop responding entirely and force you to kill everything with the task manager.
F***ing quotes
Parameters often need to be passed to processes. This is a headache in itself. Especially if you're dealing with file paths. Say... 'C:/My Documents/whatever/'. If you don't have quotes, the string will often be split at the space and interpreted as two arguments. If you need nested quotes you can use ' and ". But if you need to use more than two layers of quotes, you have to do some nasty escaping, for example: "cmd /k 'python \'path 1\' \'path 2\''".
A good solution to this problem is passing parameters as a list rather than as a single string. Subprocess allows you to do this.
Can't easily return data from a subprocess.
You can use stdout of course. But what if you want to throw a print in there for debugging purposes? That's gonna screw up the parent if it's expecting output formatted a certain way. In functions you can print one string and return another and everything works just fine.
Obscure command-line flags and a crappy terminal based help system.
These are problems I often run into when using os level apps. Like the /k flag I mentioned, for holding a cmd window open, who's idea was that? Unix apps don't tend to be much friendlier in this regard. Hopefully you can use google or StackOverflow to find the answer you need. But if not, you've got a lot of boring reading and frusterating trial and error to do.
External factors.
This one's kind of fuzzy. But when you leave the relatively sheltered harbor of your own scripts to deal with external processes you find yourself having to deal with the "outside world" to a much greater extent. And that's a scary place. All sorts of things can go wrong. Just to give a random example: the cwd in which a process is run can modify it's behavior.
There are probably other issues, but those are the ones I've written down so far. Any other snags you'd like to add? Any suggestions for dealing with these problems?
A:
Check out the subprocess module. It should help with output separation. I don't see any way around either separate output streams or some kind of output tagging in a single stream.
The hanging process problem is difficult as well. The only solution I have been able to make is to put a timer on the external process, and kill it if it does not return in the allotted time. Crude, nasty, and if anyone else has a good solution, I would love to hear it so I can use it too.
One thing you could do to help deal with the problem of completely un-managed shutdown is to keep a directory of pid files. Whenever you kick off an external process, write a file into your pid file directory with a name that is the pid for the process. Erase the pid file when you know the process has exited cleanly. You can use the stuff in the pid directory to help cleanup on crashes or re-starts.
This may not provide any satisfying or useful answers, but maybe it's a start.
| Dealing with external processes | I've been working on a gui app that needs to manage external processes. Working with external processes leads to a lot of issues that can make a programmer's life difficult. I feel like maintenence on this app is taking an unacceptably long time. I've been trying to list the things that make working with external processes difficult so that I can come up with ways of mitigating the pain. This kind of turned into a rant which I thought I'd post here in order to get some feedback and to provide some guidance to anybody thinking about sailing into these very murky waters. Here's what I've got so far:
Output from the child can get mixed up with output from the parent. This can make both outputs misleading and hard to read. It can be hard to tell what came from where. It becomes harder to figure out what's going on when things are asynchronous. Here's a contrived example:
import textwrap, os, time
from subprocess import Popen
test_path = 'test_file.py'
with open(test_path, 'w') as file:
file.write(textwrap.dedent('''
import time
for i in range(3):
print 'Hello %i' % i
time.sleep(1)'''))
proc = Popen('python -B "%s"' % test_path)
for i in range(3):
print 'Hello %i' % i
time.sleep(1)
os.remove(test_path)
Output:
Hello 0
Hello 0
Hello 1
Hello 1
Hello 2
Hello 2
I guess I could have the child process write its output to a file. But it can be annoying to have to open up a file every time I want to see the result of a print statement.
If I have code for the child process I could add a label, something like print 'child: Hello %i', but it can be annoying to do that for every print. And it adds some noise to the output. And of course I can't do it if I don't have access to the code.
I could manually manage the process output. But then you open up a huge can of worms with threads and polling and stuff like that.
A simple solution is to treat processes like synchronous functions, that is, no further code executes until the process completes. In other words, make the process block. But that doesn't work if you're building a gui app. Which brings me to the next problem...
Blocking processes cause the gui to become unresponsive.
import textwrap, sys, os
from subprocess import Popen
from PyQt4.QtGui import *
from PyQt4.QtCore import *
test_path = 'test_file.py'
with open(test_path, 'w') as file:
file.write(textwrap.dedent('''
import time
for i in range(3):
print 'Hello %i' % i
time.sleep(1)'''))
app = QApplication(sys.argv)
button = QPushButton('Launch process')
def launch_proc():
# Can't move the window until process completes
proc = Popen('python -B "%s"' % test_path)
proc.communicate()
button.connect(button, SIGNAL('clicked()'), launch_proc)
button.show()
app.exec_()
os.remove(test_path)
Qt provides a process wrapper of its own called QProcess which can help with this. You can connect functions to signals to capture output relatively easily. This is what I'm currently using. But I'm finding that all these signals behave suspiciously like goto statements and can lead to spaghetti code. I think I want to get sort-of blocking behavior by having the 'finished' signal from QProcess call a function containing all the code that comes after the process call. I think that should work but I'm still a bit fuzzy on the details...
Stack traces get interrupted when you go from the child process back to the parent process. If a normal function screws up, you get a nice complete stack trace with filenames and line numbers. If a subprocess screws up, you'll be lucky if you get any output at all. You end up having to do a lot more detective work everytime something goes wrong.
Speaking of which, output has a way of disappearing when dealing external processes. Like if you run something via the windows 'cmd' command, the console will pop up, execute the code, and then disappear before you have a chance to see the output. You have to pass the /k flag to make it stick around. Similar issues seem to crop up all the time.
I suppose both problems 3 and 4 have the same root cause: no exception handling. Exception handling is meant to be used with functions, it doesn't work with processes. Maybe there's some way to get something like exception handling for processes? I guess that's what stderr is for? But dealing with two different streams can be annoying in itself. Maybe I should look into this more...
Processes can hang and stick around in the background without you realizing it. So you end up yelling at your computer cuz it's going so slow until you finally bring up your task manager and see 30 instances of the same process hanging out in the background.
Also, hanging background processes can interefere with other instances of the process in various fun ways, such as causing permissions errors by holding a handle to a file or someting like that.
It seems like an easy solution to this would be to have the parent process kill the child process on exit if the child process didn't close itself. But if the parent process crashes, cleanup code might not get called and the child can be left hanging.
Also, if the parent waits for the child to complete, and the child is in an infinite loop or something, you can end up with two hanging processes.
This problem can tie in to problem 2 for extra fun, causing your gui to stop responding entirely and force you to kill everything with the task manager.
F***ing quotes
Parameters often need to be passed to processes. This is a headache in itself. Especially if you're dealing with file paths. Say... 'C:/My Documents/whatever/'. If you don't have quotes, the string will often be split at the space and interpreted as two arguments. If you need nested quotes you can use ' and ". But if you need to use more than two layers of quotes, you have to do some nasty escaping, for example: "cmd /k 'python \'path 1\' \'path 2\''".
A good solution to this problem is passing parameters as a list rather than as a single string. Subprocess allows you to do this.
Can't easily return data from a subprocess.
You can use stdout of course. But what if you want to throw a print in there for debugging purposes? That's gonna screw up the parent if it's expecting output formatted a certain way. In functions you can print one string and return another and everything works just fine.
Obscure command-line flags and a crappy terminal based help system.
These are problems I often run into when using os level apps. Like the /k flag I mentioned, for holding a cmd window open, who's idea was that? Unix apps don't tend to be much friendlier in this regard. Hopefully you can use google or StackOverflow to find the answer you need. But if not, you've got a lot of boring reading and frusterating trial and error to do.
External factors.
This one's kind of fuzzy. But when you leave the relatively sheltered harbor of your own scripts to deal with external processes you find yourself having to deal with the "outside world" to a much greater extent. And that's a scary place. All sorts of things can go wrong. Just to give a random example: the cwd in which a process is run can modify it's behavior.
There are probably other issues, but those are the ones I've written down so far. Any other snags you'd like to add? Any suggestions for dealing with these problems?
| [
"Check out the subprocess module. It should help with output separation. I don't see any way around either separate output streams or some kind of output tagging in a single stream. \nThe hanging process problem is difficult as well. The only solution I have been able to make is to put a timer on the external process, and kill it if it does not return in the allotted time. Crude, nasty, and if anyone else has a good solution, I would love to hear it so I can use it too.\nOne thing you could do to help deal with the problem of completely un-managed shutdown is to keep a directory of pid files. Whenever you kick off an external process, write a file into your pid file directory with a name that is the pid for the process. Erase the pid file when you know the process has exited cleanly. You can use the stuff in the pid directory to help cleanup on crashes or re-starts.\nThis may not provide any satisfying or useful answers, but maybe it's a start.\n"
] | [
2
] | [] | [] | [
"external_process",
"pyqt",
"python",
"subprocess",
"user_interface"
] | stackoverflow_0002892756_external_process_pyqt_python_subprocess_user_interface.txt |
Q:
How to run own python script in Trac
I want to customize the project page (trac/templates/index.html).
I want to use a table to show more project-specific information. For instance the admin list of each project, the build status of each project. These information are stored in trac's database.
I am afraid that the default template engine is not able to give me there information. At least I have found nothing valuable from its documentaton.
So I decided to write a python script (on the server side) to generate these information as a JSON string. I injected also a chunk javascript to fetch the JSON from this python script by using Ajax.
But I do not know how to make my python script interpreted by trac.
Can anyone help me?
A:
I've customized trac in a more simple way by adding an iframe to the top of all trac project pages. You can do this by going to templates directory in the trac environment directory, and adding a site.html file.
I have something like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/" py:strip="">
<!--! Custom match templates go here -->
<head py:match="head" py:attrs="select('@*')">
${select('*|comment()|text()[local-name()!="script"]')}
<link rel="stylesheet" type="text/css" href="http://mysite.com/nav.css" />
</head>
<body py:match="body" py:attrs="select('@*')">
<iframe src ="http://mysite.com/nav.html"
width="100%"
id="navbar-iframe"
height="30px"
frameborder="0"
marginheight="0"
scrolling="no"
marginwidth="0">
</iframe>
<div id="tdtracbody">
${select('*|text()')}
</div>
</body>
</html>
A:
The Trac extension API allows you to intercept arbitrary pages and insert new data. For example, the BatchModifyPlugin intercepts requests and adds content to the custom query page. See the ITemplateStreamFilter methods at http://trac-hacks.org/browser/batchmodifyplugin/0.11/trunk/batchmod/web_ui.py Take a look at the Trac Hacks website for more examples.
| How to run own python script in Trac | I want to customize the project page (trac/templates/index.html).
I want to use a table to show more project-specific information. For instance the admin list of each project, the build status of each project. These information are stored in trac's database.
I am afraid that the default template engine is not able to give me there information. At least I have found nothing valuable from its documentaton.
So I decided to write a python script (on the server side) to generate these information as a JSON string. I injected also a chunk javascript to fetch the JSON from this python script by using Ajax.
But I do not know how to make my python script interpreted by trac.
Can anyone help me?
| [
"I've customized trac in a more simple way by adding an iframe to the top of all trac project pages. You can do this by going to templates directory in the trac environment directory, and adding a site.html file.\nI have something like:\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:py=\"http://genshi.edgewall.org/\" py:strip=\"\">\n <!--! Custom match templates go here -->\n <head py:match=\"head\" py:attrs=\"select('@*')\">\n ${select('*|comment()|text()[local-name()!=\"script\"]')}\n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://mysite.com/nav.css\" />\n </head>\n\n<body py:match=\"body\" py:attrs=\"select('@*')\">\n <iframe src =\"http://mysite.com/nav.html\"\n width=\"100%\"\n id=\"navbar-iframe\"\n height=\"30px\"\n frameborder=\"0\"\n marginheight=\"0\"\n scrolling=\"no\"\n marginwidth=\"0\">\n </iframe>\n <div id=\"tdtracbody\">\n ${select('*|text()')}\n </div>\n </body>\n</html>\n\n",
"The Trac extension API allows you to intercept arbitrary pages and insert new data. For example, the BatchModifyPlugin intercepts requests and adds content to the custom query page. See the ITemplateStreamFilter methods at http://trac-hacks.org/browser/batchmodifyplugin/0.11/trunk/batchmod/web_ui.py Take a look at the Trac Hacks website for more examples.\n"
] | [
1,
1
] | [] | [] | [
"customization",
"interface",
"python",
"trac"
] | stackoverflow_0002809310_customization_interface_python_trac.txt |
Q:
How to set a local image in pynotify?
If I run the following in python in Ubuntu 10.04:
>>> import pynotify
>>> p = pynotify.Notification ("Notice","","/home/george/Pictures/test.png")
>>> p.show()
true
The message displays as expected, except the image does not appear in the OSD. How can I display a local image?
In fact, for what I need, it would be better if I could display a remote image. (via HTTP)
How can I do that?
A:
The following definitely works for me:
>>> import pynotify
>>> p = pynotify.Notification("Notice", "", "/usr/share/pixmaps/firefox.png")
>>> p.show()
alt text http://www.imagebanana.com/img/qfmebkr5/screenshot_009.png
Are you sure the image is there? With correct permissions?
A:
That works for me. Maybe your backend doesn't support icons, or you are not noticing. For KDE 4, it's small but definitely there in the upper-left. Also, I don't think there's any pynotify support for remote images, so use:
urllib.urlretrieve("http://some/remote/file.png", "/some/local/file.png")
as needed.
| How to set a local image in pynotify? | If I run the following in python in Ubuntu 10.04:
>>> import pynotify
>>> p = pynotify.Notification ("Notice","","/home/george/Pictures/test.png")
>>> p.show()
true
The message displays as expected, except the image does not appear in the OSD. How can I display a local image?
In fact, for what I need, it would be better if I could display a remote image. (via HTTP)
How can I do that?
| [
"The following definitely works for me:\n>>> import pynotify\n>>> p = pynotify.Notification(\"Notice\", \"\", \"/usr/share/pixmaps/firefox.png\")\n>>> p.show()\n\nalt text http://www.imagebanana.com/img/qfmebkr5/screenshot_009.png\nAre you sure the image is there? With correct permissions?\n",
"That works for me. Maybe your backend doesn't support icons, or you are not noticing. For KDE 4, it's small but definitely there in the upper-left. Also, I don't think there's any pynotify support for remote images, so use:\nurllib.urlretrieve(\"http://some/remote/file.png\", \"/some/local/file.png\")\n\nas needed.\n"
] | [
4,
1
] | [] | [] | [
"pynotify",
"python",
"ubuntu"
] | stackoverflow_0002893462_pynotify_python_ubuntu.txt |
Q:
StringListProperty limited to 500 char strings (Google App Engine / Python)
It seems that StringListProperty can only contain strings up to 500 chars each, just like StringProperty...
Is there a way to store longer strings than that? I don't need them to be indexed or anything. What I would need would be something like a "TextListProperty", where each string in the list can be any length and not limited to 500 chars.
Can I create a property like that? Or can you experts suggest a different approach? Perhaps I should use a plain list and pickle/unpickle it in a Blob field, or something like that? I'm a bit new to Python and GAE and I would greatly appreciate some pointers instead of spending days on trial and error...thanks!
A:
Alex already answered long ago, but in case someone else comes along with the same issue:
You'd just make item_type equal to db.Text (as OP mentions in a comment).
Here's a simple example:
from google.appengine.ext import db
class LargeTextList(db.Model):
large_text_list = db.ListProperty(item_type=db.Text)
def post(self):
# get value from a POST request,
# split into list using some delimiter
# add to datastore
L = self.request.get('large_text_list').split() # your delimiter here
LTL = [db.Text(i) for i in L]
new = LargeTextList()
new.large_text_list = LTL
new.put()
def get(self):
# return one to make sure it's working
query = LargeTextList.all()
results = query.fetch(limit=1)
self.render('index.html',
{ 'results': results,
'title': 'LargeTextList Example',
})
A:
You can use a generic ListProperty with an item_type as you require (str, or unicode, or whatever).
| StringListProperty limited to 500 char strings (Google App Engine / Python) | It seems that StringListProperty can only contain strings up to 500 chars each, just like StringProperty...
Is there a way to store longer strings than that? I don't need them to be indexed or anything. What I would need would be something like a "TextListProperty", where each string in the list can be any length and not limited to 500 chars.
Can I create a property like that? Or can you experts suggest a different approach? Perhaps I should use a plain list and pickle/unpickle it in a Blob field, or something like that? I'm a bit new to Python and GAE and I would greatly appreciate some pointers instead of spending days on trial and error...thanks!
| [
"Alex already answered long ago, but in case someone else comes along with the same issue: \nYou'd just make item_type equal to db.Text (as OP mentions in a comment).\nHere's a simple example: \nfrom google.appengine.ext import db\nclass LargeTextList(db.Model):\n large_text_list = db.ListProperty(item_type=db.Text)\n\ndef post(self):\n # get value from a POST request, \n # split into list using some delimiter\n # add to datastore\n L = self.request.get('large_text_list').split() # your delimiter here\n LTL = [db.Text(i) for i in L]\n new = LargeTextList()\n new.large_text_list = LTL\n new.put()\n\ndef get(self):\n # return one to make sure it's working\n query = LargeTextList.all()\n results = query.fetch(limit=1)\n self.render('index.html', \n { 'results': results, \n 'title': 'LargeTextList Example',\n })\n\n",
"You can use a generic ListProperty with an item_type as you require (str, or unicode, or whatever).\n"
] | [
4,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002893102_google_app_engine_python.txt |
Q:
Visual Python - Visualize graphs relating to a movement
I'm working with visual python on a project where I need to simulate a physical movement.
I'd like to present, in a different window than the one the actual, 3D sim is running, two graphs, both related to the movement:
How the velocity and angular velocity
progress over time.
How the movement and rotation
progress over time.
All these vars are refreshed once per cycle (inside a while(true))
How can I accomplish this?
Thank you for your time!
A:
If you're looking to do plots of live data you can use matplotlib. Here's a live plotting example:
http://eli.thegreenplace.net/files/prog_code/wx_mpl_dynamic_graph.py.txt | Screenshot
It uses wx but matplotlib has bindings for QT or GTK. Alternatively you could use the rpy2 interface to hook into R which has an excellent plotting engine and may be slightly faster for large amounts of data.
A:
I've accomplished what I wanted with gdisplay. Reference: here
| Visual Python - Visualize graphs relating to a movement | I'm working with visual python on a project where I need to simulate a physical movement.
I'd like to present, in a different window than the one the actual, 3D sim is running, two graphs, both related to the movement:
How the velocity and angular velocity
progress over time.
How the movement and rotation
progress over time.
All these vars are refreshed once per cycle (inside a while(true))
How can I accomplish this?
Thank you for your time!
| [
"If you're looking to do plots of live data you can use matplotlib. Here's a live plotting example:\nhttp://eli.thegreenplace.net/files/prog_code/wx_mpl_dynamic_graph.py.txt | Screenshot\nIt uses wx but matplotlib has bindings for QT or GTK. Alternatively you could use the rpy2 interface to hook into R which has an excellent plotting engine and may be slightly faster for large amounts of data.\n",
"I've accomplished what I wanted with gdisplay. Reference: here\n"
] | [
2,
1
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0002891709_graphics_python.txt |
Q:
Non-Standard Optional Argument Defaults
I have two functions:
def f(a,b,c=g(b)):
blabla
def g(n):
blabla
c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?
Someone suggested:
def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
But this doesn't work. Maybe the user intended c to be None and then c will have another value.
A:
def f(a,b,c=None):
if c is None:
c = g(b)
If None can be a valid value for c then you do this:
sentinel = object()
def f(a,b,c=sentinel):
if c is sentinel:
c = g(b)
A:
You cannot do it that way.
Inside the function, check if c is specified. If not, do the calculation.
def f(a,b,c=None):
if c == None:
c = g(b)
blabla
A:
value of c will be evaluated (g(b)) at compilation time. You need g defined before f therefore. And of course you need a global b variable to be defined at that stage too.
b = 4
def g(a):
return a+1
def test(a, c=g(b)):
print(c)
test(b)
prints 5.
A:
The problem with
sentinel = object()
def f(a, b, c=sentinel):
if c is sentinel:
c = g(b)
is that sentinel is global/public unless this code is part of a function/method. So someone might still be able to call f(23, 42, sentinel). However, if f is global/public, you can use a closure to make sentinel local/private so that the caller cannot use it:
def f():
sentinel = object()
def tmp(a, b, c=sentinel):
if c is sentinel:
c = g(b)
return tmp
f = f()
If you are concerned that static code analyzers could get the wrong idea about f then, you can use the same parameters for the factory:
def f(a, b, c=object()): #@UnusedVariable
sentinel = object()
def tmp(a, b, c=sentinel):
if c is sentinel:
c = g(b)
return tmp
f = f(23, 42)
A:
def f(a,b,*args):
if len(args) == 1:
c = args[0]
elif len(args) == 0:
c = g(b)
else:
raise Exception('Function takes 2 or 3 parameters only.')
blabla
def g(n):
blabla
You can probably structure it better, but that's the main idea. Alternatively you can use **kwargs and use the function like f(a,b,c=Something), you just have to modify f accordingly.
Documentation
| Non-Standard Optional Argument Defaults | I have two functions:
def f(a,b,c=g(b)):
blabla
def g(n):
blabla
c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?
Someone suggested:
def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
But this doesn't work. Maybe the user intended c to be None and then c will have another value.
| [
"def f(a,b,c=None):\n if c is None:\n c = g(b)\n\nIf None can be a valid value for c then you do this:\nsentinel = object()\ndef f(a,b,c=sentinel):\n if c is sentinel:\n c = g(b)\n\n",
"You cannot do it that way.\nInside the function, check if c is specified. If not, do the calculation.\ndef f(a,b,c=None):\n if c == None:\n c = g(b)\n blabla\n\n",
"value of c will be evaluated (g(b)) at compilation time. You need g defined before f therefore. And of course you need a global b variable to be defined at that stage too.\nb = 4\n\ndef g(a):\n return a+1\n\ndef test(a, c=g(b)):\n print(c)\n\ntest(b)\n\nprints 5.\n",
"The problem with\nsentinel = object()\ndef f(a, b, c=sentinel):\n if c is sentinel:\n c = g(b)\n\nis that sentinel is global/public unless this code is part of a function/method. So someone might still be able to call f(23, 42, sentinel). However, if f is global/public, you can use a closure to make sentinel local/private so that the caller cannot use it:\ndef f():\n sentinel = object()\n def tmp(a, b, c=sentinel):\n if c is sentinel:\n c = g(b)\n return tmp\nf = f()\n\nIf you are concerned that static code analyzers could get the wrong idea about f then, you can use the same parameters for the factory:\ndef f(a, b, c=object()): #@UnusedVariable\n sentinel = object()\n def tmp(a, b, c=sentinel):\n if c is sentinel:\n c = g(b)\n return tmp\nf = f(23, 42)\n\n",
"def f(a,b,*args):\n if len(args) == 1:\n c = args[0]\n elif len(args) == 0:\n c = g(b)\n else:\n raise Exception('Function takes 2 or 3 parameters only.')\n blabla\n\ndef g(n):\n blabla\n\nYou can probably structure it better, but that's the main idea. Alternatively you can use **kwargs and use the function like f(a,b,c=Something), you just have to modify f accordingly.\nDocumentation\n"
] | [
28,
3,
2,
1,
0
] | [] | [] | [
"optional_arguments",
"python"
] | stackoverflow_0001118454_optional_arguments_python.txt |
Q:
Where to use a pyc file
I want to know what a pyc file(python bytecode) is. I want to know all the details.
I want to know about how pyc files interface with the compiler. Is it a replacement for exe?
Does it need to be run by python?
Is it as portable as the .py file is?
Where should I use this?
A:
To supplement Mike Graham's answer there are some interesting comments here giving some information on pyc files. Most interestingly I suspect for you is the line:
A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
Which hits the nail on the head w.r.t. the crux of a pyc file. A pyc is a pre-interpreted py file. The python bytecode is still the same as if it was generated from a py file - the difference is that when using a pyc file you don't have to go through the process of creating that pyc output (which you do when running a py file). Read as you don't have to convert the python script to python bytecode.
If you've come across .class files in java this is a similar concept - the difference is in java you have to do the compiling using javac before the java interpreter will execute the application. Different way of doing things (the internals will be very different as they're different languages) but same broad idea.
A:
Python bytecode requires Python to run, cannot be ran standalone without Python, and is specific to a particular x.y release of Python. It should be portable across platforms for the same version. There is not a common reason for you to use it; Python uses it to optimize out parsing of your .py file on repeated imports. Your life will be fine ignoring the existence of pyc files.
A:
From the docs:
As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-“byte-compiled” version of the module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don’t match.
See the ref for more info. But some specific answers:
The contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures.
It's not an executable; it's used internally by the compiler as an intermediate step.
In general, you don't make .pyc files by hand: the interpreter makes them automatically.
| Where to use a pyc file | I want to know what a pyc file(python bytecode) is. I want to know all the details.
I want to know about how pyc files interface with the compiler. Is it a replacement for exe?
Does it need to be run by python?
Is it as portable as the .py file is?
Where should I use this?
| [
"To supplement Mike Graham's answer there are some interesting comments here giving some information on pyc files. Most interestingly I suspect for you is the line:\n\nA program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded. \n\nWhich hits the nail on the head w.r.t. the crux of a pyc file. A pyc is a pre-interpreted py file. The python bytecode is still the same as if it was generated from a py file - the difference is that when using a pyc file you don't have to go through the process of creating that pyc output (which you do when running a py file). Read as you don't have to convert the python script to python bytecode.\nIf you've come across .class files in java this is a similar concept - the difference is in java you have to do the compiling using javac before the java interpreter will execute the application. Different way of doing things (the internals will be very different as they're different languages) but same broad idea.\n",
"Python bytecode requires Python to run, cannot be ran standalone without Python, and is specific to a particular x.y release of Python. It should be portable across platforms for the same version. There is not a common reason for you to use it; Python uses it to optimize out parsing of your .py file on repeated imports. Your life will be fine ignoring the existence of pyc files.\n",
"From the docs:\n\nAs an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-“byte-compiled” version of the module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don’t match.\n\nSee the ref for more info. But some specific answers:\n\nThe contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures.\n\nIt's not an executable; it's used internally by the compiler as an intermediate step.\nIn general, you don't make .pyc files by hand: the interpreter makes them automatically.\n"
] | [
17,
9,
6
] | [] | [] | [
"python"
] | stackoverflow_0002893686_python.txt |
Q:
Find the closest vector
Recently I wrote the algorithm to quantize an RGB image. Every pixel is represented by an (R,G,B) vector, and quantization codebook is a couple of 3-dimensional vectors. Every pixel of the image needs to be mapped to (say, "replaced by") the codebook pixel closest in terms of euclidean distance (more exactly, squared euclidean).
I did it as follows:
class EuclideanMetric(DistanceMetric):
def __call__(self, x, y):
d = x - y
return sqrt(sum(d * d, -1))
class Quantizer(object):
def __init__(self, codebook, distanceMetric = EuclideanMetric()):
self._codebook = codebook
self._distMetric = distanceMetric
def quantize(self, imageArray):
quantizedRaster = zeros(imageArray.shape)
X = quantizedRaster.shape[0]
Y = quantizedRaster.shape[1]
for i in xrange(0, X):
print i
for j in xrange(0, Y):
dist = self._distMetric(imageArray[i,j], self._codebook)
code = argmin(dist)
quantizedRaster[i,j] = self._codebook[code]
return quantizedRaster
...and it works awfully, almost 800 seconds on my Pentium Core Duo 2.2 GHz, 4 Gigs of memory and an image of 2600*2700 pixels:(
Is there a way to somewhat optimize this? Maybe the other algorithm or some Python-specific optimizations.
UPD: I tried to use the squared euclidean and still get an enormous time.
A:
One simple optimization is to drop the sqrt call. x is monotonic with sqrt(x), and since you don't need the actual distance, just the min distance, use x^2 instead. Should help a bit since sqrt is expensive.
This trick is used a lot when working with distances. For instance, if you have a distance threshold, you can use threshold^2 and drop the sqrt in the distance calculation. Really, the sqrt is only necessary when absolute distance is needed. For relative distances, drop the sqrt.
Update: an algorithmic change is probably needed then. Right now you are comparing every codebook vector to every pixel. It would speed things up to reduce the number of distance calculations.
You might do better using a kd-tree for this, which will reduce the search for each pixel from O(codebook) to O(log(codebook)). I've never done this in python, but some googling gave an implementation that might work here.
A:
You could use the vector quantization function vq from scipy.cluster.vq.
A:
If X is very large, you're printing i quite a lot, which can really hurt performance. For a less specific answer, read on.
To find out where the bottleneck in your process is, I suggest a timing decorator, something along the lines of
from functools import wraps
import time
def time_this(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
finish = time.time()
elapsed = (finish - start) * 1000
print '{0}: {1} ms'.format(func.__name__, elapsed)
return result
return wrapper
I found this somewhere once upon a time and have always used it to figure out where my code is slow. You can break your algorithm down into a series of separate functions, then decorate the function with this decorator to see how long each function call takes. Then it's a matter of fiddling with which statements are in which functions to see what improves how long your decorated functions take to run. Mainly you're looking for two things: 1) statements that take a long time to execute, or 2) statements that do not necessarily take long to execute, but that are executed so many times that a very small improvement in performance will have a large effect on the overall performance.
Good luck!
| Find the closest vector | Recently I wrote the algorithm to quantize an RGB image. Every pixel is represented by an (R,G,B) vector, and quantization codebook is a couple of 3-dimensional vectors. Every pixel of the image needs to be mapped to (say, "replaced by") the codebook pixel closest in terms of euclidean distance (more exactly, squared euclidean).
I did it as follows:
class EuclideanMetric(DistanceMetric):
def __call__(self, x, y):
d = x - y
return sqrt(sum(d * d, -1))
class Quantizer(object):
def __init__(self, codebook, distanceMetric = EuclideanMetric()):
self._codebook = codebook
self._distMetric = distanceMetric
def quantize(self, imageArray):
quantizedRaster = zeros(imageArray.shape)
X = quantizedRaster.shape[0]
Y = quantizedRaster.shape[1]
for i in xrange(0, X):
print i
for j in xrange(0, Y):
dist = self._distMetric(imageArray[i,j], self._codebook)
code = argmin(dist)
quantizedRaster[i,j] = self._codebook[code]
return quantizedRaster
...and it works awfully, almost 800 seconds on my Pentium Core Duo 2.2 GHz, 4 Gigs of memory and an image of 2600*2700 pixels:(
Is there a way to somewhat optimize this? Maybe the other algorithm or some Python-specific optimizations.
UPD: I tried to use the squared euclidean and still get an enormous time.
| [
"One simple optimization is to drop the sqrt call. x is monotonic with sqrt(x), and since you don't need the actual distance, just the min distance, use x^2 instead. Should help a bit since sqrt is expensive.\nThis trick is used a lot when working with distances. For instance, if you have a distance threshold, you can use threshold^2 and drop the sqrt in the distance calculation. Really, the sqrt is only necessary when absolute distance is needed. For relative distances, drop the sqrt.\nUpdate: an algorithmic change is probably needed then. Right now you are comparing every codebook vector to every pixel. It would speed things up to reduce the number of distance calculations. \nYou might do better using a kd-tree for this, which will reduce the search for each pixel from O(codebook) to O(log(codebook)). I've never done this in python, but some googling gave an implementation that might work here.\n",
"You could use the vector quantization function vq from scipy.cluster.vq.\n",
"If X is very large, you're printing i quite a lot, which can really hurt performance. For a less specific answer, read on.\nTo find out where the bottleneck in your process is, I suggest a timing decorator, something along the lines of\nfrom functools import wraps\nimport time\n\ndef time_this(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n finish = time.time()\n elapsed = (finish - start) * 1000\n print '{0}: {1} ms'.format(func.__name__, elapsed)\n return result\n return wrapper\n\nI found this somewhere once upon a time and have always used it to figure out where my code is slow. You can break your algorithm down into a series of separate functions, then decorate the function with this decorator to see how long each function call takes. Then it's a matter of fiddling with which statements are in which functions to see what improves how long your decorated functions take to run. Mainly you're looking for two things: 1) statements that take a long time to execute, or 2) statements that do not necessarily take long to execute, but that are executed so many times that a very small improvement in performance will have a large effect on the overall performance.\nGood luck!\n"
] | [
4,
2,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0002892933_optimization_python.txt |
Q:
I'm writing a spellchecking program, how do I replace ch in a string?
What am I doing wrong/what can I do?
import sys
import string
def remove(file):
punctuation = string.punctuation
for ch in file:
if len(ch) > 1:
print('error - ch is larger than 1 --| {0} |--'.format(ch))
if ch in punctuation:
ch = ' '
return ch
else:
return ch
ref = (open("ref.txt","r"))
test_file = (open("test.txt", "r"))
dictionary = ref.read().split()
file = test_file.read().lower()
file = remove(file)
print(file)
This is in Python 3.1.2
A:
In this code...:
for ch in file:
if len(ch) > 1:
the weirdly-named file (besides breaking the best practice of not hiding builtin names with your own identifier) is not a file, it's a string -- which means unicode, in Python 3, but that makes no difference to the fact that the loop is returning single characters (unicode characters, not bytes, in Python 3) so len(ch) == 1 is absolutely guaranteed by the rules of the Python language. Not sure what you're trying to accomplish with that test (rule out some subset of unicode characters?), but, whatever it is you thing you're achieving, I assure you that you're not achieving it and should recode that part.
Apart from this, you're returning -- and therefore exiting the function -- immediately, and thereby exiting the function and returning just one character (the first one in the file, or a space if that first one was a punctuation character).
The suggestion to use the translate method, which I saw in another answer, is the right one, but that answer used the wrong version of translate (one applying to byte strings, not to unicode strings as you need for Python 3). The proper unicode version is simpler, and transforms the whole body of your function into just two statements:
trans = dict.fromkeys(map(ord, string.punctuation), ' ')
return file.translate(trans)
A:
In python, strings are immutable, so you need to create a new string with your changes.
There are a few ways to do this:
One is using a list comprehension to inspect the characters and only returning the non-punctuation.
def remove(file):
return ''.join(ch for ch in file if ch not in string.punctuation)
You could also call functions to test the character or translate the character which you might have throw "weird character" exceptions or do some other functionality:
def remove(file):
return ''.join(TranslateCh(ch) for ch in file if CheckCh(ch))
Another alternative is the string module, providing replace or translate. Translate provides a nice (and more efficient than building a list) mechanism for this, see Alex's answer.
Or... you could collect a list over a forloop and join it at the end, but that's a little "unpythonic".
A:
Check out the re (regular expression) module. It has a "sub" function to replace strings that match regular expressions.
| I'm writing a spellchecking program, how do I replace ch in a string? | What am I doing wrong/what can I do?
import sys
import string
def remove(file):
punctuation = string.punctuation
for ch in file:
if len(ch) > 1:
print('error - ch is larger than 1 --| {0} |--'.format(ch))
if ch in punctuation:
ch = ' '
return ch
else:
return ch
ref = (open("ref.txt","r"))
test_file = (open("test.txt", "r"))
dictionary = ref.read().split()
file = test_file.read().lower()
file = remove(file)
print(file)
This is in Python 3.1.2
| [
"In this code...:\nfor ch in file:\n if len(ch) > 1:\n\nthe weirdly-named file (besides breaking the best practice of not hiding builtin names with your own identifier) is not a file, it's a string -- which means unicode, in Python 3, but that makes no difference to the fact that the loop is returning single characters (unicode characters, not bytes, in Python 3) so len(ch) == 1 is absolutely guaranteed by the rules of the Python language. Not sure what you're trying to accomplish with that test (rule out some subset of unicode characters?), but, whatever it is you thing you're achieving, I assure you that you're not achieving it and should recode that part.\nApart from this, you're returning -- and therefore exiting the function -- immediately, and thereby exiting the function and returning just one character (the first one in the file, or a space if that first one was a punctuation character).\nThe suggestion to use the translate method, which I saw in another answer, is the right one, but that answer used the wrong version of translate (one applying to byte strings, not to unicode strings as you need for Python 3). The proper unicode version is simpler, and transforms the whole body of your function into just two statements:\ntrans = dict.fromkeys(map(ord, string.punctuation), ' ')\nreturn file.translate(trans)\n\n",
"In python, strings are immutable, so you need to create a new string with your changes.\nThere are a few ways to do this:\nOne is using a list comprehension to inspect the characters and only returning the non-punctuation.\ndef remove(file):\n return ''.join(ch for ch in file if ch not in string.punctuation)\n\nYou could also call functions to test the character or translate the character which you might have throw \"weird character\" exceptions or do some other functionality:\ndef remove(file):\n return ''.join(TranslateCh(ch) for ch in file if CheckCh(ch))\n\nAnother alternative is the string module, providing replace or translate. Translate provides a nice (and more efficient than building a list) mechanism for this, see Alex's answer.\nOr... you could collect a list over a forloop and join it at the end, but that's a little \"unpythonic\".\n",
"Check out the re (regular expression) module. It has a \"sub\" function to replace strings that match regular expressions.\n"
] | [
2,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0002893875_python_python_3.x_string.txt |
Q:
Can I use setuptools without permissions to /usr/local etc
I want to use some packages (i.e., IPython or zdaemon), butI am doing this on a system (my university) that does not give me permissions for /usr/local, /usr/bin, or all these directories. Is there a way around it?
A:
Sure, you can use a configuration file that specifies an alternate installation directory, or use the --install-dir option. The standard place to put Python packages in your own user account is, I think, in $HOME/.local/ (if you're using Python 2.6). So for instance, pure-Python packages will wind up in $HOME/.local/lib/python2.6/site-packages/.
If your version of setuptools is recent enough to support it, also have a look at the --prefix option.
A:
Use the --install-dir option. You need to make sure this directory is in PYTHONPATH. You may find the documentation helpful.
A:
Other Option is using virtualenv to help, if available
$ virtualenv myenv
$ source myenv/bin/activate
(myenv)$ easy_install mycoolpackage
now it will end up in myenv subdir
to re-activate, just call the source line above
and to deactivate it, just close the terminal or
(myenv)$ deactivate
$
| Can I use setuptools without permissions to /usr/local etc | I want to use some packages (i.e., IPython or zdaemon), butI am doing this on a system (my university) that does not give me permissions for /usr/local, /usr/bin, or all these directories. Is there a way around it?
| [
"Sure, you can use a configuration file that specifies an alternate installation directory, or use the --install-dir option. The standard place to put Python packages in your own user account is, I think, in $HOME/.local/ (if you're using Python 2.6). So for instance, pure-Python packages will wind up in $HOME/.local/lib/python2.6/site-packages/.\nIf your version of setuptools is recent enough to support it, also have a look at the --prefix option.\n",
"Use the --install-dir option. You need to make sure this directory is in PYTHONPATH. You may find the documentation helpful. \n",
"Other Option is using virtualenv to help, if available\n$ virtualenv myenv\n$ source myenv/bin/activate\n(myenv)$ easy_install mycoolpackage\nnow it will end up in myenv subdir\nto re-activate, just call the source line above\nand to deactivate it, just close the terminal or\n(myenv)$ deactivate\n$\n"
] | [
5,
2,
1
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0002893787_python_setuptools.txt |
Q:
Socket connection to a telnet-based server hangs on read
I'm trying to write a simple socket-based client in Python that will connect to a telnet server. I can test the server by telnetting to its port (5007), and entering text. It responds with a NAK (error) or an AK (success), sometimes accompanied by other text. Seems very simple.
I wrote a client to connect and communicate with the server, but it hangs on the first attempt to read the response. The connection is successful. Queries like getsockname and getpeername are successful. The send command returns a value that equals the number of characters I'm sending, so it seems to be sending correctly. But in the end, it always hangs when I try to read the response.
I've tried using both file-based objects like readline and write (via socket.makefile), as well as using send and recv. With the file object I tried making it with "rw" and reading and writing via that object, and later tried one object for "r" and another for "w" to separate them. None of these worked.
I used a packet sniffer to watch what's going on. I'm not versed in all that I'm seeing, but during a telnet session I can see my typed text and the server's text coming back. During my Python socket connection, I can see my text going to the server, but packets back don't seem to have any text in them.
Any ideas on what I'm doing wrong, or any strategies to try?
Here's the code I'm using (in this case, it's with send and recv):
#!/usr/bin/python
host = "localhost"
port = 5007
msg = "HELLO EMC 1 1"
msg2 = "HELLO"
import socket
import sys
try:
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print("Error creating socket: %s" % e)
sys.exit(1)
try:
skt.connect((host,port))
except socket.gaierror, e:
print("Address-related error connecting to server: %s" % e)
sys.exit(1)
except socket.error, e:
print("Error connecting to socket: %s" % e)
sys.exit(1)
try:
print(skt.send(msg))
print("SEND: %s" % msg)
except socket.error, e:
print("Error sending data: %s" % e)
sys.exit(1)
while 1:
try:
buf = skt.recv(1024)
print("RECV: %s" % buf)
except socket.error, e:
print("Error receiving data: %s" % e)
sys.exit(1)
if not len(buf):
break
sys.stdout.write(buf)
Oh, in case it's useful, here's an example telnet session done manually:
ubuntu:~/mac/python$ telnet localhost 5007
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HELLO EMC 1 1
HELLO ACK EMCNETSVR 1.1
The first 'HELLO' line is what I typed, the second one is the response.
A:
You probably need to terminate your msg with some kind of "line-ending characters" -- perhaps \r\n, perhaps just one of the two. When you're in telnet, didn't you terminate your typed text by hitting a Return or Enter key? In the Python code, you're not doing the equivalent of that.
A:
You need to flush the socket right after the send, to force the TCP stack to actually send the data. Otherwise it will wait for more data to send, in order to fill a packet effectively. While you are waiting for a response from the server nothing has actually been sent yet.
| Socket connection to a telnet-based server hangs on read | I'm trying to write a simple socket-based client in Python that will connect to a telnet server. I can test the server by telnetting to its port (5007), and entering text. It responds with a NAK (error) or an AK (success), sometimes accompanied by other text. Seems very simple.
I wrote a client to connect and communicate with the server, but it hangs on the first attempt to read the response. The connection is successful. Queries like getsockname and getpeername are successful. The send command returns a value that equals the number of characters I'm sending, so it seems to be sending correctly. But in the end, it always hangs when I try to read the response.
I've tried using both file-based objects like readline and write (via socket.makefile), as well as using send and recv. With the file object I tried making it with "rw" and reading and writing via that object, and later tried one object for "r" and another for "w" to separate them. None of these worked.
I used a packet sniffer to watch what's going on. I'm not versed in all that I'm seeing, but during a telnet session I can see my typed text and the server's text coming back. During my Python socket connection, I can see my text going to the server, but packets back don't seem to have any text in them.
Any ideas on what I'm doing wrong, or any strategies to try?
Here's the code I'm using (in this case, it's with send and recv):
#!/usr/bin/python
host = "localhost"
port = 5007
msg = "HELLO EMC 1 1"
msg2 = "HELLO"
import socket
import sys
try:
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print("Error creating socket: %s" % e)
sys.exit(1)
try:
skt.connect((host,port))
except socket.gaierror, e:
print("Address-related error connecting to server: %s" % e)
sys.exit(1)
except socket.error, e:
print("Error connecting to socket: %s" % e)
sys.exit(1)
try:
print(skt.send(msg))
print("SEND: %s" % msg)
except socket.error, e:
print("Error sending data: %s" % e)
sys.exit(1)
while 1:
try:
buf = skt.recv(1024)
print("RECV: %s" % buf)
except socket.error, e:
print("Error receiving data: %s" % e)
sys.exit(1)
if not len(buf):
break
sys.stdout.write(buf)
Oh, in case it's useful, here's an example telnet session done manually:
ubuntu:~/mac/python$ telnet localhost 5007
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HELLO EMC 1 1
HELLO ACK EMCNETSVR 1.1
The first 'HELLO' line is what I typed, the second one is the response.
| [
"You probably need to terminate your msg with some kind of \"line-ending characters\" -- perhaps \\r\\n, perhaps just one of the two. When you're in telnet, didn't you terminate your typed text by hitting a Return or Enter key? In the Python code, you're not doing the equivalent of that.\n",
"You need to flush the socket right after the send, to force the TCP stack to actually send the data. Otherwise it will wait for more data to send, in order to fill a packet effectively. While you are waiting for a response from the server nothing has actually been sent yet.\n"
] | [
7,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0002893562_python_sockets.txt |
Q:
What is an efficient way to write password cracking algorithm (python)
This problem might be relatively simple, but I'm given two text files. One text file contains all encrypted passwords encrypted via crypt.crypt in python. The other list contains over 400k+ normal dictionary words.
The assignment is that given 3 different functions which transform strings from their normal case to all different permutations of capitalizations, transforms a letter to a number (if it looks alike, e.g. G -> 6, B -> 8), and reverses a string. The thing is that given the 10 - 20 encrypted passwords in the password file, what is the most efficient way to get the fastest running solution in python to run those functions on dictionary word in the words file? It is given that all those words, when transformed in whatever way, will encrypt to a password in the password file.
Here is the function which checks if a given string, when encrypted, is the same as the encrypted password passed in:
def check_pass(plaintext,encrypted):
crypted_pass = crypt.crypt(plaintext,encrypted)
if crypted_pass == encrypted:
return True
else:
return False
Thanks in advance.
A:
Without knowing details about the underlying hash algorithm and possible weaknesses of the algorithm all you can do is to run a brute-force attack trying all possible transformations of the words in your password list.
The only way to speed up such a brute-force attack is to get more powerful hardware and to split the task and run the cracker in parallel.
A:
On my slow laptop, crypt.crypt takes about 20 microseconds:
$ python -mtimeit -s'import crypt' 'crypt.crypt("foobar", "zappa")'
10000 loops, best of 3: 21.8 usec per loop
so, the brute force approach (really the only sensible one) is "kinda" feasible. By applying your transformation functions you'll get (ballpark estimate) about 100 transformed words per dictionary word (mostly from the capitalization changes), so, about 40 million transformed words out of your whole dictionary. At 20 microseconds each, that will take about 800 seconds, call it 15 minutes, for the effort of trying to crack one of the passwords that doesn't actually correspond to any of the variations; expected time about half that, to crack a password that does correspond.
So, if you have 10 passwords to crack, and they all do correspond to a transformed dictionary word, you should be done in an hour or two. Is that OK? Because there isn't much else you can do except distribute this embarassingly parallel problem over as many nodes and cores as you can grasp (oh, and, use a faster machine in the first place -- that might buy you perhaps a factor of two or thereabouts).
There is no deep optimization trick that you can add, so the general logic will be that of a triple-nested loop: one level loops over the encrypted passwords, one over the words in the dictionary, one over the variants of each dictionary word. There isn't much difference regarding how you nest things (except the loop on the variants must come within the loop on the words, for simplicity). I recommend encapsulating "give me all variants of this word" as a generator (for simplicity, not for speed) and otherwise minimizing the number of function calls (e.g. there is no reason to use that check_pass function since the inline code is just as clear, and will be microscopically faster).
| What is an efficient way to write password cracking algorithm (python) | This problem might be relatively simple, but I'm given two text files. One text file contains all encrypted passwords encrypted via crypt.crypt in python. The other list contains over 400k+ normal dictionary words.
The assignment is that given 3 different functions which transform strings from their normal case to all different permutations of capitalizations, transforms a letter to a number (if it looks alike, e.g. G -> 6, B -> 8), and reverses a string. The thing is that given the 10 - 20 encrypted passwords in the password file, what is the most efficient way to get the fastest running solution in python to run those functions on dictionary word in the words file? It is given that all those words, when transformed in whatever way, will encrypt to a password in the password file.
Here is the function which checks if a given string, when encrypted, is the same as the encrypted password passed in:
def check_pass(plaintext,encrypted):
crypted_pass = crypt.crypt(plaintext,encrypted)
if crypted_pass == encrypted:
return True
else:
return False
Thanks in advance.
| [
"Without knowing details about the underlying hash algorithm and possible weaknesses of the algorithm all you can do is to run a brute-force attack trying all possible transformations of the words in your password list. \nThe only way to speed up such a brute-force attack is to get more powerful hardware and to split the task and run the cracker in parallel.\n",
"On my slow laptop, crypt.crypt takes about 20 microseconds:\n$ python -mtimeit -s'import crypt' 'crypt.crypt(\"foobar\", \"zappa\")'\n10000 loops, best of 3: 21.8 usec per loop\n\nso, the brute force approach (really the only sensible one) is \"kinda\" feasible. By applying your transformation functions you'll get (ballpark estimate) about 100 transformed words per dictionary word (mostly from the capitalization changes), so, about 40 million transformed words out of your whole dictionary. At 20 microseconds each, that will take about 800 seconds, call it 15 minutes, for the effort of trying to crack one of the passwords that doesn't actually correspond to any of the variations; expected time about half that, to crack a password that does correspond.\nSo, if you have 10 passwords to crack, and they all do correspond to a transformed dictionary word, you should be done in an hour or two. Is that OK? Because there isn't much else you can do except distribute this embarassingly parallel problem over as many nodes and cores as you can grasp (oh, and, use a faster machine in the first place -- that might buy you perhaps a factor of two or thereabouts).\nThere is no deep optimization trick that you can add, so the general logic will be that of a triple-nested loop: one level loops over the encrypted passwords, one over the words in the dictionary, one over the variants of each dictionary word. There isn't much difference regarding how you nest things (except the loop on the variants must come within the loop on the words, for simplicity). I recommend encapsulating \"give me all variants of this word\" as a generator (for simplicity, not for speed) and otherwise minimizing the number of function calls (e.g. there is no reason to use that check_pass function since the inline code is just as clear, and will be microscopically faster).\n"
] | [
3,
2
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0002893391_algorithm_python.txt |
Q:
gae error : Error: Server Error, how to debug it
when i upload my project to google-app-engine , it show this :
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
why ?
how can i debug this error ?
thanks
A:
Look at the logs in the online administrative console of your App Engine account. That's where the info about the "why" hides;-).
Incidentally, it's very unlikely (although not impossible) that you'd immediately see such an error on the actual online App Engine without hints in your local development toolkit environment -- have you thoroughly exercised your app in the SDK before uploading it?
| gae error : Error: Server Error, how to debug it | when i upload my project to google-app-engine , it show this :
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
why ?
how can i debug this error ?
thanks
| [
"Look at the logs in the online administrative console of your App Engine account. That's where the info about the \"why\" hides;-).\nIncidentally, it's very unlikely (although not impossible) that you'd immediately see such an error on the actual online App Engine without hints in your local development toolkit environment -- have you thoroughly exercised your app in the SDK before uploading it?\n"
] | [
1
] | [] | [] | [
"debugging",
"google_app_engine",
"python"
] | stackoverflow_0002894357_debugging_google_app_engine_python.txt |
Q:
for x in y, type iteration in python. Can I find out what iteration I'm currently on?
I have a question about the loop construct in Python in the form of: for x in y: In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: aa bb cc dd etc. So, I would like to know the current iteration. Is it possible, or do I need to use a more traditional C style for loop with an index?
A:
for i,x in enumerate(y):
....
A:
Use enumerate:
for index,x in enumerate(y):
# do stuff, on iteration #index
Alternatively, just create a variable and increment it inside the loop body. This isn't quite as 'pythonic', though.
cur = 0
for x in y:
cur += 1
# do stuff, on iteration #cur
A:
If what you are doing is inserting a space after each pair of characters, you might want to do something with list comprehensions like:
' '.join([''.join(characterPair) for characterPair in zip(*[iter(line + ' ')] * 2)])
Without appending the extra space, the last character of lines with an odd number of characters will be dropped; with the appended space, lines with an odd number of characters will have an extra space at the end.
(There may well be a more pythonic way to do it than what I've done.)
A:
I can't really make a case that this is better than the enumerate method, but it is less obvious to someone coming from a C perspective, so I thought I'd point it out for completeness:
from itertools import izip_longest
' '.join(j + k for j,k in izip_longest(fillvalue='', *([iter(line)]*2)))
In Python it's often preferred (or at least encouraged) to do something with generators or list comprehensions like this, instead of relying on enumerate.
This is a variation on the grouper method from the itertools module documentation.
| for x in y, type iteration in python. Can I find out what iteration I'm currently on? | I have a question about the loop construct in Python in the form of: for x in y: In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: aa bb cc dd etc. So, I would like to know the current iteration. Is it possible, or do I need to use a more traditional C style for loop with an index?
| [
"for i,x in enumerate(y):\n ....\n\n",
"Use enumerate:\nfor index,x in enumerate(y):\n # do stuff, on iteration #index\n\nAlternatively, just create a variable and increment it inside the loop body. This isn't quite as 'pythonic', though.\ncur = 0\nfor x in y:\n cur += 1\n # do stuff, on iteration #cur\n\n",
"If what you are doing is inserting a space after each pair of characters, you might want to do something with list comprehensions like:\n' '.join([''.join(characterPair) for characterPair in zip(*[iter(line + ' ')] * 2)])\n\nWithout appending the extra space, the last character of lines with an odd number of characters will be dropped; with the appended space, lines with an odd number of characters will have an extra space at the end.\n(There may well be a more pythonic way to do it than what I've done.)\n",
"I can't really make a case that this is better than the enumerate method, but it is less obvious to someone coming from a C perspective, so I thought I'd point it out for completeness:\nfrom itertools import izip_longest\n' '.join(j + k for j,k in izip_longest(fillvalue='', *([iter(line)]*2)))\n\nIn Python it's often preferred (or at least encouraged) to do something with generators or list comprehensions like this, instead of relying on enumerate.\nThis is a variation on the grouper method from the itertools module documentation.\n"
] | [
23,
3,
0,
0
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0002894323_iteration_python.txt |
Q:
Is there a more up to date RSS feed API for Python than Feedparser?
Seems it hasn't been updated in a while, and lacks support for things like sy:updateFrequency.
A:
feedparser trunk in it's SVN repository was last updated a few days ago: feedparser.py
You can try it to see if it fits your needs, or even look in it's source to see if it can be extended to support what you need...
I also found this one but I have never used it...
hope it helps.
| Is there a more up to date RSS feed API for Python than Feedparser? | Seems it hasn't been updated in a while, and lacks support for things like sy:updateFrequency.
| [
"feedparser trunk in it's SVN repository was last updated a few days ago: feedparser.py\nYou can try it to see if it fits your needs, or even look in it's source to see if it can be extended to support what you need...\nI also found this one but I have never used it...\nhope it helps.\n"
] | [
2
] | [] | [] | [
"feedparser",
"python",
"rdf",
"rss"
] | stackoverflow_0002894407_feedparser_python_rdf_rss.txt |
Q:
How to customize a many-to-many inline model in django admin
I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship.
In models.py:
class Product(models.Model):
name = models.TextField()
price = models.DecimalField(max_digits=10,decimal_places=2)
class Invoice(models.Model):
company = models.ForeignKey(Company)
customer = models.ForeignKey(Customer)
products = models.ManyToManyField(Product)
In admin.py:
class ProductInline(admin.StackedInline):
model = Invoice.products.through
class InvoiceAdmin(admin.ModelAdmin):
inlines = [FilteredApartmentInline,]
admin.site.register(Product, ProductAdmin)
The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic.
I don't need the products to be updatable via the invoice form. How can I change it so that it'll just display the product's name in the inline table?
Which form should I override, and how?
A:
I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal
| How to customize a many-to-many inline model in django admin | I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship.
In models.py:
class Product(models.Model):
name = models.TextField()
price = models.DecimalField(max_digits=10,decimal_places=2)
class Invoice(models.Model):
company = models.ForeignKey(Company)
customer = models.ForeignKey(Customer)
products = models.ManyToManyField(Product)
In admin.py:
class ProductInline(admin.StackedInline):
model = Invoice.products.through
class InvoiceAdmin(admin.ModelAdmin):
inlines = [FilteredApartmentInline,]
admin.site.register(Product, ProductAdmin)
The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic.
I don't need the products to be updatable via the invoice form. How can I change it so that it'll just display the product's name in the inline table?
Which form should I override, and how?
| [
"I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal \n"
] | [
4
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"many_to_many",
"python"
] | stackoverflow_0002893924_django_django_admin_django_forms_many_to_many_python.txt |
Q:
Why is this dictionary line number count not working?
I have this piece of code, the last bit of the code starting from d = {}.
I'm trying to print the words with its line number located in the text but it is not working, it's only printing the words - anyone know why?
import sys
import string
text = []
infile = open(sys.argv[1], 'r').read()
for punct in string.punctuation:
infile = infile.replace(punct, "")
text = infile.split("\n")
dict = open(sys.argv[2], 'r').read()
dictset = []
dictset = dict.split()
words = []
words = list(set(text) - set(dictset))
words = [text.lower() for text in words]
words.sort()
d = {}
counter = 0
for lines in text:
counter += 1
if word not in d:
d[words] = [counter]
else:
d[words.append[counter]
print(word, d)
This code outputs:
helo
goin
ist
I want it to output :
helo #tab# 3 4
goin #tab# 1 2
A:
text is a list of WORDS, it's not a list of LINES. When you do:
text = infile.split()
you're irreversibly, forever throwing away all connections between a word and the line it was in. So when you later write
for lines in text:
it's a lie: text's items are words, not lines. If they weren't, then this other earlier line:
words = list(set(text) - set(dictset))
would be totally broken -- this depends on text's items being words, not lines.
And, by the way, when you do:
words = [text.lower() for text in words]
text is now left bound to the last item in words -- you've destroyed whatever other value it had previously.
Recommendation number one: stop reusing identifiers for many different, incompatible purposes. Make a commitment to yourself that no identifier shall ever be bound to two different things within any one of your programs. This will, at least, reduce the incredible amount of utter confusion that you manager to pile onto so few lines.
| Why is this dictionary line number count not working? | I have this piece of code, the last bit of the code starting from d = {}.
I'm trying to print the words with its line number located in the text but it is not working, it's only printing the words - anyone know why?
import sys
import string
text = []
infile = open(sys.argv[1], 'r').read()
for punct in string.punctuation:
infile = infile.replace(punct, "")
text = infile.split("\n")
dict = open(sys.argv[2], 'r').read()
dictset = []
dictset = dict.split()
words = []
words = list(set(text) - set(dictset))
words = [text.lower() for text in words]
words.sort()
d = {}
counter = 0
for lines in text:
counter += 1
if word not in d:
d[words] = [counter]
else:
d[words.append[counter]
print(word, d)
This code outputs:
helo
goin
ist
I want it to output :
helo #tab# 3 4
goin #tab# 1 2
| [
"text is a list of WORDS, it's not a list of LINES. When you do:\ntext = infile.split()\n\nyou're irreversibly, forever throwing away all connections between a word and the line it was in. So when you later write\nfor lines in text:\n\nit's a lie: text's items are words, not lines. If they weren't, then this other earlier line:\n words = list(set(text) - set(dictset))\n\nwould be totally broken -- this depends on text's items being words, not lines.\nAnd, by the way, when you do:\n words = [text.lower() for text in words]\n\ntext is now left bound to the last item in words -- you've destroyed whatever other value it had previously.\nRecommendation number one: stop reusing identifiers for many different, incompatible purposes. Make a commitment to yourself that no identifier shall ever be bound to two different things within any one of your programs. This will, at least, reduce the incredible amount of utter confusion that you manager to pile onto so few lines.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002894668_python.txt |
Q:
Most efficient way to update attribute of one instance
I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?
Right now, I'm doing the following:
1) Manage the instances in a list.
2) Iterate through the list to find a key value.
3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.
for Instance within ListofInstances:
if Instance.KeyValue == SearchValue:
Instance.AttributeToChange = 10
This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.
Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?
Thanks,
Mike
A:
As you mention, you need to keep an auxiliary dictionary with the key value as the key and the instance (or list of instance with that value for their attribute) as the value(s) -- way more efficient. Indeed, there's nothing more efficient than a dictionary for such uses.
A:
Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?)
Yes, if you are mapping from a key to a value (which you are in this case), such that one typically accesses an element via its key, then a dict rather than a list is better.
Is a dictionary any more efficient in this case?
Yes, it is much more efficient. A dictionary takes O(1) on average to lookup an item by its key whereas a list takes O(n) to lookup an item by its key, which is what you are currently doing.
Using a Dictionary
# Construct the dictionary
d = {}
# Insert items into the dictionary
d[key1] = value1
d[key2] = value2
# ...
# Checking if an item exists
if key in d:
# Do something requiring d[key]
# such as updating an attribute:
d[key].attr = val
A:
It depends on what the other needs of your program are. If all you ever do with these objects is access the one with that particular key value, then sure, a dictionary is perfect. But if you need to preserve the order of the elements, storing them in a dictionary won't do that. (You could store them in both a dict and a list, or there might be a data structure that provides a compromise between random access and order preservation) Alternatively, if more than one object can have the same key value, then you can't store both of them in a single dict at the same time, at least not directly. (You could have a dict of lists or something)
| Most efficient way to update attribute of one instance | I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?
Right now, I'm doing the following:
1) Manage the instances in a list.
2) Iterate through the list to find a key value.
3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.
for Instance within ListofInstances:
if Instance.KeyValue == SearchValue:
Instance.AttributeToChange = 10
This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.
Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?
Thanks,
Mike
| [
"As you mention, you need to keep an auxiliary dictionary with the key value as the key and the instance (or list of instance with that value for their attribute) as the value(s) -- way more efficient. Indeed, there's nothing more efficient than a dictionary for such uses.\n",
"\nShould I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?)\n\nYes, if you are mapping from a key to a value (which you are in this case), such that one typically accesses an element via its key, then a dict rather than a list is better.\n\nIs a dictionary any more efficient in this case?\n\nYes, it is much more efficient. A dictionary takes O(1) on average to lookup an item by its key whereas a list takes O(n) to lookup an item by its key, which is what you are currently doing.\nUsing a Dictionary\n # Construct the dictionary\n d = {}\n\n # Insert items into the dictionary\n d[key1] = value1\n d[key2] = value2\n # ...\n\n # Checking if an item exists\n if key in d:\n # Do something requiring d[key]\n # such as updating an attribute:\n d[key].attr = val\n\n",
"It depends on what the other needs of your program are. If all you ever do with these objects is access the one with that particular key value, then sure, a dictionary is perfect. But if you need to preserve the order of the elements, storing them in a dictionary won't do that. (You could store them in both a dict and a list, or there might be a data structure that provides a compromise between random access and order preservation) Alternatively, if more than one object can have the same key value, then you can't store both of them in a single dict at the same time, at least not directly. (You could have a dict of lists or something)\n"
] | [
1,
1,
1
] | [] | [] | [
"dictionary",
"list",
"multiple_instances",
"oop",
"python"
] | stackoverflow_0002894733_dictionary_list_multiple_instances_oop_python.txt |
Q:
Advice on translating code from very unrelated languages (in this case Scheme to Python)?
Reasoning: I'm trying to convert a large library from Scheme to Python
Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional.
Totally subjective so I'm making it community wiki
A:
I would treat the original language implementation almost like a requirements specification, and write up a design based on it (most importantly including detailed interface definitions, both for the external interfaces and for those between modules within the library). Then I would implement from that design.
What I would most definitely NOT do is any kind of function-by-function translation.
A:
Use the scheme implementation as a way of generating test cases. I'd write a function that can call scheme code, and read the output, converting it back into python.
That way, you can write test cases that look like this:
def test_f():
assert_equal(library.f(42), reference_implementation('(f 42)'))
This doesn't help you translate the library, but it will give you pretty good confidence that what you have gives the right results.
Of course, depending on what the scheme does, it may not be quite as simple as this...
A:
I would setup a bunch of whiteboards and write out the algorithms from the Scheme code. Then I would implement the algorithms in Python. Then, as @PaulHankin suggests, use the Scheme code as a way to write test cases to test the Python code
A:
If you don't have time to do as the others have suggested and actually re-implement the functionality, there is no reason you CAN'T implement it in a strictly functional fashion.
Python supports the key features necessary to do functional programming, and you might find that your time was better spent doing other things, especially if absolute optimization is not required. On the other hand, you might find bug-hunting to be quite hard.
A:
Write a Python interpreter in Scheme and directly translate your program to that :-) You can start with def:
(define-syntax def
(syntax-rules ()
((def func-name rest ...)
(define func-name (lambda rest ...)))))
;; test
(def sqr (x) (* x x))
(sqr 2) => 4
| Advice on translating code from very unrelated languages (in this case Scheme to Python)? | Reasoning: I'm trying to convert a large library from Scheme to Python
Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional.
Totally subjective so I'm making it community wiki
| [
"I would treat the original language implementation almost like a requirements specification, and write up a design based on it (most importantly including detailed interface definitions, both for the external interfaces and for those between modules within the library). Then I would implement from that design. \nWhat I would most definitely NOT do is any kind of function-by-function translation.\n",
"Use the scheme implementation as a way of generating test cases. I'd write a function that can call scheme code, and read the output, converting it back into python.\nThat way, you can write test cases that look like this:\ndef test_f():\n assert_equal(library.f(42), reference_implementation('(f 42)'))\n\nThis doesn't help you translate the library, but it will give you pretty good confidence that what you have gives the right results.\nOf course, depending on what the scheme does, it may not be quite as simple as this...\n",
"I would setup a bunch of whiteboards and write out the algorithms from the Scheme code. Then I would implement the algorithms in Python. Then, as @PaulHankin suggests, use the Scheme code as a way to write test cases to test the Python code\n",
"If you don't have time to do as the others have suggested and actually re-implement the functionality, there is no reason you CAN'T implement it in a strictly functional fashion.\nPython supports the key features necessary to do functional programming, and you might find that your time was better spent doing other things, especially if absolute optimization is not required. On the other hand, you might find bug-hunting to be quite hard.\n",
"Write a Python interpreter in Scheme and directly translate your program to that :-) You can start with def:\n (define-syntax def\n (syntax-rules ()\n ((def func-name rest ...)\n (define func-name (lambda rest ...)))))\n\n ;; test\n\n (def sqr (x) (* x x))\n (sqr 2) => 4\n\n"
] | [
7,
6,
1,
0,
0
] | [] | [] | [
"code_translation",
"python",
"scheme"
] | stackoverflow_0002893313_code_translation_python_scheme.txt |
Q:
Up To Date Documentation on Wrapping gobjects with Python
I'm looking for up-to-date documentation and tutorials on creating Python bindings for gobjects. Everything I can find on the web is either incomplete or out of date.
A:
gobject's aren't special - the standard Python documentation is what you want. Check out the Extending and Embedding Tutorial (at least the "Extending" parts), and then keep a copy of the Python/C API in your back pocket.
Also, Google Code Search is generally your friend when the tutorials don't have examples of what you want to do.
| Up To Date Documentation on Wrapping gobjects with Python | I'm looking for up-to-date documentation and tutorials on creating Python bindings for gobjects. Everything I can find on the web is either incomplete or out of date.
| [
"gobject's aren't special - the standard Python documentation is what you want. Check out the Extending and Embedding Tutorial (at least the \"Extending\" parts), and then keep a copy of the Python/C API in your back pocket.\nAlso, Google Code Search is generally your friend when the tutorials don't have examples of what you want to do.\n"
] | [
0
] | [] | [] | [
"gobject",
"pygobject",
"python"
] | stackoverflow_0002895054_gobject_pygobject_python.txt |
Q:
How to use python to create a GUI application which have cool animation/effects under Linux (like 3D wall in Cooliris, compiz effects etc...)
I am not sure if my question title makes sense to you or not. I am seeing many cool applications which have cool animations/effects. I would like to learn how to use python to create this kind of GUI applications under Linux.
"cool animation/effects" like 3D wall in Cooliris which is written in flash and compiz effects with opengl.
I also heard of some python GUI library like wxPython and pyQT. Since I am completely new to python GUI programming, can anyone suggest me where to start and what I should learn to achieve and create such application? maybe learn pyQT with openGL feature? pyopengl binding? I have no clue on where to start. thank you very much for your time and suggestion.
By the way, in case if someone need to know which kind of application I am going to create, well, just any kind of applications. maybe photo explorer with 3D wall, maybe IM client, maybe facebook client etc...
A:
http://techbase.kde.org/Development/Languages/Python
Many KDE styles use SVG and plenty of animation. The user can always change themes. I think you should be more specific about what kind of animations you want to do. I don't think 3D wall type affects really fall into the widget category that QT is. It sounds to me like you want to make a 3D interface for an application. If that is the case, you may want to look more into 3D engine type libraries used mainly in games. I know that some have excellent GUI widgets for programming game menus and the like. I guess you'd decide on your engine and the see if there are python language bindings. One of my favorite engines: http://irrlicht.sourceforge.net/links.html
Another thing you would want to consider is how you want to handle the window management. Do you want to make a full screen interface? Or is to to be windowed? Also how would such an application integrate into a 3D window manager or rather a window manager with compositing.
Edit:
In that case the qtopengl module is probably something to look into: http://doc.qt.nokia.com/4.6/qtopengl.html
I do recommend QT. It's clean and easy to use and cross platform. So your app could run on windows as well.
One thing you'd want to think about before hand is the type of FX you want to perform. For example, if you want to create a page curl type effect when renaming the image, you'd have to think about how to program that, or look for libraries/code snipets that do that math. 3D engines that are used in games often have a lot of support for those kind of typical FX or animations that you'd see in a game. If you use something like qtopengl, you'd need to think about this as well. qtopengl can pretty much only render. Think of it as a viewport. However, it is the correct approach to making a 3D application for the desktop.
Programming 3D applications is really interesting and fun. I enjoyed it a lot. However, don't get discouraged be the math. I recommend getting a book about it if you are serious. I liked this one: http://www.amazon.com/Primer-Graphics-Development-Wordware-Library/dp/1556229119
However, IIRC the examples are C++ which you may not be comfortable with. When you understand such mathematical concepts, it easier to think about how you would make a page curl type affect. Of course, if you find libraries or code that shows you how to do the math, that may be fine.
A:
May be, just create a GUI and all effects will make compiz?
Anyway, as I know QT have ability to use openGL.
http://doc.qt.nokia.com/4.1/examples.html#opengl-examples
| How to use python to create a GUI application which have cool animation/effects under Linux (like 3D wall in Cooliris, compiz effects etc...) | I am not sure if my question title makes sense to you or not. I am seeing many cool applications which have cool animations/effects. I would like to learn how to use python to create this kind of GUI applications under Linux.
"cool animation/effects" like 3D wall in Cooliris which is written in flash and compiz effects with opengl.
I also heard of some python GUI library like wxPython and pyQT. Since I am completely new to python GUI programming, can anyone suggest me where to start and what I should learn to achieve and create such application? maybe learn pyQT with openGL feature? pyopengl binding? I have no clue on where to start. thank you very much for your time and suggestion.
By the way, in case if someone need to know which kind of application I am going to create, well, just any kind of applications. maybe photo explorer with 3D wall, maybe IM client, maybe facebook client etc...
| [
"http://techbase.kde.org/Development/Languages/Python\nMany KDE styles use SVG and plenty of animation. The user can always change themes. I think you should be more specific about what kind of animations you want to do. I don't think 3D wall type affects really fall into the widget category that QT is. It sounds to me like you want to make a 3D interface for an application. If that is the case, you may want to look more into 3D engine type libraries used mainly in games. I know that some have excellent GUI widgets for programming game menus and the like. I guess you'd decide on your engine and the see if there are python language bindings. One of my favorite engines: http://irrlicht.sourceforge.net/links.html\nAnother thing you would want to consider is how you want to handle the window management. Do you want to make a full screen interface? Or is to to be windowed? Also how would such an application integrate into a 3D window manager or rather a window manager with compositing.\nEdit:\nIn that case the qtopengl module is probably something to look into: http://doc.qt.nokia.com/4.6/qtopengl.html\nI do recommend QT. It's clean and easy to use and cross platform. So your app could run on windows as well.\nOne thing you'd want to think about before hand is the type of FX you want to perform. For example, if you want to create a page curl type effect when renaming the image, you'd have to think about how to program that, or look for libraries/code snipets that do that math. 3D engines that are used in games often have a lot of support for those kind of typical FX or animations that you'd see in a game. If you use something like qtopengl, you'd need to think about this as well. qtopengl can pretty much only render. Think of it as a viewport. However, it is the correct approach to making a 3D application for the desktop.\nProgramming 3D applications is really interesting and fun. I enjoyed it a lot. However, don't get discouraged be the math. I recommend getting a book about it if you are serious. I liked this one: http://www.amazon.com/Primer-Graphics-Development-Wordware-Library/dp/1556229119\nHowever, IIRC the examples are C++ which you may not be comfortable with. When you understand such mathematical concepts, it easier to think about how you would make a page curl type affect. Of course, if you find libraries or code that shows you how to do the math, that may be fine.\n",
"May be, just create a GUI and all effects will make compiz?\nAnyway, as I know QT have ability to use openGL. \nhttp://doc.qt.nokia.com/4.1/examples.html#opengl-examples\n"
] | [
3,
0
] | [] | [] | [
"pyqt",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0002895404_pyqt_python_user_interface_wxpython.txt |
Q:
prints line number in both txtfile and list?
i have this code which prints the line number in infile but also the linenumber in words what do i do to only print the line number of the txt file next to the words???
d = {}
counter = 0
wrongwords = []
for line in infile:
infile = line.split()
wrongwords.extend(infile)
counter += 1
for word in infile:
if word not in d:
d[word] = [counter]
if word in d:
d[word].append(counter)
for stuff in wrongwords:
print(stuff, d[stuff])
the output is :
hello [1, 2, 7, 9] # this is printing the linenumber of the txt file
hello [1] # this is printing the linenumber of the list words
hello [1]
what i want is:
hello [1, 2, 7, 9]
A:
Four things:
You can keep track of the line number by doing this instead of handling a
counter on your own:
for line_no, word in enumerate(infile):
As sateesh pointed out above, you probably need an else in your
conditions:
if word not in d:
d[word] = [counter]
else:
d[word].append(counter)
Also note that the above code snippet is exactly what defaultdicts are
for:
from collections import defaultdict
d = defaultdict(list)
Then in your main loop, you can get rid of the if..else part:
d[word].append(counter)
Why are you doing wrongwords.extend(infile)?
Also, I don't really understand how you are supposed to decide what "wrong words" are. I assume that you have a set named wrongwords that contains the wrong words, which makes your final code something like this:
from collections import defaultdict
d = defaultdict(list)
wrongwords = set(["hello", "foo", "bar", "baz"])
for counter, line in enumerate(infile):
infile = line.split()
for word in infile:
if word in wrongwords:
d[word].append(counter)
| prints line number in both txtfile and list? | i have this code which prints the line number in infile but also the linenumber in words what do i do to only print the line number of the txt file next to the words???
d = {}
counter = 0
wrongwords = []
for line in infile:
infile = line.split()
wrongwords.extend(infile)
counter += 1
for word in infile:
if word not in d:
d[word] = [counter]
if word in d:
d[word].append(counter)
for stuff in wrongwords:
print(stuff, d[stuff])
the output is :
hello [1, 2, 7, 9] # this is printing the linenumber of the txt file
hello [1] # this is printing the linenumber of the list words
hello [1]
what i want is:
hello [1, 2, 7, 9]
| [
"Four things:\n\nYou can keep track of the line number by doing this instead of handling a\ncounter on your own:\nfor line_no, word in enumerate(infile):\n\nAs sateesh pointed out above, you probably need an else in your\nconditions:\nif word not in d:\n d[word] = [counter]\nelse:\n d[word].append(counter)\n\nAlso note that the above code snippet is exactly what defaultdicts are\nfor:\nfrom collections import defaultdict\nd = defaultdict(list)\n\nThen in your main loop, you can get rid of the if..else part:\nd[word].append(counter)\n\nWhy are you doing wrongwords.extend(infile)?\n\nAlso, I don't really understand how you are supposed to decide what \"wrong words\" are. I assume that you have a set named wrongwords that contains the wrong words, which makes your final code something like this:\nfrom collections import defaultdict\nd = defaultdict(list)\nwrongwords = set([\"hello\", \"foo\", \"bar\", \"baz\"])\nfor counter, line in enumerate(infile):\n infile = line.split()\n for word in infile:\n if word in wrongwords:\n d[word].append(counter)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002895428_python.txt |
Q:
Python del() built-in can't be used in assignment?
I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running:
map(lambda x: del(x) if not x.isAlive() else x, self.threads)
Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda.
This fails with a syntax error at del(x). With some messing around, I think the problem is del() doesn't return a value. For example, this fails with the same error:
b = 5
x = del(b)
This doesn't, however:
def rmThis(x): del(x)
Which means I'm using this workaround:
map(lambda x: rmThis(x) if not x.isAlive() else x, self.threads)
So is the limitation just because del() doesn't return a value? Why not?
I'm using python 2.6.2
A:
The limitation is that del is a statement and not an expression. It doesn't "return a value" because statements don't return values in Python.
The lambda form only allows you to mention expressions (because there is an implicit return before the expression), while the def form allows a single statement function to be specified on one line (as you have done with rmThis).
Normally del is used without parentheses, as:
del x
However, including parentheses around the argument as del(x) is allowed but doesn't mean it's a function call.
A:
Two problems. The first one is more subtle so I'll explain that first.
The issue is that del removes a variable binding. Passing it a value will not serve your purpose.
Here's an illustration
>>> a = 5
>>> del(a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> def mydel(x): del(x)
...
>>> a = 5
>>> mydel(a)
>>> a
5
>>>
As you can see. In the first case, the variable a has been removed from the current namespace. There's no way to refer to the object it pointed to anymore (assuming nothing else points to the same thing).
In the second case, you are not removing a from the namespace. You are deleting the binding of x in the function namespace the effect of which is that you won't be able to use x as as an rvalue anymore in the function (ie. it's an undefined variable).
The second problem is the SyntaxError which is simpler. Python lambda functions can only have expressions in them and not statements. del in not an expression (i.e., not a function call) - it's a statement (the del_stmt) and so it can't appear in the body of the lambda. You'd see the same issue if you tried putting a print in the body of the lambda.
>>> lambda x: print x
File "<stdin>", line 1
lambda x: print x
^
SyntaxError: invalid syntax
This also accounts for why the x=del(a) fails. The statement syntax is invalid. It's not a function that can be called.
| Python del() built-in can't be used in assignment? | I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running:
map(lambda x: del(x) if not x.isAlive() else x, self.threads)
Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda.
This fails with a syntax error at del(x). With some messing around, I think the problem is del() doesn't return a value. For example, this fails with the same error:
b = 5
x = del(b)
This doesn't, however:
def rmThis(x): del(x)
Which means I'm using this workaround:
map(lambda x: rmThis(x) if not x.isAlive() else x, self.threads)
So is the limitation just because del() doesn't return a value? Why not?
I'm using python 2.6.2
| [
"The limitation is that del is a statement and not an expression. It doesn't \"return a value\" because statements don't return values in Python.\nThe lambda form only allows you to mention expressions (because there is an implicit return before the expression), while the def form allows a single statement function to be specified on one line (as you have done with rmThis).\nNormally del is used without parentheses, as:\ndel x\n\nHowever, including parentheses around the argument as del(x) is allowed but doesn't mean it's a function call.\n",
"Two problems. The first one is more subtle so I'll explain that first. \nThe issue is that del removes a variable binding. Passing it a value will not serve your purpose. \nHere's an illustration \n>>> a = 5\n>>> del(a)\n>>> a\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'a' is not defined\n>>> def mydel(x): del(x)\n... \n>>> a = 5\n>>> mydel(a)\n>>> a\n5\n>>> \n\nAs you can see. In the first case, the variable a has been removed from the current namespace. There's no way to refer to the object it pointed to anymore (assuming nothing else points to the same thing). \nIn the second case, you are not removing a from the namespace. You are deleting the binding of x in the function namespace the effect of which is that you won't be able to use x as as an rvalue anymore in the function (ie. it's an undefined variable). \nThe second problem is the SyntaxError which is simpler. Python lambda functions can only have expressions in them and not statements. del in not an expression (i.e., not a function call) - it's a statement (the del_stmt) and so it can't appear in the body of the lambda. You'd see the same issue if you tried putting a print in the body of the lambda. \n>>> lambda x: print x\n File \"<stdin>\", line 1\n lambda x: print x\n ^\nSyntaxError: invalid syntax\n\nThis also accounts for why the x=del(a) fails. The statement syntax is invalid. It's not a function that can be called. \n"
] | [
15,
13
] | [] | [] | [
"built_in",
"python"
] | stackoverflow_0002895629_built_in_python.txt |
Q:
How can I set Invitee in Google Calendar through Python?
I am Setting Google Calendar via python command like this
def _InsertQuickAddEvent(self,
content="Tennis with dddddd on 5/19/2010 4am-5:30am"):
"""Creates an event with the quick_add property set to true so the content
is processed as quick add content instead of as an event description."""
event = gdata.calendar.CalendarEventEntry()
who = whois("himanshu.sojitra@searce.com")
event.content = atom.Content(text=content)
event.quick_add = gdata.calendar.QuickAdd(value='true');
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
return new_event
this code is given by Google API
Can any one suggest what to do to add invitee in this?
Important links for that
http://code.google.com/apis/calendar/data/1.0/developers_guide_python.html
A:
I got after lots of Research in this.....
event_audit=gdata.calendar.AttendeeStatus("http://schemas.google.com/g/2005#event.invited")
event.who.append(gdata.calendar.Who(email="xyz@pqr.com",rel="http://schemas.google.com/g/2005#event.invited"))
| How can I set Invitee in Google Calendar through Python? | I am Setting Google Calendar via python command like this
def _InsertQuickAddEvent(self,
content="Tennis with dddddd on 5/19/2010 4am-5:30am"):
"""Creates an event with the quick_add property set to true so the content
is processed as quick add content instead of as an event description."""
event = gdata.calendar.CalendarEventEntry()
who = whois("himanshu.sojitra@searce.com")
event.content = atom.Content(text=content)
event.quick_add = gdata.calendar.QuickAdd(value='true');
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
return new_event
this code is given by Google API
Can any one suggest what to do to add invitee in this?
Important links for that
http://code.google.com/apis/calendar/data/1.0/developers_guide_python.html
| [
"I got after lots of Research in this.....\nevent_audit=gdata.calendar.AttendeeStatus(\"http://schemas.google.com/g/2005#event.invited\")\nevent.who.append(gdata.calendar.Who(email=\"xyz@pqr.com\",rel=\"http://schemas.google.com/g/2005#event.invited\"))\n\n"
] | [
0
] | [] | [] | [
"google_apps",
"python"
] | stackoverflow_0002887612_google_apps_python.txt |
Q:
Java code translation of Python array-splitting code
Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here:
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
I don't know any python but can really use the above code in my Java app. Thanks
A:
Maybe something like this:
List<List<T>> splitList(List<T> alist, int wantedParts) {
ArrayList<List<T>> result = new ArrayList<List<T>>();
int length = alist.length;
for (int i = 0; i < wantedParts; i++) {
result.append(alist.subList(i*length/wantedParts,
(i+1)*length/wantedParts));
}
return result;
}
If your alist will be structurally modified later in any way, you will have to make a copy of the sublist created by the subList method within the code, otherwise the results will be unpredictable.
A:
Don't reinvent the wheel, the google collections api has a function called partition which does precisely that
| Java code translation of Python array-splitting code | Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here:
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
I don't know any python but can really use the above code in my Java app. Thanks
| [
"Maybe something like this:\nList<List<T>> splitList(List<T> alist, int wantedParts) {\n ArrayList<List<T>> result = new ArrayList<List<T>>();\n int length = alist.length;\n\n for (int i = 0; i < wantedParts; i++) {\n result.append(alist.subList(i*length/wantedParts,\n (i+1)*length/wantedParts));\n }\n\n return result;\n}\n\nIf your alist will be structurally modified later in any way, you will have to make a copy of the sublist created by the subList method within the code, otherwise the results will be unpredictable.\n",
"Don't reinvent the wheel, the google collections api has a function called partition which does precisely that\n"
] | [
1,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0002895664_java_python.txt |
Q:
Inserting rows while fetching(from another table) in SQLite
I'm getting this error no matter what with python and sqlite.
File "addbooks.py", line 77, in saveBook
conn.commit()
sqlite3.OperationalError: cannot commit transaction - SQL statements in progress
The code looks like this:
conn = sqlite3.connect(fname)
cread = conn.cursor()
cread.execute('''select book_text from table''')
while True:
row = cread.fetchone()
if row is None:
break
....
for entry in getEntries(doc):
saveBook(entry, conn)
Can't do a fetchall() because table and column size are big, and the memory is scarce.
What can be done without resorting to dirty tricks(as getting the rowids in memory, which would probably fit, and then selecting the rows one by one)?.
A:
The problem is that you've left the connection in auto-commit mode. Wrap a single transaction around the whole lot so that a commit only happens after you've done all the updates, and it should all work fine.
A:
Don't know if this count as "dirty tricks" too ;-)
My solution to this problem is to use SELECT... LIMIT clause, assumed you have primary key integer field id
current_id = 0
while True:
cread.execute('''select book_text from table where id > %s limit 2''' % current_id)
results = cread.fetchall()
if results is None:
break;
for row in results:
... (save book) ...
current_id = row.id
A:
The problem is that there should be no more than a single active cursor for a connection.
The solution is to use a new connection for the updates.
Unfortunatelly I do not remember the exact place in docs where I read it, so I can not prove it.
UPD:
The following code works on my Windows XP:
import sqlite3
import os
conn1 = sqlite3.connect('test.db')
cursor1 = conn1.cursor()
conn2 = sqlite3.connect('test.db')
cursor2 = conn2.cursor()
cursor1.execute("CREATE TABLE my_table (a INT, b TEXT)")
cursor1.executemany("INSERT INTO my_table (a, b) VALUES (?, NULL);", zip(range(5)))
conn1.commit()
cursor1.execute("SELECT * FROM my_table")
for a, b in cursor1:
cursor2.execute("UPDATE my_table SET b='updated' WHERE a = ?", (a, ))
conn2.commit()
print "results:"
print 10 * '-'
cursor1.execute("SELECT * FROM my_table")
for a, b in cursor1:
print a, b
cursor1.close()
conn1.close()
cursor2.close()
conn2.close()
os.unlink('test.db')
And returns the following as expected:
results:
----------
0 updated
1 updated
2 updated
3 updated
4 updated
If I move the conn2.commit() into the for loop, I get the same error as you mention:
Traceback (most recent call last):
File "concurent.py", line 16, in <module>
conn2.commit()
sqlite3.OperationalError: database is locked
Thus, the solution is to commit once at the end instead of committing after each line.
| Inserting rows while fetching(from another table) in SQLite | I'm getting this error no matter what with python and sqlite.
File "addbooks.py", line 77, in saveBook
conn.commit()
sqlite3.OperationalError: cannot commit transaction - SQL statements in progress
The code looks like this:
conn = sqlite3.connect(fname)
cread = conn.cursor()
cread.execute('''select book_text from table''')
while True:
row = cread.fetchone()
if row is None:
break
....
for entry in getEntries(doc):
saveBook(entry, conn)
Can't do a fetchall() because table and column size are big, and the memory is scarce.
What can be done without resorting to dirty tricks(as getting the rowids in memory, which would probably fit, and then selecting the rows one by one)?.
| [
"The problem is that you've left the connection in auto-commit mode. Wrap a single transaction around the whole lot so that a commit only happens after you've done all the updates, and it should all work fine.\n",
"Don't know if this count as \"dirty tricks\" too ;-)\nMy solution to this problem is to use SELECT... LIMIT clause, assumed you have primary key integer field id\ncurrent_id = 0\nwhile True: \n cread.execute('''select book_text from table where id > %s limit 2''' % current_id)\n results = cread.fetchall()\n if results is None:\n break;\n for row in results:\n ... (save book) ...\n current_id = row.id\n\n",
"The problem is that there should be no more than a single active cursor for a connection.\nThe solution is to use a new connection for the updates.\nUnfortunatelly I do not remember the exact place in docs where I read it, so I can not prove it.\nUPD:\nThe following code works on my Windows XP:\nimport sqlite3\nimport os\nconn1 = sqlite3.connect('test.db')\ncursor1 = conn1.cursor()\nconn2 = sqlite3.connect('test.db')\ncursor2 = conn2.cursor()\n\n\ncursor1.execute(\"CREATE TABLE my_table (a INT, b TEXT)\")\ncursor1.executemany(\"INSERT INTO my_table (a, b) VALUES (?, NULL);\", zip(range(5)))\nconn1.commit()\n\ncursor1.execute(\"SELECT * FROM my_table\")\nfor a, b in cursor1:\n cursor2.execute(\"UPDATE my_table SET b='updated' WHERE a = ?\", (a, ))\n\nconn2.commit()\n\nprint \"results:\"\nprint 10 * '-'\ncursor1.execute(\"SELECT * FROM my_table\")\nfor a, b in cursor1:\n print a, b\ncursor1.close()\nconn1.close()\ncursor2.close()\nconn2.close()\nos.unlink('test.db')\n\nAnd returns the following as expected:\nresults:\n----------\n0 updated\n1 updated\n2 updated\n3 updated\n4 updated\n\nIf I move the conn2.commit() into the for loop, I get the same error as you mention:\nTraceback (most recent call last):\n File \"concurent.py\", line 16, in <module>\n conn2.commit()\nsqlite3.OperationalError: database is locked\n\nThus, the solution is to commit once at the end instead of committing after each line.\n"
] | [
2,
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0002844267_python_sqlite.txt |
Q:
how do i edit a running python program?
scenario: a modular app that loads .py modules on the fly as it works. programmer (me) wishes to edit the code of a module and then re-load it into the program without halting execution.
can this be done?
i have tried running import a second time on an updated module.py, but the changes are not picked up
A:
While reload does reload a module, as the other answer mentions, you need quite a few precautions to make it work smoothly -- and for some things you might believe would work easily, you're in for quite a shock in terms of amount of work actually needed.
If you ever use the form from module import afunction, then you've almost ensured reload won't work: you must exclusively import modules, never functions, classes, etc, from inside modules, if you want to have any hope of reload doing something useful all all (otherwise you'd have to somehow chases all the bits and pieces imported here and there from the module, and rebind each and every one of them -- eep;-). Note that I prefer following this rule anyway, whether I plan to do any reloading or not, but, with reload, it's crucial.
The difficult problem is: if you have, alive anywhere, instances of classes that existed in the previous version of the module, reload per se will do absolutely nothing to upgrade those instances. That problem is a truly hard one; one of the longest, hardest recipes in the Python Cookbook (2nd edition) is all about how to code your modules to support such "reload that actually upgrades existing instances". This only matters if you program in OOP style, of course, but... any Python program complex enough to need "reload this plugin" functionality is very likely to have lots of OOP in it, so it's hardly a minor issue.
The docs for reload are pretty complete and do mention this issue, but give no hint how to solve it. This recipe by Michael Hudson, from the Python Cookbook online, is better, but it's only the start of what we evolved into the printed (2nd edition) -- recipe 20.15, the online version of that is here (incomplete unless you sign up for a free time-limited preview of O'Reilly's commercial online books service).
A:
reload() will do what you need. You just have to be careful about what code executes in your module upon re-compile; it is usually easiest if your module just contains definitions.
A:
use the builtin command:
reload(module)
How do I unload (reload) a Python module?
A:
You may get some use from the livecoding module.
A:
Alex's answer and the others cover the general case.
However, since these modules you're working on are your own and you'll edit only them, it's possible to implement some kind of a local reloading mechanism rather than rely on the builtin reload. You can architect your module loader as something that loads up the files, compiles it and evals them into a specific namespace and tells the calling code that it's ready. You can take care of reloading by making sure that there's a decent init function which reinitialises the module properly. I assume you'll be editing only these.
It's a bit of work but might be interesting and worth your time.
| how do i edit a running python program? | scenario: a modular app that loads .py modules on the fly as it works. programmer (me) wishes to edit the code of a module and then re-load it into the program without halting execution.
can this be done?
i have tried running import a second time on an updated module.py, but the changes are not picked up
| [
"While reload does reload a module, as the other answer mentions, you need quite a few precautions to make it work smoothly -- and for some things you might believe would work easily, you're in for quite a shock in terms of amount of work actually needed.\nIf you ever use the form from module import afunction, then you've almost ensured reload won't work: you must exclusively import modules, never functions, classes, etc, from inside modules, if you want to have any hope of reload doing something useful all all (otherwise you'd have to somehow chases all the bits and pieces imported here and there from the module, and rebind each and every one of them -- eep;-). Note that I prefer following this rule anyway, whether I plan to do any reloading or not, but, with reload, it's crucial.\nThe difficult problem is: if you have, alive anywhere, instances of classes that existed in the previous version of the module, reload per se will do absolutely nothing to upgrade those instances. That problem is a truly hard one; one of the longest, hardest recipes in the Python Cookbook (2nd edition) is all about how to code your modules to support such \"reload that actually upgrades existing instances\". This only matters if you program in OOP style, of course, but... any Python program complex enough to need \"reload this plugin\" functionality is very likely to have lots of OOP in it, so it's hardly a minor issue.\nThe docs for reload are pretty complete and do mention this issue, but give no hint how to solve it. This recipe by Michael Hudson, from the Python Cookbook online, is better, but it's only the start of what we evolved into the printed (2nd edition) -- recipe 20.15, the online version of that is here (incomplete unless you sign up for a free time-limited preview of O'Reilly's commercial online books service).\n",
"reload() will do what you need. You just have to be careful about what code executes in your module upon re-compile; it is usually easiest if your module just contains definitions.\n",
"use the builtin command:\nreload(module)\n\nHow do I unload (reload) a Python module?\n",
"You may get some use from the livecoding module.\n",
"Alex's answer and the others cover the general case. \nHowever, since these modules you're working on are your own and you'll edit only them, it's possible to implement some kind of a local reloading mechanism rather than rely on the builtin reload. You can architect your module loader as something that loads up the files, compiles it and evals them into a specific namespace and tells the calling code that it's ready. You can take care of reloading by making sure that there's a decent init function which reinitialises the module properly. I assume you'll be editing only these.\nIt's a bit of work but might be interesting and worth your time. \n"
] | [
6,
0,
0,
0,
0
] | [] | [] | [
"import",
"modular",
"python"
] | stackoverflow_0002894235_import_modular_python.txt |
Q:
Show me some cool python list comprehensions
One of the major strengths of python and a few other (functional) programming languages are the list comprehension. They allow programmers to write complex expressions in 1 line. They may be confusing at first but if one gets used to the syntax, it is much better than nested complicated for loops.
With that said, please share with me some of the coolest uses of list comprehensions. (By cool, I just mean useful) It could be for some programming contest, or a production system.
For example:
To do the transpose of a matrix mat
>>> mat = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>> [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Please include a description of the expression and where it was used (if possible).
A:
A lot of people don't know that Python allows you to filter the results of a list comprehension using if:
>>> [i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]
A:
I often use comprehensions to construct dicts:
my_dict = dict((k, some_func(k)) for k in input_list)
Note Python 3 has dict comprehensions, so this becomes:
my_dict = {k:some_func(k) for k in input_list}
For constructing CSV-like data from a list of tuples:
data = "\n".join(",".join(x) for x in input)
Not actually a list comprehension, but still useful: Produce a list of ranges from a list of 'cut points':
ranges = zip(cuts, cuts[1:])
A:
To do the transpose of a matrix mat:
>>> [list(row) for row in zip(*mat)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
A:
To flatten a list of lists:
>>> matrix = [[1,2,3], [4,5,6]]
>>> [x for row in matrix for x in row]
[1, 2, 3, 4, 5, 6]
A:
If "cool" means crazy, I like this one:
def cointoss(n,t):
return (lambda a:"\n".join(str(i)+":\t"+"*"*a.count(i) for i in range(min(a),max(a)+1)))([sum(randint(0,1) for _ in range(n)) for __ in range(t)])
>>> print cointoss(20,100)
3: **
4: ***
5: **
6: *****
7: *******
8: *********
9: *********
10: ********************
11: *****************
12: *********
13: *****
14: *********
15: *
16: **
n and t control the number of coin tosses per test and the number of times the test is run and the distribution is plotted.
A:
I use this all the time when loading tab-separated files with optional comment lines starting with a hash mark:
data = [line.strip().split("\t") for line in open("my_file.tab") \
if not line.startswith('#')]
Of course it works for any other comment and separator character as well.
A:
I currently have several scripts that need to group a set of points into "levels" by height. The assumption is that the z-values of the points will cluster loosely around certain values corresponding to the levels, with large-ish gaps in between the clusters.
So I have the following function:
def level_boundaries(zvalues, threshold=10.0):
'''Finds all elements z of zvalues such that no other element
w of zvalues satisfies z <= w < z+threshold.'''
zvals = zvalues[:]
zvals.sort()
return [zvals[i] for i, (a, b) in enumerate(pairs(zvals)) if b-a >= threshold]
"pairs" is taken straight from the itertools module documentation, but for reference:
def pairs(iterable):
'iterable -> (iterable[n], iterable[n+1]) for n=0, 1, 2, ...'
from itertools import izip, tee
first, second = tee(iterable)
second.next()
return izip(first, second)
A contrived usage example (my actual data sets are quite a bit too large to use as examples):
>>> import random
>>> z_vals = [100 + random.uniform(-1.5,1.5) for n in range(10)]
>>> z_vals += [120 + random.uniform(-1.5,1.5) for n in range(10)]
>>> z_vals += [140 + random.uniform(-1.5,1.5) for n in range(10)]
>>> random.shuffle(z_vals)
>>> z_vals
[141.33225473458657, 121.1713952666894, 119.40476193163271, 121.09926601186737, 119.63057973814858, 100.09095882968982, 99.226542624083109, 98.845285642062763, 120.90864911044898, 118.65196386994897, 98.902094334035326, 121.2741094217216, 101.18463497862281, 138.93502941970601, 120.71184773326806, 139.15404600347946, 139.56377827641663, 119.28279815624718, 99.338144106822554, 139.05438770927282, 138.95405784704622, 119.54614935118973, 139.9354467277665, 139.47260445000273, 100.02478729763811, 101.34605205591622, 138.97315450408186, 99.186025111246295, 140.53885845445572, 99.893009827114568]
>>> level_boundaries(z_vals)
[101.34605205591622, 121.2741094217216]
A:
As long as you are after functional programming inspired parts of Python, consider map, filter, reduce, and zip----all offered in python.
| Show me some cool python list comprehensions | One of the major strengths of python and a few other (functional) programming languages are the list comprehension. They allow programmers to write complex expressions in 1 line. They may be confusing at first but if one gets used to the syntax, it is much better than nested complicated for loops.
With that said, please share with me some of the coolest uses of list comprehensions. (By cool, I just mean useful) It could be for some programming contest, or a production system.
For example:
To do the transpose of a matrix mat
>>> mat = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>> [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Please include a description of the expression and where it was used (if possible).
| [
"A lot of people don't know that Python allows you to filter the results of a list comprehension using if:\n>>> [i for i in range(10) if i % 2 == 0]\n[0, 2, 4, 6, 8]\n\n",
"I often use comprehensions to construct dicts:\nmy_dict = dict((k, some_func(k)) for k in input_list)\n\nNote Python 3 has dict comprehensions, so this becomes:\nmy_dict = {k:some_func(k) for k in input_list}\n\nFor constructing CSV-like data from a list of tuples:\ndata = \"\\n\".join(\",\".join(x) for x in input)\n\nNot actually a list comprehension, but still useful: Produce a list of ranges from a list of 'cut points':\nranges = zip(cuts, cuts[1:])\n\n",
"To do the transpose of a matrix mat:\n>>> [list(row) for row in zip(*mat)]\n[[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n\n",
"To flatten a list of lists:\n>>> matrix = [[1,2,3], [4,5,6]]\n>>> [x for row in matrix for x in row]\n[1, 2, 3, 4, 5, 6]\n\n",
"If \"cool\" means crazy, I like this one:\ndef cointoss(n,t):\n return (lambda a:\"\\n\".join(str(i)+\":\\t\"+\"*\"*a.count(i) for i in range(min(a),max(a)+1)))([sum(randint(0,1) for _ in range(n)) for __ in range(t)])\n\n>>> print cointoss(20,100)\n3: **\n4: ***\n5: **\n6: *****\n7: *******\n8: *********\n9: *********\n10: ********************\n11: *****************\n12: *********\n13: *****\n14: *********\n15: *\n16: **\n\nn and t control the number of coin tosses per test and the number of times the test is run and the distribution is plotted.\n",
"I use this all the time when loading tab-separated files with optional comment lines starting with a hash mark:\ndata = [line.strip().split(\"\\t\") for line in open(\"my_file.tab\") \\\n if not line.startswith('#')]\n\nOf course it works for any other comment and separator character as well.\n",
"I currently have several scripts that need to group a set of points into \"levels\" by height. The assumption is that the z-values of the points will cluster loosely around certain values corresponding to the levels, with large-ish gaps in between the clusters.\nSo I have the following function:\ndef level_boundaries(zvalues, threshold=10.0):\n '''Finds all elements z of zvalues such that no other element\n w of zvalues satisfies z <= w < z+threshold.'''\n zvals = zvalues[:]\n zvals.sort()\n return [zvals[i] for i, (a, b) in enumerate(pairs(zvals)) if b-a >= threshold]\n\n\"pairs\" is taken straight from the itertools module documentation, but for reference:\ndef pairs(iterable):\n 'iterable -> (iterable[n], iterable[n+1]) for n=0, 1, 2, ...'\n from itertools import izip, tee\n first, second = tee(iterable)\n second.next()\n return izip(first, second)\n\nA contrived usage example (my actual data sets are quite a bit too large to use as examples):\n>>> import random\n>>> z_vals = [100 + random.uniform(-1.5,1.5) for n in range(10)]\n>>> z_vals += [120 + random.uniform(-1.5,1.5) for n in range(10)]\n>>> z_vals += [140 + random.uniform(-1.5,1.5) for n in range(10)]\n>>> random.shuffle(z_vals)\n>>> z_vals\n[141.33225473458657, 121.1713952666894, 119.40476193163271, 121.09926601186737, 119.63057973814858, 100.09095882968982, 99.226542624083109, 98.845285642062763, 120.90864911044898, 118.65196386994897, 98.902094334035326, 121.2741094217216, 101.18463497862281, 138.93502941970601, 120.71184773326806, 139.15404600347946, 139.56377827641663, 119.28279815624718, 99.338144106822554, 139.05438770927282, 138.95405784704622, 119.54614935118973, 139.9354467277665, 139.47260445000273, 100.02478729763811, 101.34605205591622, 138.97315450408186, 99.186025111246295, 140.53885845445572, 99.893009827114568]\n>>> level_boundaries(z_vals)\n[101.34605205591622, 121.2741094217216]\n\n",
"As long as you are after functional programming inspired parts of Python, consider map, filter, reduce, and zip----all offered in python.\n"
] | [
16,
9,
8,
8,
8,
4,
3,
2
] | [] | [] | [
"algorithm",
"list_comprehension",
"python"
] | stackoverflow_0002893569_algorithm_list_comprehension_python.txt |
Q:
Any PHP or Python alternatives for Liferay and Alfresco?
My company wants to use Liferay for developing a portal and integrate Alfresco with it for document management.
But both Liferay and Alfresco are Java based and i would like to know if there are any alternatives to Liferay and Alfresco in PHP or Python.
Thank You
A:
Maybe you can have a look at KnowledgeTree as a substitution of Alfresco. It's mainly written in PHP.
A:
It seems both are content management systems. Here you'll find a couple of proprietary PHP based CMS. As for opensource solutions, there are many.
PHP
Joomla
Drupal
And many more
Python
Django-CMS
And others..
I don't know how enterprisy these are (nor do I have much experience with them), but Joomla and Drupal are quite popular. Django is great, so I would expect a django based CMS to be good.
| Any PHP or Python alternatives for Liferay and Alfresco? | My company wants to use Liferay for developing a portal and integrate Alfresco with it for document management.
But both Liferay and Alfresco are Java based and i would like to know if there are any alternatives to Liferay and Alfresco in PHP or Python.
Thank You
| [
"Maybe you can have a look at KnowledgeTree as a substitution of Alfresco. It's mainly written in PHP.\n",
"It seems both are content management systems. Here you'll find a couple of proprietary PHP based CMS. As for opensource solutions, there are many.\n\nPHP\n\n\nJoomla \nDrupal\nAnd many more\n\nPython\n\n\nDjango-CMS\nAnd others..\n\n\nI don't know how enterprisy these are (nor do I have much experience with them), but Joomla and Drupal are quite popular. Django is great, so I would expect a django based CMS to be good. \n"
] | [
3,
0
] | [] | [] | [
"alfresco",
"java",
"liferay",
"php",
"python"
] | stackoverflow_0002896269_alfresco_java_liferay_php_python.txt |
Q:
Creating a sliding frame containing widgets in tkinter in python
I am trying really hard to make a sliding frame containing widgets in tkinter in python. There is this frame inside a big window with different widgets. And as soon as i click on the next button on that frame the frame should slowly slide towards the left and vanish ultimately. As soon as it vanishes, i want new frame with widgets to come sliding towards right.
What should i do?
Anticipating your suggestions and ideas.
A:
How you do it depends on the geometry manager, but the basic idea is simply to set the width of the frame to smaller and smaller values until it has a width of zero. You don't need a loop though -- the code is already running in the event loop, so take advantage of that. Use 'after' to schedule a job that changes the width a tiny bit, then reschedules itself for a few milliseconds later.
| Creating a sliding frame containing widgets in tkinter in python | I am trying really hard to make a sliding frame containing widgets in tkinter in python. There is this frame inside a big window with different widgets. And as soon as i click on the next button on that frame the frame should slowly slide towards the left and vanish ultimately. As soon as it vanishes, i want new frame with widgets to come sliding towards right.
What should i do?
Anticipating your suggestions and ideas.
| [
"How you do it depends on the geometry manager, but the basic idea is simply to set the width of the frame to smaller and smaller values until it has a width of zero. You don't need a loop though -- the code is already running in the event loop, so take advantage of that. Use 'after' to schedule a job that changes the width a tiny bit, then reschedules itself for a few milliseconds later. \n"
] | [
0
] | [] | [] | [
"frame",
"python",
"sliding",
"tkinter",
"user_interface"
] | stackoverflow_0002882060_frame_python_sliding_tkinter_user_interface.txt |
Q:
Can DBRefs contain additional fields?
I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself.
{$ref:'user', $id:'10285102912A', username:'Soviut'}
For example, I may want to have the username available even though the user document is referenced. This would provide me all the benefits of a single document approach; Faster querying and eliminating the need to do manual dereferencing in my code. While at the same time allowing me to use references where they make sense.
The idea being that when the referenced document is updated (a user changes their name, for example) my business layer can automatically update all the documents that reference it.
Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs? Will it break anything? Will I lose my data each time a reference is rewritten? Will drivers like pymongo support it?
A:
Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs?
It might be cleaner to have separate "cached" and "ref" fields... it depends one what your data is like.
Will I lose my data each time a reference is rewritten?
You could, but not if you're careful. If you're updating the DB ref subobject, just make sure you're updating the specific fields you want updated, not overwriting the whole subobject.
Remember that references as they are just normal objects. The database reference is a standard, not a special type.
Will drivers like pymongo support it?
The driver's dereferencing helpers will still work. The helpers just do a findOne with the $ref and $id fields.
| Can DBRefs contain additional fields? | I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself.
{$ref:'user', $id:'10285102912A', username:'Soviut'}
For example, I may want to have the username available even though the user document is referenced. This would provide me all the benefits of a single document approach; Faster querying and eliminating the need to do manual dereferencing in my code. While at the same time allowing me to use references where they make sense.
The idea being that when the referenced document is updated (a user changes their name, for example) my business layer can automatically update all the documents that reference it.
Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs? Will it break anything? Will I lose my data each time a reference is rewritten? Will drivers like pymongo support it?
| [
"\nUltimately, I'm wondering if it's considered good form to store additional fields on my DBRefs?\n\nIt might be cleaner to have separate \"cached\" and \"ref\" fields... it depends one what your data is like.\n\nWill I lose my data each time a reference is rewritten?\n\nYou could, but not if you're careful. If you're updating the DB ref subobject, just make sure you're updating the specific fields you want updated, not overwriting the whole subobject. \nRemember that references as they are just normal objects. The database reference is a standard, not a special type.\n\nWill drivers like pymongo support it?\n\nThe driver's dereferencing helpers will still work. The helpers just do a findOne with the $ref and $id fields.\n"
] | [
5
] | [] | [] | [
"dbref",
"mongodb",
"nosql",
"pymongo",
"python"
] | stackoverflow_0002893858_dbref_mongodb_nosql_pymongo_python.txt |
Q:
how can i increase the speed of socket
how can i increase speed of socket in python ?
my code :
import urllib
proxies = {'http': 'http://75.21.47.2:8080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
A:
75.21.47.2:8080 seems to be a public HTTP proxy server? these are invariably slow because of what they are.
If you want better performance via a proxy, implement your own or use a commercial service.
A:
Measure all stages of the pipeline (Opening the connection, sending the message, receiving the response etc.). Figure out where the largest bang for the buck is and think of a way to do it. From your question, the only answer is Kimvais's - Buy a better internet!
A:
Thought about compression? Sure, depends on what you're doing, but if possible it should definitely be used.
| how can i increase the speed of socket | how can i increase speed of socket in python ?
my code :
import urllib
proxies = {'http': 'http://75.21.47.2:8080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
| [
"75.21.47.2:8080 seems to be a public HTTP proxy server? these are invariably slow because of what they are.\nIf you want better performance via a proxy, implement your own or use a commercial service.\n",
"Measure all stages of the pipeline (Opening the connection, sending the message, receiving the response etc.). Figure out where the largest bang for the buck is and think of a way to do it. From your question, the only answer is Kimvais's - Buy a better internet!\n",
"Thought about compression? Sure, depends on what you're doing, but if possible it should definitely be used.\n"
] | [
2,
0,
0
] | [
"What is the baud rate you are using? You can probably increase it.\nOk, now once the question has been cleared, I shall recommend to opt for a better solution (like implementing your own) rather than using the public proxy service. It is slow.\n"
] | [
-1
] | [
"python",
"sockets"
] | stackoverflow_0002896193_python_sockets.txt |
Q:
Server side command line queuing
Is it possible to have a server side program that queues and manages processes that are executed at the command line?
The project I am working on takes an image from the user, modifies the image then applies it as a texture to a 3D shape. This 3D scene is generated by blender/Cinema 4d at the command line which outputs it as an image. It is this process that needs to be queued or somehow managed from the server side program. The end result sent back to the user is a video containing an animated 3D shape with their image as a texture applied to it.
These renders may take a while (they may not) but how can I ensure that they are executed at the right times and done so in a queued manner?
This will preferably be done in python.
A:
Lacking more details about how/why you're doing queuing (can only run so many at a time, things need to be done in the right order, etc?), it's hard to suggest a specific solution. However, the basic answer for any situation is that you want to use the subprocess module to fire off the processes, and then you can watch them (using the tools afforded to you by that module) to wait until they're complete and then execute the next one in the queue.
| Server side command line queuing | Is it possible to have a server side program that queues and manages processes that are executed at the command line?
The project I am working on takes an image from the user, modifies the image then applies it as a texture to a 3D shape. This 3D scene is generated by blender/Cinema 4d at the command line which outputs it as an image. It is this process that needs to be queued or somehow managed from the server side program. The end result sent back to the user is a video containing an animated 3D shape with their image as a texture applied to it.
These renders may take a while (they may not) but how can I ensure that they are executed at the right times and done so in a queued manner?
This will preferably be done in python.
| [
"Lacking more details about how/why you're doing queuing (can only run so many at a time, things need to be done in the right order, etc?), it's hard to suggest a specific solution. However, the basic answer for any situation is that you want to use the subprocess module to fire off the processes, and then you can watch them (using the tools afforded to you by that module) to wait until they're complete and then execute the next one in the queue.\n"
] | [
1
] | [] | [] | [
"command_line",
"python",
"queue",
"rendering"
] | stackoverflow_0002896614_command_line_python_queue_rendering.txt |
Q:
Best resources for learning PyGame?
Just curious if anyone knows of good sites for learning and understanding PyGame.
I've programmed a bunch in Python, so I'm well-equipped with that. Just curious if anyone knows a good site or more for learning PyGame.
Thanks for any help!
A:
I have several Pygame bookmarks on my delicious page that I think are worth a look. The links cover both tutorials and libraries to make your Pygame development easier. It would also be worth looking at a good, complete game written with Pygame to get an idea of how it should be structured. There are plenty of excellent ones on Ian Mallett's page, for instance. Good luck on your game writing!
A:
Eli Bendersky writes well and has written a tutorial "not for beginners". It's certainly worth a look.
A:
I really liked this tutorial: http://rene.f0o.com/mywiki/PythonGameProgramming. I found that it was an excellent way to get started with learning the basics of the library itself.
The whole of http://pygame.org is brilliant if you haven't found that already. The documentation section is great, as is the tutorial section.
A:
Invent Your Own Computer Games with Python -ebook has some nice PyGame chapters.
http://inventwithpython.com/
A:
Others pointed to good tutorials so I rather give an advice. Start to download some games listed on pygame.org and learn, examine their sources. Play around them, make changes and see how they behave. This is the best way to get practice.
I am a pygame hobbyist too, so if you will have anything to release in the future, I could offer my page to do it (beside pygame.org of course): http://sites.google.com/site/sipygames/
A:
I usually recommend the Line By Line Chimp tutorial since Ive found it to cover the most parts in the shortest time.
A:
No one has mentioned this yet as a source of games written in pygame, but check out www.pyweek.org - it's a week-long programming competition featuring games built in python. In many cases they use pygame, though there are other libs such as pyglet and opengl that are used.
| Best resources for learning PyGame? | Just curious if anyone knows of good sites for learning and understanding PyGame.
I've programmed a bunch in Python, so I'm well-equipped with that. Just curious if anyone knows a good site or more for learning PyGame.
Thanks for any help!
| [
"I have several Pygame bookmarks on my delicious page that I think are worth a look. The links cover both tutorials and libraries to make your Pygame development easier. It would also be worth looking at a good, complete game written with Pygame to get an idea of how it should be structured. There are plenty of excellent ones on Ian Mallett's page, for instance. Good luck on your game writing!\n",
"Eli Bendersky writes well and has written a tutorial \"not for beginners\". It's certainly worth a look.\n",
"I really liked this tutorial: http://rene.f0o.com/mywiki/PythonGameProgramming. I found that it was an excellent way to get started with learning the basics of the library itself.\nThe whole of http://pygame.org is brilliant if you haven't found that already. The documentation section is great, as is the tutorial section.\n",
"Invent Your Own Computer Games with Python -ebook has some nice PyGame chapters.\nhttp://inventwithpython.com/\n",
"Others pointed to good tutorials so I rather give an advice. Start to download some games listed on pygame.org and learn, examine their sources. Play around them, make changes and see how they behave. This is the best way to get practice.\nI am a pygame hobbyist too, so if you will have anything to release in the future, I could offer my page to do it (beside pygame.org of course): http://sites.google.com/site/sipygames/\n",
"I usually recommend the Line By Line Chimp tutorial since Ive found it to cover the most parts in the shortest time.\n",
"No one has mentioned this yet as a source of games written in pygame, but check out www.pyweek.org - it's a week-long programming competition featuring games built in python. In many cases they use pygame, though there are other libs such as pyglet and opengl that are used.\n"
] | [
5,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0002865003_pygame_python.txt |
Q:
Python: UTF16 decoding adds a new blank line on Windows boxes
I'm running into an issue with extra newlines on windows versus *nix platforms.
file = open('UTF16file.xml', 'rb')
html = file.read().decode('utf-16')
file.close()
regexp = re.compile(self.originalurl, re.S)
(html, changes) = regexp.subn(self.newurl, html)
file = open('UTF16file-regexed.xml', 'w+')
file.write(html.encode('utf-16'))
file.close()
Running this code on my mac works - I get my file back without the extra line breaks. So far I've tried:
Encoding the regular expression as utf-16 instead of decoding the file - breaks on Windows and OSX.
Writing in mode 'wb' instead of 'w+' - breaks on Windows.
Any ideas?
A:
C:\Documents and Settings\Nick>python
ActivePython 2.6.4.10 (ActiveState Software Inc.) based on
Python 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit (Intel)]...
Type "help", "copyright", "credits" or "license" for more information.
>>> txt = """here
... is all
... my text n stuff."""
>>> f = open('u16.txt','wb')
>>> f.write(txt.encode('utf-16'))
>>> f.close()
>>> exit()
C:\Documents and Settings\Nick>notepad u16.txt
Looks like:
here is allmy text n stuff.
(though when I copy-pasted it from Notepad to FF it actually put in line breaks)...but this:
C:\Documents and Settings\Nick>
"C:\Program Files\Windows NT\Accessories\wordpad.exe" u16.txt
Looks like:
here
is all
my text n stuff.
(on Windows XP SP3 32-bit)
| Python: UTF16 decoding adds a new blank line on Windows boxes | I'm running into an issue with extra newlines on windows versus *nix platforms.
file = open('UTF16file.xml', 'rb')
html = file.read().decode('utf-16')
file.close()
regexp = re.compile(self.originalurl, re.S)
(html, changes) = regexp.subn(self.newurl, html)
file = open('UTF16file-regexed.xml', 'w+')
file.write(html.encode('utf-16'))
file.close()
Running this code on my mac works - I get my file back without the extra line breaks. So far I've tried:
Encoding the regular expression as utf-16 instead of decoding the file - breaks on Windows and OSX.
Writing in mode 'wb' instead of 'w+' - breaks on Windows.
Any ideas?
| [
"C:\\Documents and Settings\\Nick>python\nActivePython 2.6.4.10 (ActiveState Software Inc.) based on\nPython 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit (Intel)]...\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> txt = \"\"\"here\n... is all\n... my text n stuff.\"\"\"\n>>> f = open('u16.txt','wb')\n>>> f.write(txt.encode('utf-16'))\n>>> f.close()\n>>> exit()\n\nC:\\Documents and Settings\\Nick>notepad u16.txt\n\nLooks like:\nhere is allmy text n stuff.\n\n(though when I copy-pasted it from Notepad to FF it actually put in line breaks)...but this:\nC:\\Documents and Settings\\Nick>\n \"C:\\Program Files\\Windows NT\\Accessories\\wordpad.exe\" u16.txt\n\nLooks like:\nhere \nis all\nmy text n stuff.\n\n(on Windows XP SP3 32-bit)\n"
] | [
0
] | [] | [] | [
"python",
"utf_16"
] | stackoverflow_0002897252_python_utf_16.txt |
Q:
Python templates for huge HTML/XML
Recently I needed to generate a huge HTML page containing a report with several thousand row table. And, obviously, I did not want to build the whole HTML (or the underlying tree) in memory. As result, I built the page with the old good string interpolation, but I do not like the solution.
Thus, I wonder whether there are Python templating engines that can yield resulting page content by parts.
UPD 1: I am not interested in listing all available frameworks and templating engines.
I am interested in templating solutions that I can use separately from any framework and which can yield content by portions instead of building the whole result in memory.
I understand the usability enhancements from partial content loading with client scripting, but that is out of the scope of my current question. Say, I want to generate a huge HTML/XML and stream it into a local file.
A:
Most popular template engines have a way to generate or write rendered result to file objects with chunks. For example:
Template.generate() in Jinja2
Template.render_context() in Mako
Stream.serialize() in Genshi
A:
It'd be more user-friendly (assuming they have javascript enabled) to build the table via javascript by using e.g. a jQuery plugin which allows automatical loading of contents as soon as you scroll down. Then only few rows are loaded initially and when the user scrolls down more rows are loaded on demand.
If that's not a solution, you could use three templates: one for everything before the rows, one for everything after the rows and a third one for the rows.
Then you first send the before-rows template, then generate the rows and send them immediately, then the after-rows template. Then you will have only one block/row in memory instead of the whole table.
A:
There is no problem with building something like this in memory. Several thousand rows is by no means big.
For your templating needs you can use any of the:
rst http://docutils.sourceforge.net/rst.html (just needs core docutils)
markdown http://daringfireball.net/projects/markdown/ (python lib)
sphinx https://www.sphinx-doc.org (python based)
json http://www.json.org/ (python lib)
There are some tools that allow generation of HTML from these markup languages.
A:
You don't need a streaming templating engine - I do this all the time, and long before you run into anything vaguely heavy server-side, the browser will start to choke. Rendering a 10000 row table will peg the CPU for several seconds in pretty much any browser; scrolling it will be bothersomely choppy in chrome, and the browser mem usage will rise regardless of browser.
What you can do (and I've previously implemented, even though in retrospect it turns out not to be necessary) is use client-side xslt. Printing the xslt processing instruction and the opening and closing tag using strings is easy and fairly safe; then you can stream each individual row as a standalone xml element using whatever xml writer technique you prefer.
However - you really don't need this, and likely never will - if ever your html generator gets too slow, the browser will be an order of magnitude more problematic.
So, unless you benchmarked this and have determined you really have a problem, don't waste your time. If you do have a problem, you can solve it without fundamentally changing the method - in memory generation can work just fine.
A:
Are you using a web framework for this?
http://www.pylonshq.com includes compatibility with several templating engines.
http://www.djangoproject.com/ Django has its own templating language.
I think an answer that included lazy loading of the rows with javascript would work for web view, but I presume the report is going to need to be printed, in which case you'll have to build the whole thing at some point, right?
| Python templates for huge HTML/XML | Recently I needed to generate a huge HTML page containing a report with several thousand row table. And, obviously, I did not want to build the whole HTML (or the underlying tree) in memory. As result, I built the page with the old good string interpolation, but I do not like the solution.
Thus, I wonder whether there are Python templating engines that can yield resulting page content by parts.
UPD 1: I am not interested in listing all available frameworks and templating engines.
I am interested in templating solutions that I can use separately from any framework and which can yield content by portions instead of building the whole result in memory.
I understand the usability enhancements from partial content loading with client scripting, but that is out of the scope of my current question. Say, I want to generate a huge HTML/XML and stream it into a local file.
| [
"Most popular template engines have a way to generate or write rendered result to file objects with chunks. For example:\n\nTemplate.generate() in Jinja2\nTemplate.render_context() in Mako\nStream.serialize() in Genshi\n\n",
"It'd be more user-friendly (assuming they have javascript enabled) to build the table via javascript by using e.g. a jQuery plugin which allows automatical loading of contents as soon as you scroll down. Then only few rows are loaded initially and when the user scrolls down more rows are loaded on demand.\nIf that's not a solution, you could use three templates: one for everything before the rows, one for everything after the rows and a third one for the rows.\nThen you first send the before-rows template, then generate the rows and send them immediately, then the after-rows template. Then you will have only one block/row in memory instead of the whole table.\n",
"There is no problem with building something like this in memory. Several thousand rows is by no means big.\nFor your templating needs you can use any of the:\n\nrst http://docutils.sourceforge.net/rst.html (just needs core docutils)\nmarkdown http://daringfireball.net/projects/markdown/ (python lib)\nsphinx https://www.sphinx-doc.org (python based)\njson http://www.json.org/ (python lib)\n\nThere are some tools that allow generation of HTML from these markup languages.\n",
"You don't need a streaming templating engine - I do this all the time, and long before you run into anything vaguely heavy server-side, the browser will start to choke. Rendering a 10000 row table will peg the CPU for several seconds in pretty much any browser; scrolling it will be bothersomely choppy in chrome, and the browser mem usage will rise regardless of browser.\nWhat you can do (and I've previously implemented, even though in retrospect it turns out not to be necessary) is use client-side xslt. Printing the xslt processing instruction and the opening and closing tag using strings is easy and fairly safe; then you can stream each individual row as a standalone xml element using whatever xml writer technique you prefer.\nHowever - you really don't need this, and likely never will - if ever your html generator gets too slow, the browser will be an order of magnitude more problematic.\nSo, unless you benchmarked this and have determined you really have a problem, don't waste your time. If you do have a problem, you can solve it without fundamentally changing the method - in memory generation can work just fine.\n",
"Are you using a web framework for this?\n http://www.pylonshq.com includes compatibility with several templating engines.\n http://www.djangoproject.com/ Django has its own templating language.\nI think an answer that included lazy loading of the rows with javascript would work for web view, but I presume the report is going to need to be printed, in which case you'll have to build the whole thing at some point, right?\n"
] | [
5,
2,
2,
1,
0
] | [] | [] | [
"python",
"templates"
] | stackoverflow_0002832915_python_templates.txt |
Q:
Are there any guidelines available for beginning Python with Python 2.6 to write applications easily migratable to Python 3 in future?
Possible Duplicate:
Tips on upgrading to python 3.0?
I am beginning Python and Python 3 is hardly a choice today. But I want the new code I write to have no problems running or being converted to Python 3. Are there any issues known that I should keep in mind for this?
A:
The full correct answer is in the comments, of course - but if you only do one thing to prepare for Python 3, make it learning to use parentheses with 'print'.
Python 2.x:
print 'Hello, World!'
Python 3.x:
print('Hello, World!')
It's the number one most common error in my code when I try to write Python 3.
(And since both methods work with 2.x, you might as well go ahead and get used to using the parens!)
| Are there any guidelines available for beginning Python with Python 2.6 to write applications easily migratable to Python 3 in future? |
Possible Duplicate:
Tips on upgrading to python 3.0?
I am beginning Python and Python 3 is hardly a choice today. But I want the new code I write to have no problems running or being converted to Python 3. Are there any issues known that I should keep in mind for this?
| [
"The full correct answer is in the comments, of course - but if you only do one thing to prepare for Python 3, make it learning to use parentheses with 'print'.\nPython 2.x:\nprint 'Hello, World!'\n\nPython 3.x:\nprint('Hello, World!')\n\nIt's the number one most common error in my code when I try to write Python 3.\n(And since both methods work with 2.x, you might as well go ahead and get used to using the parens!)\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002896364_python_python_3.x.txt |
Q:
Crossfading audio with PyQT4 and Phonon
I'm trying to get audio files to crossfade with phonon. I'm using PyQT4. I have tracks queuing properly, but I'm stuck with the fade effect. I think I need to be using the KVolumeFader effect. Here's my current code:
def music_play(self):
self.delayedInit()
self.m_media.setCurrentSource(Phonon.MediaSource(self.playlist[self.playlist_pos]))
self.m_media.play()
def music_stop(self):
self.m_media.stop()
def delayedInit(self):
if not self.m_media:
self.m_media = Phonon.MediaObject(self)
audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
Phonon.createPath(self.m_media, audioOutput)
def enqueueNextSource(self):
if len(self.playlist) >= self.playlist_pos+1:
self.playlist_pos += 1
self.m_media.enqueue(Phonon.MediaSource(self.playlist[self.playlist_pos]))
else:
self.m_media.stop()
Can anyone give me some advice on implementing the effect?
A:
Seems I found the solution I was looking for. Although it's not supported by every phonon backend, setting the MediaObject's transitionTime with a negative number will crossfade.
| Crossfading audio with PyQT4 and Phonon | I'm trying to get audio files to crossfade with phonon. I'm using PyQT4. I have tracks queuing properly, but I'm stuck with the fade effect. I think I need to be using the KVolumeFader effect. Here's my current code:
def music_play(self):
self.delayedInit()
self.m_media.setCurrentSource(Phonon.MediaSource(self.playlist[self.playlist_pos]))
self.m_media.play()
def music_stop(self):
self.m_media.stop()
def delayedInit(self):
if not self.m_media:
self.m_media = Phonon.MediaObject(self)
audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
Phonon.createPath(self.m_media, audioOutput)
def enqueueNextSource(self):
if len(self.playlist) >= self.playlist_pos+1:
self.playlist_pos += 1
self.m_media.enqueue(Phonon.MediaSource(self.playlist[self.playlist_pos]))
else:
self.m_media.stop()
Can anyone give me some advice on implementing the effect?
| [
"Seems I found the solution I was looking for. Although it's not supported by every phonon backend, setting the MediaObject's transitionTime with a negative number will crossfade.\n"
] | [
2
] | [] | [] | [
"phonon",
"pyqt4",
"python"
] | stackoverflow_0002878521_phonon_pyqt4_python.txt |
Q:
file layout and setuptools configuration for the python bit of a multi-language library
So we're writing a full-text search framework MongoDb. MongoDB is pretty much javascript-native, so we wrote the javascript library first, and it works.
Now I'm trying to write a python framework for it, which will be partially in python, but partially use those same stored javascript functions - the javascript functions are an intrinsic part of the library. On the other hand, the javascript framework does not depend on python. since they are pretty intertwined it seems like it's worthwhile keeping them in the same repository.
I'm trying to work out a way of structuring the whole project to give the javascript and python frameworks equal status (maybe a ruby driver or whatever in the future?), but still allow the python library to install nicely.
Currently it looks like this: (simplified a little)
javascript/jstest/test1.js
javascript/mongo-fulltext/search.js
javascript/mongo-fulltext/util.js
python/docs/indext.rst
python/tests/search_test.py
python/tests/__init__.py
python/mongofulltextsearch/__init__.py
python/mongofulltextsearch/mongo_search.py
python/mongofulltextsearch/util.py
python/setup.py
I've skipped out a few files for simplicity, but you get the general idea; it' a pretty much standard python project... except that it depends critcally ona whole bunch of javascript which is stored in a sibling directory tree.
What's the preferred setup for dealing with this kind of thing when it comes to setuptools? I can work out how to use package_data etc to install data files that live inside my python project as per the setuptools docs.
The problem is if i want to use setuptools to install stuff, including the javascript files from outside the python code tree, and then also access them in a consistent way when I'm developing the python code and when it is easy_installed to someone's site.
Is that supported behaviour for setuptools? Should i be using paver or distutils2 or Distribute or something? (basic distutils is not an option; the whole reason I'm doing this is to enable requirements tracking) How should i be reading the contents of those files into python scripts?
A:
The short answer is that none of the Python distribution tools is going to do what you want, the exact way you want it. Even if you use distutils' data_files feature, you're still going to have to have your javascript files copied into your Python project directory (i.e., somewhere under the same directory as your setup.py.)
Given that, you might as well just copy the .js files to your package (i.e. alongside mongofulltextsearch/init.py) as part of your build process, and use package_data or include_package_data=True.
(Or alternatively, you could possibly use symlinks, externals, or some such, if your revision control system supports those. I believe that when building source distributions, the Python distribution tools convert symlinks to real files. At least, you could give that a try.)
| file layout and setuptools configuration for the python bit of a multi-language library | So we're writing a full-text search framework MongoDb. MongoDB is pretty much javascript-native, so we wrote the javascript library first, and it works.
Now I'm trying to write a python framework for it, which will be partially in python, but partially use those same stored javascript functions - the javascript functions are an intrinsic part of the library. On the other hand, the javascript framework does not depend on python. since they are pretty intertwined it seems like it's worthwhile keeping them in the same repository.
I'm trying to work out a way of structuring the whole project to give the javascript and python frameworks equal status (maybe a ruby driver or whatever in the future?), but still allow the python library to install nicely.
Currently it looks like this: (simplified a little)
javascript/jstest/test1.js
javascript/mongo-fulltext/search.js
javascript/mongo-fulltext/util.js
python/docs/indext.rst
python/tests/search_test.py
python/tests/__init__.py
python/mongofulltextsearch/__init__.py
python/mongofulltextsearch/mongo_search.py
python/mongofulltextsearch/util.py
python/setup.py
I've skipped out a few files for simplicity, but you get the general idea; it' a pretty much standard python project... except that it depends critcally ona whole bunch of javascript which is stored in a sibling directory tree.
What's the preferred setup for dealing with this kind of thing when it comes to setuptools? I can work out how to use package_data etc to install data files that live inside my python project as per the setuptools docs.
The problem is if i want to use setuptools to install stuff, including the javascript files from outside the python code tree, and then also access them in a consistent way when I'm developing the python code and when it is easy_installed to someone's site.
Is that supported behaviour for setuptools? Should i be using paver or distutils2 or Distribute or something? (basic distutils is not an option; the whole reason I'm doing this is to enable requirements tracking) How should i be reading the contents of those files into python scripts?
| [
"The short answer is that none of the Python distribution tools is going to do what you want, the exact way you want it. Even if you use distutils' data_files feature, you're still going to have to have your javascript files copied into your Python project directory (i.e., somewhere under the same directory as your setup.py.)\nGiven that, you might as well just copy the .js files to your package (i.e. alongside mongofulltextsearch/init.py) as part of your build process, and use package_data or include_package_data=True.\n(Or alternatively, you could possibly use symlinks, externals, or some such, if your revision control system supports those. I believe that when building source distributions, the Python distribution tools convert symlinks to real files. At least, you could give that a try.)\n"
] | [
2
] | [] | [] | [
"javascript",
"project_structure",
"python",
"setuptools"
] | stackoverflow_0002891575_javascript_project_structure_python_setuptools.txt |
Q:
Getting Omni complete to work on vim 7.2 on windows
I am trying to use the Omni complete feature with gVim 7.2 but on windows I keep getting an error that says
Error: require vim compiled with +python
E117: unknown function: pythoncomplete#complete
seems like it might be because gvim 7.2 is compiled with 2.4 and I have 2.5 installed. I have downloaded the 2.5 compiled binaries from here , but still no joy.
The python I have on my machine was installed as part of Cygwin (I have python.exe and python2.5.exe in c:\cygwin\bin) . I tried copying these two files to a directory C:\python25 in case that was the path that was specified during recompilation.
Is there anyway to get omni complete to work without having to recompile gvim myself?
A:
The Cygwin Python won't work. Just install the Windows Python from http://python.org.
I had the same problem, but with a plugin - pyflakes. I solved it by installing Python 2.6 FOR ALL USERS, and using a gvim.exe binary downloaded from here:
http://www.gooli.org/blog/gvim-72-with-python-2526-support-windows-binaries/
| Getting Omni complete to work on vim 7.2 on windows | I am trying to use the Omni complete feature with gVim 7.2 but on windows I keep getting an error that says
Error: require vim compiled with +python
E117: unknown function: pythoncomplete#complete
seems like it might be because gvim 7.2 is compiled with 2.4 and I have 2.5 installed. I have downloaded the 2.5 compiled binaries from here , but still no joy.
The python I have on my machine was installed as part of Cygwin (I have python.exe and python2.5.exe in c:\cygwin\bin) . I tried copying these two files to a directory C:\python25 in case that was the path that was specified during recompilation.
Is there anyway to get omni complete to work without having to recompile gvim myself?
| [
"The Cygwin Python won't work. Just install the Windows Python from http://python.org.\nI had the same problem, but with a plugin - pyflakes. I solved it by installing Python 2.6 FOR ALL USERS, and using a gvim.exe binary downloaded from here:\nhttp://www.gooli.org/blog/gvim-72-with-python-2526-support-windows-binaries/\n"
] | [
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0002897022_python_vim.txt |
Q:
How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1
I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC XO 8.2.1 release laptops running Sugar). This means I cannot just ./ez_install to perform a system-wide setuptools/pkg_resources installation.
Example directory structure:
My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py
I am wondering how best to import and use library1 and library2 from within test.py with no pkg_resources system-wide installation. Is my best option simply to unzip the .egg files?
Thanks for any tips.
A:
If you want to be able to use pkg_resources, just copy pkg_resources.py alongside your application's main script. It's designed to be able to be used this way as a standalone runtime.
A:
Include pkg_resources.py in the lib/ directory.
Add at the top of example.py...
import sys
sys.path.append("lib/")
import pkg_resources
and then you can...
sys.path.append("library1.egg")
sys.path.append("libs/library2.egg")
import library1
import library2
| How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1 | I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC XO 8.2.1 release laptops running Sugar). This means I cannot just ./ez_install to perform a system-wide setuptools/pkg_resources installation.
Example directory structure:
My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py
I am wondering how best to import and use library1 and library2 from within test.py with no pkg_resources system-wide installation. Is my best option simply to unzip the .egg files?
Thanks for any tips.
| [
"If you want to be able to use pkg_resources, just copy pkg_resources.py alongside your application's main script. It's designed to be able to be used this way as a standalone runtime.\n",
"Include pkg_resources.py in the lib/ directory.\nAdd at the top of example.py...\n import sys\n sys.path.append(\"lib/\")\n import pkg_resources\n\nand then you can...\n sys.path.append(\"library1.egg\")\n sys.path.append(\"libs/library2.egg\")\n import library1\n import library2\n\n"
] | [
1,
0
] | [] | [] | [
"egg",
"olpc",
"python",
"python_2.5"
] | stackoverflow_0001252910_egg_olpc_python_python_2.5.txt |
Q:
Compiling ODE on windows without Visual Studio (for PyODE)
I'm new to compiling programs written by someone else, so I hope I'm not missing anything obvious.
What I am really trying to do is install PyODE, and I think I managed that just fine, but when running the PyODE examples I get an error:
Traceback (most recent call last):
File "C:\Python26\pyode-examples\tutorial3.py", line 12, in <module>
import ode
ImportError: DLL load failed: The specified module could not be found.
which assume means that it can't find ODE installed. I thought PyODE came bundled with ODE but I guess not.. so now I'm trying to compile ODE according to these instructions:
http://opende.sourceforge.net/wiki/index.php/Manual_%28Install_and_Use%29
but they all seem to revolve around creating configuration files for visual studio which I don't have.
Could someone please clue me in on the proper procedure here?
Thanks! :)
-Leav
A:
My Problem was completley unrelated to whether or not you could compile ODE without visual studio.
Simply copied ODE.dll which was in the python directory into the example's directory.
Thanks Thomas! :)
| Compiling ODE on windows without Visual Studio (for PyODE) | I'm new to compiling programs written by someone else, so I hope I'm not missing anything obvious.
What I am really trying to do is install PyODE, and I think I managed that just fine, but when running the PyODE examples I get an error:
Traceback (most recent call last):
File "C:\Python26\pyode-examples\tutorial3.py", line 12, in <module>
import ode
ImportError: DLL load failed: The specified module could not be found.
which assume means that it can't find ODE installed. I thought PyODE came bundled with ODE but I guess not.. so now I'm trying to compile ODE according to these instructions:
http://opende.sourceforge.net/wiki/index.php/Manual_%28Install_and_Use%29
but they all seem to revolve around creating configuration files for visual studio which I don't have.
Could someone please clue me in on the proper procedure here?
Thanks! :)
-Leav
| [
"My Problem was completley unrelated to whether or not you could compile ODE without visual studio.\nSimply copied ODE.dll which was in the python directory into the example's directory.\nThanks Thomas! :)\n"
] | [
0
] | [] | [] | [
"dll",
"pyode",
"python",
"windows"
] | stackoverflow_0002897590_dll_pyode_python_windows.txt |
Q:
Problem trying to achieve a join using the `comments` contrib in Django
I have this model, comments are managed with the django_comments contrib:
class Fortune(models.Model):
author = models.CharField(max_length=45, blank=False)
title = models.CharField(max_length=200, blank=False)
slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date')
content = models.TextField(blank=False)
pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now())
votes = models.IntegerField(default=0)
comments = generic.GenericRelation(
Comment,
content_type_field='content_type',
object_id_field='object_pk'
)
I want to retrieve Fortune objects with a supplementary nb_comments value for each, counting their respectve number of comments ; I try this query:
>>> Fortune.objects.annotate(nb_comments=models.Count('comments'))
From the shell:
>>> from django_fortunes.models import Fortune
>>> from django.db.models import Count
>>> Fortune.objects.annotate(nb_comments=Count('comments'))
[<Fortune: My first fortune, from NiKo>, <Fortune: Another One, from Dude>, <Fortune: A funny one, from NiKo>]
>>> from django.db import connection
>>> connection.queries.pop()
{'time': '0.000', 'sql': u'SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21'}
Below is the properly formatted sql query:
SELECT "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes",
COUNT("django_comments"."id") AS "nb_comments"
FROM "django_fortunes_fortune"
LEFT OUTER JOIN "django_comments"
ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk")
GROUP BY "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes"
LIMIT 21
Can you spot the problem? Django won't LEFT JOIN the django_comments table with the content_type data (which contains a reference to the fortune one).
This is the kind of query I'd like to be able to generate using the ORM:
SELECT "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
COUNT("django_comments"."id") AS "nb_comments"
FROM "django_fortunes_fortune"
LEFT OUTER JOIN "django_comments"
ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk")
LEFT OUTER JOIN "django_content_type"
ON ("django_comments"."content_type_id" = "django_content_type"."id")
GROUP BY "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes"
LIMIT 21
But I don't manage to do it, so help from Django veterans would be much appreciated :)
Hint: I'm using Django 1.2-DEV
Thanks in advance for your help.
A:
http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/
http://djangosnippets.org/snippets/2034/
UPDATE:
http://github.com/coleifer/django-generic-aggregation/
A:
Why do you want to join the content type table? The original query is wrong, but not for that reason. The reference to content type is to identify which target model the comments are associated with - but you already know that, since you're only selecting the comments associated with Fortune. Django will have already queried the ContentType model to get the value for Fortune, so should simply be adding a single WHERE clause:
... WHERE django_comments_comment.content_type_id = xx
You might be able to make this work properly by adding the ORM equivalent of that:
...filter(comment__content_type=ContentType.objects.get_for_model(Fortune))
although it does seem to be a bug that Django is not doing this automatically.
A:
It's a bug in Django, see ticket #10870. You'll have to wait for Django 1.3 at least or fix it by yourself.
| Problem trying to achieve a join using the `comments` contrib in Django | I have this model, comments are managed with the django_comments contrib:
class Fortune(models.Model):
author = models.CharField(max_length=45, blank=False)
title = models.CharField(max_length=200, blank=False)
slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date')
content = models.TextField(blank=False)
pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now())
votes = models.IntegerField(default=0)
comments = generic.GenericRelation(
Comment,
content_type_field='content_type',
object_id_field='object_pk'
)
I want to retrieve Fortune objects with a supplementary nb_comments value for each, counting their respectve number of comments ; I try this query:
>>> Fortune.objects.annotate(nb_comments=models.Count('comments'))
From the shell:
>>> from django_fortunes.models import Fortune
>>> from django.db.models import Count
>>> Fortune.objects.annotate(nb_comments=Count('comments'))
[<Fortune: My first fortune, from NiKo>, <Fortune: Another One, from Dude>, <Fortune: A funny one, from NiKo>]
>>> from django.db import connection
>>> connection.queries.pop()
{'time': '0.000', 'sql': u'SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21'}
Below is the properly formatted sql query:
SELECT "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes",
COUNT("django_comments"."id") AS "nb_comments"
FROM "django_fortunes_fortune"
LEFT OUTER JOIN "django_comments"
ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk")
GROUP BY "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes"
LIMIT 21
Can you spot the problem? Django won't LEFT JOIN the django_comments table with the content_type data (which contains a reference to the fortune one).
This is the kind of query I'd like to be able to generate using the ORM:
SELECT "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
COUNT("django_comments"."id") AS "nb_comments"
FROM "django_fortunes_fortune"
LEFT OUTER JOIN "django_comments"
ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk")
LEFT OUTER JOIN "django_content_type"
ON ("django_comments"."content_type_id" = "django_content_type"."id")
GROUP BY "django_fortunes_fortune"."id",
"django_fortunes_fortune"."author",
"django_fortunes_fortune"."title",
"django_fortunes_fortune"."slug",
"django_fortunes_fortune"."content",
"django_fortunes_fortune"."pub_date",
"django_fortunes_fortune"."votes"
LIMIT 21
But I don't manage to do it, so help from Django veterans would be much appreciated :)
Hint: I'm using Django 1.2-DEV
Thanks in advance for your help.
| [
"http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/\nhttp://djangosnippets.org/snippets/2034/\nUPDATE:\nhttp://github.com/coleifer/django-generic-aggregation/\n",
"Why do you want to join the content type table? The original query is wrong, but not for that reason. The reference to content type is to identify which target model the comments are associated with - but you already know that, since you're only selecting the comments associated with Fortune. Django will have already queried the ContentType model to get the value for Fortune, so should simply be adding a single WHERE clause:\n... WHERE django_comments_comment.content_type_id = xx\n\nYou might be able to make this work properly by adding the ORM equivalent of that:\n...filter(comment__content_type=ContentType.objects.get_for_model(Fortune))\n\nalthough it does seem to be a bug that Django is not doing this automatically.\n",
"It's a bug in Django, see ticket #10870. You'll have to wait for Django 1.3 at least or fix it by yourself. \n"
] | [
3,
2,
2
] | [] | [] | [
"django",
"django_models",
"orm",
"python",
"sql"
] | stackoverflow_0002754320_django_django_models_orm_python_sql.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.