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:
Why has Python decided against constant references?
Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers.
I have a large data structure, and I want to expose it to other modules, on a read-only basis. The only way to do that in Python is to deep-copy the particular pieces I'd like to expose - prohibitively expensive in my case.
I am sure this is a very common problem, and it seems like a constant reference would be the perfect solution. But I must be missing something. Perhaps constant references are hard to implement in Python. Perhaps they don't quite do what I think they do.
Any insights would be appreciated.
While the answers are helpful, I haven't seen a single reason why const would be either hard to implement or unworkable in Python. I guess "un-Pythonic" would also count as a valid reason, but is it really? Python does do scrambling of private instance variables (starting with __) to avoid accidental bugs, and const doesn't seem to be that different in spirit.
EDIT: I just offered a very modest bounty. I am looking for a bit more detail about why Python ended up without const. I suspect the reason is that it's really hard to implement to work perfectly; I would like to understand why it's so hard.
A:
It's the same as with private methods: as consenting adults authors of code should agree on an interface without need of force. Because really really enforcing the contract is hard, and doing it the half-assed way leads to hackish code in abundance.
Use get-only descriptors, and state clearly in your documentation that these data is meant to be read only. After all, a determined coder could probably find a way to use your code in different ways you thought of anyways.
A:
In PEP 351, Barry Warsaw proposed a protocol for "freezing" any mutable data structure, analogous to the way that frozenset makes an immutable set. Frozen data structures would be hashable and so capable being used as keys in dictionaries.
The proposal was discussed on python-dev, with Raymond Hettinger's criticism the most detailed.
It's not quite what you're after, but it's the closest I can find, and should give you some idea of the thinking of the Python developers on this subject.
A:
There are many design questions about any language, the answer to most of which is "just because". It's pretty clear that constants like this would go against the ideology of Python.
You can make a read-only class attribute, though, using descriptors. It's not trivial, but it's not very hard. The way it works is that you can make properties (things that look like attributes but call a method on access) using the property decorator; if you make a getter but not a setter property then you will get a read-only attribute. The reason for the metaclass programming is that since __init__ receives a fully-formed instance of the class, you actually can't set the attributes to what you want at this stage! Instead, you have to set them on creation of the class, which means you need a metaclass.
Code from this recipe:
# simple read only attributes with meta-class programming
# method factory for an attribute get method
def getmethod(attrname):
def _getmethod(self):
return self.__readonly__[attrname]
return _getmethod
class metaClass(type):
def __new__(cls,classname,bases,classdict):
readonly = classdict.get('__readonly__',{})
for name,default in readonly.items():
classdict[name] = property(getmethod(name))
return type.__new__(cls,classname,bases,classdict)
class ROClass(object):
__metaclass__ = metaClass
__readonly__ = {'a':1,'b':'text'}
if __name__ == '__main__':
def test1():
t = ROClass()
print t.a
print t.b
def test2():
t = ROClass()
t.a = 2
test1()
A:
While one programmer writing code is a consenting adult, two programmers working on the same code seldom are consenting adults. More so if they do not value the beauty of the code but them deadlines or research funds.
For such adults there is some type safety, provided by Enthought's Traits.
You could look into Constant and ReadOnly traits.
A:
For some additional thoughts, there is a similar question posed about Java here:
Why is there no Constant feature in Java?
When asking why Python has decided against constant references, I think it's helpful to think of how they would be implemented in the language. Should Python have some sort of special declaration, const, to create variable references that can't be changed? Why not allow variables to be declared a float/int/whatever then...these would surely help prevent programming bugs as well. While we're at it, adding class and method modifiers like protected/private/public/etc. would help enforce compile-type checking against illegal uses of these classes. ...pretty soon, we've lost the beauty, simplicity, and elegance that is Python, and we're writing code in some sort of bastard child of C++/Java.
Python also currently passes everything by reference. This would be some sort of special pass-by-reference-but-flag-it-to-prevent-modification...a pretty special case (and as the Tao of Python indicates, just "un-Pythonic").
As mentioned before, without actually changing the language, this type of behaviour can be implemented via classes & descriptors. It may not prevent modification from a determined hacker, but we are consenting adults. Python didn't necessarily decide against providing this as an included module ("batteries included") - there was just never enough demand for it.
| Why has Python decided against constant references? | Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers.
I have a large data structure, and I want to expose it to other modules, on a read-only basis. The only way to do that in Python is to deep-copy the particular pieces I'd like to expose - prohibitively expensive in my case.
I am sure this is a very common problem, and it seems like a constant reference would be the perfect solution. But I must be missing something. Perhaps constant references are hard to implement in Python. Perhaps they don't quite do what I think they do.
Any insights would be appreciated.
While the answers are helpful, I haven't seen a single reason why const would be either hard to implement or unworkable in Python. I guess "un-Pythonic" would also count as a valid reason, but is it really? Python does do scrambling of private instance variables (starting with __) to avoid accidental bugs, and const doesn't seem to be that different in spirit.
EDIT: I just offered a very modest bounty. I am looking for a bit more detail about why Python ended up without const. I suspect the reason is that it's really hard to implement to work perfectly; I would like to understand why it's so hard.
| [
"It's the same as with private methods: as consenting adults authors of code should agree on an interface without need of force. Because really really enforcing the contract is hard, and doing it the half-assed way leads to hackish code in abundance.\nUse get-only descriptors, and state clearly in your documentatio... | [
13,
10,
8,
1,
1
] | [] | [] | [
"constants",
"language_design",
"language_features",
"python",
"reference"
] | stackoverflow_0004192053_constants_language_design_language_features_python_reference.txt |
Q:
'C-style' strings in Python
A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\0'). Using C(or maybe C++), it is possible to use pointers to manipulate the string to reverse its contents in-place.
If somebody asks the question, "How do you reverse a C-style string in Python?", what would some of the possible answers be?
Thanks
A:
If you need to "reverse a C-style string in Python", I think the end result must also be a c-style string.
That is how I would understand the question, but the above answers do not support this.
See the interactive session below:
>>>
>>> original = "abc\0"
>>> finish_correct = "cba\0"
>>> original
'abc\x00'
>>> finish_correct
'cba\x00'
>>>
>>> answer = original[:-1] # remove final null
>>> answer = answer[::-1] # reverse string
>>> # Extended slice syntax: [begin:end:step]
>>> # So, [::-1] means take whole string, but in reverse.
>>> answer
'cba'
>>> answer = answer + "\0"
>>> answer
'cba\x00'
>>> answer == finish_correct
True
Also note, Python strings are immutable. This means that they can never be changed. You can make new strings that are assigned to the same variable name, but the in-memory image for a given strings will never change. Thus, the notion of "reverse a string in place" can not happen in Python.
Hope this helps. If so, please up-vote and accept the answer. Thanks. :-)
A:
Python doesn't use C-style strings; Python strings can contain an embedded NUL, so C-style strings are not used, but rather an explicit length.
>>> 'abc\0def'[::-1]
'fed\x00cba'
A:
Since C doesn't have a string type, it represents character strings as pointers to char, where the last byte (assuming ASCII, not wide-characters) is \0. It's a representation. By the way, this default implementation has the deficiency that \0 can't be part of such a string. If that's needed, a different representation is required (such as representing a string as a pointer + a length integer).
Python, OTOH has a string type, and it's opaque to the user how this type is represented. Therefore, a "C-style string" is a meaningless concept in Python.
A:
Python strings are immutable. You could emulate a C-style string with a table of chars, but I don't see why you would bother.
But if you did have a C-style "string" (ie table of characters), then all you'd need to do is swap s[i] with s[len(s)-i-1]:
for i in range(0, len(a) - 2):
a[i], a[len(a) - 1 - i] = a[len(a) - 1 - i], a[i]
(if a is your C-style string)
Note how you don't need a temporary variable(granted you don't need one in C either, considering how you could use the null character as a temp space).
| 'C-style' strings in Python | A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\0'). Using C(or maybe C++), it is possible to use pointers to manipulate the string to reverse its contents in-place.
If somebody asks the question, "How do you reverse a C-style string in Python?", what would some of the possible answers be?
Thanks
| [
"If you need to \"reverse a C-style string in Python\", I think the end result must also be a c-style string. \nThat is how I would understand the question, but the above answers do not support this.\nSee the interactive session below:\n>>> \n>>> original = \"abc\\0\"\n>>> finish_correct = \"cba\\0\"\n>>> original\... | [
5,
3,
3,
1
] | [] | [] | [
"null",
"python",
"string"
] | stackoverflow_0004238537_null_python_string.txt |
Q:
Python: Replace tags but preserve inner text?
I have a string.
"This is an [[example]] sentence. It is [[awesome]]."
I want to replace all instances of [[.]] with <b>.</b> preserving the wildcard text matched by .
The result should be:
"This is an <b>example</b> sentence. It is <b>awesome</b>."
I could go in and manually replace [[ with <b> and ]] with </b>, but it makes more sense to just do it at once and preserve the text between tags.
How do I do this?
Note: This is for taking source from a database and converting it to HTML. It's supposed to mimic wiki-style syntax. In this case, [[x]] results in a bold typeface.
A:
You can just use the replace method on the string.
>>> s = 'This is an [[example]] sentence. It is [[awesome]].'
>>> s.replace('[[', '<b>').replace(']]', '</b>')
'This is an <b>example</b> sentence. It is <b>awesome</b>.'
Just to get some timeit results in here:
$ python -mtimeit -s'import re' "re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')"''
100000 loops, best of 3: 19.7 usec per loop
$ python -mtimeit '"This is an [[example]] sentence. It is [[awesome]]".replace("[[", "<b>").replace("]]", "</b>")'
100000 loops, best of 3: 1.94 usec per loop
If we compile the regex we get slightly better performance:
$ python -mtimeit -s"import re; r = re.compile(r'\[\[(.*?)\]\]')" "r.sub( r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')"
100000 loops, best of 3: 16.9 usec per loop
A:
How about the use of re.sub() and a little regular expression magic:
import re
re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>', "This is an [[example]] sentence. It is [[awesome]]");
A:
This code allows you to extend the replacements list at will.
import re
_replacements = {
'[[': '<b>',
']]': '</b>',
'{{': '<i>',
'}}': '</i>',
}
def _do_replace(match):
return _replacements.get(match.group(0))
def replace_tags(text, _re=re.compile('|'.join(re.escape(r) for r in _replacements))):
return _re.sub(_do_replace, text)
print replace_tags("This is an [[example]] sentence. It is [[{{awesome}}]].")
This is an <b>example</b> sentence. It is <b><i>awesome</i></b>.
A:
... the advantage of using the regex approach here might be that it prevents doing substitutions when the source text doesn't have matching pairs of [[ and ]].
Maybe important, maybe not.
A:
The methods suggested by the other posters will certainly work, however I would like to point out that using Regular Expresions for this task will incur quite a performance hit.
The example you supplied could be solved just as well using native Python string operations, and would perform roughly 3 times faster.
For instance:
>>> import timeit
>>> st = 's = "This is an [[example]] sentence. It is [[awesome]]"'
>>> t = timeit.Timer('s.replace("[[","<b>").replace("]]","</b>")',st)
>>> t.timeit() # Run 1000000 times
1.1733845739904609
>>> tr = timeit.Timer("re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>',s)",'import re; ' + st)
>>> tr.timeit() # Run 1000000 times
3.7482673050677704
>>>
Hope this helps :)
| Python: Replace tags but preserve inner text? | I have a string.
"This is an [[example]] sentence. It is [[awesome]]."
I want to replace all instances of [[.]] with <b>.</b> preserving the wildcard text matched by .
The result should be:
"This is an <b>example</b> sentence. It is <b>awesome</b>."
I could go in and manually replace [[ with <b> and ]] with </b>, but it makes more sense to just do it at once and preserve the text between tags.
How do I do this?
Note: This is for taking source from a database and converting it to HTML. It's supposed to mimic wiki-style syntax. In this case, [[x]] results in a bold typeface.
| [
"You can just use the replace method on the string.\n>>> s = 'This is an [[example]] sentence. It is [[awesome]].'\n>>> s.replace('[[', '<b>').replace(']]', '</b>')\n\n'This is an <b>example</b> sentence. It is <b>awesome</b>.'\n\nJust to get some timeit results in here:\n$ python -mtimeit -s'import re' \"re.sub(r'... | [
5,
3,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004236243_python_regex.txt |
Q:
Look for multiple occurances of a character using regex
i using the pattern pat='dd|dddd' , and i thought it would either match dd or dddd.
import re
re.search(pat,'ddd')
re.search(pat,'ddddd')
any number of d(s) matches for that matter why is it so ?
A:
You'll need to anchor the regular expression somehow. A regular expression searches within strings to find a pattern. So "dd" will be found in "dddddddd" at offset 0,1,2,3,4,5,6.
If you want to match only entire strings try ^dd$. ^ matches the beginning of a string, $ matches the end. So ^(dd|dddd)$ will have the behavior you want.
If you want it to match only dd or dddd but within a string. Then you might want to use: [^d](dd|dddd)[^d] Which will match "anything that isn't d" then either two or four ds then "anything that isn't d"
A:
As already pointed out by Charles Duffy, search isn't really the function that you should be using. Try using match or even findall.
>>> import re
>>> re.match('dd|dddd','dd').group()
'dd'
>>> re.findall('dd|dddd','dd')
['dd']
>>> re.match('dd|dddd','ddddd').group()
'dd'
>>> re.match('dddd|dd','ddddd').group()
'dddd'
| Look for multiple occurances of a character using regex | i using the pattern pat='dd|dddd' , and i thought it would either match dd or dddd.
import re
re.search(pat,'ddd')
re.search(pat,'ddddd')
any number of d(s) matches for that matter why is it so ?
| [
"You'll need to anchor the regular expression somehow. A regular expression searches within strings to find a pattern. So \"dd\" will be found in \"dddddddd\" at offset 0,1,2,3,4,5,6.\nIf you want to match only entire strings try ^dd$. ^ matches the beginning of a string, $ matches the end. So ^(dd|dddd)$ will... | [
10,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004239346_python_regex.txt |
Q:
Suggestions on how to speed up a distance calculation
Consider the following class:
class SquareErrorDistance(object):
def __init__(self, dataSample):
variance = var(list(dataSample))
if variance == 0:
self._norm = 1.0
else:
self._norm = 1.0 / (2 * variance)
def __call__(self, u, v): # u and v are floats
return (u - v) ** 2 * self._norm
I use it to calculate the distance between two elements of a vector. I basically create one instance of that class for every dimension of the vector that uses this distance measure (there are dimensions that use other distance measures). Profiling reveals that the __call__ function of this class accounts for 90% of the running-time of my knn-implementation (who would have thought). I do not think there is any pure-Python way to speed this up, but maybe if I implement it in C?
If I run a simple C program that just calculates distances for random values using the formula above, it is orders of magnitude faster than Python. So I tried using ctypes and call a C function that does the computation, but apparently the conversion of the parameters and return-values is far to expensive, because the resulting code is much slower.
I could of course implement the entire knn in C and just call that, but the problem is that, like I described, I use different distance functions for some dimension of the vectors, and translating these to C would be too much work.
So what are my alternatives? Will writing the C-function using the Python C-API get rid of the overhead? Are there any other ways to speed this calculation up?
A:
The following cython code (I realize the first line of __init__ is different, I replaced it with random stuff because I don't know var and because it doesn't matter anyway - you stated __call__ is the bottleneck):
cdef class SquareErrorDistance:
cdef double _norm
def __init__(self, dataSample):
variance = round(sum(dataSample)/len(dataSample))
if variance == 0:
self._norm = 1.0
else:
self._norm = 1.0 / (2 * variance)
def __call__(self, double u, double v): # u and v are floats
return (u - v) ** 2 * self._norm
Compiled via a simple setup.py (just the example from the docs with the file name altered), it performs nearly 20 times better than the equivalent pure python in a simple contrieved timeit benchmark. Note that the only changed were cdefs for the _norm field and the __call__ parameters. I consider this pretty impressive.
A:
This probably won't help much, but you can rewrite it using nested functions:
def SquareErrorDistance(dataSample):
variance = var(list(dataSample))
if variance == 0:
def f(u, v):
x = u - v
return x * x
else:
norm = 1.0 / (2 * variance)
def f(u, v):
x = u - v
return x * x * norm
return f
| Suggestions on how to speed up a distance calculation | Consider the following class:
class SquareErrorDistance(object):
def __init__(self, dataSample):
variance = var(list(dataSample))
if variance == 0:
self._norm = 1.0
else:
self._norm = 1.0 / (2 * variance)
def __call__(self, u, v): # u and v are floats
return (u - v) ** 2 * self._norm
I use it to calculate the distance between two elements of a vector. I basically create one instance of that class for every dimension of the vector that uses this distance measure (there are dimensions that use other distance measures). Profiling reveals that the __call__ function of this class accounts for 90% of the running-time of my knn-implementation (who would have thought). I do not think there is any pure-Python way to speed this up, but maybe if I implement it in C?
If I run a simple C program that just calculates distances for random values using the formula above, it is orders of magnitude faster than Python. So I tried using ctypes and call a C function that does the computation, but apparently the conversion of the parameters and return-values is far to expensive, because the resulting code is much slower.
I could of course implement the entire knn in C and just call that, but the problem is that, like I described, I use different distance functions for some dimension of the vectors, and translating these to C would be too much work.
So what are my alternatives? Will writing the C-function using the Python C-API get rid of the overhead? Are there any other ways to speed this calculation up?
| [
"The following cython code (I realize the first line of __init__ is different, I replaced it with random stuff because I don't know var and because it doesn't matter anyway - you stated __call__ is the bottleneck):\ncdef class SquareErrorDistance:\n cdef double _norm\n\n def __init__(self, dataSample):\n ... | [
2,
0
] | [] | [] | [
"performance",
"python",
"python_c_api"
] | stackoverflow_0004239371_performance_python_python_c_api.txt |
Q:
How can I get the key_name of the entry in Model() on GAE for Python?
I have a Model() called Member and I'm inserting new entries using Member.get_or_insert(key_name='lipis') for example.
My question is how can I get a key_name that I used to insert a new entry for a specific member?
A:
Do you mean how do you then find that record using the key name, or how do you take an entity and find its key name?
To get that record back out of the datastore, do:
myMember = Member.get_by_key_name('lipis')
...if you have the member record and want to get its key name, you can then do:
keyName = myMember.key().name()
A:
You actually use key().name():
lipis = Member.get_or_insert(key_name='lipis')
key_name = lipis.key().name()
If it was inserted with a key_name (and not an id), that will return it.
| How can I get the key_name of the entry in Model() on GAE for Python? | I have a Model() called Member and I'm inserting new entries using Member.get_or_insert(key_name='lipis') for example.
My question is how can I get a key_name that I used to insert a new entry for a specific member?
| [
"Do you mean how do you then find that record using the key name, or how do you take an entity and find its key name?\nTo get that record back out of the datastore, do:\nmyMember = Member.get_by_key_name('lipis')\n\n...if you have the member record and want to get its key name, you can then do:\nkeyName = myMember.... | [
20,
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004239709_google_app_engine_google_cloud_datastore_python.txt |
Q:
Dynamic Module loading scope in Python
When I run the following sample:
def a():
exec('import math')
b()
def b():
print math.cos(90)
a()
I get the following error:
NameError: global name 'math' is not defined
What I am trying to do is to dynamically load some modules from within the a() function
and use them in function b()
I want it to be as seamless as possible for the b()'s point of view. That means, I don't want to load the module with _ _ import _ _ in a() and pass a reference to the b() function, in fact it is mandatory that the b()'s function signature remains just this: b()
is there any way to do this guys?
thanks!
A:
One approach for Python 2.x would be:
def a():
exec 'import math' in globals()
b()
def b():
print math.cos(90)
a()
But I would generally recommend using __import__(). I don't know what you are actually trying to achieve, but maybe this works for you:
def a():
global hurz
hurz = __import__("math")
b()
def b():
print hurz.cos(90)
a()
A:
Upon comments on the post: if want to load modules runtime, load where you need it:
def b():
m = __import__("math")
return m.abs(-1)
Answering to your question:
def a():
if not globals().has_key('math'):
globals()['math'] = __import__('math')
def b():
"""returns the absolute value of -1, a() must be called before to load necessary modules"""
return math.abs(-1)
| Dynamic Module loading scope in Python | When I run the following sample:
def a():
exec('import math')
b()
def b():
print math.cos(90)
a()
I get the following error:
NameError: global name 'math' is not defined
What I am trying to do is to dynamically load some modules from within the a() function
and use them in function b()
I want it to be as seamless as possible for the b()'s point of view. That means, I don't want to load the module with _ _ import _ _ in a() and pass a reference to the b() function, in fact it is mandatory that the b()'s function signature remains just this: b()
is there any way to do this guys?
thanks!
| [
"One approach for Python 2.x would be:\ndef a():\n exec 'import math' in globals()\n b()\n\ndef b():\n print math.cos(90)\n\na()\n\nBut I would generally recommend using __import__(). I don't know what you are actually trying to achieve, but maybe this works for you:\ndef a():\n global hurz\n hurz =... | [
2,
2
] | [] | [] | [
"dynamic",
"module",
"python",
"scope"
] | stackoverflow_0004239797_dynamic_module_python_scope.txt |
Q:
Which Python libraries exist for extracting useful data from tweets?
I've found this: https://github.com/dryan/twitter-text-py based on Matt Sanford's Ruby code however it hasn't been updated since June 2010.
I've also found this: https://github.com/BonsaiDen/twitter-text-python based on Matt Sanford's Java code.
Are there any others?
A:
Twitter has a list of libraries: http://dev.twitter.com/pages/libraries .
| Which Python libraries exist for extracting useful data from tweets? | I've found this: https://github.com/dryan/twitter-text-py based on Matt Sanford's Ruby code however it hasn't been updated since June 2010.
I've also found this: https://github.com/BonsaiDen/twitter-text-python based on Matt Sanford's Java code.
Are there any others?
| [
"Twitter has a list of libraries: http://dev.twitter.com/pages/libraries .\n"
] | [
1
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0004239984_python_twitter.txt |
Q:
How do I duplicate certificate authentication (Mumble (c/c++)) in Python?
Alright so, before I really get into this post, I am going to have to warn you that this might not be an easy fix. Whoever reads and is able to reply to this post must know a lot of c/c++, and at least some python to be able to answer the question I have above.
Basically, I have a connection method from Mumble (a VOIP client), that connects to a server and sends it an SSL certificate for authentication purposes. I also have a Python script that connects to the same Mumble VOIP server, but I don't send a certificate.
I need to modify my existing code to send a certificate, as the current Mumble client does.
--
Here is the C++ code that seems to send a certificate:
ServerHandler::ServerHandler() {
MumbleSSL::addSystemCA();
{
QList<QSslCipher> pref;
foreach(QSslCipher c, QSslSocket::defaultCiphers()) {
if (c.usedBits() < 128)
continue;
pref << c;
}
if (pref.isEmpty())
qFatal("No ciphers of at least 128 bit found");
QSslSocket::setDefaultCiphers(pref);
}
void ServerHandler::run() {
qbaDigest = QByteArray();
QSslSocket *qtsSock = new QSslSocket(this);
qtsSock->setPrivateKey(g.s.kpCertificate.second);
qtsSock->setLocalCertificate(g.s.kpCertificate.first.at(0));
QList<QSslCertificate> certs = qtsSock->caCertificates();
certs << g.s.kpCertificate.first;
qtsSock->setCaCertificates(certs);
cConnection = ConnectionPtr(new Connection(this, qtsSock));
qtsSock->setProtocol(QSsl::TlsV1);
qtsSock->connectToHostEncrypted(qsHostName, usPort);
void ServerHandler::serverConnectionConnected() {
tConnectionTimeoutTimer->stop();
qscCert = cConnection->peerCertificateChain();
qscCipher = cConnection->sessionCipher();
if (! qscCert.isEmpty()) {
const QSslCertificate &qsc = qscCert.last();
qbaDigest = sha1(qsc.publicKey().toDer());
bUdp = Database::getUdp(qbaDigest);
} else {
bUdp = true;
}
QStringList tokens = Database::getTokens(qbaDigest);
foreach(const QString &qs, tokens)
mpa.add_tokens(u8(qs));
QMap<int, CELTCodec *>::const_iterator i;
for (i=g.qmCodecs.constBegin(); i != g.qmCodecs.constEnd(); ++i)
mpa.add_celt_versions(i.key());
sendMessage(mpa);
--
And alas, this is what I do to connect to it right now (in python):
try:
self.socket.connect(self.host)
except:
print self.threadName,"Couldn't connect to server"
return
self.socket.setblocking(0)
print self.threadName,"connected to server"
--
Soo... what do I need to do more to my Python source to connect to servers that require a certificate? Because my source currently connects just fine to any mumble server with requirecert set to false. I need it to work on all servers, as this will be used on my own server (which ironically enough, has requirecerts on.)
I can pregenerate the certificate as a .p12 or w/e type file, so I don't need the program to generate the cert. I just need it to send the cert as the server wants it (as is done in the c++ I posted).
Please help me really soon! If you need more info, message me again.
Stripped out all irrelevant code, now it's just the code that deals with ssl.
A:
From the C++ code it looks like you simply need to have ssl support and negotiate with the correct certification file and encrypt the payload with the correct private key. Those certifications and privates keys are most likely stored in your original program somewhere. If there are non-standard Authorities that the C++ might be loading up you'll need to find out where to put those root authorities in your python installation, or make sure python simply ignores those issues, which is less secure.
In python you can create a socket, like above, except with urllib. This library has support for HTTPs and providing the certification and private keys. URLOpener
Example Usage:
opener = urllib.URLopener(key_file = 'mykey.key', cert_file = 'mycert.cer')
self.socket = opener.open(url)
You'll probably need to make it more robust with the appropriate error checking and such, but hopefully this info will help you out.
| How do I duplicate certificate authentication (Mumble (c/c++)) in Python? | Alright so, before I really get into this post, I am going to have to warn you that this might not be an easy fix. Whoever reads and is able to reply to this post must know a lot of c/c++, and at least some python to be able to answer the question I have above.
Basically, I have a connection method from Mumble (a VOIP client), that connects to a server and sends it an SSL certificate for authentication purposes. I also have a Python script that connects to the same Mumble VOIP server, but I don't send a certificate.
I need to modify my existing code to send a certificate, as the current Mumble client does.
--
Here is the C++ code that seems to send a certificate:
ServerHandler::ServerHandler() {
MumbleSSL::addSystemCA();
{
QList<QSslCipher> pref;
foreach(QSslCipher c, QSslSocket::defaultCiphers()) {
if (c.usedBits() < 128)
continue;
pref << c;
}
if (pref.isEmpty())
qFatal("No ciphers of at least 128 bit found");
QSslSocket::setDefaultCiphers(pref);
}
void ServerHandler::run() {
qbaDigest = QByteArray();
QSslSocket *qtsSock = new QSslSocket(this);
qtsSock->setPrivateKey(g.s.kpCertificate.second);
qtsSock->setLocalCertificate(g.s.kpCertificate.first.at(0));
QList<QSslCertificate> certs = qtsSock->caCertificates();
certs << g.s.kpCertificate.first;
qtsSock->setCaCertificates(certs);
cConnection = ConnectionPtr(new Connection(this, qtsSock));
qtsSock->setProtocol(QSsl::TlsV1);
qtsSock->connectToHostEncrypted(qsHostName, usPort);
void ServerHandler::serverConnectionConnected() {
tConnectionTimeoutTimer->stop();
qscCert = cConnection->peerCertificateChain();
qscCipher = cConnection->sessionCipher();
if (! qscCert.isEmpty()) {
const QSslCertificate &qsc = qscCert.last();
qbaDigest = sha1(qsc.publicKey().toDer());
bUdp = Database::getUdp(qbaDigest);
} else {
bUdp = true;
}
QStringList tokens = Database::getTokens(qbaDigest);
foreach(const QString &qs, tokens)
mpa.add_tokens(u8(qs));
QMap<int, CELTCodec *>::const_iterator i;
for (i=g.qmCodecs.constBegin(); i != g.qmCodecs.constEnd(); ++i)
mpa.add_celt_versions(i.key());
sendMessage(mpa);
--
And alas, this is what I do to connect to it right now (in python):
try:
self.socket.connect(self.host)
except:
print self.threadName,"Couldn't connect to server"
return
self.socket.setblocking(0)
print self.threadName,"connected to server"
--
Soo... what do I need to do more to my Python source to connect to servers that require a certificate? Because my source currently connects just fine to any mumble server with requirecert set to false. I need it to work on all servers, as this will be used on my own server (which ironically enough, has requirecerts on.)
I can pregenerate the certificate as a .p12 or w/e type file, so I don't need the program to generate the cert. I just need it to send the cert as the server wants it (as is done in the c++ I posted).
Please help me really soon! If you need more info, message me again.
Stripped out all irrelevant code, now it's just the code that deals with ssl.
| [
"From the C++ code it looks like you simply need to have ssl support and negotiate with the correct certification file and encrypt the payload with the correct private key. Those certifications and privates keys are most likely stored in your original program somewhere. If there are non-standard Authorities that ... | [
0
] | [] | [] | [
"c++",
"python",
"ssl",
"ssl_certificate",
"voip"
] | stackoverflow_0003455472_c++_python_ssl_ssl_certificate_voip.txt |
Q:
Convert seconds to hh:mm:ss in Python
How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss?
I need to do this with Python code (and if possible in a Django template).
A:
I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'
Doing it in a Django template's more finicky, since the time filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:
>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
... tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'
Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.
A:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
A:
Read up on the datetime module.
SilentGhost's answer has the details my answer leaves out and is reposted here:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
A:
Code that does what was requested, with examples, and showing how cases he didn't specify are handled:
def format_seconds_to_hhmmss(seconds):
hours = seconds // (60*60)
seconds %= (60*60)
minutes = seconds // 60
seconds %= 60
return "%02i:%02i:%02i" % (hours, minutes, seconds)
def format_seconds_to_mmss(seconds):
minutes = seconds // 60
seconds %= 60
return "%02i:%02i" % (minutes, seconds)
minutes = 60
hours = 60*60
assert format_seconds_to_mmss(7*minutes + 30) == "07:30"
assert format_seconds_to_mmss(15*minutes + 30) == "15:30"
assert format_seconds_to_mmss(1000*minutes + 30) == "1000:30"
assert format_seconds_to_hhmmss(2*hours + 15*minutes + 30) == "02:15:30"
assert format_seconds_to_hhmmss(11*hours + 15*minutes + 30) == "11:15:30"
assert format_seconds_to_hhmmss(99*hours + 15*minutes + 30) == "99:15:30"
assert format_seconds_to_hhmmss(500*hours + 15*minutes + 30) == "500:15:30"
You can--and probably should--store this as a timedelta rather than an int, but that's a separate issue and timedelta doesn't actually make this particular task any easier.
A:
You can calculate the number of minutes and hours from the number of seconds by simple division:
seconds = 12345
minutes = seconds // 60
hours = minutes // 60
print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)
Here // is Python's integer division.
A:
If you use divmod, you are immune to different flavors of integer division:
# show time strings for 3800 seconds
# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)
# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(3800,),60,60])
# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
return "%02d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(round(t*1000),),1000,60,60])
print secondsToStr(3800.123)
Prints:
63:20
01:03:20
01:03:20.123
A:
Not being a Python person, but the easiest without any libraries is just:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
A:
Just be careful when dividing by 60: division between integers returns an integer ->
12/60 = 0 unless you import division from future.
The following is copy and pasted from Python 2.6.2:
IDLE 2.6.2
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001
A:
If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:
try:
from itertools import product
except ImportError:
def product(*seqs):
if len(seqs) == 1:
for p in seqs[0]:
yield p,
else:
for s in seqs[0]:
for p in product(*seqs[1:]):
yield (s,) + p
hhmmss = []
for (h, m, s) in product(range(24), range(60), range(60)):
hhmmss.append("%02d:%02d:%02d" % (h, m, s))
Now conversion of seconds to format string is a fast indexed lookup:
print hhmmss[12345]
prints
'03:25:45'
EDIT:
Updated to 2020, removing Py2 compatibility ugliness, and f-strings!
import sys
from itertools import product
hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
for h, m, s in product(range(24), range(60), range(60))]
# we can still just index into the list, but define as a function
# for common API with code below
seconds_to_str = hhmmss.__getitem__
print(seconds_to_str(12345))
How much memory does this take? sys.getsizeof of a list won't do, since it will just give us the size of the list and its str refs, but not include the memory of the strs themselves:
# how big is a list of 24*60*60 8-character strs?
list_size = sys.getsizeof(hhmmss) + sum(sys.getsizeof(s) for s in hhmmss)
print("{:,}".format(list_size))
prints:
5,657,616
What if we just had one big str? Every value is exactly 8 characters long, so we can slice into this str and get the correct str for second X of the day:
hhmmss_str = ''.join([f"{h:02d}:{m:02d}:{s:02d}"
for h, m, s in product(range(24),
range(60),
range(60))])
def seconds_to_str(n):
loc = n * 8
return hhmmss_str[loc: loc+8]
print(seconds_to_str(12345))
Did that save any space?
# how big is a str of 24*60*60*8 characters?
str_size = sys.getsizeof(hhmmss_str)
print("{:,}".format(str_size))
prints:
691,249
Reduced to about this much:
print(str_size / list_size)
prints:
0.12218026108523448
On the performance side, this looks like a classic memory vs. CPU tradeoff:
import timeit
print("\nindex into pre-calculated list")
print(timeit.timeit("hhmmss[6]", '''from itertools import product; hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
for h, m, s in product(range(24),
range(60),
range(60))]'''))
print("\nget slice from pre-calculated str")
print(timeit.timeit("hhmmss_str[6*8:7*8]", '''from itertools import product; hhmmss_str=''.join([f"{h:02d}:{m:02d}:{s:02d}"
for h, m, s in product(range(24),
range(60),
range(60))])'''))
print("\nuse datetime.timedelta from stdlib")
print(timeit.timeit("timedelta(seconds=6)", "from datetime import timedelta"))
print("\ninline compute of h, m, s using divmod")
print(timeit.timeit("n=6;m,s=divmod(n,60);h,m=divmod(m,60);f'{h:02d}:{m:02d}:{s:02d}'"))
On my machine I get:
index into pre-calculated list
0.0434853
get slice from pre-calculated str
0.1085147
use datetime.timedelta from stdlib
0.7625738
inline compute of h, m, s using divmod
2.0477764
| Convert seconds to hh:mm:ss in Python | How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss?
I need to do this with Python code (and if possible in a Django template).
| [
"I can't believe any of the many answers gives what I'd consider the \"one obvious way to do it\" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):\n>>> import time\n>>> time.strftime('%H:%M:%S', time.gmtime(12345))\n'03:25:45'\n\nDoing it in a Django templa... | [
211,
106,
28,
27,
15,
12,
1,
1,
0
] | [
"Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:\nminutes = seconds / 60\nhours = minutes / 60\n\nNow, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59\n"
] | [
-2
] | [
"django",
"python",
"time"
] | stackoverflow_0001384406_django_python_time.txt |
Q:
How to Identify Dynamically created window/buttons in wxpython?
I am creating a series of buttons(Or windows) etc on RUN time.
Now how do i identify when user clicks on these buttons?
A:
HI,
I did an R&D on wx.Event(GetEventObject) and found out that i can get object details.
SO i solved my problem using this.
| How to Identify Dynamically created window/buttons in wxpython? | I am creating a series of buttons(Or windows) etc on RUN time.
Now how do i identify when user clicks on these buttons?
| [
"HI,\nI did an R&D on wx.Event(GetEventObject) and found out that i can get object details. \nSO i solved my problem using this.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004239896_python_wxpython.txt |
Q:
Importing values in Python
I have a little module that creates a window (program1). I've imported this into another python program of mine (program2).
How do I make program 2 get self.x and x that's in program1?
This is program1.
import Tkinter
class Class(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.Main()
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
self.x = 34
x = 62
def run():
app = Class(None)
app.mainloop()
if __name__ == "__main__":
run()
A:
You can access the variable self.x as a member of an instance of Class:
c = Class(parent)
print(c.x)
You cannot access the local variable - it goes out of scope when the method call ends.
A:
I'm not sure exactly what the purpose of 'self.x' and 'x' are but one thing to note in the 'Main' method of class Class
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
self.x = 34
x = 62
is that 'x' and 'self.x' are two different variables. The variable 'x' is a local variable for the method 'Main' and 'self.x' is an instance variable. Like Mark says you can access the instance variable 'self.x' as an attribute of an instance of Class, but the method variable 'x' is only accessible from within the 'Main' method. If you would like to have the ability to access the method variable 'x' then you could change the signature of the 'Main' method as follows.
def Main(self,x=62):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
self.x = 34
return x
This way you can set the value of the method variable 'x' when you call the 'Main' method from an instance of Class
>> c = Class()
>> c.Main(4)
4
or just keep the default
>> c.Main()
62
and as before like Mark said you will have access to the instance variable 'self.x'
>> c.x
34
| Importing values in Python | I have a little module that creates a window (program1). I've imported this into another python program of mine (program2).
How do I make program 2 get self.x and x that's in program1?
This is program1.
import Tkinter
class Class(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.Main()
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
self.x = 34
x = 62
def run():
app = Class(None)
app.mainloop()
if __name__ == "__main__":
run()
| [
"You can access the variable self.x as a member of an instance of Class:\nc = Class(parent)\nprint(c.x)\n\nYou cannot access the local variable - it goes out of scope when the method call ends.\n",
"I'm not sure exactly what the purpose of 'self.x' and 'x' are but one thing to note in the 'Main' method of class C... | [
5,
1
] | [] | [] | [
"class",
"import",
"python",
"tkinter"
] | stackoverflow_0004240266_class_import_python_tkinter.txt |
Q:
How to read cookies in a python script when using mod_python
I've got a website that I wrote in python using the CGI. This was great up until very recently, when the ability to scale became important.
I decided, because it was very simple, to use mod_python. Most of the functionality of my site is stored in a python module which I call to render the various pages. One of the CGI scripts might look like this:
#!/usr/bin/python
import mysite
mysite.init()
mysite.foo_page()
mysite.close()
and in mysite, I might have something like this:
def get_username():
cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE",""))
sessionid = cookie['sessionid'].value
ip = os.environ['REMOTE_ADDR']
username = select username from sessions where ip = %foo and session = %bar
return(username)
to fetch the current user's username. Problem is that this depends on os.envrion getting populated when os is imported to the script (at the top of the module). Because I'm now using mod_python, the interpreter only loads this module once, and only populates it once. I can't read cookies because it's os has the environment variables of the local machine, not the remote user.
I'm sure there is a way around this, but I'm not sure what it is. I tried re-importing os in the get_username function, but no dice :(.
Any thoughts?
A:
Which version of mod_python are you using? Mod_python 3.x includes a separate Cookie class to make this easier (see here)
Under earlier versions IIRC you can get the incoming cookies inside of the headers_in member of the request object.
| How to read cookies in a python script when using mod_python | I've got a website that I wrote in python using the CGI. This was great up until very recently, when the ability to scale became important.
I decided, because it was very simple, to use mod_python. Most of the functionality of my site is stored in a python module which I call to render the various pages. One of the CGI scripts might look like this:
#!/usr/bin/python
import mysite
mysite.init()
mysite.foo_page()
mysite.close()
and in mysite, I might have something like this:
def get_username():
cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE",""))
sessionid = cookie['sessionid'].value
ip = os.environ['REMOTE_ADDR']
username = select username from sessions where ip = %foo and session = %bar
return(username)
to fetch the current user's username. Problem is that this depends on os.envrion getting populated when os is imported to the script (at the top of the module). Because I'm now using mod_python, the interpreter only loads this module once, and only populates it once. I can't read cookies because it's os has the environment variables of the local machine, not the remote user.
I'm sure there is a way around this, but I'm not sure what it is. I tried re-importing os in the get_username function, but no dice :(.
Any thoughts?
| [
"Which version of mod_python are you using? Mod_python 3.x includes a separate Cookie class to make this easier (see here)\nUnder earlier versions IIRC you can get the incoming cookies inside of the headers_in member of the request object.\n"
] | [
0
] | [] | [] | [
"cookies",
"mod_python",
"python"
] | stackoverflow_0004241131_cookies_mod_python_python.txt |
Q:
Looking for parallel function to actionscript's BitmapData.draw() but in OpenGL
I have a flash application that I have been working on for 11 months, and would like to translate it to a different language / platform, preferably Python and OpenGL.
One of the main features in my program is to draw flash vector graphics (or display objects) and then redraw them to a bitmap texture. Is there any way to do this in OpenGL? Basically to draw some polygons on the screen, and then draw these polygons onto a texture. If the texture is displayed directly below the polygons , and the polygons are in motion, then there is a dragging/drawing/painting effect.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#draw() --> here is the flash function which I use.
Hopefully someone who is knowledgable in OpenGL & Actionscript would be able to answer this question or provide me with some details. Thankyou!
A:
OpenGL doesn't provide any features for drawing your typical 2D vector graphics. It's a very generic API, but mostly suited for 3D solutions. Implementing the rendering capabilities of Flash in OpenGL is possible, but a lot of work to do yourself.
If you want only a subset (drawing sprites, triangles, convex polygons, lines; alpha blending), then yes, OpenGL may be a good and quick solution.
Otherwise, there's a standard called OpenVG which might be what you want. There are several implementations, some of which may already run on hardware. I haven't tried it so far, though - you'll have to check that one yourself.
| Looking for parallel function to actionscript's BitmapData.draw() but in OpenGL | I have a flash application that I have been working on for 11 months, and would like to translate it to a different language / platform, preferably Python and OpenGL.
One of the main features in my program is to draw flash vector graphics (or display objects) and then redraw them to a bitmap texture. Is there any way to do this in OpenGL? Basically to draw some polygons on the screen, and then draw these polygons onto a texture. If the texture is displayed directly below the polygons , and the polygons are in motion, then there is a dragging/drawing/painting effect.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#draw() --> here is the flash function which I use.
Hopefully someone who is knowledgable in OpenGL & Actionscript would be able to answer this question or provide me with some details. Thankyou!
| [
"OpenGL doesn't provide any features for drawing your typical 2D vector graphics. It's a very generic API, but mostly suited for 3D solutions. Implementing the rendering capabilities of Flash in OpenGL is possible, but a lot of work to do yourself.\nIf you want only a subset (drawing sprites, triangles, convex poly... | [
2
] | [] | [] | [
"actionscript",
"flash",
"opengl",
"python"
] | stackoverflow_0004240625_actionscript_flash_opengl_python.txt |
Q:
Python smtplib slower than PHP mail()
I ported some PHP applications to Python.
To my surprise, performance dropped by ten times in the newsletter module (100k+ subscribers). I was expecting some overhead for using SMTP (I think PHP calls sendmail directly), but not that much.
How can I speedup Pythons mail delivery?
EDITED: For anyone digging this question, I solved this using celery with 8 workers to delivery e-mail in background, with this setup I can deliver about 200K messages per hour. Celery integrates very well wit django, and AMQP rocks.
A:
PHP's mail() does indeed use sendmail. You can do the same thing in Python by invoking it via subprocess.
| Python smtplib slower than PHP mail() | I ported some PHP applications to Python.
To my surprise, performance dropped by ten times in the newsletter module (100k+ subscribers). I was expecting some overhead for using SMTP (I think PHP calls sendmail directly), but not that much.
How can I speedup Pythons mail delivery?
EDITED: For anyone digging this question, I solved this using celery with 8 workers to delivery e-mail in background, with this setup I can deliver about 200K messages per hour. Celery integrates very well wit django, and AMQP rocks.
| [
"PHP's mail() does indeed use sendmail. You can do the same thing in Python by invoking it via subprocess.\n"
] | [
3
] | [] | [] | [
"php",
"python",
"smtp",
"smtplib"
] | stackoverflow_0004241434_php_python_smtp_smtplib.txt |
Q:
How to get the path to the opened file from a script inside a OS X .app bundle?
So I have Foo.app, which is configured to run Foo.app/Contents/MacOS/foo.py when it is launched. In the app's Info.plist file I also have it set as the application to handle the launching of ".bar" files. When I double-click a .bar file, Foo.app opens as expected.
The problem is that when a file is opened in this way, I can't figure out how to get the path to the opened file in my foo.py script. I assumed it would be in sys.argv[1], but it's not. Instead, sys.argv[1] contains a strange string like "-psn_0_2895682".
Does anyone know how I can get the absolute path to the opened file? I've also checked os.environ, but it's not there either.
A:
You can get your app's process ID then ask the OS for all open files using lsof, looking for your process's ID:
from string import *
from os import getpid
from subprocess import check_output, STDOUT
pid = getpid()
lsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split("\n")
for line in lsof[1:]:
print line
The regular files will be of type 'REG' in the fifth column, [4] if you're indexing in.
Files open within the running code can be displayed in a similar way:
from string import *
from os import getpid
from subprocess import check_output, STDOUT
import re
pid = getpid()
f = open('./trashme.txt', 'w')
f.write('This is a test\n')
lsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split("\n")
print lsof[0]
for line in lsof[1:]:
if (re.search('trashme', line)): print line
f.close
Which results in:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 6995 greg 3w REG 14,2 0 2273252 /Users/greg/Desktop/trashme.txt
| How to get the path to the opened file from a script inside a OS X .app bundle? | So I have Foo.app, which is configured to run Foo.app/Contents/MacOS/foo.py when it is launched. In the app's Info.plist file I also have it set as the application to handle the launching of ".bar" files. When I double-click a .bar file, Foo.app opens as expected.
The problem is that when a file is opened in this way, I can't figure out how to get the path to the opened file in my foo.py script. I assumed it would be in sys.argv[1], but it's not. Instead, sys.argv[1] contains a strange string like "-psn_0_2895682".
Does anyone know how I can get the absolute path to the opened file? I've also checked os.environ, but it's not there either.
| [
"You can get your app's process ID then ask the OS for all open files using lsof, looking for your process's ID:\nfrom string import *\nfrom os import getpid\nfrom subprocess import check_output, STDOUT\n\npid = getpid()\n\nlsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split(\"\\n\")\nfor... | [
2
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004241458_macos_python.txt |
Q:
Why is my system using my old PYTHONPATH after explicitly setting?
I am running a script that explicitly sets the PYTHONPATH to avoid naming collisions. However, even if I say os.environ['PYTHONPATH'] = '', it looks as though the system is still able to find my old path that "lives" outside the script.
How is my system able to see the old PYTHONPATH even after I explicitly set it to a new one?
A:
The PYTHONPATH environment variable is parsed at startup and inserted into sys.path. If you need to adjust the path from within your Python code, manipulate sys.path, not PYTHONPATH.
| Why is my system using my old PYTHONPATH after explicitly setting? | I am running a script that explicitly sets the PYTHONPATH to avoid naming collisions. However, even if I say os.environ['PYTHONPATH'] = '', it looks as though the system is still able to find my old path that "lives" outside the script.
How is my system able to see the old PYTHONPATH even after I explicitly set it to a new one?
| [
"The PYTHONPATH environment variable is parsed at startup and inserted into sys.path. If you need to adjust the path from within your Python code, manipulate sys.path, not PYTHONPATH.\n"
] | [
4
] | [] | [] | [
"collision",
"python",
"pythonpath",
"setting"
] | stackoverflow_0004241632_collision_python_pythonpath_setting.txt |
Q:
Appengine Django Template - Read template tags
UPDATE 1
ADDED UPDATED CODE
I have a django template on app engine. Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine.
eg. file : p1.html
{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}
Can I load and read these template into some value and go.
template['price']
which would be
$259
I can easily inject data into the template, but I want to parse out the data between my block tags.
UPDATED 2
With the help of aaronasterling (THANKS) the final code is this.
Final code to get the value out of a Django template on app engine.
path = os.path.join(os.path.dirname(file), 'home/p2.html')
file = open(path)
entry = file.read()
file.close()
entry = entry.replace("{% extends \"product.html\" %}","")
t = Template(entry)
product = {}
for node in t.nodelist[0].nodelist :
if hasattr(node, 'name'):
product[node.name] = node.render(Context())
A:
Sounds like you've shot yourself in the foot. Lets just pretend we aren't to blame and fix it:
entry = """{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%} """
parsedentry = dict([(j[0].split(' ')[-1], j[-1]) for j in [i.partition("%}") for i in entry.split("{%endblock%}")] if j[0].split(' ')[-1]])
print parsedentry['price']
A:
Update 1 fixed to traverse the whole node tree.
Update 2 Actually tested it so now it works.
Here's one way to do it.
from django.template import Template, Context
t = Template(template_string) # get it with open(filename).read() I guess
def get_block_contents(t, block_name, context=None):
if context is None:
context = Context()
stack = t.nodelist[:]
while stack:
node = stack.pop()
if hasattr(node, 'name') and node.name == block_name:
return node.render(context)
if hasattr(node, 'nodelist'):
stack.extend(node.nodelist)
return False # Or raise an error
| Appengine Django Template - Read template tags | UPDATE 1
ADDED UPDATED CODE
I have a django template on app engine. Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine.
eg. file : p1.html
{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}
Can I load and read these template into some value and go.
template['price']
which would be
$259
I can easily inject data into the template, but I want to parse out the data between my block tags.
UPDATED 2
With the help of aaronasterling (THANKS) the final code is this.
Final code to get the value out of a Django template on app engine.
path = os.path.join(os.path.dirname(file), 'home/p2.html')
file = open(path)
entry = file.read()
file.close()
entry = entry.replace("{% extends \"product.html\" %}","")
t = Template(entry)
product = {}
for node in t.nodelist[0].nodelist :
if hasattr(node, 'name'):
product[node.name] = node.render(Context())
| [
"Sounds like you've shot yourself in the foot. Lets just pretend we aren't to blame and fix it:\nentry = \"\"\"{%block price%}$259{%endblock%} \n{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%} \n{%block info%}http://www.inov-8.co.nz/oroc280.html{%end... | [
3,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004241595_django_google_app_engine_python.txt |
Q:
Why are list(), dict(), and tuple() slower than [], {}, and ()?
I've recently looked into using list(), dict(), tuple() in place of [], {}, and (), respectively when needing to create an empty one of of the three. The reasoning is that it seemed more readable. I was going to ask for opinions on the style, but then I decided to test performance. I did this:
>>> from timeit import Timer
>>> Timer('for x in range(5): y = []').timeit()
0.59327821802969538
>>> from timeit import Timer
>>> Timer('for x in range(5): y = list()').timeit()
1.2198944904251618
I tried dict(), tuple() and list() and the function call version of each was incredibly worse than the syntactical version ({} [], ()) So, I have 3 questions:
Why are the function calls more expensive?
Why is there so much difference?
Why the heck does it take 1.2 seconds to create 5 empty lists in my timer? I know timeit turns off garbage collection, but that couldn't possibly have an effect when considering I only used range(5).
A:
the function call requires a variable name lookup, followed by a function invocation. the function called then creates a list and returns it. The list syntax literal gets the interpreter to just make a list:
>>> import dis
>>> foo = lambda :[]
>>> bar = lambda :list()
>>> dis.dis(foo)
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(bar)
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>>
A:
To answer #3.
timeit actually repeats your program 1 000 000 times by default. So in fact, you are creating 5 million lists in 1.2 seconds.
A:
>>> from dis import dis
>>> dis(lambda: list())
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>> dis(lambda: [])
1 0 BUILD_LIST 0
3 RETURN_VALUE
A:
Scope lookups are required in order to find dict, tuple, and list, and multiple scopes need to be searched in order to find them. With the syntactic sugar the compiler can know that a specific object needs to be created and so can emit the proper bytecode to do so.
| Why are list(), dict(), and tuple() slower than [], {}, and ()? | I've recently looked into using list(), dict(), tuple() in place of [], {}, and (), respectively when needing to create an empty one of of the three. The reasoning is that it seemed more readable. I was going to ask for opinions on the style, but then I decided to test performance. I did this:
>>> from timeit import Timer
>>> Timer('for x in range(5): y = []').timeit()
0.59327821802969538
>>> from timeit import Timer
>>> Timer('for x in range(5): y = list()').timeit()
1.2198944904251618
I tried dict(), tuple() and list() and the function call version of each was incredibly worse than the syntactical version ({} [], ()) So, I have 3 questions:
Why are the function calls more expensive?
Why is there so much difference?
Why the heck does it take 1.2 seconds to create 5 empty lists in my timer? I know timeit turns off garbage collection, but that couldn't possibly have an effect when considering I only used range(5).
| [
"the function call requires a variable name lookup, followed by a function invocation. the function called then creates a list and returns it. The list syntax literal gets the interpreter to just make a list:\n>>> import dis\n>>> foo = lambda :[]\n>>> bar = lambda :list()\n>>> dis.dis(foo)\n 1 0 BUILD_... | [
19,
6,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004241716_python.txt |
Q:
recursion with python argparse
I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programname.py -options arg FILENAME FILENAME and python programname.py FILENAME FILENAME -options arg. I could painstakingly search for a '-' and work it out with a ton of if statements, but i feel like there should be a better way.
not sure that it matters, but here are my argparse declarations:
parser = argparse.ArgumentParser(description='Personal upload script. (defaults to ' + user + '@' + server + directory + ')')
parser.add_argument('files', nargs="+", help='file(s) to upload')
parser.add_argument('-s', metavar='example.com', default=server, help='server to upload to')
parser.add_argument('-u', metavar='username', default=user, help='ftp username')
parser.add_argument('-p', metavar='password', default=password, help='ftp password')
parser.add_argument('-d', metavar='example/', default=directory, help='directory to place file in')
parser.add_argument('-n', metavar='myfile.txt', help='name to save file as')
parser.add_argument('-c', metavar='###', help='chmod upload')
parser.add_argument('-l', action='store_true', help='print out new url(s)')
parser.add_argument('-r', action='store_true', help='recursive')
parser.add_argument('-F', action='store_true', help='force (overwrite files / create non-existing dirs)')
parser.add_argument('-v', action='store_true', help='verbose')
args = parser.parse_args()
thanks so much!
A:
You're just making life difficult for yourself. You don't make programs recursive, you make functions recursive. Making a program recursive is an excellent way to run out of memory and generally overwhelm a system.
Rewrite your application so that the recursive work is confined to a function that calls itself, instead of another instance of your application.
Or, better, eliminate recursiveness entirely. It looks like you're just iterating through a directory tree. There's no reason to do that recursively. In fact, Python has a library function that will take care of walking a directory tree for you. See os.walk.
A:
You probably shouldn't be doing process-level recursion. That said, I think that argparse's treatment of "--" might provide the tool you're looking for (if I understand correctly). Search the argparse doc for the string "--".
| recursion with python argparse | I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programname.py -options arg FILENAME FILENAME and python programname.py FILENAME FILENAME -options arg. I could painstakingly search for a '-' and work it out with a ton of if statements, but i feel like there should be a better way.
not sure that it matters, but here are my argparse declarations:
parser = argparse.ArgumentParser(description='Personal upload script. (defaults to ' + user + '@' + server + directory + ')')
parser.add_argument('files', nargs="+", help='file(s) to upload')
parser.add_argument('-s', metavar='example.com', default=server, help='server to upload to')
parser.add_argument('-u', metavar='username', default=user, help='ftp username')
parser.add_argument('-p', metavar='password', default=password, help='ftp password')
parser.add_argument('-d', metavar='example/', default=directory, help='directory to place file in')
parser.add_argument('-n', metavar='myfile.txt', help='name to save file as')
parser.add_argument('-c', metavar='###', help='chmod upload')
parser.add_argument('-l', action='store_true', help='print out new url(s)')
parser.add_argument('-r', action='store_true', help='recursive')
parser.add_argument('-F', action='store_true', help='force (overwrite files / create non-existing dirs)')
parser.add_argument('-v', action='store_true', help='verbose')
args = parser.parse_args()
thanks so much!
| [
"You're just making life difficult for yourself. You don't make programs recursive, you make functions recursive. Making a program recursive is an excellent way to run out of memory and generally overwhelm a system.\nRewrite your application so that the recursive work is confined to a function that calls itself, in... | [
7,
1
] | [] | [] | [
"argparse",
"python",
"recursion"
] | stackoverflow_0004241652_argparse_python_recursion.txt |
Q:
Python Inspect - Lookup the data type for a property in a GAE db.model Class
class Employee(db.Model):
firstname = db.StringProperty()
lastname = db.StringProperty()
address1 = db.StringProperty()
timezone = db.FloatProperty() #might be -3.5 (can contain fractions)
class TestClassAttributes(webapp.RequestHandler):
"""
Enumerate attributes of a db.Model class
"""
def get(self):
for item in Employee.properties():
self.response.out.write("<br/>" + item)
#for subitem in item.__dict__:
# self.response.out.write("<br/> --" + subitem)
The above will give me a list of the property names for the variable "item".
My idea of item.__dict__ didn't work because item was a str.
How can I then display the data field type for each property, such as db.FloatProperty() for the property called timezone?
GAE = Google App Engine - but I'm sure the same answer would work for any class.
Thanks,
Neal Walters
A:
Iterate using "for name, property in Employee.properties().items()". The property argument is the Property instance, which you can compare using instanceof.
A:
For problems like these, the interactive Python shell is really handy. If you had used it to poke around at your Employee object, you might have discovered the answer to your question through trial and error.
Something like:
>>> from groups.models import Group
>>> Group.properties()
{'avatar': <google.appengine.ext.db.StringProperty object at 0x19f73b0>,
'created_at': <google.appengine.ext.db.DateTimeProperty object at 0x19f7330>,
'description': <google.appengine.ext.db.TextProperty object at 0x19f7210>,
'group_type': <google.appengine.ext.db.StringProperty object at 0x19f73d0>}
From that you know that the properties() method of a db.Model object returns a dict mapping the model's property names to the actual property objects they represent.
A:
I add the same problem, and the first 2 answers did not help me 100%.
I was not able to get the type information, from the meta data of the class or the
instance property, which is bizarre. So I had to use a dictionary.
The method GetType() will return the type of the property as a string.
Here is my answer:
class RFolder(db.Model):
def GetPropertyTypeInstance(self, pname):
for name, property in self.properties().items():
if name==pname:
return property
return None
def GetType(self, pname):
t = self.GetPropertyTypeInstance(pname)
return RFolder.__DB_PROPERTY_INFO[type(t)]
__DB_PROPERTY_INFO = {
db.StringProperty :"String",
db.ByteStringProperty :"ByteString",
db.BooleanProperty :"Boolean",
db.IntegerProperty :"Integer",
db.FloatProperty :"Float",
db.DateTimeProperty :"DateTime",
db.DateProperty :"Date",
db.TimeProperty :"Time",
db.ListProperty :"List",
db.StringListProperty :"StringList",
db.ReferenceProperty :"Reference",
db.SelfReferenceProperty :"SelfReference",
db.UserProperty :"User",
db.BlobProperty :"Blob",
db.TextProperty :"Text",
db.CategoryProperty :"Category",
db.LinkProperty :"Link",
db.EmailProperty :"Email",
db.GeoPtProperty :"GeoPt",
db.IMProperty :"IM",
db.PhoneNumberProperty :"PhoneNumber",
db.PostalAddressProperty :"PostalAddress",
db.RatingProperty :"Rating"
}
| Python Inspect - Lookup the data type for a property in a GAE db.model Class | class Employee(db.Model):
firstname = db.StringProperty()
lastname = db.StringProperty()
address1 = db.StringProperty()
timezone = db.FloatProperty() #might be -3.5 (can contain fractions)
class TestClassAttributes(webapp.RequestHandler):
"""
Enumerate attributes of a db.Model class
"""
def get(self):
for item in Employee.properties():
self.response.out.write("<br/>" + item)
#for subitem in item.__dict__:
# self.response.out.write("<br/> --" + subitem)
The above will give me a list of the property names for the variable "item".
My idea of item.__dict__ didn't work because item was a str.
How can I then display the data field type for each property, such as db.FloatProperty() for the property called timezone?
GAE = Google App Engine - but I'm sure the same answer would work for any class.
Thanks,
Neal Walters
| [
"Iterate using \"for name, property in Employee.properties().items()\". The property argument is the Property instance, which you can compare using instanceof.\n",
"For problems like these, the interactive Python shell is really handy. If you had used it to poke around at your Employee object, you might have dis... | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"inspection",
"python",
"reflection"
] | stackoverflow_0001440958_google_app_engine_inspection_python_reflection.txt |
Q:
Sending serial data with python gives an error on windows but not on linux
I'm using python to send data out to my arduino and for some reason under windows it's giving me an error.
Below is my code.
import serial
ser = serial.Serial("COM3")
ser.write('1')
Here is the error.
File "C:\Python25\lib\site-packages\serial\serialwin32.py",
line 255, in write
raise SerialException("WriteFile failed
(%s)" % ctypes.WinError())
serial.serialutil.SerialException: WriteFile failed ([Error 9] The handle
is invalid.)
Any idea why it's giving me this?
A:
Are you sure COM3 is a valid serial port on your Windows box? Can you open it with HyperTerminal and send stuff to it?
If it is, another thing to try is to replace it with the fully qualified name, for example:
port = "\\\\.\\COM3"
ser = serial.Serial(port, 38400)
| Sending serial data with python gives an error on windows but not on linux | I'm using python to send data out to my arduino and for some reason under windows it's giving me an error.
Below is my code.
import serial
ser = serial.Serial("COM3")
ser.write('1')
Here is the error.
File "C:\Python25\lib\site-packages\serial\serialwin32.py",
line 255, in write
raise SerialException("WriteFile failed
(%s)" % ctypes.WinError())
serial.serialutil.SerialException: WriteFile failed ([Error 9] The handle
is invalid.)
Any idea why it's giving me this?
| [
"Are you sure COM3 is a valid serial port on your Windows box? Can you open it with HyperTerminal and send stuff to it?\nIf it is, another thing to try is to replace it with the fully qualified name, for example:\nport = \"\\\\\\\\.\\\\COM3\"\nser = serial.Serial(port, 38400)\n\n"
] | [
1
] | [] | [] | [
"python",
"serial_port"
] | stackoverflow_0004242256_python_serial_port.txt |
Q:
How do I check out a file from perforce in python?
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
A:
Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:
http://www.perforce.com/perforce/loadsupp.html#api
You will find their documentation of the scripting API to be helpful:
http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf
Use of the Python API is quite similar to the command-line client:
PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import P4
>>> p4 = P4.P4()
>>> p4.connect() # connect to the default server, with the default clientspec
>>> desc = {"Description": "My new changelist description",
... "Change": "new"
... }
>>> p4.input = desc
>>> p4.run("changelist", "-i")
['Change 2579505 created.']
>>>
I'll verify it from the command line:
P:\>p4 changelist -o 2579505
# A Perforce Change Specification.
#
# Change: The change number. 'new' on a new changelist.
# Date: The date this specification was last modified.
# Client: The client on which the changelist was created. Read-only.
# User: The user who created the changelist.
# Status: Either 'pending' or 'submitted'. Read-only.
# Description: Comments about the changelist. Required.
# Jobs: What opened jobs are to be closed by this changelist.
# You may delete jobs from this list. (New changelists only.)
# Files: What opened files from the default changelist are to be added
# to this changelist. You may delete files from this list.
# (New changelists only.)
Change: 2579505
Date: 2008/10/08 13:57:02
Client: MYCOMPUTER-DT
User: myusername
Status: pending
Description:
My new changelist description
A:
Here's what I came up with:
import os
def CreateNewChangeList(description):
"Create a new changelist and returns the changelist number as a string"
p4in, p4out = os.popen2("p4 changelist -i")
p4in.write("change: new\n")
p4in.write("description: " + description)
p4in.close()
changelist = p4out.readline().split()[1]
return changelist
def OpenFileForEdit(file, changelist = ""):
"Open a file for edit, if a changelist is passed in then open it in that list"
cmd = "p4 edit "
if changelist:
cmd += " -c " + changelist + " "
ret = os.popen(cmd + file).readline().strip()
if not ret.endswith("opened for edit"):
print "Couldn't open", file, "for edit:"
print ret
raise ValueError
A:
Perforce's P4 Python module mentioned in another answer is the way to go, but if installing this module isn't an option you can use the -G flag to help parse p4.exe output:
p4 [ options ] command [ arg ... ]
options:
-c client -C charset -d dir -H host -G -L language
-p port -P pass -s -Q charset -u user -x file
The -G flag causes all output (and batch input for form commands
with -i) to be formatted as marshalled Python dictionary objects.
A:
Building from p4python source requires downloading and extracting the p4 api recommended for that version. For example, if building the Windows XP x86 version of P4Python 2008.2 for activepython 2.5:
download and extract both the p4python and p4api
fixup the setup.cfg for p4python to
point to the p4api directory.
To open files for edit (do a checkout), on the command line, see 'p4 help open'.
You can check out files without making a changelist if you add the file to the default changelist, but it's a good idea to make a changelist first.
P4Python doesn't currently compile for activepython 2.6 without visual studio 2008; the provided libs are built with 2005 or 2003. Forcing p4python to build against mingw is nearly impossible, even with pexports of python26.dll and reimp/reassembly of the provided .lib files into .a files.
In that case, you'll probably rather use subprocess, and return p4 results as marshalled python objects. You can write your own command wrapper that takes an arg array, constructs and runs the commands, and returns the results dictionary.
You might try changing everything, testing, and on success, opening the files that are different with something equivalent to 'p4 diff -se //...'
A:
You may want to check out the P4Python module. It's available on the perforce site and it makes things very simple.
A:
Remember guys to install the development package for Python for the p4api or it will complain about missing headers. In Ubuntu 10.10, just do a simple:
apt-get install python2.6-dev
Or
apt-get install python3.1-dev
| How do I check out a file from perforce in python? | I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
| [
"Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:\nhttp://www.perforce.com/perforce/loadsupp.html#api\nYou will find their documentation of the scripting API to be helpful:\nhttp://www.perforce.com/perforce/doc.current/manuals/p4script/p4sc... | [
22,
7,
4,
3,
2,
2
] | [] | [] | [
"perforce",
"python",
"scripting"
] | stackoverflow_0000184187_perforce_python_scripting.txt |
Q:
How do you maintain user data when updating a Django site?
I have a live Django site that already has registered users. I am trying to update the site with a new version that is different from the original site -similar idea but different models.
How can I keep the current users on the new site?
I have heard South may be a good solution, but the old site doesn't have it installed. Is it possible to use South in this case?
Thanks for the help!
A:
yes http://south.aeracode.org/docs/convertinganapp.html#converting-an-app
A:
+1 to South, but...
We need more information! Are you doing radical changes to your Models, or just adding or removing fields here or there?
South can handle some pretty radical migrations, but you'll have to write some custom migration code. Personally, I use South if I'm adding a new field, but not for this kind of more radical stuff.
If it's a big Schema change, completely re-organizing your site, then I'd just write your own script to read the old objects, and create the new ones. Make a copy of your production database (via pg_dump, mysqldump, etc.) and load it on to your local machine, where you can test and debug the custom conversion script. Make sure your "old models" and "new models" have different names, and keep everything in your settings.py so that you can always read & write everything.
Write & test the migration script, and after that works, you can create another changelist to delete all the old objects, and then remove their corresponding source code if you want.
| How do you maintain user data when updating a Django site? | I have a live Django site that already has registered users. I am trying to update the site with a new version that is different from the original site -similar idea but different models.
How can I keep the current users on the new site?
I have heard South may be a good solution, but the old site doesn't have it installed. Is it possible to use South in this case?
Thanks for the help!
| [
"yes http://south.aeracode.org/docs/convertinganapp.html#converting-an-app\n",
"+1 to South, but...\nWe need more information! Are you doing radical changes to your Models, or just adding or removing fields here or there?\nSouth can handle some pretty radical migrations, but you'll have to write some custom migr... | [
2,
0
] | [] | [] | [
"django_database",
"django_south",
"mysql",
"python"
] | stackoverflow_0004241227_django_database_django_south_mysql_python.txt |
Q:
Getting registry information using Python
I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a .bat file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code:
My working bat file:
echo rfsqlcl01app >> foo.txt
reg query "\\rfsqlcl01app\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo GLADGSQL01 >> foo.txt
reg query "\\GLADGSQL01\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo GLADGWEB01 >> foo.txt
reg query "\\GLADGWEB01\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo PAPERVISION >> foo.txt
My python code structure:
>>> server_list = open('server_test.txt', 'r')
>>> for line in server_list:
print r'reg query \\%s\blah\blah\blah' % line.strip()
reg query \\foo\blah\blah\blah
reg query \\moo\blah\blah\blah
reg query \\boo\blah\blah\blah
>>> server_list.close()
A:
Without knowing much about your setup, this might work for you the way that you want.
import _winreg
################################################################################
class HKEY:
'Hive Constants'
CLASSES_ROOT = -2147483648
CURRENT_USER = -2147483647
LOCAL_MACHINE = -2147483646
USERS = -2147483645
CURRENT_CONFIG = -2147483643
class KEY:
'Mode Constants'
QUERY_VALUE = 1
SET_VALUE = 2
CREATE_SUB_KEY = 4
ENUMERATE_SUB_KEYS = 8
NOTIFY = 16
CREATE_LINK = 32
WRITE = 131078
EXECUTE = 131097
READ = 131097
ALL_ACCESS = 983103
class REG:
'Type Constants'
NONE = 0
SZ = 1
EXPAND_SZ = 2
BINARY = 3
DWORD = 4
DWORD_BIG_ENDIAN = 5
LINK = 6
MULTI_SZ = 7
RESOURCE_LIST = 8
FULL_RESOURCE_DESCRIPTOR = 9
RESOURCE_REQUIREMENTS_LIST = 10
QWORD = 11
################################################################################
class _Value(object):
'_Value(value) -> _Value'
def __init__(self, value):
'Initialize the _Value object.'
self.__value = value
self.__repr = '%s(%r)' % (self.__class__.__name__, value)
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def __get_value(self):
'Private class method.'
return self.__value
value = property(__get_value, doc='Value of this object.')
class REG_NONE(_Value): pass
class REG_SZ(_Value): pass
class REG_EXPAND_SZ(_Value): pass
class REG_BINARY(_Value): pass
class REG_DWORD(_Value): pass
class REG_DWORD_BIG_ENDIAN(_Value): pass
class REG_LINK(_Value): pass
class REG_MULTI_SZ(_Value): pass
class REG_RESOURCE_LIST(_Value): pass
class REG_FULL_RESOURCE_DESCRIPTOR(_Value): pass
class REG_RESOURCE_REQUIREMENTS_LIST(_Value): pass
class REG_QWORD(_Value): pass
################################################################################
class Registry(object):
'Registry([computer]) -> Registry'
def __init__(self, computer=None):
'Initialize the Registry object.'
self.__computer = computer
self.__repr = 'Registry()' if computer is None else 'Registry(%r)' % computer
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def __iter__(self):
'Iterate over hives defined in HKEY.'
return (Key(key, computer=self.__computer) for key in map(HKEY.__dict__.__getitem__, filter(str.isupper, dir(HKEY))))
def __HKEY_CLASSES_ROOT(self):
'Private class method.'
return Key(HKEY.CLASSES_ROOT, computer=self.__computer)
def __HKEY_CURRENT_USER(self):
'Private class method.'
return Key(HKEY.CURRENT_USER, computer=self.__computer)
def __HKEY_LOCAL_MACHINE(self):
'Private class method.'
return Key(HKEY.LOCAL_MACHINE, computer=self.__computer)
def __HKEY_USERS(self):
'Private class method.'
return Key(HKEY.USERS, computer=self.__computer)
def __HKEY_CURRENT_CONFIG(self):
'Private class method.'
return Key(HKEY.CURRENT_CONFIG, computer=self.__computer)
HKEY_CLASSES_ROOT = property(__HKEY_CLASSES_ROOT, doc='The CLASSES_ROOT hive.')
HKEY_CURRENT_USER = property(__HKEY_CURRENT_USER, doc='The CURRENT_USER hive.')
HKEY_LOCAL_MACHINE = property(__HKEY_LOCAL_MACHINE, doc='The LOCAL_MACHINE hive.')
HKEY_USERS = property(__HKEY_USERS, doc='The USERS hive.')
HKEY_CURRENT_CONFIG = property(__HKEY_CURRENT_CONFIG, doc='The CURRENT_CONFIG hive.')
################################################################################
class Key(object):
'''Key(key[, subkey][, mode][, computer]) -> Key
Key(key) -> Key
Key(key, subkey) -> Key
Key(key, mode=value) -> Key
Key(key, subkey, mode) -> Key
Key(key, computer=value) -> Key
Key(key, subkey, computer=value) -> Key
Key(key, mode=value, computer=value) -> Key
Key(key, subkey, mode, computer) -> Key'''
def __init__(self, key, subkey=None, mode=None, computer=None):
'Initialize the Key object.'
if isinstance(key, (int, _winreg.HKEYType)) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, '')
elif isinstance(key, Key) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, '')
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, subkey)
elif isinstance(key, Key) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey)
elif isinstance(key, (int, _winreg.HKEYType)) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, '', 0, mode)
elif isinstance(key, Key) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, '', 0, mode)
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, subkey, 0, mode)
elif isinstance(key, Key) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey, 0, mode)
elif isinstance(key, int) and subkey is None and mode is None and isinstance(computer, str):
self.__key = _winreg.ConnectRegistry(computer, key)
elif isinstance(key, int) and isinstance(subkey, str) and mode is None and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey)
elif isinstance(key, int) and subkey is None and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), '', 0, mode)
elif isinstance(key, int) and isinstance(subkey, str) and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey, 0, mode)
else:
raise TypeError, 'Please check documentation.'
self.__keys = Keys(self.__key)
self.__values = Values(self.__key)
self.__info = Info(self.__key)
self.__repr = 'Key(%s)' % ', '.join([repr(key)] + ['%s=%r' % (key, value) for key, value in zip(('subkey', 'mode', 'computer'), (subkey, mode, computer)) if value is not None])
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def save(self, file_name):
'Save this key to file.'
_winreg.SaveKey(self.__key, file_name)
def load(self, subkey, file_name):
'Load subkey from file.'
_winreg.LoadKey(self.__key, subkey, file_name)
def __get_keys(self):
'Private class method.'
return self.__keys
def __set_keys(self, keys):
'Private class method.'
if isinstance(keys, str):
_winreg.CreateKey(self.__key, keys)
elif isinstance(keys, (list, tuple)):
for key in keys:
self.keys = key
else:
raise TypeError, 'Key Could Not Be Created'
def __del_keys(self):
'Private class method.'
try:
while True:
_winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0))
except EnvironmentError:
pass
def __get_values(self):
'Private class method.'
return self.__values
def __set_values(self, values):
'Private class method.'
if isinstance(values, str):
_winreg.SetValueEx(self.__key, values, 0, REG.SZ, _winreg.QueryValue(self.__key, ''))
elif isinstance(values, (list, tuple)):
for value in values:
self.values = value
else:
raise TypeError, 'Value Could Not Be Created'
def __del_values(self):
'Private class method.'
try:
while True:
_winreg.DeleteValue(self.__key, _winreg.EnumValue(self.__key, 0)[0])
except EnvironmentError:
pass
def __get_value(self):
'Private class method.'
return _winreg.QueryValue(self.__key, '')
def __set_value(self, value):
'Private class method.'
_winreg.SetValue(self.__key, '', REG.SZ, value)
def __del_value(self):
'Private class method.'
_winreg.DeleteValue(self.__key, '')
def __get_info(self):
'Private class method.'
return self.__info
keys = property(__get_keys, __set_keys, __del_keys, 'Keys of this key.')
values = property(__get_values, __set_values, __del_values, 'Values of this key.')
value = property(__get_value, __set_value, __del_value, 'Value of this key.')
info = property(__get_info, doc='Information about this key.')
################################################################################
class Keys(object):
'Keys(key) -> Keys'
def __init__(self, key):
'Initialize the Keys object.'
self.__key = key
self.__repr = 'Keys(%r)' % key
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def __len__(self):
'Return the number of keys.'
return _winreg.QueryInfoKey(self.__key)[0]
def __getitem__(self, key):
'Return the specified key.'
return Key(self.__key, key)
def __setitem__(self, key, value):
'Assign the item to a key.'
key = Key(_winreg.CreateKey(self.__key, key), mode=KEY.ALL_ACCESS)
for name in value.values:
key.values[name] = value.values[name]
for name in value.keys:
key.keys[name] = value.keys[name]
def __delitem__(self, key):
'Delete the specified key.'
_winreg.DeleteKey(self.__key, key)
def __iter__(self):
'Iterate over the key names.'
return iter(tuple(_winreg.EnumKey(self.__key, index) for index in xrange(_winreg.QueryInfoKey(self.__key)[0])))
def __contains__(self, item):
'Check for a key\'s existence.'
item = item.lower()
for index in xrange(_winreg.QueryInfoKey(self.__key)[0]):
if _winreg.EnumKey(self.__key, index).lower() == item:
return True
return False
################################################################################
class Values(object):
'Values(key) -> Values'
TYPES = REG_NONE, REG_SZ, REG_EXPAND_SZ, REG_BINARY, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_LINK, REG_MULTI_SZ, REG_RESOURCE_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_RESOURCE_REQUIREMENTS_LIST, REG_QWORD
def __init__(self, key):
'Initialize the Values object.'
self.__key = key
self.__repr = 'Values(%r)' % key
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def __len__(self):
'Return the number of values.'
return _winreg.QueryInfoKey(self.__key)[1]
def __getitem__(self, key):
'Return the specified value.'
item_value, item_type = _winreg.QueryValueEx(self.__key, key)
return self.TYPES[item_type](item_value)
def __setitem__(self, key, value):
'Assign the item to a value.'
if isinstance(value, self.TYPES):
_winreg.SetValueEx(self.__key, key, 0, list(self.TYPES).index(value.__class__), value.value)
else:
_winreg.SetValueEx(self.__key, key, 0, _winreg.QueryValueEx(self.__key, key)[1], value)
def __delitem__(self, key):
'Delete the specified value.'
_winreg.DeleteValue(self.__key, key)
def __iter__(self):
'Iterate over the value names.'
return iter(tuple(_winreg.EnumValue(self.__key, index)[0] for index in xrange(_winreg.QueryInfoKey(self.__key)[1])))
def __contains__(self, item):
'Check for a value\'s existence.'
item = item.lower()
for index in xrange(_winreg.QueryInfoKey(self.__key)[1]):
if _winreg.EnumValue(self.__key, index)[0].lower() == item:
return True
return False
################################################################################
class Info(object):
'Info(key) -> Info'
def __init__(self, key):
'Initialize the Info object.'
self.__key = key
self.__repr = 'Info(%r)' % key
def __repr__(self):
'Return the object\'s representation.'
return self.__repr
def __get_keys(self):
'Private class method.'
return _winreg.QueryInfoKey(self.__key)[0]
def __get_values(self):
'Private class method.'
return _winreg.QueryInfoKey(self.__key)[1]
def __get_modified(self):
'Private class method.'
return _winreg.QueryInfoKey(self.__key)[2]
def __get_difference(self):
'Private class method.'
return _time.time() + 11644473600.0 - self.modified / 10000000.0
keys = property(__get_keys, doc='Number of keys.')
values = property(__get_values, doc='Number of values.')
modified = property(__get_modified, doc='Time last modified.')
difference = property(__get_difference, doc='Seconds since modified.')
################################################################################
if __name__ == '__main__':
def echo(key, prefix=''):
for name in key.values:
print ' ' + name + ' = ' + repr(key.values[name])
for name in key.keys:
print prefix + '\\' + name
echo(key.keys[name], prefix + '\\' + name)
key = '''\
SOFTWARE\\Network Associates\\TVD\\Shared Components\\\
On Access Scanner\\McShield\\Configuration\\Default'''
server_list = open('server_test.txt')
for computer in server_list:
echo(Registry(computer).HKEY_LOCAL_MACHINE.keys[key])
server_list.close()
A:
Have a look at the Python 3rd-party regobj module. It makes Windows registry access even easier than using Python's built-in _winreg module.
| Getting registry information using Python | I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a .bat file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code:
My working bat file:
echo rfsqlcl01app >> foo.txt
reg query "\\rfsqlcl01app\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo GLADGSQL01 >> foo.txt
reg query "\\GLADGSQL01\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo GLADGWEB01 >> foo.txt
reg query "\\GLADGWEB01\HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\TVD\Shared Components\On Access Scanner\McShield\Configuration\Default" >> foo.txt
echo PAPERVISION >> foo.txt
My python code structure:
>>> server_list = open('server_test.txt', 'r')
>>> for line in server_list:
print r'reg query \\%s\blah\blah\blah' % line.strip()
reg query \\foo\blah\blah\blah
reg query \\moo\blah\blah\blah
reg query \\boo\blah\blah\blah
>>> server_list.close()
| [
"Without knowing much about your setup, this might work for you the way that you want.\nimport _winreg\n\n################################################################################\n\nclass HKEY:\n 'Hive Constants'\n CLASSES_ROOT = -2147483648\n CURRENT_USER = -2147483647\n LOCAL_MACHINE = -214748... | [
2,
0
] | [] | [] | [
"python",
"winreg"
] | stackoverflow_0002424648_python_winreg.txt |
Q:
Linux email server, how to know a new email has arrived
I am developing an email parsing application using python POP3 library on a linux server using Dovecot email server. I have parsed the emails to get the contents and the attachments etc. using POP3 library.
Now the issue is how to notify a user or actually the application that a new email has arrived? I guess there should be some notification system on email server itself which I am missing or something on linux which we can use to implement the same.
Please suggest.
Thanks in advance.
A:
POP3 does not have push ability. Like a regular ol' post office you need to actually go to check your e-mail. IMAP does have functionality similar to (but not exactly the same as) mail pushing. I'd suggest taking a look at it.
| Linux email server, how to know a new email has arrived | I am developing an email parsing application using python POP3 library on a linux server using Dovecot email server. I have parsed the emails to get the contents and the attachments etc. using POP3 library.
Now the issue is how to notify a user or actually the application that a new email has arrived? I guess there should be some notification system on email server itself which I am missing or something on linux which we can use to implement the same.
Please suggest.
Thanks in advance.
| [
"POP3 does not have push ability. Like a regular ol' post office you need to actually go to check your e-mail. IMAP does have functionality similar to (but not exactly the same as) mail pushing. I'd suggest taking a look at it.\n"
] | [
2
] | [] | [] | [
"email",
"linux",
"python"
] | stackoverflow_0004242540_email_linux_python.txt |
Q:
wxPython not binding callbacks to events properly
Here's a roughly minimal demonstrative example:
import wx
app = wx.App(False)
frame = wx.Frame(None)
menuBar = wx.MenuBar()
menu = wx.Menu()
menuBar.Append(menu, "&Menu")
frame.SetMenuBar(menuBar)
for name in ['foo','bar','baz']:
menuitem = menu.Append(-1,"&"+name,name)
def menuclick(e):
print(name)
frame.Bind(wx.EVT_MENU, menuclick, menuitem)
frame.Show(True)
app.MainLoop()
The issue is that every menu item, when clicked, prints "baz". Shouldn't the menuclick function wrap up the appropriate name in its closure and keep the original name around?
A:
After the for loop name will be "baz", it's value will not go back in time to when you bound the menuclick to the menu event.
You can get to the menu item name via the event itself like this:
def menuclick(e):
print(menu.FindItemById(e.Id).Label)
A:
I found this solution, by I'm not sure why this works where the inner-def version doesn't:
from functools import partial
def onclick(name,e):
print(name)
for name in ['foo','bar','baz']:
menuitem = menu.Append(-1,"&"+name,name)
frame.Bind(wx.EVT_MENU, partial(onclick,name), menuitem)
| wxPython not binding callbacks to events properly | Here's a roughly minimal demonstrative example:
import wx
app = wx.App(False)
frame = wx.Frame(None)
menuBar = wx.MenuBar()
menu = wx.Menu()
menuBar.Append(menu, "&Menu")
frame.SetMenuBar(menuBar)
for name in ['foo','bar','baz']:
menuitem = menu.Append(-1,"&"+name,name)
def menuclick(e):
print(name)
frame.Bind(wx.EVT_MENU, menuclick, menuitem)
frame.Show(True)
app.MainLoop()
The issue is that every menu item, when clicked, prints "baz". Shouldn't the menuclick function wrap up the appropriate name in its closure and keep the original name around?
| [
"After the for loop name will be \"baz\", it's value will not go back in time to when you bound the menuclick to the menu event.\nYou can get to the menu item name via the event itself like this:\ndef menuclick(e):\n print(menu.FindItemById(e.Id).Label)\n\n",
"I found this solution, by I'm not sure why this wo... | [
2,
0
] | [] | [] | [
"closures",
"python",
"wxpython"
] | stackoverflow_0004242147_closures_python_wxpython.txt |
Q:
python 3.1 boolean check with for loop
How can I add a Boolean check to a for loop? I was trying something like this:
for i in range (0, someNumber) and keepGoing == True
It is giving me the error 'bool' object is not iterable. Thanks for the help.
A:
This isn't a for loop like in C; what you're doing here is creating a range object and iterating over each element in it (naming it "i") in the process. In C, you can have multiple checks during an iteration of a loop, but in Python you iterate over iterable objects such as lists or tuples.
for i in range(0, someNumber):
if keepGoing:
# Code
Basically, you can't set a flag to stop the loop, because the "loop" is going to iterate over the entire range object. The only way to add a "stop flag" is to break out of the loop.
for i in range(0, someNumber):
if not keepGoing:
break
else:
# Code
or even
for i in range(0, someNumber):
if not keepGoing:
break
# Code
| python 3.1 boolean check with for loop | How can I add a Boolean check to a for loop? I was trying something like this:
for i in range (0, someNumber) and keepGoing == True
It is giving me the error 'bool' object is not iterable. Thanks for the help.
| [
"This isn't a for loop like in C; what you're doing here is creating a range object and iterating over each element in it (naming it \"i\") in the process. In C, you can have multiple checks during an iteration of a loop, but in Python you iterate over iterable objects such as lists or tuples.\nfor i in range(0, so... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0004242913_python.txt |
Q:
Pattern and design for functions that differ greatly from each other but are processed similarly
I'm writing some Python code to scrape websites, and what I'm going to end up with is a growing collection of custom scrapers, each about 50 lines long and tailored extract specific information from a specific website.
My first iteration of the program is one giant file that takes a website as an argument, and scrapes that website if it recognizes it and has custom code for it (using a giant case statement to check if it recognizes the website).
Obviously, this isn't a great design, so what I'd like to do is pull the custom scrape functions into their own files/classes, and have a small script that I can use to call them by name. For example:
scrape.py --site google
And I'd like to have a file structure similar to:
scrape.py
sites/
google.py
yahoo.py
...
bing.py
I haven't mastered object orientation yet, but I recognize that this is calling out for it, and that what I'm looking for is probably a common OO pattern.
Any help getting this code refactored properly?
PS - I've looked at Scrapy, and it's not really what I need for various reasons.
PPS - I'm not actually scraping search websites, I'm scraping U.S. court websites.
A:
You can put the code in a class with an __init__ method to get everything configured, a _download method to connect to the site and download it, a _store method to save the results and a run method to tie it all together, like so:
class Scraper(object):
def __init__(self, parser, page_generator):
self._parser = parser
self._pages = pages
def _download(self, page):
# do whatever you're already doing to download it
return html
def _store(self, data):
# Do whatever you're already doing to store the data
def run(self):
for page in pages:
html = self._download(page)
data = self._parser.parse(html)
self._store(data)
This class can live in your parser.py file.
In each one of your site specific files, put two things.
class Parser(object):
def parse(html):
# All of your rules go here
def pages(some, args, if_, you, need, them): # but they should be the same for all files
return a_list_of_pages_or_generator
Then you can set up your python.py file with the following function:
def get_scraper(name):
mod = __import__(name)
parser = mod.Parser()
pages = mod.pages() # Pass whatever args you need to figure out the urls
return Scraper(parser, pages)
You can then use it like
scraper = get_scraper('google')
scraper.run()
Doing it this way has the advantage of not requiring you to make any changes to the Scraper class. If you need to do different tricks to get the servers to talk to your scraper, then you can create a Downloader class in each module and use it just like the Parser class. If you have two or more parsers that do the same thing, just define them as a generic parser in a separate module and import that into the module of each site that requires it. Or subclass it to make tweaks. Without knowing how you're downloading and parsing the sites, it's hard to be more specific.
My feeling is that you might have to ask several questions to get all of the details ironed out but it will be a good learning experience.
A:
Your technique for refactoring is how I would go. Here is how, I look at implementing this problem.
First
I would create a single function called ScrapeHandler in all the files inside the site directory - google.py, yahoo.py etc
def ScrapeHandler(...):
...
Second
I would create a __init__.py in sites directory with the following content.
scrapers = ["google", "yahoo", ...]
Third
In the main file scrape.py, I would load the scraper at runtime to choose the appropriate scraping logic.
from sites import scrapers
all_scrapers = {}
......
# Load all scrapers
for scraper_name in scrapers:
all_scrapers[scraper_name] = __import__('%s.%s' % (sites.__name__, scraper_name), fromlist=[scraper_name], level=0)
# get the input on what to scrape via command line etc
scraper_name = ..
assert scraper_name not in scrapers
# call the function based on name
scrapeHandler = all_scrapers.get(scraper_name, None)
if scrapeHandler is not None:
scrapeHandler(....)
| Pattern and design for functions that differ greatly from each other but are processed similarly | I'm writing some Python code to scrape websites, and what I'm going to end up with is a growing collection of custom scrapers, each about 50 lines long and tailored extract specific information from a specific website.
My first iteration of the program is one giant file that takes a website as an argument, and scrapes that website if it recognizes it and has custom code for it (using a giant case statement to check if it recognizes the website).
Obviously, this isn't a great design, so what I'd like to do is pull the custom scrape functions into their own files/classes, and have a small script that I can use to call them by name. For example:
scrape.py --site google
And I'd like to have a file structure similar to:
scrape.py
sites/
google.py
yahoo.py
...
bing.py
I haven't mastered object orientation yet, but I recognize that this is calling out for it, and that what I'm looking for is probably a common OO pattern.
Any help getting this code refactored properly?
PS - I've looked at Scrapy, and it's not really what I need for various reasons.
PPS - I'm not actually scraping search websites, I'm scraping U.S. court websites.
| [
"You can put the code in a class with an __init__ method to get everything configured, a _download method to connect to the site and download it, a _store method to save the results and a run method to tie it all together, like so:\nclass Scraper(object):\n def __init__(self, parser, page_generator):\n se... | [
5,
1
] | [] | [] | [
"design_patterns",
"oop",
"python",
"web_scraping"
] | stackoverflow_0004243491_design_patterns_oop_python_web_scraping.txt |
Q:
Is Django's templating markup for views safe for end user editing like rails liquid templating?
I want end users to be able to edit their view templates online, so it has to be safe or 'jailed' such that only the objects I explicitly push to the view page are made accessible.
i.e. I don't want the end user to be able to write python code, or figure out my connection string information etc. etc.
Is django's templating markup for views safe for this type of usage?
A:
Django templates are safe for this kind of code as far as I know.
The only kind of logic beyond simple loops/branches that can be executed in the template is whatever is registered as a template tag or filter. TT or Filters can only be registered through the backend code.
Here you can see a list of template tags and filters: http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs most of the just work on strings or dates etc.
Cheers
EDIT: You definitely want to make sure that the settings object isn't available in the template context.
A:
Django templates are safe for the most part but this is based on what you exposed to the template context.
The biggest issue is exposing objects to the template since all the methods get passed along. This is especially true for QuerySets which are the most common object passed to the template and the most vulnerable.
If you pass articles from the view to the template
articles = Articles.objects.all()
I could do the following
{% for article in articles %}
{{ article.delete }}
{% endfor %}
| Is Django's templating markup for views safe for end user editing like rails liquid templating? | I want end users to be able to edit their view templates online, so it has to be safe or 'jailed' such that only the objects I explicitly push to the view page are made accessible.
i.e. I don't want the end user to be able to write python code, or figure out my connection string information etc. etc.
Is django's templating markup for views safe for this type of usage?
| [
"Django templates are safe for this kind of code as far as I know.\nThe only kind of logic beyond simple loops/branches that can be executed in the template is whatever is registered as a template tag or filter. TT or Filters can only be registered through the backend code.\nHere you can see a list of template tags... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004219735_django_python.txt |
Q:
How can I augment the method of a Python object?
I have a list of Spam objects:
class Spam:
def update(self):
print('updating spam!')
some of them might be SpamLite objects:
class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)
I would like to be able to take an arbitrary object from the list, and add something to it's update method, something like:
def poison(spam):
tmp = spam.update
def newUpdate(self):
print 'this spam has been poisoned!'
tmp(self)
spam.update = newUpdate
I want spam.update() to now either print:
this spam has been poisoned!
updating spam!
or
this spam has been poisoned!
this spam is lite!
updating spam!
depending on whether it was a SpamLite or just a Spam.
But that doesn't work, because spam.update() won't pass in the self argument automatically, and because if tmp leaves scope or changes then it won't call the old update. Is there a way I can do this?
A:
def poison(spam):
tmp = spam.update
def newUpdate():
print 'this spam has been poisoned!'
tmp()
spam.update = newUpdate
Full Script:
class Spam:
def update(self):
print('updating spam!')
class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)
def poison(spam):
tmp = spam.update # it is a bound method that doesn't take any arguments
def newUpdate():
print 'this spam has been poisoned!'
tmp()
spam.update = newUpdate
from operator import methodcaller
L = [Spam(), SpamLite()]
map(methodcaller('update'), L)
map(poison, L)
print "*"*79
map(methodcaller('update'), L)
Output:
updating spam!
this spam is lite!
updating spam!
*******************************************************************************
this spam has been poisoned!
updating spam!
this spam has been poisoned!
this spam is lite!
updating spam!
A:
Another approach, with MethodType:
class Spam:
def update(self):
print('updating spam!')
class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)
def poison(spam):
import types
tmp = spam.update
def newUpdate(self):
print 'this spam has been poisoned!'
tmp()
newUpdate = types.MethodType(newUpdate, spam, Spam)
spam.update = newUpdate
spam = Spam()
spam_lite = SpamLite()
poison(spam)
poison(spam_lite)
spam.update()
print
spam_lite.update()
A:
MonkeyPatching is frowned upon, in the python world.
You should really use the Mixin approach and use Multiple inheritance.
You can then dynamically replace (update) the parents to achieve the desired effect.
A:
Use decorators like this:
def method_decorator(f):
def wrapper(self, *args, **kwargs):
print('this spam has been poisoned!')
return f(self)
return wrapper
class Spam:
def update(self):
print('updating spam!')
@method_decorator
def update2(self):
print('updating spam!')
Spam().update()
Spam().update2()
This prints:
updating spam!
this spam has been poisoned!
updating spam!
If you want to know more about decorators read this: http://www.drdobbs.com/web-development/184406073
The above is not a "good citizen" decorator, read the article to know how to write one. Be sure to check also decorator library: http://pypi.python.org/pypi/decorator
HTH
| How can I augment the method of a Python object? | I have a list of Spam objects:
class Spam:
def update(self):
print('updating spam!')
some of them might be SpamLite objects:
class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)
I would like to be able to take an arbitrary object from the list, and add something to it's update method, something like:
def poison(spam):
tmp = spam.update
def newUpdate(self):
print 'this spam has been poisoned!'
tmp(self)
spam.update = newUpdate
I want spam.update() to now either print:
this spam has been poisoned!
updating spam!
or
this spam has been poisoned!
this spam is lite!
updating spam!
depending on whether it was a SpamLite or just a Spam.
But that doesn't work, because spam.update() won't pass in the self argument automatically, and because if tmp leaves scope or changes then it won't call the old update. Is there a way I can do this?
| [
"def poison(spam):\n tmp = spam.update\n def newUpdate():\n print 'this spam has been poisoned!'\n tmp()\n spam.update = newUpdate\n\nFull Script:\nclass Spam:\n def update(self):\n print('updating spam!')\n\nclass SpamLite(Spam):\n def update(self):\n print('this spam is ... | [
4,
3,
0,
0
] | [] | [] | [
"methods",
"python"
] | stackoverflow_0004243586_methods_python.txt |
Q:
run python command from C code with specific encoding
int PyRun_SimpleString(const char *command)
is the function which can run a command of Python.
I call this function in my program, but how can I specify the encoding of the command argument. I found that Python 3 seems to use UTF-8 as the default encoding when I run a command. Can I change this encoding in the C level API? ...or with an extra parameter when call PyRun_SimpleString-like function?
A:
You can prepend one of the "magic comments" described in PEP 263 to your command:
char buf[1024];
snprintf(buf, sizeof(buf), "-*- coding: %s -*-\n", yourEncoding);
strncat(buf, yourCommand, sizeof(buf) - strlen(buf) - 1);
PyRun_SimpleString(buf);
| run python command from C code with specific encoding | int PyRun_SimpleString(const char *command)
is the function which can run a command of Python.
I call this function in my program, but how can I specify the encoding of the command argument. I found that Python 3 seems to use UTF-8 as the default encoding when I run a command. Can I change this encoding in the C level API? ...or with an extra parameter when call PyRun_SimpleString-like function?
| [
"You can prepend one of the \"magic comments\" described in PEP 263 to your command:\nchar buf[1024];\nsnprintf(buf, sizeof(buf), \"-*- coding: %s -*-\\n\", yourEncoding);\nstrncat(buf, yourCommand, sizeof(buf) - strlen(buf) - 1);\nPyRun_SimpleString(buf);\n\n"
] | [
3
] | [] | [] | [
"c",
"embed",
"encoding",
"python",
"python_3.x"
] | stackoverflow_0004244082_c_embed_encoding_python_python_3.x.txt |
Q:
What is wrong with this Python code?
Can anyone tell me what is wrong with this? I'm getting a syntax error after the 2nd quote on the print line... It seems like this should work perfectly fine. Thanks
def main():
print "blah"
return
main()
A:
In case you're using Python 3, the print statement is gone in that version and you need to use the print() function.
See: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function
A:
You're using python 3.
use
print("blah")
The print statement turned into the print function in the transition.
A:
Remember if your using python 2.x then to help with the transition you can always have
from __future__ import print_function
At the top of your code, this will convert print into a function meaning 2.x code can be written with
print('This')
And run happily
A:
Posting the exact error you get would be very helpful. I'm going to assume that this is an indentation error though. Don't mix tabs and spaces.
| What is wrong with this Python code? | Can anyone tell me what is wrong with this? I'm getting a syntax error after the 2nd quote on the print line... It seems like this should work perfectly fine. Thanks
def main():
print "blah"
return
main()
| [
"In case you're using Python 3, the print statement is gone in that version and you need to use the print() function.\nSee: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function\n",
"You're using python 3.\nuse \nprint(\"blah\")\n\nThe print statement turned into the print function in the tra... | [
4,
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004241529_python.txt |
Q:
to parse a file with text (with offset information) and binary data in python
I have an xml file, which contains a set of textual element tags (each contains the decimal offset value and data length of the corresponding binary element) and the whole binary data of all the elements at the end. An example is as follows.
<?xml version="1.0" encoding="UTF-8"?>
<Package>
<element>
<offset>0</offset>
<length>2961181</length>
<checksum>4238515972</checksum>
<format>gzip</format>
</element>
<element>
<offset>2961181</offset>
<length>5442</length>
<checksum>4238515972</checksum>
<format>bin</format>
</element>
</Package>
BINARY_DATA
please note, the offset is decimal and counts from the first byte after the headers.
How can I parse this file in python, grab the corresponding element based on the offset, uncompressed it (if its format is gzip) and store it as a file?
well, based on the replies from OmnipotentEntity and Jakob_B, I made the following short script, just to see if it works for the 1st element:
import zlib
f = open("file.xml", "r")
text = f.read()
position = text.find("</Package>\n")
headerSize=position+ len("</Package>\n") + 1
offset=0
f.seek(headerSize + offset)
length = 2961181
bin_data = f.read(length)
zipped=1
if (zipped):
ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
print(ungziped_str)
f.close()
however, I got the following error:
Traceback (most recent call last):
File "file_parse.py", line 11, in ?
ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
zlib.error: Error -3 while decompressing: invalid block type
what is the problem? the input file is incorrect, or the code is incorrect?
A:
The trick is going to be stopping XML parsers from puking on the binary data. lxml lets you feed a line at a time to a parser, so you can watch for the last XML tag and stop there:
from lxml import etree
def process(filename):
f = file(filename,"r")
parser = etree.XMLParser()
for l in f:
parser.feed(l)
if l=="</Package>\n":
break
return parser.close()
That returns an
r=process("junk.xml")
<Element Package at 9f14eb4>
which is an lxml object you can get the data out of. The second object's offset is here:
>>> r[1][0].text
'2961181'
and so on. That should be enough for you to make a workable solution. Beware the line ending on the Package tag though, there might be a better way to do that, this might not work if the file has a different line ending.
A:
Why not run a search for the end tag using lxml? Then when the end tag is found just .seek() to that point and read binary data.
A:
Determine header size.
Grab offset and data length using xml magic
import zlib
python.seek(headerSize+offset)
mydata = python.read(length)
if (zipped):
ungziped_str = zlib.decompressobj().decompress('x\x9c' + mydata)
Then write to file as normal.
Source for gunzip magic http://codingrecipes.com/ungzip-a-string-in-python-gzinflate-in-python
| to parse a file with text (with offset information) and binary data in python | I have an xml file, which contains a set of textual element tags (each contains the decimal offset value and data length of the corresponding binary element) and the whole binary data of all the elements at the end. An example is as follows.
<?xml version="1.0" encoding="UTF-8"?>
<Package>
<element>
<offset>0</offset>
<length>2961181</length>
<checksum>4238515972</checksum>
<format>gzip</format>
</element>
<element>
<offset>2961181</offset>
<length>5442</length>
<checksum>4238515972</checksum>
<format>bin</format>
</element>
</Package>
BINARY_DATA
please note, the offset is decimal and counts from the first byte after the headers.
How can I parse this file in python, grab the corresponding element based on the offset, uncompressed it (if its format is gzip) and store it as a file?
well, based on the replies from OmnipotentEntity and Jakob_B, I made the following short script, just to see if it works for the 1st element:
import zlib
f = open("file.xml", "r")
text = f.read()
position = text.find("</Package>\n")
headerSize=position+ len("</Package>\n") + 1
offset=0
f.seek(headerSize + offset)
length = 2961181
bin_data = f.read(length)
zipped=1
if (zipped):
ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
print(ungziped_str)
f.close()
however, I got the following error:
Traceback (most recent call last):
File "file_parse.py", line 11, in ?
ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
zlib.error: Error -3 while decompressing: invalid block type
what is the problem? the input file is incorrect, or the code is incorrect?
| [
"The trick is going to be stopping XML parsers from puking on the binary data. lxml lets you feed a line at a time to a parser, so you can watch for the last XML tag and stop there:\nfrom lxml import etree\n\ndef process(filename):\n f = file(filename,\"r\")\n parser = etree.XMLParser()\n for l in f:\n ... | [
2,
1,
0
] | [] | [] | [
"binary_data",
"file",
"parsing",
"python"
] | stackoverflow_0004243855_binary_data_file_parsing_python.txt |
Q:
Django Models Foreign Key Field Match
I have the following Django Model -
class M(models.Model):
...
disp_name = models.CharField(max_length=256, db_index=True)
...
class XX(models.Model):
x = models.ForeignKey(User)
y = models.ForeignKey(M, unique=True)
Now in my views.py, I want to do a partial string match on all items in XX with the field y.disp_name.
Normally one would do this - M.objects.filter(disp_name__istartswith='string')
But here M is a foreignkey in Model XX. So if I do XX.objects.filter(y.disp_name__istartswith='string') I get an error.
Also, this too fails -
u = User.objects.get(id=1)
u.xx_set.filter(y.disp_name__istartswith='string')
Exception that I get says is - SyntaxError: keyword can't be an expression (<console>, line 1)
How to do this?
A:
I wish you had used proper field names rather than X, Y and M - it's really hard to follow.
But in any case, you should always use the double-underscore syntax to follow relations on the left hand side of the filter expression:
XX.objects.filter(y__disp_name__istartswith='string')
(The technical reason for this is that the parameters to filter are actually keyword arguments to a function, so the left-hand side of that has to be a string rather than an expression.)
| Django Models Foreign Key Field Match | I have the following Django Model -
class M(models.Model):
...
disp_name = models.CharField(max_length=256, db_index=True)
...
class XX(models.Model):
x = models.ForeignKey(User)
y = models.ForeignKey(M, unique=True)
Now in my views.py, I want to do a partial string match on all items in XX with the field y.disp_name.
Normally one would do this - M.objects.filter(disp_name__istartswith='string')
But here M is a foreignkey in Model XX. So if I do XX.objects.filter(y.disp_name__istartswith='string') I get an error.
Also, this too fails -
u = User.objects.get(id=1)
u.xx_set.filter(y.disp_name__istartswith='string')
Exception that I get says is - SyntaxError: keyword can't be an expression (<console>, line 1)
How to do this?
| [
"I wish you had used proper field names rather than X, Y and M - it's really hard to follow.\nBut in any case, you should always use the double-underscore syntax to follow relations on the left hand side of the filter expression:\nXX.objects.filter(y__disp_name__istartswith='string')\n\n(The technical reason for th... | [
2
] | [] | [] | [
"django",
"django_models",
"python",
"string_matching"
] | stackoverflow_0004244552_django_django_models_python_string_matching.txt |
Q:
PyGTK app is not quitting properly
I wrote a little PyGTK app: Workcycler
Now I have the problem that I need to hit the quit button twice for it to quit and I don't know why.
I´ve tested it extensively and it allways calls all quit functions but the program simply doesn't close after the first time.
It's a pretty short script so could someone please have a look over it?
I think the problem may come from using python's timers or a part from the pygame lib (mixer).
These are the important files I think: workcycle.py and tray.py
A:
You are running the workcycle.ui.tray.WorkcycleTray.start method twice (so gtk.main run twice )
once in the workcycler and another in workcycle.py line 20, comment that line and everything works fine.
| PyGTK app is not quitting properly | I wrote a little PyGTK app: Workcycler
Now I have the problem that I need to hit the quit button twice for it to quit and I don't know why.
I´ve tested it extensively and it allways calls all quit functions but the program simply doesn't close after the first time.
It's a pretty short script so could someone please have a look over it?
I think the problem may come from using python's timers or a part from the pygame lib (mixer).
These are the important files I think: workcycle.py and tray.py
| [
"You are running the workcycle.ui.tray.WorkcycleTray.start method twice (so gtk.main run twice )\nonce in the workcycler and another in workcycle.py line 20, comment that line and everything works fine.\n"
] | [
1
] | [] | [] | [
"pygame",
"pygtk",
"python"
] | stackoverflow_0004243911_pygame_pygtk_python.txt |
Q:
Want to find date data in python shell
I have a model something like this.
#models.py
class ItemStatusHistory(models.Model):
date = models.DateTimeField(auto_now = True)
contact = models.ForeignKey(Contact)
item = models.ForeignKey(StorageItem)
status = models.ForeignKey(Status)
user = models.ForeignKey(User)
def __unicode__(self):
return str(self.status)
I want to be able to find the date data using
python manage.py shell
But I want to keep the unicode object as status. Do I use a filter lookup?
A:
Get the object from the django db in the usual way and access foo.name_of_attribute:
The example in the django docs should help, see:
http://docs.djangoproject.com/en/dev/intro/tutorial01/
>>> p = Poll.objects.get(pk=1)
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
And thats a standard python datetime thing.
A:
When returning date to the python shell you could just use
from time import asctime
#print asctime()
| Want to find date data in python shell | I have a model something like this.
#models.py
class ItemStatusHistory(models.Model):
date = models.DateTimeField(auto_now = True)
contact = models.ForeignKey(Contact)
item = models.ForeignKey(StorageItem)
status = models.ForeignKey(Status)
user = models.ForeignKey(User)
def __unicode__(self):
return str(self.status)
I want to be able to find the date data using
python manage.py shell
But I want to keep the unicode object as status. Do I use a filter lookup?
| [
"Get the object from the django db in the usual way and access foo.name_of_attribute:\nThe example in the django docs should help, see:\nhttp://docs.djangoproject.com/en/dev/intro/tutorial01/\n >>> p = Poll.objects.get(pk=1)\n >>> p.pub_date\n datetime.datetime(2007, 7, 15, 12, 00, 53)\n\nAnd thats a standard pytho... | [
1,
0
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0004245243_django_models_python.txt |
Q:
How do I access template cache? - Django
I am caching html within a few templates e.g.:
{% cache 900 stats %}
{{ stats }}
{% endcache %}
Can I access the cache using the low level library? e.g.
html = cache.get('stats')
I really need to have some fine-grained control over the template caching :)
Any ideas? Thanks everyone! :D
A:
This is how I access the template cache in my project:
from django.utils.hashcompat import md5_constructor
from django.utils.http import urlquote
def someView(request):
variables = [var1, var2, var3]
hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))
cache_key = 'template.cache.%s.%s' % ('table', hash.hexdigest())
if cache.has_key(cache_key):
#do some stuff...
The way I use the cache tag, I have:
{% cache TIMEOUT table var1 var2 var3 %}
You probably just need to pass an empty list to variables.
So, yourvariables and cache_key will look like:
variables = []
hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))
cache_key = 'template.cache.%s.%s' % ('stats', hash.hexdigest())
A:
Looking at the code for the cache templatetag, the key is generated like this:
args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())
so you could build something simliar in your view to get the cache directly: in your case, you're not using any vary_on parameters so you could use an empty argument to md5_constructor.
| How do I access template cache? - Django | I am caching html within a few templates e.g.:
{% cache 900 stats %}
{{ stats }}
{% endcache %}
Can I access the cache using the low level library? e.g.
html = cache.get('stats')
I really need to have some fine-grained control over the template caching :)
Any ideas? Thanks everyone! :D
| [
"This is how I access the template cache in my project:\nfrom django.utils.hashcompat import md5_constructor\nfrom django.utils.http import urlquote\n\ndef someView(request):\n variables = [var1, var2, var3] \n hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))\n cache_key = 'template.... | [
6,
2
] | [] | [] | [
"caching",
"django",
"django_cache",
"django_templates",
"python"
] | stackoverflow_0004245081_caching_django_django_cache_django_templates_python.txt |
Q:
How do you write special characters ("\n","\b",...) to a file in Python?
I'm using Python to process some plain text into LaTeX, so I need to be able to write things like \begin{enumerate} or \newcommand to a file. When Python writes this to a file, though, it interprets \b and \n as special characters.
How do I get Python to write \newcommand to a file, instead of writing ewcommand on a new line?
The code is something like this ...
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3, Mac OS 10.5 PPC
A:
One solution is to escape the escape character (\). This will result in a literal backslash before the b character instead of escaping b:
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\\begin{enumerate}[1.]\n")
This will be written to the file as
\begin{enumerate}[1.]<newline>
(I assume that the \n at the end is an intentional newline. If not, use double-escaping here as well: \\n.)
A:
You just need to double the backslash: \\n, \\b. This will escape the backslash. You can also put the r prefix in front of your string: r'\begin'. As detailed here, this will prevent substitutions.
A:
You can also use raw strings:
with open(fileout,'w',encoding='utf-8') as fout:
fout.write(r"\begin{enumerate}[1.]\n")
Note the 'r' before \begin
| How do you write special characters ("\n","\b",...) to a file in Python? | I'm using Python to process some plain text into LaTeX, so I need to be able to write things like \begin{enumerate} or \newcommand to a file. When Python writes this to a file, though, it interprets \b and \n as special characters.
How do I get Python to write \newcommand to a file, instead of writing ewcommand on a new line?
The code is something like this ...
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3, Mac OS 10.5 PPC
| [
"One solution is to escape the escape character (\\). This will result in a literal backslash before the b character instead of escaping b:\nwith open(fileout,'w',encoding='utf-8') as fout:\n fout.write(\"\\\\begin{enumerate}[1.]\\n\")\n\nThis will be written to the file as\n\\begin{enumerate}[1.]<newline>\n\n(I... | [
11,
9,
4
] | [] | [] | [
"latex",
"python"
] | stackoverflow_0004245709_latex_python.txt |
Q:
How can I annotate a class in pypy?
I am using pypy to translate some python script to C language.
Say that I have a python class like this:
class A:
def __init__(self):
self.a = 0
def func(self):
pass
I notice that A.func is a unbound method rather than a function so that it cannot be translated by pypy. So I change the code slightly:
def func(self):
pass
class A:
def __init__(self):
self.a = 0
A.func = func
def target(*args):
return func, None
Now func seems to be able to be translated by pypy. However when I try translate.py --source test.py, an exception [translation:ERROR] TypeError: signature mismatch: func() takes exactly 2 arguments (1 given) is raised. I notice that it might because I haven't annotate self argument yet. However this self have type A, so how can I annotate a class?
Thank you for your reading and answer.
A:
Essentially PyPy's entry point is a function (accepting sys.argv usually as an argument). Whatever this function calls (create objects, call methods) will get annotated. There is no way to annotate a class, since PyPy's compiled code does not export this as API, but rather as a standalone program.
You might want to for example:
def f():
a = A()
a.func()
or even:
a = A()
def f():
a.func()
in which case a is a prebuilt constant.
A:
Are you wanting a staticmethod or a classmethod?
| How can I annotate a class in pypy? | I am using pypy to translate some python script to C language.
Say that I have a python class like this:
class A:
def __init__(self):
self.a = 0
def func(self):
pass
I notice that A.func is a unbound method rather than a function so that it cannot be translated by pypy. So I change the code slightly:
def func(self):
pass
class A:
def __init__(self):
self.a = 0
A.func = func
def target(*args):
return func, None
Now func seems to be able to be translated by pypy. However when I try translate.py --source test.py, an exception [translation:ERROR] TypeError: signature mismatch: func() takes exactly 2 arguments (1 given) is raised. I notice that it might because I haven't annotate self argument yet. However this self have type A, so how can I annotate a class?
Thank you for your reading and answer.
| [
"Essentially PyPy's entry point is a function (accepting sys.argv usually as an argument). Whatever this function calls (create objects, call methods) will get annotated. There is no way to annotate a class, since PyPy's compiled code does not export this as API, but rather as a standalone program.\nYou might want ... | [
5,
1
] | [] | [] | [
"annotate",
"pypy",
"python"
] | stackoverflow_0004241673_annotate_pypy_python.txt |
Q:
Buttons with line breaks don't display properly on Mac OS X
This code works fine in Windows. On Mac OS X it only shows "Multiple" in the button and everything past the newline gets wiped out. I'm running Python 2.6.5 on Mac.
import Tkinter as tk
class App:
def __init__(self, master):
self.a_button = tk.Button(master, text="Multiple\nLines\nOf Text")
self.a_button.pack()
ROOT = tk.Tk()
APP = App(ROOT)
ROOT.mainloop()
A:
Mac native pushbuttons don't let you do that; they have 3 predefined heights for the various control sizes and that's it. Other button styles do support arbitrary dimensions; one option is to use a Tile button instead:
self.a_button = tk.Widget(master, 'ttk::button',
dict(text="Multiple\nLines\nOf Text"))
| Buttons with line breaks don't display properly on Mac OS X | This code works fine in Windows. On Mac OS X it only shows "Multiple" in the button and everything past the newline gets wiped out. I'm running Python 2.6.5 on Mac.
import Tkinter as tk
class App:
def __init__(self, master):
self.a_button = tk.Button(master, text="Multiple\nLines\nOf Text")
self.a_button.pack()
ROOT = tk.Tk()
APP = App(ROOT)
ROOT.mainloop()
| [
"Mac native pushbuttons don't let you do that; they have 3 predefined heights for the various control sizes and that's it. Other button styles do support arbitrary dimensions; one option is to use a Tile button instead:\n self.a_button = tk.Widget(master, 'ttk::button',\n dict(text=\... | [
4
] | [] | [] | [
"button",
"macos",
"python",
"tkinter"
] | stackoverflow_0004244855_button_macos_python_tkinter.txt |
Q:
Question about whether to include something in the __init__() method
I am new to OOP and hence, am looking for suggestions on good practice for coding something where the following issue arises.
I am defining a Seller(a, b, c, d) class. There are many attributes of this class, two of which are, mostRecentProfit and profitHistory. However, values of these two are not known when the class is initialized. Some other steps in the program have to be executed before these are realized. My questions is:
In the __init__(a, b, c, d) of the seller class, should I write
self.mostRecentProfit = None
self.profitHistory = []
or, should I not define these at all in the __init__ method. The reason former appears attractive to me is that by looking at the __init__() method, I can know all the attributes for the class. However, that may not be a good reason for doing this. Any suggestions would be appreciated.
Thank you.
A:
Defining the attributes in __init__() makes the code better for when someone who has not seen the code has to start working with it. It can be confusing when a class starts accessing an attribute that doesn't seem to exist at first.
Also, since one of your default values is a list instead of None, initializing it means you can always treat the attribute as a list and never have to worry about it's state.
A:
I would define them. In my experience, not doing so when the code dealing with the instances makes frequent references to those properties, means you end up forever typing if object.profitHistory: before looping etc. With an empty list there, you can skip those conditions. And as you say, it makes it much more legible.
A:
I would define them all in the __init() method because that would not only document what they all normally were, but if you define their default values to all be something valid, allow most of the rest of your code to easily process instances of the class even if these attributes never get updated.
So, in your example, that would mean initializing self.mostRecentProfit to 0 or perhaps 0.0 rather than None. Doing this would allow it to be used as a number without checking for it's existence with a value not equal to None before each reference to it or wrapping each of them in a try/except block to handle the cases where they were never explicitly set to another value.
| Question about whether to include something in the __init__() method | I am new to OOP and hence, am looking for suggestions on good practice for coding something where the following issue arises.
I am defining a Seller(a, b, c, d) class. There are many attributes of this class, two of which are, mostRecentProfit and profitHistory. However, values of these two are not known when the class is initialized. Some other steps in the program have to be executed before these are realized. My questions is:
In the __init__(a, b, c, d) of the seller class, should I write
self.mostRecentProfit = None
self.profitHistory = []
or, should I not define these at all in the __init__ method. The reason former appears attractive to me is that by looking at the __init__() method, I can know all the attributes for the class. However, that may not be a good reason for doing this. Any suggestions would be appreciated.
Thank you.
| [
"Defining the attributes in __init__() makes the code better for when someone who has not seen the code has to start working with it. It can be confusing when a class starts accessing an attribute that doesn't seem to exist at first.\nAlso, since one of your default values is a list instead of None, initializing it... | [
4,
3,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004245566_oop_python.txt |
Q:
Parsing spanish text and saving it in a db
I'm parsing a web page written in spanish with scrapy. The problem is that I can't save the text because of the wrong encoding.
This is the parse function:
def parse(self, response):
hxs = HtmlXPathSelector(response)
text = hxs.select('//text()').extract() # Ex: [u' Sustancia mineral, m\xe1s o menos dura y compacta, que no es terrosa ni de aspecto met\xe1lico.']
s = "".join(text)
db = dbf.Dbf("test.dbf", new=True)
db.addField(
("WORD", "C", 25),
("DATA", "M", 15000), # Memo field
)
rec = db.newRecord()
rec["WORD"] = "Stone"
rec["DATA"] = s
rec.store()
db.close()
When I try to save it to a db(a dbf db) I get an ASCII(128) error. I tried decoding/encoding using 'utf-8' and 'latin1' but with no success.
Edit:
To save the db I'm using dbfpy. I added the dbf saving code in the parse function above.
This is the error message:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 1179, in mainLoop
self.runUntilCurrent()
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 778, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 280, in callback
self._startRunCallbacks(result)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 354, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 371, in _runCallbacks
self.result = callback(self.result, *args, **kw)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/rae_spider.py", line 54, in parse
rec.store()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 211, in store
self.dbf.append(self)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/dbf.py", line 214, in append
record._write()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 173, in _write
self.dbf.stream.write(self.toString())
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 223, in toString
for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/fields.py", line 215, in encodeValue
return str(value)[:self.length].ljust(self.length)
exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 18: ordinal not in range(128)
A:
Please, don't remember that DBF files don't support unicode at all
and I also suggest to use Ethan Furman's dbf package (link in another answer)
You can use only 'table = dbf.Table('filename') to guess real type.
Example of usage with non cp437 encoding is:
#!/usr/bin/env python
# coding: koi8-r
import dbf
text = 'текст в koi8-r'
table = dbf.Table(':memory:', ['test M'], 128, False, False, True, False, 'dbf', 'koi8-r')
record = table.append()
record.test = text
Please note following information about version 0.87.14 and 'dbf' table type:
With DBF package 0.87.14 you can found exception 'TypeError: ord() excepted character...' at ".../site-packages/dbf/tables.py", line 686
Only 'dbf' table type has affected with this tupo!
DISCLAIMER: I don't know real correct values to use in following values, so don't blame me about incompatibility with this "fix".
You can to replace values '' to '\0' (at least) at lines 490 and 491 to make this test workable.
A:
Looks like http://sourceforge.net/projects/dbfpy is what you are talking about. Whatever gave you the idea that it could handle creating a VFP-compatible DBF file just by throwing Unicode at it? There's no docs worth the description AFAICT and the source simply doesn't contain .encode( and there's no supported way of changing the default "signature" away from 0x03 (very plain dBaseIII dile)/
If you encode your text fields in cp850 or cp437 before you throw them at the dbf it may work, but you'll need to check that you can open the resulting file using VFP and that all your accented Spanish characters are represented properly when you view the text fields on the screen.
If that doesn't work (and even if it does), you should have a look at Ethan Furman's dbf package ... it purports to know all about VFP and language driver IDs and codepages and suchlike.
Update: I see that you have 15000-byte memo field defined. One of us is missing something ... the code that I'm reading says in fields.py about line 330 Note: memos aren't currenly [sic] completely supported followed a bit later by two occurrences of raise NotImplementedError ... back up to line 3: TODO: - make memos work. When I tried the code that you say you used (with plain ASCII data), it raised NotImplementedError from the rec.store(). Have you managed to get it to work at all?
| Parsing spanish text and saving it in a db | I'm parsing a web page written in spanish with scrapy. The problem is that I can't save the text because of the wrong encoding.
This is the parse function:
def parse(self, response):
hxs = HtmlXPathSelector(response)
text = hxs.select('//text()').extract() # Ex: [u' Sustancia mineral, m\xe1s o menos dura y compacta, que no es terrosa ni de aspecto met\xe1lico.']
s = "".join(text)
db = dbf.Dbf("test.dbf", new=True)
db.addField(
("WORD", "C", 25),
("DATA", "M", 15000), # Memo field
)
rec = db.newRecord()
rec["WORD"] = "Stone"
rec["DATA"] = s
rec.store()
db.close()
When I try to save it to a db(a dbf db) I get an ASCII(128) error. I tried decoding/encoding using 'utf-8' and 'latin1' but with no success.
Edit:
To save the db I'm using dbfpy. I added the dbf saving code in the parse function above.
This is the error message:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 1179, in mainLoop
self.runUntilCurrent()
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 778, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 280, in callback
self._startRunCallbacks(result)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 354, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 371, in _runCallbacks
self.result = callback(self.result, *args, **kw)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/rae_spider.py", line 54, in parse
rec.store()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 211, in store
self.dbf.append(self)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/dbf.py", line 214, in append
record._write()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 173, in _write
self.dbf.stream.write(self.toString())
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 223, in toString
for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/fields.py", line 215, in encodeValue
return str(value)[:self.length].ljust(self.length)
exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 18: ordinal not in range(128)
| [
"Please, don't remember that DBF files don't support unicode at all \nand I also suggest to use Ethan Furman's dbf package (link in another answer)\nYou can use only 'table = dbf.Table('filename') to guess real type.\nExample of usage with non cp437 encoding is:\n#!/usr/bin/env python\n# coding: koi8-r\nimport dbf\... | [
1,
0
] | [] | [] | [
"parsing",
"python",
"unicode"
] | stackoverflow_0004175246_parsing_python_unicode.txt |
Q:
python - wx.lib.pubsub.Publisher not working when called from buttons pressed?
I'm implementing a MVC app using wxPyton, and I have an issue with wx.lib.pubsub.Publisher.
I'd like to keep my Controller as separated from my View as possible. For example, I don't want my controller to 'know' the names of the buttons used in the view. On the wxPython example, the controller has to know them, so it can bind actions to them.
class Controller:
...
self.view2.add.Bind(wx.EVT_BUTTON, self.AddMoney)
self.view2.remove.Bind(wx.EVT_BUTTON, self.RemoveMoney)
I thought about 'decoupling' things a bit more, using wx.lib.pubsub.Publisher messages instead:
from wx.lib.pubsub import Publisher as pub
class Controller:
...
pub.subscribe(self.AddMoney, "MONEY ADDED")
pub.subscribe(self.RemoveMoney, "MONEY REMOVED")
The view would bind the controls to an action that would just send the messages.
But alas, it doesn't seem to work. Either the view refuses to send events, or the controller refuses to receive messages from the view. I'm not sure.
Here's a small sample app that illustrates my problem (I've tested it with python 2.6.6 and wxPython 2.8)
import wxversion
wxversion.ensureMinimal('2.8')
import wx
from wx.lib.pubsub import Publisher as pub
class View(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Main View")
self.button = wx.Button(self, -1, "foo?")
self.button.Bind(wx.EVT_BUTTON, self.ChangeFoo)
def ChangeFoo(self, evt):
print('Binding works')
pub.sendMessage("FOO CHANGED")
class Controller:
def __init__(self, app):
self.view = View()
pub.subscribe(self.FooChanged, "FOO CHANGED")
self.view.Show()
def FooChanged(self, message):
print('Messaging works')
app = wx.App(False)
Controller(app)
app.MainLoop()
The app shows a window with a big button. The expected output after pressing it is:
Binding works
Messaging works
But instead I get:
Binding works
Does anyone know how to solve this?
A:
You need to save a reference to your controller otherwise the object gets GC'd and therefore won't exist by the time the message is sent. Change the second-to-last line to:
controller = Controller(app)
| python - wx.lib.pubsub.Publisher not working when called from buttons pressed? | I'm implementing a MVC app using wxPyton, and I have an issue with wx.lib.pubsub.Publisher.
I'd like to keep my Controller as separated from my View as possible. For example, I don't want my controller to 'know' the names of the buttons used in the view. On the wxPython example, the controller has to know them, so it can bind actions to them.
class Controller:
...
self.view2.add.Bind(wx.EVT_BUTTON, self.AddMoney)
self.view2.remove.Bind(wx.EVT_BUTTON, self.RemoveMoney)
I thought about 'decoupling' things a bit more, using wx.lib.pubsub.Publisher messages instead:
from wx.lib.pubsub import Publisher as pub
class Controller:
...
pub.subscribe(self.AddMoney, "MONEY ADDED")
pub.subscribe(self.RemoveMoney, "MONEY REMOVED")
The view would bind the controls to an action that would just send the messages.
But alas, it doesn't seem to work. Either the view refuses to send events, or the controller refuses to receive messages from the view. I'm not sure.
Here's a small sample app that illustrates my problem (I've tested it with python 2.6.6 and wxPython 2.8)
import wxversion
wxversion.ensureMinimal('2.8')
import wx
from wx.lib.pubsub import Publisher as pub
class View(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Main View")
self.button = wx.Button(self, -1, "foo?")
self.button.Bind(wx.EVT_BUTTON, self.ChangeFoo)
def ChangeFoo(self, evt):
print('Binding works')
pub.sendMessage("FOO CHANGED")
class Controller:
def __init__(self, app):
self.view = View()
pub.subscribe(self.FooChanged, "FOO CHANGED")
self.view.Show()
def FooChanged(self, message):
print('Messaging works')
app = wx.App(False)
Controller(app)
app.MainLoop()
The app shows a window with a big button. The expected output after pressing it is:
Binding works
Messaging works
But instead I get:
Binding works
Does anyone know how to solve this?
| [
"You need to save a reference to your controller otherwise the object gets GC'd and therefore won't exist by the time the message is sent. Change the second-to-last line to:\ncontroller = Controller(app)\n\n"
] | [
4
] | [] | [] | [
"messaging",
"python",
"wxpython"
] | stackoverflow_0004245224_messaging_python_wxpython.txt |
Q:
installing libxml2 on python 2.7 windows
I've searched but theres no libxml2 binaries for py2.7.
I have also tried running setup.py for version py2.6.9 but it gave me the error
failed to find headers for libxml2: update includes_dir
Does anyone have a solution?
A:
Some time before I found a good page with prebuilt libraries for different versions of python and arch: http://www.lfd.uci.edu/~gohlke/pythonlibs/
I suspect it will be useful for you.
| installing libxml2 on python 2.7 windows | I've searched but theres no libxml2 binaries for py2.7.
I have also tried running setup.py for version py2.6.9 but it gave me the error
failed to find headers for libxml2: update includes_dir
Does anyone have a solution?
| [
"Some time before I found a good page with prebuilt libraries for different versions of python and arch: http://www.lfd.uci.edu/~gohlke/pythonlibs/ \nI suspect it will be useful for you.\n"
] | [
10
] | [] | [] | [
"libxml2",
"python"
] | stackoverflow_0003520826_libxml2_python.txt |
Q:
Python input string error (don't want to use raw_input)
I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input.
My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any number besides that ones, the else statement says to the user pick a number from 1 to 10.
The problem is if the user types an string, lets say for example qwert. It gives me an error because its an string. I understand why and I don want to use raw_input.
What can I do to wen the user types a string it goes to my else statement and print for example "Only numbers are valid. Pick a number from 1 to 10"
I don't want to use any advanced programing to do this
Regards,
Favolas
EDIT
Thanks for all your answers and sorry for the late response but I had some health problems.
I couldn't use try or except because my teacher didn't allow it.
In the end, I've used raw_input because it was the simplest alternative but was glad to see that are many ways to solve this problem.
Regards,
Favolas
A:
You can throw an exception when you try to convert your string into a number.
Example:
try:
int(myres)
except:
print "Only numbers are valid"
A:
Im not sure what you consider advanced - a simple way to do it would be with something like this.
def getUserInput():
while True:
a = raw_input("Enter a number between 1 and 10: ")
try:
number = int(a)
if (0 < number <= 10):
return number
else:
print "Between 1 and 10 please"
except:
print "Im sorry, please enter a number between 1 and 10"
Here, I have used try/except statements, to ensure that the entered string can be converted to an integer. And a loop (which will keep running) until the entered number is between 1 and 10 (0< number <=10)
A:
You should use raw_input(), even if you don't want to :) This will always give you a string. You can then use code like
s = raw_input()
try:
choice = int(s)
except ValueError:
# choice is invalid...
to try to convert to an int.
A:
What you really are after is how to figure out if something could pass as an integer. The following would do the job:
try:
i = int(string_from_input)
ecxept ValueError:
# actions in case the input is anything other than int, like continuing the loop
A:
You clearly have something against exception handling. I don't understand why -- it's a fundamental part of (not just Python) programming and something you should be comfortable with. It's no more 'advanced' than handling error codes, just a different mentality.
Here are the docs. It's pretty simple:
It is possible to write programs that
handle selected exceptions. Look at
the following example, which asks the
user for input until a valid integer
has been entered, but allows the user
to interrupt the program (using
Control-C or whatever the operating
system supports); note that a
user-generated interruption is
signalled by raising the
KeyboardInterrupt exception.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
The try statement works as follows.
First, the try clause (the
statement(s) between the try and
except keywords) is executed. If no
exception occurs, the except clause is
skipped and execution of the try
statement is finished. If an exception
occurs during execution of the try
clause, the rest of the clause is
skipped. Then if its type matches the
exception named after the except
keyword, the except clause is
executed, and then execution continues
after the try statement. If an
exception occurs which does not match
the exception named in the except
clause, it is passed on to outer try
statements; if no handler is found, it
is an unhandled exception and
execution stops with a message as
shown above. A try statement may have
more than one except clause, to
specify handlers for different
exceptions. At most one handler will
be executed. Handlers only handle
exceptions that occur in the
corresponding try clause, not in other
handlers of the same try statement. An
except clause may name multiple
exceptions as a parenthesized tuple,
for example:
... except (RuntimeError, TypeError, NameError):
... pass
The last except clause may omit the
exception name(s), to serve as a
wildcard. Use this with extreme
caution, since it is easy to mask a
real programming error in this way! It
can also be used to print an error
message and then re-raise the
exception (allowing a caller to handle
the exception as well):
A:
Personally, I liked my first answer better. However, this one should fit your requirements with more code.
import sys
def get_number(a, z):
if a > z:
a, z = z, a
while True:
line = get_line('Please enter a number: ')
if line is None:
sys.exit()
if line:
number = str_to_int(line)
if number is None:
print('You must enter base 10 digits.')
elif a <= number <= z:
return number
else:
print('Your number must be in this range:', a, '-', z)
else:
print('You must enter a number.')
def get_line(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()
if line:
return line[:-1]
def str_to_int(string):
zero = ord('0')
integer = 0
for character in string:
if '0' <= character <= '9':
integer *= 10
integer += ord(character) - zero
else:
return
return integer
A:
May I recommend using this function in Python 3.1? The two arguments are the expected number range.
def get_number(a, z):
if a > z:
a, z = z, a
while True:
try:
line = input('Please enter a number: ')
except EOFError:
raise SystemExit()
else:
if line:
try:
number = int(line)
assert a <= number <= z
except ValueError:
print('You must enter base 10 digits.')
except AssertionError:
print('Your number must be in this range:', a, '-', z)
else:
return number
else:
print('You must enter a number.')
| Python input string error (don't want to use raw_input) | I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input.
My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any number besides that ones, the else statement says to the user pick a number from 1 to 10.
The problem is if the user types an string, lets say for example qwert. It gives me an error because its an string. I understand why and I don want to use raw_input.
What can I do to wen the user types a string it goes to my else statement and print for example "Only numbers are valid. Pick a number from 1 to 10"
I don't want to use any advanced programing to do this
Regards,
Favolas
EDIT
Thanks for all your answers and sorry for the late response but I had some health problems.
I couldn't use try or except because my teacher didn't allow it.
In the end, I've used raw_input because it was the simplest alternative but was glad to see that are many ways to solve this problem.
Regards,
Favolas
| [
"You can throw an exception when you try to convert your string into a number.\nExample:\ntry:\n int(myres)\nexcept:\n print \"Only numbers are valid\"\n\n",
"Im not sure what you consider advanced - a simple way to do it would be with something like this.\ndef getUserInput():\n while True:\n a = ra... | [
5,
4,
4,
3,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004245637_python.txt |
Q:
How to increase the font size of a Text widget?
How to increase the font size of a Text widget?
A:
There are several ways to specify a font: the simplest is a tuple of the form (family, size, style).
import Tkinter as tk
root=tk.Tk()
text=tk.Text(width = 40, height=4, font=("Helvetica", 32))
text.pack()
root.mainloop()
| How to increase the font size of a Text widget? | How to increase the font size of a Text widget?
| [
"There are several ways to specify a font: the simplest is a tuple of the form (family, size, style).\nimport Tkinter as tk\n\nroot=tk.Tk()\ntext=tk.Text(width = 40, height=4, font=(\"Helvetica\", 32))\ntext.pack() \nroot.mainloop()\n\n"
] | [
21
] | [] | [] | [
"block",
"font_size",
"python",
"textbox",
"tkinter"
] | stackoverflow_0004246353_block_font_size_python_textbox_tkinter.txt |
Q:
python function call syntax ... result = foo() ['abc']
number = droid.readPhoneState()['result']['incomingNumber']
What are 'result' and 'incomingNumber' in this syntax -- are they not parameters?
How are they related to the function readPhoneState?
import android
droid = android.Android()
droid.startTrackingPhoneState()
number = droid.readPhoneState()['result']['incomingNumber']
if number != None:
droid.speak('Call from '+str(number))
else:
droid.makeToast('No incoming call')
A:
droid.readPhoneState() returns a dict of dicts. Equivalent code:
outerDict = droid.readPhoneState()
innerDict = outerDict['result']
number = innerDict['incomingNumber']
A:
result and incomingNumber are keys to a dictionary or an instance of a class that implements method __getitem__. This means that readPhoneState() returns a dictionary object, which supposed to have a key result and the corresponding value is a dictionary object which supposed to have a key incomingNumber.
A:
the interpretation is that droid.readPhoneState() returns a dict, whose value corresponding to the key 'result' is another dict.
A:
readPhoneState() is the method and it returns a dictionary object.
The dictionary object contains the property result which is also a dictionary object containing the property incomingNumber
A:
Supposedly, readPhoneState() returns a dictionary where values are, again, dictionaries.
With this syntax, you get the dictionary - returned by readPhoneState() - associated with key 'result' and ask it for the value whose key is 'incomingNumber'.
| python function call syntax ... result = foo() ['abc'] | number = droid.readPhoneState()['result']['incomingNumber']
What are 'result' and 'incomingNumber' in this syntax -- are they not parameters?
How are they related to the function readPhoneState?
import android
droid = android.Android()
droid.startTrackingPhoneState()
number = droid.readPhoneState()['result']['incomingNumber']
if number != None:
droid.speak('Call from '+str(number))
else:
droid.makeToast('No incoming call')
| [
"droid.readPhoneState() returns a dict of dicts. Equivalent code:\nouterDict = droid.readPhoneState()\ninnerDict = outerDict['result']\nnumber = innerDict['incomingNumber']\n\n",
"result and incomingNumber are keys to a dictionary or an instance of a class that implements method __getitem__. This means that readP... | [
9,
2,
1,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0004246535_python_syntax.txt |
Q:
ICMP Ping packet is not generating a reply when using Scapy
I recently began exploring Scapy. A wonderful tool indeed!
I have a problem... When I monitor my network card using Wireshark and I do a regular ping from the systems command prompt with the standard PING installation, wireshark pops up with "Ping request" and then "Ping reply" indication that it sent a reply. But when i do it manually in Scapy, it sends no reply back.. How can this be? I spent alot of time trying to figure this out so i really hope someone can shed some light on this issue of mine...
Here is the code i used:
>>> from scapy.all import IP, ICMP, send
>>> IP = IP(dst="127.0.0.1")
>>> Ping = ICMP()
>>> send(IP/Ping)
The packet is sent successfully and Wireshark shows a Ping request received, but not that it has sent a reply back.
A:
This is an FAQ item:
I can't ping 127.0.0.1. Scapy does not work with 127.0.0.1 or on the loopback interface
The loopback interface is a very special interface. Packets going through it are not really assembled and dissassembled. The kernel routes the packet to its destination while it is still stored an internal structure. What you see with tcpdump -i lo is only a fake to make you think everything is normal. The kernel is not aware of what Scapy is doing behind his back, so what you see on the loopback interface is also a fake. Except this one did not come from a local structure. Thus the kernel will never receive it.
In order to speak to local applications, you need to build your packets one layer upper, using a PF_INET/SOCK_RAW socket instead of a PF_PACKET/SOCK_RAW (or its equivalent on other systems that Linux) :
>>> conf.L3socket
<class __main__.L3PacketSocket at 0xb7bdf5fc>
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
<IP version=4L ihl=5L tos=0x0 len=28 id=40953 flags= frag=0L ttl=64 proto=ICMP chksum=0xdce5 src=127.0.0.1 dst=127.0.0.1 options='' |<ICMP type=echo-reply code=0 chksum=0xffff id=0x0 seq=0x0 |>>
A:
Try this
def ping(host, repeat=3):
packet = IP(dst=host)/ICMP()
for x in range(repeat):
response = sr1(packet)
response.show2()
Your not storing the reply properly
| ICMP Ping packet is not generating a reply when using Scapy | I recently began exploring Scapy. A wonderful tool indeed!
I have a problem... When I monitor my network card using Wireshark and I do a regular ping from the systems command prompt with the standard PING installation, wireshark pops up with "Ping request" and then "Ping reply" indication that it sent a reply. But when i do it manually in Scapy, it sends no reply back.. How can this be? I spent alot of time trying to figure this out so i really hope someone can shed some light on this issue of mine...
Here is the code i used:
>>> from scapy.all import IP, ICMP, send
>>> IP = IP(dst="127.0.0.1")
>>> Ping = ICMP()
>>> send(IP/Ping)
The packet is sent successfully and Wireshark shows a Ping request received, but not that it has sent a reply back.
| [
"This is an FAQ item:\n\nI can't ping 127.0.0.1. Scapy does not work with 127.0.0.1 or on the loopback interface\nThe loopback interface is a very special interface. Packets going through it are not really assembled and dissassembled. The kernel routes the packet to its destination while it is still stored an inter... | [
8,
0
] | [] | [] | [
"ping",
"python",
"scapy"
] | stackoverflow_0004245810_ping_python_scapy.txt |
Q:
Python "map or" on elements in list
What's the most elegant way of doing something like this:
>>> tests = [false, false, false]
>>> map_or(test)
false
>>> tests = [true, false, false]
>>> map_or(test)
true
The map_or function should return true if one or more of list elements are true.
A:
Use any(). It is a built-in function that just does what you want.
A:
any(tests)
Built in function :)
A:
any(tests)
(and the rest of this is padding because yet again StackOverflow treats users like idiots and sets minimum answer lengths)
| Python "map or" on elements in list | What's the most elegant way of doing something like this:
>>> tests = [false, false, false]
>>> map_or(test)
false
>>> tests = [true, false, false]
>>> map_or(test)
true
The map_or function should return true if one or more of list elements are true.
| [
"Use any(). It is a built-in function that just does what you want.\n",
"any(tests)\n\nBuilt in function :)\n",
"any(tests)\n\n(and the rest of this is padding because yet again StackOverflow treats users like idiots and sets minimum answer lengths)\n"
] | [
9,
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0004246984_python.txt |
Q:
Having a console in a single-threaded Python script
I would like to have an interactive console in a single-threaded script that has several TCP connections open. This means I can't just have a standard input blocking the thread.
Is there an easy way to do this? Or should I just put the console in its own thread and be done with it?
A:
You can subclass InteractiveConsole (from the builtin 'code' module) and
override the push() method with a wrapper that redirects stdout/stderr
to a StringIO instance before forwarding to the base
InteractiveConsole's push() method. Your wrapper can return a 2-tuple
(more, result) where 'more' indicates whether InteractiveConsole expects
more input, and 'result' is whatever InteractiveConsole.push() wrote to
your StringIO instance.
It sounds harder than it is. Here's the basic premise:
import sys
from cStringIO import StringIO
from code import InteractiveConsole
from contextlib import contextmanager
__all__ = ['Interpreter']
@contextmanager
def std_redirector(stdin=sys.stdin, stdout=sys.stdin, stderr=sys.stderr):
"""Temporarily redirect stdin/stdout/stderr"""
tmp_fds = stdin, stdout, stderr
orig_fds = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = tmp_fds
yield
sys.stdin, sys.stdout, sys.stderr = orig_fds
class Interpreter(InteractiveConsole):
"""Remote-friendly InteractiveConsole subclass
This class behaves just like InteractiveConsole, except that it
returns all output as a string rather than emitting to stdout/stderr
"""
banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
'Type "help", "copyright", "credits" or "license" '
'for more information.\n')
ps1 = getattr(sys, "ps1", ">>> ")
ps2 = getattr(sys, "ps2", "... ")
def __init__(self, locals=None):
InteractiveConsole.__init__(self, locals=locals)
self.output = StringIO()
self.output = StringIO()
def push(self, command):
"""Return the result of executing `command`
This function temporarily redirects stdout/stderr and then simply
forwards to the base class's push() method. It returns a 2-tuple
(more, result) where `more` is a boolean indicating whether the
interpreter expects more input [similar to the base class push()], and
`result` is the captured output (if any) from running `command`.
"""
self.output.reset()
self.output.truncate()
with std_redirector(stdout=self.output, stderr=self.output):
try:
more = InteractiveConsole.push(self, command)
result = self.output.getvalue()
except (SyntaxError, OverflowError):
pass
return more, result
Check out this complete example, which accepts input from a UDP socket:
http://files.evadeflow.com/pyrrepl.zip
Start two consoles and run server.py in one, client.py in the other.
What you see in client.py should be indistinguishable from python's
regular interactive interpreter, even though all commands are being
round-tripped to server.py for evaluation.
Of course, using sockets like this is terribly insecure, but it
illustrates how to evaluate an external input asynchronously. You
should be able to adapt it to your situation, as long as you trust the
input source. Things get 'interesting' when someone types:
while True: continue
But that's another problem entirely... :-)
A:
Either single-threaded or multi-threaded will do, but if you choose not to use threads, you will need to use polling (in C this may be done using poll(2), for example) and check for whether the console and/or the TCP connections have input ready.
| Having a console in a single-threaded Python script | I would like to have an interactive console in a single-threaded script that has several TCP connections open. This means I can't just have a standard input blocking the thread.
Is there an easy way to do this? Or should I just put the console in its own thread and be done with it?
| [
"You can subclass InteractiveConsole (from the builtin 'code' module) and\noverride the push() method with a wrapper that redirects stdout/stderr\nto a StringIO instance before forwarding to the base\nInteractiveConsole's push() method. Your wrapper can return a 2-tuple\n(more, result) where 'more' indicates wheth... | [
3,
0
] | [] | [] | [
"console",
"interactive",
"multithreading",
"python"
] | stackoverflow_0004241234_console_interactive_multithreading_python.txt |
Q:
Python keeping newlines in lxml.html after cssselect and text_content()
In python, How do I preserve paragraphs (i.e. keep newlines) when using lxml.html?
For example, the following will strip <p></p> tags and join the lines, which is not what I want:
body = doc.cssselect("div.body")[0]
content = body.text_content()
Here's what I've tried that doesn't work:
lxml.html.clean.clean_html:
Won't preserve the newlines.
content.replace(" "*3,"\n\n"):
Doesn't work consistently, because
combined text does not have the same
number of spaces.
A:
The lxml text_content is doing what is supposed to according to the docs, it is stripping the html tags and leaving the text behind.
You can fix this up by adding your own newlines before outputting the content.
body = doc.cssselect("div.body")[0]
for para in body.xpath("*//p"):
para.text = "\n%s\n" % para.text
content = body.text_content()
print content
| Python keeping newlines in lxml.html after cssselect and text_content() | In python, How do I preserve paragraphs (i.e. keep newlines) when using lxml.html?
For example, the following will strip <p></p> tags and join the lines, which is not what I want:
body = doc.cssselect("div.body")[0]
content = body.text_content()
Here's what I've tried that doesn't work:
lxml.html.clean.clean_html:
Won't preserve the newlines.
content.replace(" "*3,"\n\n"):
Doesn't work consistently, because
combined text does not have the same
number of spaces.
| [
"The lxml text_content is doing what is supposed to according to the docs, it is stripping the html tags and leaving the text behind.\nYou can fix this up by adding your own newlines before outputting the content.\nbody = doc.cssselect(\"div.body\")[0]\nfor para in body.xpath(\"*//p\"):\n para.text = \"\\n%s\\n\... | [
2
] | [] | [] | [
"html_parsing",
"lxml",
"newline",
"python"
] | stackoverflow_0004242712_html_parsing_lxml_newline_python.txt |
Q:
is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc?
is there any efficient and easy way to execute statements similar to:
CREATE TABLE IF NOT EXISTS fubar ( id int, name varchar(80))
for columns as you perform insert statements.
I'd imagine it will be a lot more complicated, but just for the sake of explanation, i guess I'm looking for something like....
IF NOT EXISTS
(
SELECT * FROM information_schema.COLUMNS
WHERE
COLUMN_NAME='new_column' AND
TABLE_NAME='the_table' AND
TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` bigint(20) unsigned NOT NULL default 1;
alternatively, is there a way a python library that might handle the process?
basically, i want the 'id's' of a 'dictionary' to define the columns, and create them if they do not already exist.
i also would like the database to stay reasonably efficient, so i guess some dynamic handling of the type of data would also be necessary?
just wondering if anything like this exists at the moment, and if not looking for advice on how best to achieve it....
A:
I believe that you're looking for an Object Relational Mapping system.
For Python there are a couple available:
SQLAlchemy: http://www.sqlalchemy.org/
SQLObject: http://sqlobject.org/
Or if you're building a website, the Django project includes an ORM system: http://www.djangoproject.com/
To simplify the process, you can add something like Elixir on top of SQLAlchemy: http://elixir.ematia.de/trac/wiki
You would get code like this:
class Movie(Entity):
title = Field(Unicode(30))
year = Field(Integer)
description = Field(UnicodeText)
This is how to insert:
>>> Movie(title=u"Blade Runner", year=1982)
<Movie "Blade Runner" (1982)>
>>> session.commit()
Or fetch the results:
>>> Movie.query.all()
[<Movie "Blade Runner" (1982)>]
| is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc? | is there any efficient and easy way to execute statements similar to:
CREATE TABLE IF NOT EXISTS fubar ( id int, name varchar(80))
for columns as you perform insert statements.
I'd imagine it will be a lot more complicated, but just for the sake of explanation, i guess I'm looking for something like....
IF NOT EXISTS
(
SELECT * FROM information_schema.COLUMNS
WHERE
COLUMN_NAME='new_column' AND
TABLE_NAME='the_table' AND
TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` bigint(20) unsigned NOT NULL default 1;
alternatively, is there a way a python library that might handle the process?
basically, i want the 'id's' of a 'dictionary' to define the columns, and create them if they do not already exist.
i also would like the database to stay reasonably efficient, so i guess some dynamic handling of the type of data would also be necessary?
just wondering if anything like this exists at the moment, and if not looking for advice on how best to achieve it....
| [
"I believe that you're looking for an Object Relational Mapping system.\nFor Python there are a couple available:\n\nSQLAlchemy: http://www.sqlalchemy.org/\nSQLObject: http://sqlobject.org/\n\nOr if you're building a website, the Django project includes an ORM system: http://www.djangoproject.com/\nTo simplify the ... | [
2
] | [] | [] | [
"dynamic",
"mysql",
"python"
] | stackoverflow_0004246876_dynamic_mysql_python.txt |
Q:
how do i insert inputs to find value of integrals in python?
I am working a physics coursework, and I am currently stuck at this section.
I've trying but I couldn't get it right.
Really need help here.
Its about the trapezium rule,
Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^2)
this is the code I've tried, but I can not get the answer
from math import *
def f(x):
f(x)=x**4*(1-x)**4/(1+x**2)
return f(x)
def trap0 (f,a,b,n):
h= float (b-a)/n
s =0.5*( f(a)+f(b))
for i in range (1,n):
s=s+f(a+i*h)
return s*h
A:
Your definition of f is bogus. This is all you need to write:
def f(x):
return x**4 * (1 - x)**4 / (1 + x**2)
The rest of your code looks good to me, so long as you call trap0 with floating-point arguments for a and b.
>>> trap0(math.cos, 0.0, math.pi/2, 100)
0.99997943823960744
If you want to call it with integer a and b then things can go wrong, because f ends up doing integer division instead of floating-point division:
>>> f(4.0)
1219.7647058823529
>>> f(4)
1219
The easiest fix to is to coerce the division to be floating-point, perhaps like this:
def g(x):
return x**4 * (1 - x)**4 / (1.0 + x**2)
>>> g(4.0) == g(4)
True
A:
from math import *
Is considered incorrect when doing imports. Granted this is just a ten minute wonder, this style of imports are frowned upon as they clutter namespaces and overwrite local variables if they are also assigned in the module or your source.
Considering you used ** over pow() means that you don't actually need the math import to begin with. But if you are on python 2.x you might want to use.
from __future__ import division
Gareth has the right answer for the function though im just complaining about style issues
| how do i insert inputs to find value of integrals in python? | I am working a physics coursework, and I am currently stuck at this section.
I've trying but I couldn't get it right.
Really need help here.
Its about the trapezium rule,
Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^2)
this is the code I've tried, but I can not get the answer
from math import *
def f(x):
f(x)=x**4*(1-x)**4/(1+x**2)
return f(x)
def trap0 (f,a,b,n):
h= float (b-a)/n
s =0.5*( f(a)+f(b))
for i in range (1,n):
s=s+f(a+i*h)
return s*h
| [
"Your definition of f is bogus. This is all you need to write:\ndef f(x):\n return x**4 * (1 - x)**4 / (1 + x**2)\n\nThe rest of your code looks good to me, so long as you call trap0 with floating-point arguments for a and b.\n>>> trap0(math.cos, 0.0, math.pi/2, 100)\n0.99997943823960744\n\nIf you want to call i... | [
2,
0
] | [] | [] | [
"input",
"integral",
"python"
] | stackoverflow_0004247380_input_integral_python.txt |
Q:
Python "join" function like unix "join"
I am curious if there is a built-in python join function like the unix version (see http://linux.about.com/library/cmd/blcmdl_join.htm https://www.man7.org/linux/man-pages/man1/join.1.html). I know the functionality is included through the built in sqlite3 module and probably through some other modules like pytables.
Sorry if this is a basic question, but I'm finding that searching for "python join" and related queries is fairly polluted by the standard python join function. Also, if there is no such functionality, I would not expect to find that information so easily.
A:
Here's a python version of the join function, does not handle all of the potential error cases. But demonstrates the basic idea.
# usage join(open('f1.txt'), open('f2.txt'))
def join(fd_a, fd_b) :
result = []
la = fd_a.readline()
lb = fd_b.readline()
while la and lb :
start_a, rest_a = la.split(' ', 1)
start_b, rest_b = lb.split(' ', 1)
if cmp(start_a, start_b) == 0 :
result.append([start_a, [rest_a, rest_b]])
la = fd_a.readline()
lb = fd_b.readline()
elif cmp(start_a, start_b) < 0 :
la = fd_a.readline()
else :
lb = fd_b.readline()
return result
A:
You can easily simulate a join using dictionaries:
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
print dict((key, (d1[key], d2[key])) for key in d1 if key in d2)
{'b': (2, 3)}
Or, the last line in Python 3.x:
print {key: (d1[key], d2[key]) for key in d1.keys() & d2.keys()}
{'b': (2, 3)}
(The 2.x line also works in Python 3.x, but the use of & to get the intersection of the dictionary keys may speed things up if only a small percentage of the keys of d1 are in the intersection.)
I don't know of a built-in to do this in a single function call.
A:
No.
If you are running Python on Unix, you can run the command externally using the subprocess module.
| Python "join" function like unix "join" | I am curious if there is a built-in python join function like the unix version (see http://linux.about.com/library/cmd/blcmdl_join.htm https://www.man7.org/linux/man-pages/man1/join.1.html). I know the functionality is included through the built in sqlite3 module and probably through some other modules like pytables.
Sorry if this is a basic question, but I'm finding that searching for "python join" and related queries is fairly polluted by the standard python join function. Also, if there is no such functionality, I would not expect to find that information so easily.
| [
"Here's a python version of the join function, does not handle all of the potential error cases. But demonstrates the basic idea.\n# usage join(open('f1.txt'), open('f2.txt'))\n\ndef join(fd_a, fd_b) :\n result = []\n la = fd_a.readline()\n lb = fd_b.readline()\n while la and lb :\n start_a, res... | [
6,
4,
1
] | [] | [] | [
"join",
"python"
] | stackoverflow_0004247792_join_python.txt |
Q:
Returning random element from a Python array based on search criteria
Apologies if this is straightforward, but I've been looking for a little while now and can't find a simple, efficient solution.
I have a two-dimensional Python list of lists which only consists of 1's and 0's.
e.g.:
a=[[0,1,0],[0,1,1],[1,0,1]]
I wish to return, at random, the indices of a random element which is = 1. In this case I would like to return either:
[0,1], [1,1], [1,2], [2,0], or [2,2]
with an equal probability.
I could iterate through every element in the structure and compile a list of eligible indices and then choose one at random using random.choice(list) - but this seems very slow and I can't help feeling there is a neater, more Pythonic way to approach this. I will be doing this for probably a 20x20 array and will need to do it many times, so I could do with it being as efficient as possible.
Thanks in advance for any help and advice!
A:
I'd use a list comprehension to generate a list of tuples (positions of 1), then random.choice :
from random import choice
a = [[0,1,0],[0,1,1],[1,0,1]]
mylist = []
[[mylist.append((i,j)) for j, x in enumerate(v) if x == 1] for i, v in enumerate(a)]
print(choice(mylist))
A:
I would use a NumPy array to achieve this:
from numpy import array
random_index = tuple(random.choice(array(array(a).nonzero()).T))
If your store your data in NumPy arrays right from the beginning, this approach will probably be faster than anything you can do with a list of lists.
If you want do choose many indices for the same data, there are even faster approaches.
A:
random.choice allow us to pick an element at random from a list, so we just need to use a list comprehension to create a list of the indexes where the elements are 1 and then pick one at random.
We can use the follow list comprehension:
>>> a = [[0,1,0],[0,1,1],[1,0,1]]
>>> [(x,y) for x in range(len(a)) for y in range(len(a[x])) if a[x][y] == 1]
[(0, 1), (1, 1), (1, 2), (2, 0), (2, 2)]
Which means we can do:
>>> import random
>>> random.choice([(x,y) for x in range(len(a)) for y in range(len(a[x])) if a[x][y] == 1])
(1, 1)
If you will be doing this many times it may be worth caching the list of indexes generated by the comprehension and then picking from it several times, rather than calculating the list comprehension every single time.
A:
When you get your result from random.choice check if it is how you would like it with the correct elements if it is not random again
def return_random(li):
item = random.choice(li)
if item == 1: #insert check here
return item
else:
return_random(li)
Edit: to avoid confusion with re module, thanks
A:
Another idea would be to store the data in a completely different way: Instead of a list of lists, use a set of index pairs representing the entries that are 1. In your example, this would be
s = set((0, 1), (1, 1), (1, 2), (2, 0), (2, 2))
To randomly choose an index pair, use
random.choice(list(s))
To set an entry to 1, use
s.add((i, j))
To set an entry to 0, use
s.remove((i, j))
To flip an entry, use
s.symmetric_difference_update([(i, j)])
To check if an entry is 1, use
(i, j) in s
| Returning random element from a Python array based on search criteria | Apologies if this is straightforward, but I've been looking for a little while now and can't find a simple, efficient solution.
I have a two-dimensional Python list of lists which only consists of 1's and 0's.
e.g.:
a=[[0,1,0],[0,1,1],[1,0,1]]
I wish to return, at random, the indices of a random element which is = 1. In this case I would like to return either:
[0,1], [1,1], [1,2], [2,0], or [2,2]
with an equal probability.
I could iterate through every element in the structure and compile a list of eligible indices and then choose one at random using random.choice(list) - but this seems very slow and I can't help feeling there is a neater, more Pythonic way to approach this. I will be doing this for probably a 20x20 array and will need to do it many times, so I could do with it being as efficient as possible.
Thanks in advance for any help and advice!
| [
"I'd use a list comprehension to generate a list of tuples (positions of 1), then random.choice :\nfrom random import choice\n\na = [[0,1,0],[0,1,1],[1,0,1]]\nmylist = []\n\n[[mylist.append((i,j)) for j, x in enumerate(v) if x == 1] for i, v in enumerate(a)]\nprint(choice(mylist))\n\n",
"I would use a NumPy array... | [
2,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"indices",
"python",
"search"
] | stackoverflow_0004247983_arrays_indices_python_search.txt |
Q:
Python Thread not returning the value
Using: Django with Python
Overall objective: Call a function which processes video conversion (internally makes a curl command to the media server) and should immediately return back to the user.
Using message queue would be an overkill for the app.
So I had decided to use threads, I have written a class which overwrites the init and run method and calls the curl command
class process_video(Thread):
def __init__ (self,video_id,video_title,fileURI):
Thread.__init__(self)
self.video_id = video_id
self.video_title = video_title
self.fileURI = fileURI
self.status =-1
def run(self):
logging.debug("FileURi" + self.fileURI)
curlCmd = "curl --data-urlencode \"fileURI=%s\" %s/finalize"% (self.fileURI, settings.MEDIA_ROOT)
logging.debug("Command to be executed" + str(curlCmd))
#p = subprocess.call(str(curlCmd), shell=True)
output_media_server,error = subprocess.Popen(curlCmd,stdout = subprocess.PIPE).communicate()
logging.debug("value returned from media server:")
logging.debug(output_media_server)
And I instantiate this class from another function called createVideo
which calls like this success = process_video(video_id, video_title, fileURI)
Problem:
The user gets redirected back to the other view from the createVideo and the processVideo gets called, however for some reason the created thread (process_video) doesn't wait for the output from the media server.
A:
I wouldn't rely on threads being executed correctly within web applications. Depending on the web server's MPM, the process that executes the request might get killed after a request is done (I guess).
I'd recommend to make the media server request synchronously but let the media server return immediately after it started the encoding without problems (if you have control over its source code). Then a background process (or cron) could poll for the result regularly. This is only one solution - you should provide more information about your infrastructure (e.g. do you control the media server?).
Also check the duplicates in another question's comments for some answers about using task queues in such a scenario.
BTW I assume that no exception occurs in the background thread?!
A:
Here is the thing what I did for getting around the issue which I was facing.
I used django piston to create an API for calling the processvideo with the parameters passed as GET, I was getting a 403 CSRF error when I was trying to send the parameters as POST.
and from the createVideo function I was calling the API like this
cmd = "curl \"%s/api/process_video/?video_id=%s&fileURI=%s&video_title=%s\" > /dev/null 2>&1 &" %(settings.SITE_URL, str(video_id),urllib.quote(fileURI),urllib.quote(video_title))
and this worked.
I feel it would have been helpful if I could have got the session_id and post parameters to work. Not sure how I could get off that csrf thing to work.
| Python Thread not returning the value | Using: Django with Python
Overall objective: Call a function which processes video conversion (internally makes a curl command to the media server) and should immediately return back to the user.
Using message queue would be an overkill for the app.
So I had decided to use threads, I have written a class which overwrites the init and run method and calls the curl command
class process_video(Thread):
def __init__ (self,video_id,video_title,fileURI):
Thread.__init__(self)
self.video_id = video_id
self.video_title = video_title
self.fileURI = fileURI
self.status =-1
def run(self):
logging.debug("FileURi" + self.fileURI)
curlCmd = "curl --data-urlencode \"fileURI=%s\" %s/finalize"% (self.fileURI, settings.MEDIA_ROOT)
logging.debug("Command to be executed" + str(curlCmd))
#p = subprocess.call(str(curlCmd), shell=True)
output_media_server,error = subprocess.Popen(curlCmd,stdout = subprocess.PIPE).communicate()
logging.debug("value returned from media server:")
logging.debug(output_media_server)
And I instantiate this class from another function called createVideo
which calls like this success = process_video(video_id, video_title, fileURI)
Problem:
The user gets redirected back to the other view from the createVideo and the processVideo gets called, however for some reason the created thread (process_video) doesn't wait for the output from the media server.
| [
"I wouldn't rely on threads being executed correctly within web applications. Depending on the web server's MPM, the process that executes the request might get killed after a request is done (I guess).\nI'd recommend to make the media server request synchronously but let the media server return immediately after i... | [
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004242770_django_django_views_python.txt |
Q:
How to exclude comment lines when searching with regular expression?
Need to exclude blocks that are located with a regular expression when preceded with # and any number of spaces. Here is a example file
&START A=23 ... more data ...
B=24 &END
# &START A=34 ... more data ...
B=24 &END
&START .... block 3 of data across multiple lines .... &END
&START .... block 4 of data across multiple lines .... &END
The following regular expression does not exclude the commented entry as I expected -
(?!#\s*)&START(.+?)&END
The desire is to walk through the entries and the file for processing. Python code to do this (which works well other than comment lines making it through) -
f=open(filename)
data=f.read()
f.close()
pattern=re.compiler(r'(?!#\s*)&START(.+?)&END, re.DOTALL)
get_entries = pattern.findall
for entry in get_entries(data):
# process the entry
print entry
Likely a basic oversight as I am green when it comes to regular expressions. Many thanks for anyone who can make a suggestion.
A:
Skip the line altogether.
if line.lstrip().startswith('#'):
continue
A:
This seems to work:
import re
target="""
&START A=23 ... more data ...
B=24 &END
# &START A=C34 ... more data ...
B=C24 &END
&START .... block 3 of data across multiple lines .... &END
&START .... block 4 of data across multiple lines .... &END
"""
regex = re.compile("^(?!#)&START (.*?)&END",re.MULTILINE|re.DOTALL)
for s in regex.findall(target):
print s
Returns:
A=23 ... more data ...
B=24
.... block 3 of data across multiple lines ....
.... block 4 of data across multiple lines ....
A:
This is best worked into a generator.
Using the (m) multiline tag will allow it to search the next line till it finds your end tag.
| How to exclude comment lines when searching with regular expression? | Need to exclude blocks that are located with a regular expression when preceded with # and any number of spaces. Here is a example file
&START A=23 ... more data ...
B=24 &END
# &START A=34 ... more data ...
B=24 &END
&START .... block 3 of data across multiple lines .... &END
&START .... block 4 of data across multiple lines .... &END
The following regular expression does not exclude the commented entry as I expected -
(?!#\s*)&START(.+?)&END
The desire is to walk through the entries and the file for processing. Python code to do this (which works well other than comment lines making it through) -
f=open(filename)
data=f.read()
f.close()
pattern=re.compiler(r'(?!#\s*)&START(.+?)&END, re.DOTALL)
get_entries = pattern.findall
for entry in get_entries(data):
# process the entry
print entry
Likely a basic oversight as I am green when it comes to regular expressions. Many thanks for anyone who can make a suggestion.
| [
"Skip the line altogether.\nif line.lstrip().startswith('#'):\n continue\n\n",
"This seems to work:\nimport re\n\ntarget=\"\"\"\n&START A=23 ... more data ...\n B=24 &END\n# &START A=C34 ... more data ...\n B=C24 &END\n&START .... block 3 of data across multiple ... | [
6,
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004248010_python_string.txt |
Q:
Error with new version
I have Arch linux and recently it's python packages was upgraded to the 3rd branch. Now I'm not able to run selenium-python bindings. When I run it (even with old-python version) I get:
from selenium import selenium
File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/selenium/__init__.py", line 23, in <module>
from selenium.selenium import selenium
File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/selenium/selenium/selenium.py", line 193
raise Exception, result
What could it be? (Btw, looks like my selenium was built with 2.6 python).
UPD I tried to get selenium again but:
easy_install-2.7 selenium
install_dir /usr/lib/python2.7/site-packages/
Searching for selenium
Best match: selenium 2.0a5
Processing selenium-2.0a5-py2.7.egg
selenium 2.0a5 is already the active version in easy-install.pth
Using /usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg
Processing dependencies for selenium
Finished processing dependencies for selenium
A:
I've tried it and it works for me. The error doesn't make sense to me since line 193 in selenium.py is part of the Selenium object "start" method - it shouldn't be called at import time.
Maybe ask the user group?
| Error with new version | I have Arch linux and recently it's python packages was upgraded to the 3rd branch. Now I'm not able to run selenium-python bindings. When I run it (even with old-python version) I get:
from selenium import selenium
File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/selenium/__init__.py", line 23, in <module>
from selenium.selenium import selenium
File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/selenium/selenium/selenium.py", line 193
raise Exception, result
What could it be? (Btw, looks like my selenium was built with 2.6 python).
UPD I tried to get selenium again but:
easy_install-2.7 selenium
install_dir /usr/lib/python2.7/site-packages/
Searching for selenium
Best match: selenium 2.0a5
Processing selenium-2.0a5-py2.7.egg
selenium 2.0a5 is already the active version in easy-install.pth
Using /usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg
Processing dependencies for selenium
Finished processing dependencies for selenium
| [
"I've tried it and it works for me. The error doesn't make sense to me since line 193 in selenium.py is part of the Selenium object \"start\" method - it shouldn't be called at import time.\nMaybe ask the user group?\n"
] | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0004248413_python_selenium.txt |
Q:
GAE+ Picasa heavy use. Restrictions or quotes
I suppose it can be offtopic, but I didn't find this info anywhere.
I am going to build a GAE app that will heavily work with Picasa as an image hosting. It will add new images, fetch existing, update them, work with comments etc. I have read Picasa API docs and I think it can be integrated and used with GAE quite quickly, easily and conveniently. So, is that a right choice for a highloaded web app? What a restrictions or quotes for using it?
A:
I just read this blog article:
http://www.carlosble.com/?p=719
Long story short, the guy wasted 15 grand because he did not do his research and found out GAE was not appropriate for this needs.
It sounds like your app might hit the quotas imposed by GAE, I guess it would depend on how popular your app is. Here are the quotas
http://code.google.com/appengine/docs/quotas.html
I dont know of any service that it is similar to GAE and is free to start out with. You just need to make sure this is the right technology if you plan to invest heavily in it.
A:
First, you must be aware of the url fetch quota, decide if it fits your needs:
http://code.google.com/appengine/docs/quotas.html#UrlFetch
I've been recently working on a GAE project that had to perform many requests to the youtube API. Even though everything worked smoothly on my local dev server, when it was running on GAE I encountered sporadic 403 error codes when trying to fetch data from youtube.
Apparently google throttle ips that issue lots of requests at high volume peak times ( http://code.google.com/p/gdata-issues/issues/detail?id=1239 )
My solution was to make most of the youtube API calls from the client side (ajax), this way I bypassed both the quota limit and the errors.
| GAE+ Picasa heavy use. Restrictions or quotes | I suppose it can be offtopic, but I didn't find this info anywhere.
I am going to build a GAE app that will heavily work with Picasa as an image hosting. It will add new images, fetch existing, update them, work with comments etc. I have read Picasa API docs and I think it can be integrated and used with GAE quite quickly, easily and conveniently. So, is that a right choice for a highloaded web app? What a restrictions or quotes for using it?
| [
"I just read this blog article:\nhttp://www.carlosble.com/?p=719\nLong story short, the guy wasted 15 grand because he did not do his research and found out GAE was not appropriate for this needs.\nIt sounds like your app might hit the quotas imposed by GAE, I guess it would depend on how popular your app is. Here... | [
2,
1
] | [] | [] | [
"google_app_engine",
"picasa",
"python"
] | stackoverflow_0004248368_google_app_engine_picasa_python.txt |
Q:
Sandboxing web services with Python
I'm building an integration test for a web application that has multiple interdependent services. All of them depend on a shared resource in order to run correctly. I'd like to make sure that the data in the system is sane when its live so I'm leveraging a live service. I'm using Python to build it and this is my idea on how to sandbox the services:
build a test runner using multiprocessing's BaseManager
chroot jail each of the services, run them as a background service
have a listener respond to incoming connections from the services and spit out the data
Does this seem sane? Other ideas include running each service as a process or make each service have its own python virtualenv to run in.
A:
You definitely don't want to test with live data first. In order to build the integration test, you should first mock your dependencies and use I/O sets you control. Having expected input and output is very important. Building those unit tests will help you immensely when doing your integration testing.
As for your specific question, you can use a proxy to intercept the data or decorate your calling function to add logging. Take a look at Aspect Oriented Programming (AOP) for more information on interceptors.
If you are using WSGI, you can write a middleware piece to handle the interception and logging. Take a look at CherryPy's wsgiserver.py module for help with that; Django also uses middleware and their docs might be able to help regarding middleware.
A:
The third possibility is the easiest - avoid any locking issues by having your own daemon be the intermediate and have it be the only process with direct access to the resource, and all other processes need to go through it to get access.
A:
One of the easiest thing is to have a pool of python processes which serve a request, then terminate and get relaunched by a shell script.
This small library http://codespeak.net/execnet/
provide a very minimal script to create server which listen for a request and then exit.
Take a look to this recipe:
Instantiate gateways through sockets
I have used it to build a simple cluster of agnostic python processes. They can execute small python code, and if you chroot jail each of the services, you can gain a good level of isolation.
By the way, I suggest you to avoid to have different privileges (sandobox) on the same python process. It is unpratical: for instance years ago Zope/Plone have a lot of problem when it is hosted, because a bad designed plugin can take down an entire big site.
Python processes are fast to fire and shutdown, and operating system can deal the dynamic load in a better way then us application code :)
A:
Perhaps you should take a step back and ask a few questions first.
What is the most important part to have tested?
How difficult is it to setup that test?
Is the cost of setting up the test worth getting the test results?
Can I have most of what I wanted tested with a simpler test?
Any way you go I would use a fixture based on live data and expectation of what that data becomes. This allows our test to be deterministic and therefore automated.
If the most important piece is a portion of logic, that can be tested via a unit test with known input/output and mocks.
If the testing the integration part is really the most important then I would try and strike a balance between mocking out as many moving pieces as I felt comfortable doing in order to make a more manageable test.
The more networked resources you use the more complex a system, and the more tests it should have. You have to think about timing issues, service uptime, timeouts, error states, etc. You can also fall into a trap of creating a test which is nondeterministic. If your assertion ends up looking for differences in timings, rely on particular timings, or rely on an unreliable service which breaks alot; than you may end up with a test which is worthless because of the amount of "noise" from false positive breaks.
If you want to drive towards using a continuous integration model you'll also need consider the complexities of having to manage (startup and shutdown) or multiple process with each test run. In general you get a easier test to manage if you can have the test be the single process running and the other "processes" be the function calls to the appropriate starting points in the code.
A:
You can play with PyPy if you want pure python realization.
| Sandboxing web services with Python | I'm building an integration test for a web application that has multiple interdependent services. All of them depend on a shared resource in order to run correctly. I'd like to make sure that the data in the system is sane when its live so I'm leveraging a live service. I'm using Python to build it and this is my idea on how to sandbox the services:
build a test runner using multiprocessing's BaseManager
chroot jail each of the services, run them as a background service
have a listener respond to incoming connections from the services and spit out the data
Does this seem sane? Other ideas include running each service as a process or make each service have its own python virtualenv to run in.
| [
"You definitely don't want to test with live data first. In order to build the integration test, you should first mock your dependencies and use I/O sets you control. Having expected input and output is very important. Building those unit tests will help you immensely when doing your integration testing.\nAs for... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"sandbox",
"web_services"
] | stackoverflow_0003522584_python_sandbox_web_services.txt |
Q:
Dynamic symbol lookup fails with statically embedded Python on Mac OS X
I'm building a Mac OS X application that is to embed Python. My application is technically a bundle (i.e. its main executable is MH_BUNDLE); it's a plug-in for another application. I'd like it to embed Python statically, but want to be able to load extensions dynamically.
I did the following: I included a whole library (-force_load path/to/libpython2.7.a), also reexported all Python symbols (-exported_symbol_list path/to/list), and added the -u _PyMac_Error, which I got using this linking advice. The bundle itself loads fine, all internal Python code appears to work, but it fails when it it tries to import a dynamic library (time.so) with the following message:
Traceback (most recent call last):
...
ImportError: dlopen(/<stripped>/time.so, 2): Symbol not found: _PyExc_OverflowError
Referenced from: /<stripped>/time.so
Expected in: dynamic lookup
This symbol is a part of Python API and it must be in my bundle already. I can check this:
nm -g Build/Debug/pyfm | grep _PyExc_OverflowError
00172884 D _PyExc_OverflowError
0019cde0 D _PyExc_OverflowError
(It's listed twice because I have two architectures, i386 and ppc).
The time.so doesn't reference anything, which, as I understand, is by design:
otool -L "/<stripped>/time.so"
/<stripped>/time.so (architecture ppc):
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11)
/<stripped>/time.so (architecture i386):
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11)
My problem appears to be similar to this, but it's the other way round: I do link Python statically, while the other poster linked it dynamically (an our platforms are different too). For him static linking solved the problem.
Why doesn't it find the symbol?
Update. I suspect it happens because the main app loads its plug-ins (and thus my bundle) with RTLD_LOCAL.
A:
The “update” I made suggests it right: the main plug-in bundle is loaded locally (RTLD_LOCAL), so nobody can see any symbols there, unless using explicit dlopen followed by dlsym.
If it were Linux I could promote the bundle to the global namespace by dlopening it again with the RTLD_GLOBAL flag, but under Mac OS X this doesn't work. But Mac OS X nicely packs stuff into bundles, so I just made a dynamic library and put it into the plug-in bundle directory. The library loads automatically as RTLD_GLOBAL and all Python symbols are available.
| Dynamic symbol lookup fails with statically embedded Python on Mac OS X | I'm building a Mac OS X application that is to embed Python. My application is technically a bundle (i.e. its main executable is MH_BUNDLE); it's a plug-in for another application. I'd like it to embed Python statically, but want to be able to load extensions dynamically.
I did the following: I included a whole library (-force_load path/to/libpython2.7.a), also reexported all Python symbols (-exported_symbol_list path/to/list), and added the -u _PyMac_Error, which I got using this linking advice. The bundle itself loads fine, all internal Python code appears to work, but it fails when it it tries to import a dynamic library (time.so) with the following message:
Traceback (most recent call last):
...
ImportError: dlopen(/<stripped>/time.so, 2): Symbol not found: _PyExc_OverflowError
Referenced from: /<stripped>/time.so
Expected in: dynamic lookup
This symbol is a part of Python API and it must be in my bundle already. I can check this:
nm -g Build/Debug/pyfm | grep _PyExc_OverflowError
00172884 D _PyExc_OverflowError
0019cde0 D _PyExc_OverflowError
(It's listed twice because I have two architectures, i386 and ppc).
The time.so doesn't reference anything, which, as I understand, is by design:
otool -L "/<stripped>/time.so"
/<stripped>/time.so (architecture ppc):
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11)
/<stripped>/time.so (architecture i386):
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11)
My problem appears to be similar to this, but it's the other way round: I do link Python statically, while the other poster linked it dynamically (an our platforms are different too). For him static linking solved the problem.
Why doesn't it find the symbol?
Update. I suspect it happens because the main app loads its plug-ins (and thus my bundle) with RTLD_LOCAL.
| [
"The “update” I made suggests it right: the main plug-in bundle is loaded locally (RTLD_LOCAL), so nobody can see any symbols there, unless using explicit dlopen followed by dlsym. \nIf it were Linux I could promote the bundle to the global namespace by dlopening it again with the RTLD_GLOBAL flag, but under Mac OS... | [
1
] | [] | [] | [
"dynamic",
"lookup",
"macos",
"python"
] | stackoverflow_0004193539_dynamic_lookup_macos_python.txt |
Q:
URLError: urlopen error timed out
Whenever i try to make a HTTP request to some url through my django application which is running on top of apache mod_python (Machine: Ubuntu 10.04 server edition, 64-bits), it gives a timeout error.
The strange thing is that it works fine on Ubuntu 10.04 server edition, 32-bits.
I feel there could be some proxy connection issue. But i am not sure how to resolve it, if that is the case.
What could be the issue? Can anyone please throw some light on this.
Thanks in Advance.
A:
Run simple network analysis first,
tracert
ping
wireshark (for network analysis)
Check your firewall and proxy settings on the server and make sure the correct ports, routes and permissions are fine.
A:
Step 1:
Try it in the python shell first. Just take whatever you're trying to do with urlopen and do it in the python shell. You need to simplify your test.
Step 2:
If it still doesn't work maybe it's network... trying pinging the domain.
# ping domain.com
Could be a DNS issue, try looking the domain up:
# nslookup domain.com
or
# dig domain.com
If this works try pinging the IP directly.
# ping 000.000.000.000
Without more details this is all I know to try.
| URLError: urlopen error timed out | Whenever i try to make a HTTP request to some url through my django application which is running on top of apache mod_python (Machine: Ubuntu 10.04 server edition, 64-bits), it gives a timeout error.
The strange thing is that it works fine on Ubuntu 10.04 server edition, 32-bits.
I feel there could be some proxy connection issue. But i am not sure how to resolve it, if that is the case.
What could be the issue? Can anyone please throw some light on this.
Thanks in Advance.
| [
"Run simple network analysis first, \ntracert\nping \nwireshark (for network analysis)\nCheck your firewall and proxy settings on the server and make sure the correct ports, routes and permissions are fine.\n",
"Step 1:\nTry it in the python shell first. Just take whatever you're trying to do with urlopen and do ... | [
0,
0
] | [] | [] | [
"apache2",
"django",
"python",
"ubuntu"
] | stackoverflow_0004243550_apache2_django_python_ubuntu.txt |
Q:
Is there a reason I should be dissuaded from using an alternative templating engine in my Django app?
I've done a few small-ish Django projects, and each time I've been struck by the apparent limitations of Django's templating language. Just as a random example, I was shocked to learn that if, in the context of a template, I had a variable bar and a dict foo, I couldn't access foo[bar] unless I wrote my own filter to do it.
I've read that the reason for this is because Django was created for environments where the people designing the pages were not programmers. I understand that.
But let's say that's not a problem for me. Is there a reason why I should stick with Django's templating language, rather than switching over to something with a lot more power, like Mako (where you can even execute arbitrary Python expressions)?
I had the opportunity to use Mako for a school project a while back, and I really loved the power of it. For example, as part of the project, we had to make a big table, where building each row and cell was fairly complex. Yet, I could make my template look something like:
<table>
% for foo in foos:
${makerow(row)}
% endfor
</table>
<%def name="makerow(row)">
<tr>
# Blah blah blah (possibly a call to makecell somewhere)
</tr>
</%def>
Maybe this is a violation of separation of presentation and logic, but boy is it nice and clean. Subroutines! Abstraction! Good stuff.
And a follow-up question: If using an alternative templating language isn't frowned upon by the Django community, does anyone have any to suggest? Like I said, I really like Mako, but it's literally the only one I've used other than Django's.
A:
I'll be honest, I didn't thoroughly read the responses. But I'm guessing it's a lot of "no python in your templates" and "your view shouldn't have much logic" type stuff.
If you put idealism aside and opt for pragmatism then I think Mako is a fine choice. I'm using it in a production capacity (mainly for speed, power and dynamic inheritance) for 3+ years now. It hasn't failed or been otherwise annoying in any way.
The idealists are correct, but sometimes you have to go for what's doable vs what's right. If you are not limited by the Django templating engine use it. If you need more power, Mako and Jinja are fine choices.
Django makes it very easy to swap out templating engines and keep most things working as before:
http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language
A:
Executing arbitrary code in templates should not be considered an inherently good thing. Taking advantage of such functionality is usually a sign that your architecture is broken.
That said, if you read the Django documentation, it explicitly says that you should feel free to use, discard, and replace any components you wish. Django is intentionally modular, and in fact, the two most trivially-replaceable components are the templating engine and the ORM.
If you want to use Mako instead of the Django templating engine, just use Mako.
A:
The one reason I'd refrain from using jinja, Mako or anything else is that it may not make your app future proof with django enhancements.
There was a GSoc project proposal last year, by Alex Gaynor to make the template loading fast. - It was then retracted in favor of NoSQL project.
But with many more core developers and faster clearing of tickets, I'd stick to django full stack, knowing fully well, that components have to be changed to by home grown ones eventually.
If you are really looking for a glue framework on awesome python libraries, including the ones you choose, Flask is out there.
A:
addons.mozilla.org is using Django + Jinga: https://github.com/jbalogh/zamboni
Not sure whether or not the community frowns on Jinga, but many people like it, as an example.
A:
If you did mean "app", rather than "project", and it's not for entirely private use, I would recommend that you not change the template engine; it will make the app much less likely to ever be used by anyone else as it'll require them to alter some core settings, and it may break interaction between it and other apps or the project as a whole.
A:
Your example reminds me of the old PHP days when people would mix PHP with html all over the place. Felt really powerful. Until one day people realized that the mess is unmaintainable.
If the design is chopped up into "functions", will a designer understand it then? It will probably annoy him.
| Is there a reason I should be dissuaded from using an alternative templating engine in my Django app? | I've done a few small-ish Django projects, and each time I've been struck by the apparent limitations of Django's templating language. Just as a random example, I was shocked to learn that if, in the context of a template, I had a variable bar and a dict foo, I couldn't access foo[bar] unless I wrote my own filter to do it.
I've read that the reason for this is because Django was created for environments where the people designing the pages were not programmers. I understand that.
But let's say that's not a problem for me. Is there a reason why I should stick with Django's templating language, rather than switching over to something with a lot more power, like Mako (where you can even execute arbitrary Python expressions)?
I had the opportunity to use Mako for a school project a while back, and I really loved the power of it. For example, as part of the project, we had to make a big table, where building each row and cell was fairly complex. Yet, I could make my template look something like:
<table>
% for foo in foos:
${makerow(row)}
% endfor
</table>
<%def name="makerow(row)">
<tr>
# Blah blah blah (possibly a call to makecell somewhere)
</tr>
</%def>
Maybe this is a violation of separation of presentation and logic, but boy is it nice and clean. Subroutines! Abstraction! Good stuff.
And a follow-up question: If using an alternative templating language isn't frowned upon by the Django community, does anyone have any to suggest? Like I said, I really like Mako, but it's literally the only one I've used other than Django's.
| [
"I'll be honest, I didn't thoroughly read the responses. But I'm guessing it's a lot of \"no python in your templates\" and \"your view shouldn't have much logic\" type stuff.\nIf you put idealism aside and opt for pragmatism then I think Mako is a fine choice. I'm using it in a production capacity (mainly for spee... | [
4,
3,
2,
1,
0,
0
] | [] | [] | [
"django",
"mako",
"python",
"templating"
] | stackoverflow_0004241871_django_mako_python_templating.txt |
Q:
Structuring Django-App to Attach Custom Business Rules to Object Instances
I'm torn how to structure my code to accommodate business rules specific to instances of a particular model.
For example. Lets say I have a Contact model with a type field and choices=(('I','Individual'),('C','Company)). Based on the type of model that I have, I might want to have custom methods.
So thinking out loud, something like this would be nice:
class IndividualContact(Contact):
""" A custom class used for Contact instances with type='I' """
criteria = Q(type='I')
# The goal here is that Contact is now aware of IndividualContact and constructs
# objects accordingly.
Contact.register(IndividualContact)
Or even:
class SpecialContact(Contact):
""" A custom class used for the contact with pk=1 """
criteria = Q(pk=1)
At which point I have a nice home for my special instance specific code.
One of the alternatives I explored is using model inheritance and avoiding things like type fields that impart new behaviors. That way, new classes plug into the existing framework elegantly and you're nicely set up to add custom fields to your different types in case you need them.
In my case I have a resource crediting system on the site that allows me to say things like "You may only have 2 Listings and 20 Photos". Individual resource types are rationed, but there is a generic credit table that gives you credits for various content types. The logic that goes into counting up your Listings and Photos varies based on the type of object you're working with.
I.E.:
listing_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Listing), user=user, credit_amt=2)
# Should subtract **active** listings from current sum total of Listing credits.
listing_credit.credits_remaining()
photo_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Photo), user=user, credit_amt=5)
# Photos have no concept of an active status, so we just subtract all photos from the current sum total of Listing credits.
# Also, the Photo might be associated to it's user through a 'created_by' field whereas
# Listing has a user field.
photo_credit.credits_remaining()
My current approach is separate classes but I'd like to reduce that boilerplate and he necessity of creating N separate tables with only a credit_ptr_id.
A:
Take a look at django proxy models. They allow you to do exactly what you want.
http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models
But since in you case the behavior is dependent on the field value, then you should add custom managers to the proxy models that retrieve items only of only that type on queries.
| Structuring Django-App to Attach Custom Business Rules to Object Instances | I'm torn how to structure my code to accommodate business rules specific to instances of a particular model.
For example. Lets say I have a Contact model with a type field and choices=(('I','Individual'),('C','Company)). Based on the type of model that I have, I might want to have custom methods.
So thinking out loud, something like this would be nice:
class IndividualContact(Contact):
""" A custom class used for Contact instances with type='I' """
criteria = Q(type='I')
# The goal here is that Contact is now aware of IndividualContact and constructs
# objects accordingly.
Contact.register(IndividualContact)
Or even:
class SpecialContact(Contact):
""" A custom class used for the contact with pk=1 """
criteria = Q(pk=1)
At which point I have a nice home for my special instance specific code.
One of the alternatives I explored is using model inheritance and avoiding things like type fields that impart new behaviors. That way, new classes plug into the existing framework elegantly and you're nicely set up to add custom fields to your different types in case you need them.
In my case I have a resource crediting system on the site that allows me to say things like "You may only have 2 Listings and 20 Photos". Individual resource types are rationed, but there is a generic credit table that gives you credits for various content types. The logic that goes into counting up your Listings and Photos varies based on the type of object you're working with.
I.E.:
listing_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Listing), user=user, credit_amt=2)
# Should subtract **active** listings from current sum total of Listing credits.
listing_credit.credits_remaining()
photo_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Photo), user=user, credit_amt=5)
# Photos have no concept of an active status, so we just subtract all photos from the current sum total of Listing credits.
# Also, the Photo might be associated to it's user through a 'created_by' field whereas
# Listing has a user field.
photo_credit.credits_remaining()
My current approach is separate classes but I'd like to reduce that boilerplate and he necessity of creating N separate tables with only a credit_ptr_id.
| [
"Take a look at django proxy models. They allow you to do exactly what you want.\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models\nBut since in you case the behavior is dependent on the field value, then you should add custom managers to the proxy models that retrieve items only of only that typ... | [
1
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0004250092_django_models_python.txt |
Q:
Trace speed issues in python running on google app engine
I'm new to python, django and google app engine. All great tools and have been enjoying working with them.
However, on my production site its taking 4 seconds to load a webpage, which I think is horrible and needs to be less than a second. I've also verified the long amount of time is in the request to the get the page, not downloading any media files.
First thought is yes, it still has the first start issues any gae app would, I'm not trying to fix those. I understand that the first time you hit your website after uploading a new version it needs to load up the code for the first time. Additionally, if your site isn't visited often then this happens alot. All of this I'm aware of and not trying get more info on.
My site is relatively simple and its not loading big data or displaying complicated designs. And on my localhost it runs extremely fast. I should also point out that I'm using Django nonrel, which is a great tool that allows me to develop quickly with django on gae: http://www.allbuttonspressed.com/projects/django-nonrel
The problem I'm having is that its taking way to long for pages to load in production and I need to get to the bottom of it. I'm sure I've coded something poorly, but I'm not familiar enough with python and gae to know the best debugging practices, especially if it only seems to have issues in production.
So for a newbie python / django / google app engine developer, how do I quickly and easily find what functions are taking so much time?
A:
Use appstats.
| Trace speed issues in python running on google app engine | I'm new to python, django and google app engine. All great tools and have been enjoying working with them.
However, on my production site its taking 4 seconds to load a webpage, which I think is horrible and needs to be less than a second. I've also verified the long amount of time is in the request to the get the page, not downloading any media files.
First thought is yes, it still has the first start issues any gae app would, I'm not trying to fix those. I understand that the first time you hit your website after uploading a new version it needs to load up the code for the first time. Additionally, if your site isn't visited often then this happens alot. All of this I'm aware of and not trying get more info on.
My site is relatively simple and its not loading big data or displaying complicated designs. And on my localhost it runs extremely fast. I should also point out that I'm using Django nonrel, which is a great tool that allows me to develop quickly with django on gae: http://www.allbuttonspressed.com/projects/django-nonrel
The problem I'm having is that its taking way to long for pages to load in production and I need to get to the bottom of it. I'm sure I've coded something poorly, but I'm not familiar enough with python and gae to know the best debugging practices, especially if it only seems to have issues in production.
So for a newbie python / django / google app engine developer, how do I quickly and easily find what functions are taking so much time?
| [
"Use appstats.\n"
] | [
8
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004250065_django_django_nonrel_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python 'self' for function
I have read the SO post on 'self' explained, and I have read the Python documentation on classes. I think I understand the use of self in Python classes and the convention therein.
However, being relatively new to Python and its idioms, I cannot understand why some use self in a procedural type function definition. For example, in the Python documentation on integer types, the example function is:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
Replacing self with num is the same functional result; ie:
def bit_length(num):
s = bin(num) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
There is no idiom like __init__ etc that I can see here why self is being used in the first case. I have seen this use of self elsewhere in procedural functions as well, and find it confusing.
So my question: If there is no class or method, why use self in a function definition rather than a descriptive parameter name?
A:
In the example bit_length is defined as a function for the int class, so there is actually a 'class or method'. The idea is that you 'ask' an integer to give its bit_length, hence it is defined to take self as an argument.
A:
No real reason. But if you're going to monkeypatch it onto an existing class then it acts as a bit of notification for anyone that may be reading the code.
| Python 'self' for function | I have read the SO post on 'self' explained, and I have read the Python documentation on classes. I think I understand the use of self in Python classes and the convention therein.
However, being relatively new to Python and its idioms, I cannot understand why some use self in a procedural type function definition. For example, in the Python documentation on integer types, the example function is:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
Replacing self with num is the same functional result; ie:
def bit_length(num):
s = bin(num) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
There is no idiom like __init__ etc that I can see here why self is being used in the first case. I have seen this use of self elsewhere in procedural functions as well, and find it confusing.
So my question: If there is no class or method, why use self in a function definition rather than a descriptive parameter name?
| [
"In the example bit_length is defined as a function for the int class, so there is actually a 'class or method'. The idea is that you 'ask' an integer to give its bit_length, hence it is defined to take self as an argument.\n",
"No real reason. But if you're going to monkeypatch it onto an existing class then it ... | [
6,
4
] | [] | [] | [
"idioms",
"python",
"self"
] | stackoverflow_0004250222_idioms_python_self.txt |
Q:
Python Default Variable in for loop
I am wondering if Python has the concept of storing data in the default variable in for loop.
For example, in perl, the equivalent is as follow
foreach (@some_array) {
print $_
}
Thanks,
Derek
A:
No. You should just use
for each in some_array:
print each
A:
Just for fun, here's something that does just about what you desire. By default it binds the loop variable to the name "_each", but you can override this with one of your own choosing by supplying a var keyword argument to it.
import inspect
class foreach(object):
__OBJ_NAME = '_foreach'
__DEF_VAR = '_each'
def __init__(self, iterable, var=__DEF_VAR):
self.var = var
f_locals = inspect.currentframe().f_back.f_locals
if self.var not in f_locals: # inital call
self.iterable = iter(iterable)
f_locals[self.__OBJ_NAME] = self
f_locals[self.var] = self.iterable
else:
obj = f_locals[self.__OBJ_NAME]
self.iterable = obj.each = obj.iterable
def __nonzero__(self):
f_locals = inspect.currentframe().f_back.f_locals
try:
f_locals[self.var] = self.iterable.next()
return True
except StopIteration:
# finished - clean up
del f_locals[self.var]
del f_locals[self.__OBJ_NAME]
return False
some_array = [10,2,4]
while foreach(some_array):
print _each
print
while foreach("You can do (almost) anything in Python".split(), var='word'):
print word
A:
Python allows the use of the '_' variable (quotes mine). Using it in a program seems to be the Pythonic way to have a loop control variable that is ignored in the loop (see other questions, e.g. Is it possible to implement a Python for range loop without an iterator variable? or my Pythonic way to ignore for loop control variable). As a comment pointed out, this isn't the same as Perl's default variable, but it allows you to do something like:
some_list = [1, 2, 3]
for _ in some_list:
print _
A guru may correct me, but I think this is about as close as you'll get to what you're looking for.
A:
Whatever is used in the for loop syntax becomes the variable that that item in the iteration is stored against for the remainder of the loop.
for item in things:
print item
or
for googleplexme in items:
print googleplexme
The syntax looks like this
for <given variable> in <iterable>:
meaning that where given variable can be anything you like in your naming space and iterable can be an iterable source.
| Python Default Variable in for loop | I am wondering if Python has the concept of storing data in the default variable in for loop.
For example, in perl, the equivalent is as follow
foreach (@some_array) {
print $_
}
Thanks,
Derek
| [
"No. You should just use\nfor each in some_array:\n print each\n\n",
"Just for fun, here's something that does just about what you desire. By default it binds the loop variable to the name \"_each\", but you can override this with one of your own choosing by supplying a var keyword argument to it.\nimport insp... | [
15,
2,
1,
0
] | [] | [] | [
"for_loop",
"python",
"variables"
] | stackoverflow_0004247626_for_loop_python_variables.txt |
Q:
OpenCV 2.1 Python Bindings Segfaulting
Hello I have a problem when grouping the OpenCV's functions in functions of my own and getting segmentation fault.
Even with code as simple as this
def acquire_imagen():
capture = cv.CaptureFromCAM( 0 )
img = cv.QueryFrame( capture )
return img
img = acquire_image()
print img[0,0]
If I call the same instructions outside the function everything is ok. I have an Idea of what may be happening but not enough knowledge about python to prevent it. I think the object is being freed by the GC.
A:
To prevent the capture object from being garbage-collected, keep a reference to it in a variable until you no longer need the images. In your code: the "capture" variable cannot be a local variable of the function, but a variable outside the function. Or, if you want it to be initialized inside the function, return it along with the captured image, and store it in a variable after the call to the function:
def acquire_imagen():
capture = cv.CaptureFromCAM( 0 )
img = cv.QueryFrame( capture )
return capture, img
capture, img = acquire_image()
print img[0,0]
A:
The problem seems to be that the capture object cannot be freed before accessing images captured from it. Don't let the "capture" object be freed until the image is no longer accessed in your program.
| OpenCV 2.1 Python Bindings Segfaulting | Hello I have a problem when grouping the OpenCV's functions in functions of my own and getting segmentation fault.
Even with code as simple as this
def acquire_imagen():
capture = cv.CaptureFromCAM( 0 )
img = cv.QueryFrame( capture )
return img
img = acquire_image()
print img[0,0]
If I call the same instructions outside the function everything is ok. I have an Idea of what may be happening but not enough knowledge about python to prevent it. I think the object is being freed by the GC.
| [
"To prevent the capture object from being garbage-collected, keep a reference to it in a variable until you no longer need the images. In your code: the \"capture\" variable cannot be a local variable of the function, but a variable outside the function. Or, if you want it to be initialized inside the function, ret... | [
2,
1
] | [] | [] | [
"opencv",
"python",
"segmentation_fault"
] | stackoverflow_0003689871_opencv_python_segmentation_fault.txt |
Q:
Django and thread safety
If I read the django documentation, only the documents about the template tags mention the potential danger of thread safety.
However, I'm curious what kind of things I have to do / avoid to write thread-safe code in Django...
One example is, I have the following function to config the loggers used in django.
_LOGGER_CONFIGURED = False
def config_logger():
global _LOGGER_CONFIGURED
if _LOGGER_CONFIGURED: return
_LOGGER_CONFIGURED = True
rootlogger = logging.getLogger('')
stderr_handler = StreamHandler(sys.stderr)
rootlogger.addHandler(stderr_handler)
and at the end of my root urlconf, i have the following function call:
config_logger()
The question is:
Is this code threadsafe?
What kind of variables are shared between the django threads?
A:
There's not really a whole lot you can do about django templates and their issues with threading, besides not using them, or at least not using the tags that are sensitive to threading issues. There aren't many django template tags that do have issues, only the stateful ones do, such as cycle.
In the example you have given, you are not doing anything about thread safety, and you shouldn't be anyway: the logging module is already perfectly thread safe, so long as you use it in the normal way, which is to call logging.getLogger in the modules that need it, and LOGGING or LOGGING_CONFIG is set appropriately in your settings.py. No need to be clever with this.
other things you might be concerned about are database integrity in the face of concurrent updates. Don't be, if you are using PostgreSQL or MySQL/INNOdb databases, then you are completely protected from concurrency shennanegans.
| Django and thread safety | If I read the django documentation, only the documents about the template tags mention the potential danger of thread safety.
However, I'm curious what kind of things I have to do / avoid to write thread-safe code in Django...
One example is, I have the following function to config the loggers used in django.
_LOGGER_CONFIGURED = False
def config_logger():
global _LOGGER_CONFIGURED
if _LOGGER_CONFIGURED: return
_LOGGER_CONFIGURED = True
rootlogger = logging.getLogger('')
stderr_handler = StreamHandler(sys.stderr)
rootlogger.addHandler(stderr_handler)
and at the end of my root urlconf, i have the following function call:
config_logger()
The question is:
Is this code threadsafe?
What kind of variables are shared between the django threads?
| [
"There's not really a whole lot you can do about django templates and their issues with threading, besides not using them, or at least not using the tags that are sensitive to threading issues. There aren't many django template tags that do have issues, only the stateful ones do, such as cycle. \nIn the example y... | [
1
] | [] | [] | [
"django",
"python",
"thread_safety"
] | stackoverflow_0004250019_django_python_thread_safety.txt |
Q:
_tkinter.TclError: invalid command name "labelframe"
I'm getting the following error when running a python/tkinter GUI application I wrote.
I thought it could be a Tcl/Tk version issue, but the LabelFrame() command was added in Tcl/Tk 8.4, (which is the version I am using).
The other computer that I am attempting to execute the program on is able to run another python/tkinter application I wrote--the difference between the applications is that one utilizes the LabelFrame() widget and the other does not.
Traceback (most recent call last):
File "/home/nharris/python/isub_parser/isub.py", line 672, in <module>
timeFrame = LabelFrame(optFrame, text="Time Scale Options")
File "/usr/apps/Python/python2.6.1-rhel3-i686/lib/python2.6/lib-tk/Tkinter.py", line 3525, in __init__
Widget.__init__(self, master, 'labelframe', cnf, kw)
File "/usr/apps/Python/python2.6.1-rhel3-i686/lib/python2.6/lib-tk/Tkinter.py", line 1932, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: invalid command name "labelframe"
A:
python may be using its own special version of TCL/TK, depending on how it was built and installed. This is usually the case on on windows, sometimes the case on linux, and seldom the case on MacOS X. You must rely on the version reported inside python to know what version it is using.
If python is not using the installed version (as is the case you are experiencing), you can try updating python. If, on your distribution of linux, you cannot overcome the way python was built using available packages, you will have to build python from source to use a newer version of TCL/TK or to use the installed version.
A:
It is possible to get two different versions of Tcl/Tk reported using these two methods:
Method 1:
>tclsh
%info patchlevel
8.4.15
Method 2:
>python
>>>import Tkinter;print Tkinter.TkVersion
8.3
Key:
> default command line
>>> python command line
% tcl command line
An update of Tcl/Tk should fix it.
| _tkinter.TclError: invalid command name "labelframe" | I'm getting the following error when running a python/tkinter GUI application I wrote.
I thought it could be a Tcl/Tk version issue, but the LabelFrame() command was added in Tcl/Tk 8.4, (which is the version I am using).
The other computer that I am attempting to execute the program on is able to run another python/tkinter application I wrote--the difference between the applications is that one utilizes the LabelFrame() widget and the other does not.
Traceback (most recent call last):
File "/home/nharris/python/isub_parser/isub.py", line 672, in <module>
timeFrame = LabelFrame(optFrame, text="Time Scale Options")
File "/usr/apps/Python/python2.6.1-rhel3-i686/lib/python2.6/lib-tk/Tkinter.py", line 3525, in __init__
Widget.__init__(self, master, 'labelframe', cnf, kw)
File "/usr/apps/Python/python2.6.1-rhel3-i686/lib/python2.6/lib-tk/Tkinter.py", line 1932, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: invalid command name "labelframe"
| [
"python may be using its own special version of TCL/TK, depending on how it was built and installed. This is usually the case on on windows, sometimes the case on linux, and seldom the case on MacOS X. You must rely on the version reported inside python to know what version it is using. \nIf python is not using t... | [
2,
1
] | [] | [] | [
"python",
"tcl",
"tkinter"
] | stackoverflow_0004250138_python_tcl_tkinter.txt |
Q:
Python Library for packet creation//manipulation
I am currently working on libpcap-python, I found it does not help(I don't know how) in modifying packet data. Is there any library which can be used to create network packet?
A:
Did you have a look at scapy
http://www.secdev.org/projects/scapy/
| Python Library for packet creation//manipulation | I am currently working on libpcap-python, I found it does not help(I don't know how) in modifying packet data. Is there any library which can be used to create network packet?
| [
"Did you have a look at scapy\n\nhttp://www.secdev.org/projects/scapy/\n\n"
] | [
4
] | [] | [] | [
"libpcap",
"python"
] | stackoverflow_0004251076_libpcap_python.txt |
Q:
ListProperty of custom properties
Is there a elegant way of using a ListProperty for storing a subclassed db.Property type?
For example, the FuzzyDateProperty from this example uses get_value_for_datastore() and make_value_from_datastore() to convert its attributes into one int that is stored in the datastore. Since that one int is a Python primitive, it seems that you should be able to create a ListProperty of FuzzyDateProperty. How?
In my particular case, i've defined a class and helper functions to neatly serialize / deserialize its attributes. I would like to encapsulate the class as a db.Property, rather than make the implementer handle the relationship between the class and the Model property.
A:
According to the Types and Property Classes doc
The App Engine datastore supports a
fixed set of value types for
properties on data entities. Property
classes can define new types that are
converted to and from the underlying
value types, and the value types can
be used directly with Expando dynamic
properties and ListProperty aggregate
property models.
My reading of this suggests that you should be able to just specify the extended db.Property as the item_type of the for the ListProperty. But there is a logged issue that suggest otherwise.
Assuming that doesn't work, I think the next best thing is probably to subclass ListProperty and manually extend it with getters, setters, and iterators, based on the "get_value_for_datastore" and "make_value_from_datastore" functions for lists with "FuzzyDateProperty" members.
A:
You can't do this - ListProperty expects a basic Python type, not a property class. Property classes, meanwhile, expect to be attached to a Model, not another property.
A:
As recommended by @mjhm and @Nick, i've subclassed ListProperty to accept any class. I've uploaded a generic version to GitHub, named ObjectListProperty. I use it as a cleaner alternative to using parallel ListProperty's.
ObjectListProperty transparently serializes/deserializes when getting & putting the model. It has an internal serialization method that works for simple objects, but can handle more complex objects if they define their own serialization method. Here's a trivial example:
from object_list_property import ObjectListProperty
class Animal():
""" A simple object that we want to store with our model """
def __init__(self, species, sex):
self.species = species
self.sex = sex if sex == 'male' or sex == 'female' else 'unknown'
class Zoo(db.Model):
""" Our model contains of list of Animal's """
mammals = ObjectListProperty(Animal, indexed=False)
class AddMammalToZoo(webapp.RequestHandler):
def post(self):
# Implicit in get is deserializing the ObjectListProperty items
zoo = Zoo.all().get()
animal = Animal(species=self.request.get('species'),
sex=self.request.get('sex') )
# We can use our ObjectListProperty just like a list of object's
zoo.mammals.append(animal)
# Implicit in put is serializing the ObjectListProperty items
zoo.put()
| ListProperty of custom properties | Is there a elegant way of using a ListProperty for storing a subclassed db.Property type?
For example, the FuzzyDateProperty from this example uses get_value_for_datastore() and make_value_from_datastore() to convert its attributes into one int that is stored in the datastore. Since that one int is a Python primitive, it seems that you should be able to create a ListProperty of FuzzyDateProperty. How?
In my particular case, i've defined a class and helper functions to neatly serialize / deserialize its attributes. I would like to encapsulate the class as a db.Property, rather than make the implementer handle the relationship between the class and the Model property.
| [
"According to the Types and Property Classes doc\n\nThe App Engine datastore supports a\n fixed set of value types for\n properties on data entities. Property\n classes can define new types that are\n converted to and from the underlying\n value types, and the value types can\n be used directly with Expando d... | [
2,
1,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004221580_google_app_engine_google_cloud_datastore_python.txt |
Q:
Good advice for coming to javascript (from Python)
I am coming to JavaScript, from Python.
I want to write testable, modular JS code, and want advice on tools, best practices and the like. I know about:
JSLint (and the existence of Douglas Crockford)
Paul Irish (hi Paul!) and the 10 Things...From the jQuery Source podcast
jQuery, jQuery.ui and Themeroller
the existence of freenode#javascript and freenode#jquery
Mozilla's MDC Doc Center
Stumbling blocks (so far):
What am I missing? Idioms / techniques / tools welcome, particularly around arrays (which seem crippled compared to python lists... what am I missing?), namespacing, testing, and documentation (no docstrings? what do I do instead?)
(also, are we not allowed to tag things as community wiki anymore? I don't need the rep!)
Also, one answer per response please!
A:
For techniques check out this post about js patterns: https://stackoverflow.com/questions/7002/what-javascript-patterns-do-you-use-most
Also, I use Aptana (an Eclipse derivative) as an IDE. Works out pretty nicely.
A:
You should consider investigating Pyjamas which allows you to write rich internet applications using only Python. It will generate the Javascript for you. It's the same concept that Google's Web Toolkit allows Java developers to write rich internet apps (like Google Wave) but specifically for Python.
A:
I recently subscribed to this: http://javascriptweekly.com/
So far the links they send have been very very interesting.
A good one was this free book: http://addyosmani.com/blog/essentialjsdesignpatterns/
| Good advice for coming to javascript (from Python) | I am coming to JavaScript, from Python.
I want to write testable, modular JS code, and want advice on tools, best practices and the like. I know about:
JSLint (and the existence of Douglas Crockford)
Paul Irish (hi Paul!) and the 10 Things...From the jQuery Source podcast
jQuery, jQuery.ui and Themeroller
the existence of freenode#javascript and freenode#jquery
Mozilla's MDC Doc Center
Stumbling blocks (so far):
What am I missing? Idioms / techniques / tools welcome, particularly around arrays (which seem crippled compared to python lists... what am I missing?), namespacing, testing, and documentation (no docstrings? what do I do instead?)
(also, are we not allowed to tag things as community wiki anymore? I don't need the rep!)
Also, one answer per response please!
| [
"For techniques check out this post about js patterns: https://stackoverflow.com/questions/7002/what-javascript-patterns-do-you-use-most\nAlso, I use Aptana (an Eclipse derivative) as an IDE. Works out pretty nicely.\n",
"You should consider investigating Pyjamas which allows you to write rich internet applicati... | [
1,
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0004251406_javascript_python.txt |
Q:
In Django, when should I use doctests instead of unit testing?
From Django docs:
...the database is not refreshed between doctests, so if your doctest requires a certain state you should consider flushing the database or loading a fixture.
Quite frankly, 90% of my testing is currently done in doctests. A colleague of mine thought that was peculiar. In all honesty, I do very little testing so I do not pretend to be a master of that field.
Does anyone have a rule of thumb they use when deciding how to test?
Non-SO answer
A colleague of mine suggested to test model functions and constraints as doctests and views via unit tests. How does that sound for a rule of thumb?
A:
As your project grows, you'll find that unittests are far better for testing your code.
The Django project itself is in the process of converting all doctests to unittests (we'll be done by the 1.3 release). The reason we're doing this is that prior to this conversion, the order of execution in the test suite would sometimes cause hard to reproduce errors. Sometimes a bit of code would accidentally depend on previously run doctest code. Additionally, switching to unittests has speed the overall test time up, since we can be more judicious about how and when we clear the database.
The other advantage unittests have is that they are MUCH easier to maintain. Because the entire test case is self-contained, you either write another test case, or modify the small, targeted test function to suit.
Doctests tend to work by evolution - you get an instance of your widget, add green fur, make sure the fur is green, add 4 legs, make sure you have 4 legs and green fur, add a thumb, make sure you have a thumb, 4 legs, and green fur, etc... This means that if you want to add a test right after the green fur stage, you have to modify the expected results for every other test case following.
You don't want to do all this rewriting, so you add your new test at the end. Then you add another, and then after a while your tests are so hopelessly jumbled you can't figure out whether or not a specific feature is even tested! With unittests, since each test embodies a specific, concrete and limited idea, it's much easier to re-order the tests logically, and to add a new test that doesn't depend on all the previous ones. Additionally, if you change the way add_green_fur() works, you don't have to modify dozens of test case results.
The other advantage is that unittests (when written well) tell you precisely where your code failed. Failed: MyWidget.tests.test_green_fur() is a lot easier to debug than "widget test failed at line 384", which is often dozens to hundreds of lines away from the actual point of failure.
In general, unittests are the better way to test.
Edit:
In response to your colleague's idea, I respectfully suggest that he hasn't worked on a large project with many doctests. Doctests in models are just as bad as in views. They have precisely the same problems (though if anything, doctests are worse in models because flush is very expensive and absolutely necessary for thorough doctesting). Don't underestimate the cost of the time taken by running tests.
Also, don't mix your test types unless you have a VERY good reason to do so. If you do, you'll very quickly find yourself doubling up tests, or assuming that a function is tested in whichever test suite you don't happen to be looking at.
Doctests are often touted as "providing documentation" for how your code is supposed to work. That's nice, but it's not a substitute for writing readable code with good legible inline comments. If you want further documentation, write it out separately!
You can't write good tests that also function as good documentation.
A:
Doctests are great for making sure your documentation is up-to-date, but I wouldn't really use them to test code. It's really easy for your documentation to become out of date as you make changes to your code.
In short, use unit tests to test code and doctests to test documentation.
| In Django, when should I use doctests instead of unit testing? | From Django docs:
...the database is not refreshed between doctests, so if your doctest requires a certain state you should consider flushing the database or loading a fixture.
Quite frankly, 90% of my testing is currently done in doctests. A colleague of mine thought that was peculiar. In all honesty, I do very little testing so I do not pretend to be a master of that field.
Does anyone have a rule of thumb they use when deciding how to test?
Non-SO answer
A colleague of mine suggested to test model functions and constraints as doctests and views via unit tests. How does that sound for a rule of thumb?
| [
"As your project grows, you'll find that unittests are far better for testing your code.\nThe Django project itself is in the process of converting all doctests to unittests (we'll be done by the 1.3 release). The reason we're doing this is that prior to this conversion, the order of execution in the test suite wou... | [
15,
1
] | [] | [] | [
"django",
"doctest",
"python",
"testing",
"unit_testing"
] | stackoverflow_0004251381_django_doctest_python_testing_unit_testing.txt |
Q:
Using python mechanize to login on webpage with javascript md5 hashing function
I'm trying to use python / mechanize to login to this webpage:
http://www.solaradata.com/cgi-bin/mainProgram.cgi
The login form uses a Javascript function that produces an MD5 hash from several field values before submitting the results for authentication. Since mechanize can't do javascript, I tried to replicate the same functionality inside of python and then submit the resulting values. However, I'm still getting "invalid user / password" errors.
Here's my current code, can anybody point me towards where I went wrong? Thanks!
url_login = 'http://www.solaradata.com/cgi-bin/mainProgram.cgi'
import mechanize
import md5
username = 'superfly' #not my real user/pass
password = 'stickyguy' #not my real user/pass
br = mechanize.Browser()
br.open(url_login)
br.select_form(nr=0)
br.set_all_readonly(False)
session = br['session']
br['user'] = username
br['password'] = password
m1 = md5.new()
m1.update(password + username)
br['password'] = m1.digest()
m2 = md5.new()
m2.update(password + session)
br['hash'] = m2.digest()
for form in br.forms():
#print form
request2 = form.click() # mechanize.Request object
try:
response2 = mechanize.urlopen(request2)
except mechanize.HTTPError, response2:
pass
print response2.geturl()
# headers
for name, value in response2.info().items():
if name != "date":
print "%s: %s" % (name.title(), value)
print response2.read() # body
response2.close()
A:
Use m1.hexdigest() instead of m1.digest()
A:
I'm not familiar with python, but it appears the they are returning the hex value of the MD5 hash in the javascript version of the algorithm. Does the python MD5 do the same?
You should be able to test this without going through the submission process and testing for success. Instead, using a JavaScript developer tool such as Firebug or Chrome developer tools, calculate the result you get in-page. Then, using the same inputs, see what you get from your program. They should match, character for character.
A:
It way be overkill but if you really need to script access a javascript heavy site you can look at selenium-rc or source labs.
These tools allow you to script an actual browser the same as a user.
Selenium
| Using python mechanize to login on webpage with javascript md5 hashing function | I'm trying to use python / mechanize to login to this webpage:
http://www.solaradata.com/cgi-bin/mainProgram.cgi
The login form uses a Javascript function that produces an MD5 hash from several field values before submitting the results for authentication. Since mechanize can't do javascript, I tried to replicate the same functionality inside of python and then submit the resulting values. However, I'm still getting "invalid user / password" errors.
Here's my current code, can anybody point me towards where I went wrong? Thanks!
url_login = 'http://www.solaradata.com/cgi-bin/mainProgram.cgi'
import mechanize
import md5
username = 'superfly' #not my real user/pass
password = 'stickyguy' #not my real user/pass
br = mechanize.Browser()
br.open(url_login)
br.select_form(nr=0)
br.set_all_readonly(False)
session = br['session']
br['user'] = username
br['password'] = password
m1 = md5.new()
m1.update(password + username)
br['password'] = m1.digest()
m2 = md5.new()
m2.update(password + session)
br['hash'] = m2.digest()
for form in br.forms():
#print form
request2 = form.click() # mechanize.Request object
try:
response2 = mechanize.urlopen(request2)
except mechanize.HTTPError, response2:
pass
print response2.geturl()
# headers
for name, value in response2.info().items():
if name != "date":
print "%s: %s" % (name.title(), value)
print response2.read() # body
response2.close()
| [
"Use m1.hexdigest() instead of m1.digest()\n",
"I'm not familiar with python, but it appears the they are returning the hex value of the MD5 hash in the javascript version of the algorithm. Does the python MD5 do the same?\nYou should be able to test this without going through the submission process and testing ... | [
1,
0,
0
] | [] | [] | [
"autologin",
"javascript",
"md5",
"mechanize",
"python"
] | stackoverflow_0004250061_autologin_javascript_md5_mechanize_python.txt |
Q:
Problem reading hex data from image - python automatically converts to a string
I am reading in an image one byte at a time with with read(1), and appending it to a list. The image data is all hex data. When I print out the list with the print function it is in the format '\xd7'
['\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7',...]
The problem is that now I need to perform some calculations on this hex data, however, it is in string format, and this '\xd' string format isn't supported by any of the int or hex conversion functions in python. They require a '0xd7' or just a 'd7'.
Thanks for the help
A:
It's interpreting them as characters, so use ord to turn them into numbers. I.e. ord('\xd7') gives 215.
Also if you use Windows, or the program might have to run on Windows, make sure that you've got the file open in binary mode: open("imagefile.png","rb"). Makes no difference on other operating systems.
A:
You could do something like this to get them into a numeric array:
import array
data = array.array('B') # array of unsigned bytes
with open("test.dat", 'rb') as input:
data = input.read(100)
data.fromstring(data)
print data
# array('B', [215, 215, 215, 215, 215, 215, 215])
A:
If you require 'd7' or '0xd7', rather than simply 0xd7 (viz, 215), hex() or '%x' are your friend.
>>> ord('\xd7')
215
>>> ord('\xd7') == 215 == 0xd7
True
>>> hex(ord('\xd7'))
'0xd7'
>>> '%x' % ord('\xd7')
'd7'
Also as observed in other answers, do make sure you open with the 'b' in the mode, otherwise it can get messed up, thinking it's UTF-8 or something like that, on certain sequences of bytes.
A:
read() can take a size value larger than 1: read(1024) will read 1K worth of bytes from the stream. That will be a lot faster than reading a byte at a time and appending it to the previous bytes.
What are you trying to do when printing the data? See the byte values, or display the image?
The data isn't in "string format", it's just bytes, but when you print them the print routine will escape non-printing values into something that will mean more to human eyes and brains. If you want to see the values without the escaping you can iterate over the bytes and convert them to their hexadecimal values, or decimal, or binary - whatever works for you and your application. The string formatting mini-language will be a good starting place.
A:
If you are doing image processing, then you probably want to look at numpy.
There are a few packages that will help you read your image into memory too (PIL is mentioned above, another is my own mahotas or scikits.image).
If the data is in a file as raw data an you know the dimensions, you can do the following
import numpy as np
img = np.empty( (n_rows, n_cols), dtype=np.uint8) # create an empty image
img.data[:] = input_file.read()
to get your data into img.
An introductory website for image processing in python is http://pythonvision.org.
| Problem reading hex data from image - python automatically converts to a string | I am reading in an image one byte at a time with with read(1), and appending it to a list. The image data is all hex data. When I print out the list with the print function it is in the format '\xd7'
['\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7',...]
The problem is that now I need to perform some calculations on this hex data, however, it is in string format, and this '\xd' string format isn't supported by any of the int or hex conversion functions in python. They require a '0xd7' or just a 'd7'.
Thanks for the help
| [
"It's interpreting them as characters, so use ord to turn them into numbers. I.e. ord('\\xd7') gives 215.\nAlso if you use Windows, or the program might have to run on Windows, make sure that you've got the file open in binary mode: open(\"imagefile.png\",\"rb\"). Makes no difference on other operating systems.\n",... | [
4,
2,
2,
1,
0
] | [] | [] | [
"hex",
"image",
"python",
"string"
] | stackoverflow_0004250682_hex_image_python_string.txt |
Q:
Filter out the accelerometers noise using Kalman filter in Python
I get from a socket a stream of data from an accelerometer with a lot of noise.
something like this:
...
-0.014532123
0.183950298
0.003323536
-0.342343526
...
I tried with low pass filter but I can't get a really smoothed result..
I think I need to use Kalman filter so I have to implement
a function that "corrects" every element of the stream
stream_element_out = kalman(stream_element_in)
I'm using python and I searched all over the web, finding many examples, but I can't understand how I can apply it to my project :)..
someone can explain me an easy way to implement this algorithm please? :)
A:
Taking an average of the last x results could do the smoothing.
x would be a constant that can be tweaked for the best results depending on your application
You can also filter out input that is more than y off from the average of the last x numbers.
| Filter out the accelerometers noise using Kalman filter in Python | I get from a socket a stream of data from an accelerometer with a lot of noise.
something like this:
...
-0.014532123
0.183950298
0.003323536
-0.342343526
...
I tried with low pass filter but I can't get a really smoothed result..
I think I need to use Kalman filter so I have to implement
a function that "corrects" every element of the stream
stream_element_out = kalman(stream_element_in)
I'm using python and I searched all over the web, finding many examples, but I can't understand how I can apply it to my project :)..
someone can explain me an easy way to implement this algorithm please? :)
| [
"Taking an average of the last x results could do the smoothing.\nx would be a constant that can be tweaked for the best results depending on your application\nYou can also filter out input that is more than y off from the average of the last x numbers.\n"
] | [
1
] | [] | [] | [
"accelerometer",
"filter",
"kalman_filter",
"python"
] | stackoverflow_0004251596_accelerometer_filter_kalman_filter_python.txt |
Q:
possible to define a function in commandline window of a programming language?
Is it possible to define a function in commandline window of Matlab? Looks no to me.
But for R, it is possible to do so. I was wondering why there is this difference and if there is more to say behind this kind of feature of a programming language, or can I say just interpretive language (such as Python, Bash,...)?
Thanks!
A:
You can define functions in the command window of Matlab. It will be evaluated like a function, but it won't be available to you in your next Matlab session (though you can save and load it like a variable).
As an example, I copy @Dirk Eddelbuettel's function
>> cubed = @(x)x^3;
>> cubed(2)
ans =
8
EDIT 1
Note that you can only define single-statement functions as anonymous functions in Matlab, so you can't use e.g. for-loops (unless you use evil eval, which allows everything). However, if you nest anonymous functions, you can create arbitrarily complicated recursive statements. Thus, I guess that you can indeed define any function in the command line window. It might just not be worth the effort, and I bet that it'll be very difficult to understand.
EDIT 2 Here's an example of a recursive nested anonymous function to calculate factorials from Matlab central:
>> fact = @(val,branchFcns) val*branchFcns{(val <= 1)+1}(val-1,branchFcns);
>> returnOne = @(val,branchFcns) 1;
>> branchFcns = {fact returnOne};
>> fact(4,branchFcns)
ans =
24
>> fact(5,branchFcns)
ans =
120
A:
This isn't really a feature of a programming language but of an implementation of that programming language. For example, there exist C interpreters and Lisp Compilers. This is normaly called an REPL (Read-Eval-Print-Loop) and is generally a feature of interpreted implementations.
A:
Yes, if and when the language at hand supports it. So here is a trivial R example, cut and pasted from the command-prompt I am using:
R> cubed <- function(x) x^3
R> cubed(2)
[1] 8
R> cubed(3)
[1] 27
R>
| possible to define a function in commandline window of a programming language? | Is it possible to define a function in commandline window of Matlab? Looks no to me.
But for R, it is possible to do so. I was wondering why there is this difference and if there is more to say behind this kind of feature of a programming language, or can I say just interpretive language (such as Python, Bash,...)?
Thanks!
| [
"You can define functions in the command window of Matlab. It will be evaluated like a function, but it won't be available to you in your next Matlab session (though you can save and load it like a variable). \nAs an example, I copy @Dirk Eddelbuettel's function\n>> cubed = @(x)x^3;\n>> cubed(2)\nans =\n 8\n\nE... | [
4,
2,
1
] | [] | [] | [
"bash",
"matlab",
"python",
"r"
] | stackoverflow_0004251553_bash_matlab_python_r.txt |
Q:
Java and whitespace-as-syntax (ala Python)?
There is a part of java syntax that bugs the crap out of me: that's curly braces and semicolons. Is there some sort of translator that exists that will allow me to use all of the Java syntax except for this? I want to do something like this:
public class Hello:
public static void main(String[] args):
System.out.println("I like turtles.")
public class Another:
public static void somethingelse():
System.out.println("And boobs")
It's Python's whitespace as syntax model, I've grown to love it. I believe it's cleaner, and easier on the eyes. If it doesn't exist, I'm actually considering heavily investing time into writing a parser that would do this for me. (Ideally it will open it up, format it with whitespace, and when saved, save as just java syntax with braces and all)
Would this cause problems elsewhere in the language? What kind of hiccups can I expect to run into? I want to use all of the rest of the Java syntax exactly how it is otherwise, just want to modify this small niggle.
I can already write and read code just fine in Eclipse. And yes, I already know how to use code formatting tools and all the auto-complete options available to me, this is merely a preference in coding style so please don't answer with "You should learn to get used to it" or "You should use an IDE that does braces FOR you"...no. I don't want that.
A:
Can you switch to Jython? Python's syntax, Java's runtime environment.
A:
You might consider instead investing time in learning to use eclipse and the code formatter.
Python's model is great in that it (more or less) forces all developers into the same code style format. Modern software firms have code-style guidelines and use IDEs with formatters to ease enforcement of the coding style. Even if your coworkers have (subjectively)atrocious styles(to you), you can quickly reformat that code into something you find readable.
A:
You can use Jython or Scala, which drops most of curly braces and semicolons (as far as dots and parenthesis). Their syntax is much more readable, and you still all the power of JVM.
Though, if you need exactly translator (to save it as a plain Java code), you can easily write such translator by yourself. Read input file line by line, counting indents, and each time it changes, delete colon at the end of the string (if needed) and insert curly brace: opening brace for bigger indent and closing for smaller. (It doesn't take into account several possible cases, but most of them is considered as bad style.)
| Java and whitespace-as-syntax (ala Python)? | There is a part of java syntax that bugs the crap out of me: that's curly braces and semicolons. Is there some sort of translator that exists that will allow me to use all of the Java syntax except for this? I want to do something like this:
public class Hello:
public static void main(String[] args):
System.out.println("I like turtles.")
public class Another:
public static void somethingelse():
System.out.println("And boobs")
It's Python's whitespace as syntax model, I've grown to love it. I believe it's cleaner, and easier on the eyes. If it doesn't exist, I'm actually considering heavily investing time into writing a parser that would do this for me. (Ideally it will open it up, format it with whitespace, and when saved, save as just java syntax with braces and all)
Would this cause problems elsewhere in the language? What kind of hiccups can I expect to run into? I want to use all of the rest of the Java syntax exactly how it is otherwise, just want to modify this small niggle.
I can already write and read code just fine in Eclipse. And yes, I already know how to use code formatting tools and all the auto-complete options available to me, this is merely a preference in coding style so please don't answer with "You should learn to get used to it" or "You should use an IDE that does braces FOR you"...no. I don't want that.
| [
"Can you switch to Jython? Python's syntax, Java's runtime environment.\n",
"You might consider instead investing time in learning to use eclipse and the code formatter. \nPython's model is great in that it (more or less) forces all developers into the same code style format. Modern software firms have code-style... | [
2,
0,
0
] | [] | [] | [
"java",
"python",
"syntax",
"whitespace"
] | stackoverflow_0004251478_java_python_syntax_whitespace.txt |
Q:
Switching from amara to lxml in Python
I am trying to accomplish with lxml library something like this:
http://www.xml.com/pub/a/2005/01/19/amara.html
from amara import binderytools
container = binderytools.bind_file('labels.xml')
for l in container.labels.label:
print l.name, 'of', l.address.city
but I have had the hardest time to get my feel wet! What I want to do is: descend to the root node named 'X', then descend to its second child named 'Y', then grab all of its children 'named Z', then of those keep only the children than have an attribute 'name' set to 'bacon', then for each remaining node look at all of its children named 'W', and keep only a subset based on some filter, which looks at W's only children named A, B, and C. Then I need to process them with the following (non-optimized) pseudo-code:
result = []
X = root(doc(parse(xml_file_name)))
Y = X[1] # Second child
Zs = Y.children()
for Z in Zs:
if Z.name != 'bacon': continue # skip
Ws = Z.children()
record = []
assert(len(Ws) == 9)
W0 = Ws[0]
assert(W0.A == '42')
record.append(str(W0.A) + " " + W0.B + " " + W0.C))
...
W1 = Ws[1]
assert(W1.A == '256')
...
result.append(record)
This is sort of what I am trying to accomplish. Before I try to make this code cleaner, I would like to make it work.
Please help, as I am lost in this API. Let me know if you have questions.
A:
import lxml.etree as le
import io
content='''\
<foo><X><Y>skip this</Y><Y><Z name="apple"><W>not here</W></Z>
<Z name="bacon"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>
<Z name="bacon"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>
</Y></X></foo>
'''
doc=le.parse(io.BytesIO(content))
# print(le.tostring(doc, pretty_print=True))
result=[]
Zs=doc.xpath('//X/Y[2]/Z[@name="bacon"]')
for Z in Zs:
Ws=Z.xpath('W')
record=[]
assert(len(Ws)==2) #<--- Change to 9
abc=Ws[0].xpath('descendant::text()')
# print(abc)
# ['42', 'b', 'c']
assert(abc[0] == '42')
record.append(' '.join(abc))
abc=Ws[1].xpath('descendant::text()')
assert(abc[0] == '256')
result.append(record)
print(result)
# [['42 b c'], ['42 b c']]
This might be a way to tighten-up the inner loop, though I'm only guessing what records you wish to keep:
for Z in Zs:
Ws=Z.xpath('W')
assert(len(Ws)==2) #<--- Change to 9
a_vals=('42','256')
for W,a_val in zip(Ws,a_vals):
abc=W.xpath('descendant::text()')
assert(abc[0] == a_val)
result.append([' '.join(abc)])
print(result)
# [['42 b c'], ['256 b c'], ['42 b c'], ['256 b c']]
| Switching from amara to lxml in Python | I am trying to accomplish with lxml library something like this:
http://www.xml.com/pub/a/2005/01/19/amara.html
from amara import binderytools
container = binderytools.bind_file('labels.xml')
for l in container.labels.label:
print l.name, 'of', l.address.city
but I have had the hardest time to get my feel wet! What I want to do is: descend to the root node named 'X', then descend to its second child named 'Y', then grab all of its children 'named Z', then of those keep only the children than have an attribute 'name' set to 'bacon', then for each remaining node look at all of its children named 'W', and keep only a subset based on some filter, which looks at W's only children named A, B, and C. Then I need to process them with the following (non-optimized) pseudo-code:
result = []
X = root(doc(parse(xml_file_name)))
Y = X[1] # Second child
Zs = Y.children()
for Z in Zs:
if Z.name != 'bacon': continue # skip
Ws = Z.children()
record = []
assert(len(Ws) == 9)
W0 = Ws[0]
assert(W0.A == '42')
record.append(str(W0.A) + " " + W0.B + " " + W0.C))
...
W1 = Ws[1]
assert(W1.A == '256')
...
result.append(record)
This is sort of what I am trying to accomplish. Before I try to make this code cleaner, I would like to make it work.
Please help, as I am lost in this API. Let me know if you have questions.
| [
"import lxml.etree as le\nimport io\n\ncontent='''\\\n<foo><X><Y>skip this</Y><Y><Z name=\"apple\"><W>not here</W></Z>\n<Z name=\"bacon\"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>\n<Z name=\"bacon\"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>\n</Y></X></foo>\n''... | [
3
] | [] | [] | [
"amara",
"lxml",
"python",
"xml_parsing"
] | stackoverflow_0004251750_amara_lxml_python_xml_parsing.txt |
Q:
Opening Webpage using Python
I am new to Python coding and i am trying to open a web page using python. I used web browser.open to open the web page. After i opened the web page i want to click a tab called "Submit" on the web page when the timer on the page reaches zero. If i get a error then it should return to the original page without any user interaction. Is this possible?
Thanks
A:
Instead of using that particular module, maybe you want to use Selenium RC, which has python bindings.
A:
This will depend on if you need to use a "real" browser application to do this. Can you explain what you are trying to do in a bit more detail?
Anyway...
If you need a "real" browser to launch and make these requests, then the Selenium RC package is what you need.
On the other hand, if it's OK that Python does all the page loading internally, then the popular Mechanize module should do the trick.
To Explain:
If you are depending on a complex JavaScript powered page, then you must use Selenium. If it's just HTML stuff, then Mechanize can emulate it all inside python.
Hope this helps. If so, mark this answered and let me know. :-)
A:
This is what mechanize is for: http://wwwsearch.sourceforge.net/mechanize/
| Opening Webpage using Python | I am new to Python coding and i am trying to open a web page using python. I used web browser.open to open the web page. After i opened the web page i want to click a tab called "Submit" on the web page when the timer on the page reaches zero. If i get a error then it should return to the original page without any user interaction. Is this possible?
Thanks
| [
"Instead of using that particular module, maybe you want to use Selenium RC, which has python bindings.\n",
"This will depend on if you need to use a \"real\" browser application to do this. Can you explain what you are trying to do in a bit more detail?\nAnyway...\nIf you need a \"real\" browser to launch and m... | [
3,
2,
1
] | [] | [] | [
"python",
"python_webbrowser",
"url"
] | stackoverflow_0004251809_python_python_webbrowser_url.txt |
Q:
beginner question about python multiprocessing?
I have a number of records in the database I want to process. Basically, I want to run several regex substitution over tokens of the text string rows and at the end, and write them back to the database.
I wish to know whether does multiprocessing speeds up the time required to do such tasks.
I did a
multiprocessing.cpu_count
and it returns 8. I have tried something like
process = []
for i in range(4):
if i == 3:
limit = resultsSize - (3 * division)
else:
limit = division
#limit and offset indicates the subset of records the function would fetch in the db
p = Process(target=sub_table.processR,args=(limit,offset,i,))
p.start()
process.append(p)
offset += division + 1
for po in process:
po.join()
but apparently, the time taken is higher than the time required to run a single thread. Why is this so? Can someone please enlighten is this a suitable case or what am i doing wrong here?
A:
Why is this so?
Can someone please enlighten in what cases does multiprocessing gives better performances?
Here's one trick.
Multiprocessing only helps when your bottleneck is a resource that's not shared.
A shared resource (like a database) will be pulled in 8 different directions, which has little real benefit.
To find a non-shared resource, you must have independent objects. Like a list that's already in memory.
If you want to work from a database, you need to get 8 things started which then do no more database work. So, a central query that distributes work to separate processors can sometimes be beneficial.
Or 8 different files. Note that the file system -- as a whole -- is a shared resource and some kinds of file access are involve sharing something like a disk drive or a directory.
Or a pipeline of 8 smaller steps. The standard unix pipeline trick query | process1 | process2 | process3 >file works better than almost anything else because each stage in the pipeline is completely independent.
Here's the other trick.
Your computer system (OS, devices, database, network, etc.) is so complex that simplistic theories won't explain performance at all. You need to (a) take several measurements and (b) try several different algorithms until you understand all the degrees of freedom.
A question like "Can someone please enlighten in what cases does multiprocessing gives better performances?" doesn't have a simple answer.
In order to have a simple answer, you'd need a much, much simpler operating system. Fewer devices. No database and no network, for example. Since your OS is complex, there's no simple answer to your question.
A:
In general, multicpu or multicore processing help most when your problem is CPU bound (i.e., spends most of its time with the CPU running as fast as it can).
From your description, you have an IO bound problem: It takes forever to get data from disk to the CPU (which is idle) and then the CPU operation is very fast (because it is so simple).
Thus, accelerating the CPU operation does not make a very big difference overall.
A:
Here are a couple of questions:
In your processR function, does it slurp a large number of records from the database at one time, or is it fetching 1 row at a time? (Each row fetch will be very costly, performance wise.)
It may not work for your specific application, but since you are processing "everything", using database will likely be slower than a flat file. Databases are optimised for logical queries, not seqential processing. In your case, can you export the whole table column to a CSV file, process it, and then re-import the results?
Hope this helps.
| beginner question about python multiprocessing? | I have a number of records in the database I want to process. Basically, I want to run several regex substitution over tokens of the text string rows and at the end, and write them back to the database.
I wish to know whether does multiprocessing speeds up the time required to do such tasks.
I did a
multiprocessing.cpu_count
and it returns 8. I have tried something like
process = []
for i in range(4):
if i == 3:
limit = resultsSize - (3 * division)
else:
limit = division
#limit and offset indicates the subset of records the function would fetch in the db
p = Process(target=sub_table.processR,args=(limit,offset,i,))
p.start()
process.append(p)
offset += division + 1
for po in process:
po.join()
but apparently, the time taken is higher than the time required to run a single thread. Why is this so? Can someone please enlighten is this a suitable case or what am i doing wrong here?
| [
"\nWhy is this so?\nCan someone please enlighten in what cases does multiprocessing gives better performances?\n\nHere's one trick.\nMultiprocessing only helps when your bottleneck is a resource that's not shared.\nA shared resource (like a database) will be pulled in 8 different directions, which has little real b... | [
5,
1,
1
] | [] | [] | [
"multicore",
"postgresql",
"python"
] | stackoverflow_0004252126_multicore_postgresql_python.txt |
Q:
passing multiple parameters for the url using pycurl
I want to make a curl call with a URL that has multiple parameters. I have listed the code below. Is there an equivalent option for "curl -d @filter" for instance or do I have URL encode the parameters?
SER = foobar
PASS = XXX
STREAM_URL = "http://status.dummy.com/status.json?userId=12&page=1"
class Client:
def __init__(self):
self.buffer = ""
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER,PASS))
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self,data):
self.buffer += data
A:
Pycurl is a pretty thin wrapper for libcurl. If you can do it with libcurl, you can do it with pycurl. (Mostly.)
For instance:
pycurl.setopt corresponds to curl_easy_setopt in libcurl, where option is specified with the CURLOPT_* constants in libcurl, except that the CURLOPT_ prefix has been removed.
See: http://pycurl.sourceforge.net/doc/curlobject.html
That being said, the curl -d option is for sending HTTP POST requests... not the GET style your example shows.
libcurl does expect that urls it recives already be URL encoded. Just use http://docs.python.org/library/urllib.html if needed.
The sample URL in your question already has 2 parameters (userId and page).
In general the format is: URL followed by a 'question mark', followed by name=value pairs joined by an ampersand symbol. If the name or value contain special chars, you will need to percent-encoded them.
Just use the urlencode function:
>>> import urllib
>>> params = [('name1','value1'), ('name2','value2 with spaces & stuff')]
>>> pairs = urllib.urlencode(params)
>>> fullurl = 'http://status.dummy.com/status.json' + '?' + pairs
>>> print fullurl
http://status.dummy.com/status.json?name1=value1&name2=value2+with+spaces+%26+stuff
>>>
Also, see the urllib.urlopen function. Perhaps you do not need curl at all? (But I do not know your application...)
Hope this helps. If so, mark answered and let me know. :-)
| passing multiple parameters for the url using pycurl | I want to make a curl call with a URL that has multiple parameters. I have listed the code below. Is there an equivalent option for "curl -d @filter" for instance or do I have URL encode the parameters?
SER = foobar
PASS = XXX
STREAM_URL = "http://status.dummy.com/status.json?userId=12&page=1"
class Client:
def __init__(self):
self.buffer = ""
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER,PASS))
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self,data):
self.buffer += data
| [
"Pycurl is a pretty thin wrapper for libcurl. If you can do it with libcurl, you can do it with pycurl. (Mostly.)\nFor instance:\n\npycurl.setopt corresponds to curl_easy_setopt in libcurl, where option is specified with the CURLOPT_* constants in libcurl, except that the CURLOPT_ prefix has been removed.\n\nSee: ... | [
3
] | [] | [] | [
"curl",
"pycurl",
"python"
] | stackoverflow_0004252262_curl_pycurl_python.txt |
Q:
Fast algorithm to calculate delta of two list
I have two list of album names, ordered by some score.
albums_today = ['album1', 'album2', 'album3']
albums_yesterday = ['album2', 'album1', 'album3']
How can I calculate the change of list order and get something like
{'album1':1, 'album2':-1, 'album3':0}
A:
>>> albums_today = ['album1', 'album2', 'album3']
>>> albums_yesterday = ['album2', 'album1', 'album3']
>>> D = dict((k,v) for v,k in enumerate(albums_yesterday))
>>> dict((k,D[k]-v) for v,k in enumerate(albums_today))
{'album1': 1, 'album3': 0, 'album2': -1}
In Python2.7 or Python3 it can be written even more simply
>>> albums_today = ['album1', 'album2', 'album3']
>>> albums_yesterday = ['album2', 'album1', 'album3']
>>> D = {k:v for v,k in enumerate(albums_yesterday)}
>>> {k:D[k]-v for v,k in enumerate(albums_today)}
{'album1': 1, 'album3': 0, 'album2': -1}
A:
you could also use the same algorithm as i wrote above and just use a single hashmap.
def findDelta1(today,yesterday):
results = {}
ypos = 0
for i,title in enumerate(today):
if title in results:
results[title] = results[title] - i
else:
for ypos in xrange(ypos,len(yesterday)):
if yesterday[ypos] == title:
results[title] = ypos - i
ypos = ypos + 1
break
else:
results[yesterday[ypos]] = ypos
return results
still O(N), potentially faster and less RAM than my version above.
A:
how about this:
def delta(a, b):
rank_a = dict((k, v) for v, k in enumerate(a))
rank_b = enumerate(b)
return dict((k, rank_a[k]-i) for i, k in rank_b)
which only creates a single dict to look things up into.
Well, as long as every entry in both lists are present exactly once each, then we know that once we look a key up in the rank_a collection, we don't need it anymore. We can delete it. Also, to save space, we don't have to populate that collection until the moment a particular key is needed.
class LookupOnce:
def __init__(self, seq):
self.cache = {}
self.seq = iter(seq)
def get(self, key):
if key in self.cache:
value = self.cache[key]
del self.cache[key]
return value
for v,k in self.seq:
if k == key:
return v
self.cache[k] = v
raise KeyError
def delta(a, b):
rank_a = LookupOnce(enumerate(a))
rank_b = enumerate(b)
result = {}
for i, k in rank_b:
result[k] = i - rank_a.get(k)
return result
A:
>>> def transform(albums):
... return dict((album, i) for i, album in enumerate(albums))
...
>>> def show_diffs(album1, album2):
... album_dict1, album_dict2 = transform(album1), transform(album2)
... for k, v in sorted(album_dict1.iteritems()):
... print k, album_dict2[k] - v
...
>>> albums_today = ['album1', 'album2', 'album3']
>>> albums_yesterday = ['album2', 'album1', 'album3']
>>> show_diffs(albums_today, albums_yesterday)
album1 1
album2 -1
album3 0
A:
well, depending on what the sizes of your lists are, there are a number of different approaches. without knowing how big your datasets are, i'd suggest that the simplest (perhaps unnecessarily optimized) method is something like:
albums_yesterday_lookup = new HashMap();
differences = new HashMap();
foreach(albums_yesterday as position => album_title)
albums_yesterday_lookup.put(album_title,position);
foreach(albums_today as position => album_title)
differences.put(album_title, albums_yesterday_lookup.get(album_title) - position);
which runs as O(N).
A:
New and Improved and not O(n2): But still slower than two of the other answers.
The only advantage of this solution is memory savings. It avoids building a big dict and instead stores only what is necessary at the time. TokenMacGuy's second solution does this as well but this is slightly faster.
def get_deltas_aas(today, yesterday):
deltas = {}
for (new_rank, new_album), (old_rank, old_album) in \
itertools.izip(enumerate(today), enumerate(yesterday)):
if old_album in deltas:
#Believe it or not, this is faster than deltas.pop(old_album) + old_rank
yield (old_album, deltas[old_album] + old_rank)
del deltas[old_album]
else:
deltas[old_album] = old_rank
if new_album in deltas:
yield (new_album, deltas[new_album] - new_rank)
del deltas[new_album]
else:
deltas[new_album] = -new_rank
Here's some timing results for most of the answers here (all of the ones in Python unless I missed something). dict ordering is in effect. If anybody wants me to change their code in any way, just ping me.
get_deltas_token1: 1.08131885529 msecs
get_deltas_gnibbler: 1.06443881989 msecs
get_deltas_tyler: 1.61993408203 msecs
get_deltas_token2: 1.52525019646 msecs
get_deltas_hughdbrown: 3.27240777016 msecs
get_deltas_aas: 1.39379096031 msecs
The code I used to do the timing is here. I'm pleased with the timing framework I tossed together for it on top of timeit. Should be useful in the future after refactoring the code for running the tests.
A:
D = dict((title, rank) for rank, title in enumerate(albums_yesterday))
for rank, title in enumerate(albums_today):
D[title] = D[title] - rank
| Fast algorithm to calculate delta of two list | I have two list of album names, ordered by some score.
albums_today = ['album1', 'album2', 'album3']
albums_yesterday = ['album2', 'album1', 'album3']
How can I calculate the change of list order and get something like
{'album1':1, 'album2':-1, 'album3':0}
| [
">>> albums_today = ['album1', 'album2', 'album3']\n>>> albums_yesterday = ['album2', 'album1', 'album3']\n>>> D = dict((k,v) for v,k in enumerate(albums_yesterday))\n>>> dict((k,D[k]-v) for v,k in enumerate(albums_today))\n{'album1': 1, 'album3': 0, 'album2': -1}\n\nIn Python2.7 or Python3 it can be written even m... | [
6,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004251732_algorithm_python.txt |
Q:
recursive search boolean return function
Write a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn’t. Describe the base case(s) and how the smaller problem relates to the bigger one. You may not use the in operator or the index() list method.
Can anyone explain what i need to do here for the description? I dont know anything about recurrsion to know where to start. Its for a exam review lab assignment.
Here is the code i have been provided.
def search(l,key):
"""
locates key in list l. if present, returns True; else returns False.
PRE: l is a list.
POST: l is unchanged; returns True if key in l; False otherwise.
"""
Sample Main:
l1 = [1, '2', 'x', 5, -2]
print search(l1, 'x') # should output: "True"
print search(l1, 2) # should output: "False"
A:
All recursion tends to follow the same rules:
Have one or more terminating cases.
Every other case is a slightly simpler form of the current case.
So, for example, a (very inefficient) way to add two positive numbers a and b:
if b is zero, return a.
otherwise add the two numbers a+1 and b-1.
Something like:
def addtwo (a, b):
if b == 0:
return a
return addtwo (a+1, b-1)
Now let's think about the cases for your assignment:
if the list is empty, you didn't find it: return false.
if the first element of the list is equal to your key, you found it: return true.
otherwise look in the list made by removing the first element.
In pseudo-code (which is very similar to Python but different enough that you'll have to do some work):
def search (list, key):
if list is empty:
return false
if key == first item in list:
return true
return search (list with first element removed, key)
A:
Every question regarding recursion should be dealt with the same way (usually)...Ask yourself what is the base case and then build on that for higher cases...
So in this question, ask yourself, when can i be certain there is no key in the list...
It's obviously when the list is empty, you're certain it's not present.
For a bigger list, you compare the first element, if it's the same as the key, you return True right away, but incase it's not, you perform all the checks for the rest of the list....
So studying all these aspects,
Here's your Algorithm.
function locate(lst,key)
if lst == emptylist then return False
if lst[0] == key then return True
else return locate(lst[1..],key) //i use the notation lst[1...] to indicate list starting from 1 index.
| recursive search boolean return function | Write a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn’t. Describe the base case(s) and how the smaller problem relates to the bigger one. You may not use the in operator or the index() list method.
Can anyone explain what i need to do here for the description? I dont know anything about recurrsion to know where to start. Its for a exam review lab assignment.
Here is the code i have been provided.
def search(l,key):
"""
locates key in list l. if present, returns True; else returns False.
PRE: l is a list.
POST: l is unchanged; returns True if key in l; False otherwise.
"""
Sample Main:
l1 = [1, '2', 'x', 5, -2]
print search(l1, 'x') # should output: "True"
print search(l1, 2) # should output: "False"
| [
"All recursion tends to follow the same rules:\n\nHave one or more terminating cases.\nEvery other case is a slightly simpler form of the current case.\n\nSo, for example, a (very inefficient) way to add two positive numbers a and b:\n\nif b is zero, return a.\notherwise add the two numbers a+1 and b-1.\n\nSomethin... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004252471_python.txt |
Q:
Generate all possible numpad/keypad sequences
I am trying to generate all possible keypad sequences (7 digit length only right now). For example if the mobile keypad looks like this:
1 2 3
4 5 6
7 8 9
0
Some of the possible sequences can be:
123698
147896
125698
789632
The requirement is that the each digit of number should be neighbor of previous digit.
Here is how I am planning to start this:
The information about the neighbor changes from keypad to keypad so we have to hardcode it like this:
neighbors = {0: 8, 1: [2,4], 2: [1,3,5], 3: [2,6], 4: [1,5,7], 5: [2,4,6,8], 6: [3,5,9], 7: [4,8], 8: [7,5,9,0], 9: [6,8]}
I will be traversing through all digits and will append one of the possible neighbors to it until required length is achieved.
EDIT: Updated neighbors, no diagonals allowed
EDIT 2: Digits can be reused
A:
Try this.
neighbors = {0: [8],
1: [2,4],
2: [1,4,3],
3: [2,6],
4: [1,5,7],
5: [2,4,6,8],
6: [3,5,9],
7: [4,8],
8: [7,5,9,0],
9: [6,8]}
def get_sequences(n):
if not n:
return
stack = [(i,) for i in range(10)]
while stack:
cur = stack.pop()
if len(cur) == n:
yield cur
else:
stack.extend(cur + (d, ) for d in neighbors[cur[-1]])
print list(get_sequences(3))
This will produce all possible sequences. You didn't mention if you wanted ones that have cycles in them, for example (0, 8, 9, 8) so I left them in. If you don't want them, then just use
stack.extend(cur + (d, )
for d in neighbors[cur[-1]]
if d not in cur)
Note that I made the entry for 0 a list with one element instead of just an integer. This is for consistency. It's very nice be able to index into the dictionary and know that you're going to get a list back.
Also note that this isn't recursive. Recursive functions are great in languages that properly support them. In Python, you should almost always manage a stack like I demonstrate here. It's just as easy as a recursive solution and sidesteps function call overhead (python doesn't support tail recursion) and maximum recursion depth concerns.
A:
neighbors = {0: [8], 1: [2,5,4], 2: [1,4,3], 3: [2,5,6], 4: [1,5,7], 5: [2,4,6,8], 6: [3,5,9], 7: [4,5,8], 8: [7,5,9,0], 9: [6,5,8]}
def gen_neighbor_permutations(n, current_prefix, available_digit_set, removed_digits=set(), unique_digits=False):
if n == 0:
print current_prefix
return
for d in available_digit_set:
if unique_digits:
gen_neighbor_permutations(n-1, current_prefix + str(d), set(neighbors[d]).difference(removed_digits), removed_digits.union(set([d])), unique_digits=True )
else:
gen_neighbor_permutations(n-1, current_prefix + str(d), set(neighbors[d]).difference(removed_digits) )
gen_neighbor_permutations(n=3, current_prefix='', available_digit_set=start_set)
I also couldn't help but notice that in your examples, none of the digits are reused. If you want that, then you would use the unique_digits = True option; this will disallow recursion on digits that are already used.
+1 What a fun puzzle. I hope this works for you!
gen_neighbor_permutations(n=3, current_prefix='', available_digit_set=start_set, unique_digits = True)
A:
Recursion isn't really much of an issue here because the sequence is relatively short as are the choices for each digit except the first -- so there appear to "only" be 4790 possibilities disallowing diagonals. This is written as an iterator to eliminate the need to create and return a large container with all possibilities produced in it.
It occurred to me that an additional benefit of the data-driven approach of storing the neighbor adjacency information in a data structure (as the OP suggested) was that besides easily supporting different keypads, it also makes controlling whether diagonals are allowed or not trivial.
I debated briefly about whether to make it a list instead of a dictionary for faster lookups, but realized that doing so would make it more difficult to adapt to produce sequences other than digits (and likely wouldn't make it significantly faster anyway).
adjacent = {1: [2,4], 2: [1,3,4], 3: [2,6],
4: [1,5,7], 5: [2,4,6,8], 6: [3,5,9],
7: [4,8], 8: [0,5,7,9], 9: [6,8],
0: [8]}
def adj_sequences(ndigits):
seq = [None]*ndigits # pre-allocate
def next_level(i):
for neighbor in adjacent[seq[i-1]]:
seq[i] = neighbor
if i == ndigits-1: # last digit?
yield seq
else:
for digits in next_level(i+1):
yield digits
for first_digit in range(10):
seq[0] = first_digit
for digits in next_level(1):
yield digits
cnt = 1
for digits in adj_sequences(7):
print '{:d}: {!r}'.format(cnt, ''.join(map(str,digits)))
cnt += 1
A:
That's a classic recursive algorithm. Some pseudo code to show the concept:
function(numbers) {
if (length(numbers)==7) {
print numbers;
return;
}
if (numbers[last]=='1') {
function(concat(numbers, '2'));
function(concat(numbers, '4'));
return;
}
if (numbers[last]==='2') {
function(concat(numbers, '1'));
function(concat(numbers, '3'));
function(concat(numbers, '5'));
return;
}
...keep going with a condition for each digit..
}
A:
neighbors = {0: [8], 1: [2,5,4], 2: [1,4,3], 3: [2,5,6], 4: [1,5,7], 5: [2,4,6,8], 6: [3,5,9], 7: [4,5,8], 8: [7,5,9,0], 9: [6,5,8]}
def keyNeighborsRec(x, length):
if length == 0:
print x
return
for i in neighbors[x%10]:
keyNeighborsRec(x*10+i,length-1)
def keyNeighbors(l):
for i in range(10):
keyNeighborsRec(i,length-1)
keyNeighbors(7)
its really easy without the neighbor condition...
def keypadSequences(length):
return map(lambda x: '0'*(length-len(repr(x)))+repr(x), range(10**length))
keypadSequences(7)
A:
states = [
[8],
[2, 4],
[1, 3, 5],
[2, 6],
[1, 5, 7],
[2, 4, 6, 8],
[3, 5, 9],
[4, 8],
[5, 7, 9, 0],
[6, 8]
]
def traverse(distance_left, last_state):
if not distance_left:
yield []
else:
distance_left -= 1
for s in states[last_state]:
for n in traverse(distance_left, s):
yield [s] + n
def produce_all_series():
return [t for i in range(10) for t in traverse(7, i)]
from pprint import pprint
pprint(produce_all_series())
| Generate all possible numpad/keypad sequences | I am trying to generate all possible keypad sequences (7 digit length only right now). For example if the mobile keypad looks like this:
1 2 3
4 5 6
7 8 9
0
Some of the possible sequences can be:
123698
147896
125698
789632
The requirement is that the each digit of number should be neighbor of previous digit.
Here is how I am planning to start this:
The information about the neighbor changes from keypad to keypad so we have to hardcode it like this:
neighbors = {0: 8, 1: [2,4], 2: [1,3,5], 3: [2,6], 4: [1,5,7], 5: [2,4,6,8], 6: [3,5,9], 7: [4,8], 8: [7,5,9,0], 9: [6,8]}
I will be traversing through all digits and will append one of the possible neighbors to it until required length is achieved.
EDIT: Updated neighbors, no diagonals allowed
EDIT 2: Digits can be reused
| [
"Try this.\n neighbors = {0: [8], \n 1: [2,4], \n 2: [1,4,3], \n 3: [2,6], \n 4: [1,5,7], \n 5: [2,4,6,8], \n 6: [3,5,9], \n 7: [4,8], \n 8: [7,5,9,0], \n 9: [6,8]}\n\n\ndef get_sequences(n):\n if not n:\n... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"numbers",
"python"
] | stackoverflow_0004250342_algorithm_numbers_python.txt |
Q:
AppEngine Python project moved to Ubuntu from Windows will no longer run
Since moving from Windows to Ubuntu (and setting up AppEngine, AppEngine Launcher, Python 2.5), my AppEngine projects will no longer run properly.
Here is what's thrown back from any file when trying to browse the app in my web browser (running locally through dev_appserver.py), for example:
Traceback (most recent call last):
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 3211, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 3154, in _Dispatch
base_env_dict=env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 527, in Dispatch
base_env_dict=base_env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2404, in Dispatch
self._module_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2314, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2205, in ExecuteOrImportScript
handler_path, cgi_path, import_hook)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2136, in LoadTargetModule
module_code = compile(source_file.read(), cgi_path, 'exec')
File "/home/mike/Projects/..removed project name ../Site/main/main.py", line 1
from google.appengine.ext import webapp
^
SyntaxError: invalid syntax
Any idea where I start with this? I have had a fiddle but have no idea what's going on. Is this to do with the different encoding formats or something between Windows and Linux. I'm pretty clueless about that kind of thing...
Thanks for any help.
A:
Check your line endings to make sure they are Unix style, and no longer DOS style.
| AppEngine Python project moved to Ubuntu from Windows will no longer run | Since moving from Windows to Ubuntu (and setting up AppEngine, AppEngine Launcher, Python 2.5), my AppEngine projects will no longer run properly.
Here is what's thrown back from any file when trying to browse the app in my web browser (running locally through dev_appserver.py), for example:
Traceback (most recent call last):
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 3211, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 3154, in _Dispatch
base_env_dict=env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 527, in Dispatch
base_env_dict=base_env_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2404, in Dispatch
self._module_dict)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2314, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2205, in ExecuteOrImportScript
handler_path, cgi_path, import_hook)
File "/home/mike/AppEngine/google/appengine/tools/dev_appserver.py", line 2136, in LoadTargetModule
module_code = compile(source_file.read(), cgi_path, 'exec')
File "/home/mike/Projects/..removed project name ../Site/main/main.py", line 1
from google.appengine.ext import webapp
^
SyntaxError: invalid syntax
Any idea where I start with this? I have had a fiddle but have no idea what's going on. Is this to do with the different encoding formats or something between Windows and Linux. I'm pretty clueless about that kind of thing...
Thanks for any help.
| [
"Check your line endings to make sure they are Unix style, and no longer DOS style.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004252504_google_app_engine_python.txt |
Q:
Python GeoModel alternative
I'm looking for an alternative library for the app engine datastore that will do nearest-n or boxed geo-queries, currently i'm using GeoModel 0.2 and it runs quite slow ( > 1.5s in some cases). Does anyone have any suggestions?
Thanks!
A:
I have a same problem with geomodel.
For correct it, i use a resolution of 4 and i use a python sorted and filter.
SEARCHED_LOCATION = db.GeoPt("48.8566667, 2.3509871") # Location of Paris.
DISTANCE = 50000 #Between 10000 and 150000.
MAX_RESULTS = 300
# Resolution '4' is about 150 kilometers i suppose it's a good compromise.
bbox = geocell.compute_box(geocell.compute(SEARCHED_LOCATION, resolution=4))
cell = geocell.best_bbox_search_cells(bbox, geomodel.default_cost_function)
query.filter('location_geocells IN', cell)
# Python filters
def _func(x):
"""Private method used to set the distance of the model to the searched location
and return this distance.
"""
x.dist = geomath.distance(SEARCHED_LOCATION, x.location)
return x.dist
results = sorted(query.fetch(MAX_RESULTS), key=_func) # Order the result by distance
results = [x for x in results if x.dist <= DISTANCE] # Filter the result
A:
Instead of using the geomodel 0.2.0 release, use the withasync branch (see
http://code.google.com/p/geomodel/source/browse/#svn/branches/withasync). This will let you run the queries in parallel using asynctools, which will be significantly faster for many queries.
Be sure you have asynctools in your app/pythonpath as well.
A:
I can't point you to an existing library that has better performance, but as I recall, GeoModel is open source and the code isn't difficult to understand. We found that we could make some speed improvements by adjusting the code to fit our scenario.
For example, if you don't need nearest-n, you just need X results from within a particular bounding box or radius, you can probably improve GeoModel's speed, as GeoModel has to currently get every record in the appropriate geohash and then sorts for closest in memory. (Details of that implementation left as an exercise for the reader.)
You might also consider tuning how many levels of geohash you're using. If you have a lot of dense data and are querying over small areas, you might considerably increase performance by keeping 16 levels instead of 8 or 12.
(I'm not looking at the GeoModel source right now but recalling when I last used it several months ago, so take this with a grain of salt and dive into the source code yourself.)
| Python GeoModel alternative | I'm looking for an alternative library for the app engine datastore that will do nearest-n or boxed geo-queries, currently i'm using GeoModel 0.2 and it runs quite slow ( > 1.5s in some cases). Does anyone have any suggestions?
Thanks!
| [
"I have a same problem with geomodel.\nFor correct it, i use a resolution of 4 and i use a python sorted and filter.\nSEARCHED_LOCATION = db.GeoPt(\"48.8566667, 2.3509871\") # Location of Paris.\nDISTANCE = 50000 #Between 10000 and 150000.\nMAX_RESULTS = 300\n\n# Resolution '4' is about 150 kilometers i suppose it'... | [
6,
4,
2
] | [] | [] | [
"geohashing",
"gis",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003993862_geohashing_gis_google_app_engine_google_cloud_datastore_python.txt |
Q:
Uneven base-36 support in Python?
I've been working with base-36 recently and have never been satisfied with the usual answer to converting ints into base-36 strings. It looks a little imbalanced…
def to_base36(value):
if not isinstance(value, int):
raise TypeError("expected int, got %s: %r" % (value.__class__.__name__, value))
if value == 0:
return "0"
if value < 0:
sign = "-"
value = -value
else:
sign = ""
result = []
while value:
value, mod = divmod(value, 36)
result.append("0123456789abcdefghijklmnopqrstuvwxyz"[mod])
return sign + "".join(reversed(result))
…when compared to converting back…
def from_base36(value):
return int(value, 36)
Does Python really not include this particular battery?
A:
Have you tried the basin package?
>>> import basin
>>> basin.encode("0123456789abcdefghijklmnopqrstuvwxyz", 100)
'2s'
It's not batteries included, but the pypi repository is like a convenience store for picking up batteries with the minimum of fuss.
A:
Correct. Not every store carries N or J batteries.
A:
To continue the analogy, that size battery may not be included in the basic package, but it's easy enough to shop on-line for plug-compatible accessories:
http://code.activestate.com/recipes/365468-number-to-string-in-arbitrary-base/
| Uneven base-36 support in Python? | I've been working with base-36 recently and have never been satisfied with the usual answer to converting ints into base-36 strings. It looks a little imbalanced…
def to_base36(value):
if not isinstance(value, int):
raise TypeError("expected int, got %s: %r" % (value.__class__.__name__, value))
if value == 0:
return "0"
if value < 0:
sign = "-"
value = -value
else:
sign = ""
result = []
while value:
value, mod = divmod(value, 36)
result.append("0123456789abcdefghijklmnopqrstuvwxyz"[mod])
return sign + "".join(reversed(result))
…when compared to converting back…
def from_base36(value):
return int(value, 36)
Does Python really not include this particular battery?
| [
"Have you tried the basin package? \n>>> import basin\n>>> basin.encode(\"0123456789abcdefghijklmnopqrstuvwxyz\", 100)\n'2s'\n\nIt's not batteries included, but the pypi repository is like a convenience store for picking up batteries with the minimum of fuss.\n",
"Correct. Not every store carries N or J batterie... | [
8,
4,
1
] | [] | [] | [
"base36",
"python"
] | stackoverflow_0004253053_base36_python.txt |
Q:
Inserting bold characters in pyGTK's TextView/TextBuffer
I have a TextView and a TextBuffer associated with it.
When the user presses Ctrl+b, I would like the text to be start typing in bold until user presses Ctrl+b again.
I was trying my own methods, which weren't working, and then I found this post on the mailing list:
http://www.daa.com.au/pipermail/pygtk/2009-April/016951.html
Same issue as me, and the solution someone gave is
Your application will have to handle the bookkeeping required to manage
the tags in the TextBuffer. When text is inserted at the cursor your app
has to catch a signal indicating the text is being inserted and then
apply the required tags to the inserted text. I think this can be done
by catching theTextBuffer "insert-text" signal (using connect_after()
to make sure the text has already been inserted) and then applying the
tags to the text in the callback.
So I attempted this. This is my textbuffer.py
import gtk
import pango
class TextBuffer(gtk.TextBuffer):
def __init__(self):
gtk.TextBuffer.__init__(self)
self.connect_after('insert-text', self.text_inserted)
# A list to hold our active tags
self.tags_on = []
# Our Bold tag.
self.tag_bold = self.create_tag("bold", weight=pango.WEIGHT_BOLD)
def get_iter_position(self):
return self.get_iter_at_mark(self.get_insert())
def make_bold(self, text):
''' add "bold" to our active tags list '''
self.tags_on.append('bold')
def text_inserted(self, buffer, iter, text, length):
# A text was inserted in the buffer. If there are ny tags in self.tags_on, apply them
if self.tags_on:
print self.get_iter_position()
# This sets the iter back N characters
iter.backward_chars(length)
# And this applies tag from iter to end of buffer
self.apply_tag_by_name('bold', self.get_iter_position(), self.get_end_iter())
print self.get_iter_position()
the method make_bold() gets called from the main script whenever someone pressed Ctrl+b.
Theoretically, this is doing precisely what the mailing help said to do. But is not working. Text is not showing up bold as i type. If i press left arrow and move the cursor back, and then type a character, then the characters from the right of cursor tuns bold.
How can I accomplish this task?
Also, could someone add the tag 'textbuffer' to this? I cannot create new tags and I feel like that tag is more accurate than 'textview'
A:
In the sample code you make the call to iter.backward_chars in TextBuffer.text_inserted
but you never use that iter!, so I make a sample script to show you desired behavior and clarify:
import gtk
import pango
class TextBuffer(gtk.TextBuffer):
def __init__(self):
gtk.TextBuffer.__init__(self)
self.connect_after('insert-text', self.text_inserted)
# A list to hold our active tags
self.tags_on = []
# Our Bold tag.
self.tag_bold = self.create_tag("bold", weight=pango.WEIGHT_BOLD)
def get_iter_position(self):
return self.get_iter_at_mark(self.get_insert())
def make_bold(self):
''' add "bold" to our active tags list '''
if 'bold' in self.tags_on:
del self.tags_on[self.tags_on.index('bold')]
else:
self.tags_on.append('bold')
def text_inserted(self, buffer, iter, text, length):
# A text was inserted in the buffer. If there are ny tags in self.tags_on, apply them
if self.tags_on:
# This sets the iter back N characters
iter.backward_chars(length)
# And this applies tag from iter to end of buffer
self.apply_tag_by_name('bold', self.get_iter_position(), iter)
def main():
window = gtk.Window()
window.connect('destroy', lambda _: gtk.main_quit())
window.resize(300, 300)
tb = TextBuffer()
tv = gtk.TextView(buffer=tb)
accel = gtk.AccelGroup()
accel.connect_group(gtk.keysyms.b,
gtk.gdk.CONTROL_MASK,gtk.ACCEL_LOCKED,
lambda a,b,c,d: tb.make_bold())
window.add_accel_group(accel)
window.add(tv)
window.show_all()
gtk.main()
if __name__ == '__main__':
main()
| Inserting bold characters in pyGTK's TextView/TextBuffer | I have a TextView and a TextBuffer associated with it.
When the user presses Ctrl+b, I would like the text to be start typing in bold until user presses Ctrl+b again.
I was trying my own methods, which weren't working, and then I found this post on the mailing list:
http://www.daa.com.au/pipermail/pygtk/2009-April/016951.html
Same issue as me, and the solution someone gave is
Your application will have to handle the bookkeeping required to manage
the tags in the TextBuffer. When text is inserted at the cursor your app
has to catch a signal indicating the text is being inserted and then
apply the required tags to the inserted text. I think this can be done
by catching theTextBuffer "insert-text" signal (using connect_after()
to make sure the text has already been inserted) and then applying the
tags to the text in the callback.
So I attempted this. This is my textbuffer.py
import gtk
import pango
class TextBuffer(gtk.TextBuffer):
def __init__(self):
gtk.TextBuffer.__init__(self)
self.connect_after('insert-text', self.text_inserted)
# A list to hold our active tags
self.tags_on = []
# Our Bold tag.
self.tag_bold = self.create_tag("bold", weight=pango.WEIGHT_BOLD)
def get_iter_position(self):
return self.get_iter_at_mark(self.get_insert())
def make_bold(self, text):
''' add "bold" to our active tags list '''
self.tags_on.append('bold')
def text_inserted(self, buffer, iter, text, length):
# A text was inserted in the buffer. If there are ny tags in self.tags_on, apply them
if self.tags_on:
print self.get_iter_position()
# This sets the iter back N characters
iter.backward_chars(length)
# And this applies tag from iter to end of buffer
self.apply_tag_by_name('bold', self.get_iter_position(), self.get_end_iter())
print self.get_iter_position()
the method make_bold() gets called from the main script whenever someone pressed Ctrl+b.
Theoretically, this is doing precisely what the mailing help said to do. But is not working. Text is not showing up bold as i type. If i press left arrow and move the cursor back, and then type a character, then the characters from the right of cursor tuns bold.
How can I accomplish this task?
Also, could someone add the tag 'textbuffer' to this? I cannot create new tags and I feel like that tag is more accurate than 'textview'
| [
"In the sample code you make the call to iter.backward_chars in TextBuffer.text_inserted \nbut you never use that iter!, so I make a sample script to show you desired behavior and clarify:\nimport gtk\nimport pango\n\nclass TextBuffer(gtk.TextBuffer):\n def __init__(self):\n gtk.TextBuffer.__init__(self)\... | [
5
] | [] | [] | [
"gtk_textbuffer",
"pygtk",
"python",
"textview"
] | stackoverflow_0004251658_gtk_textbuffer_pygtk_python_textview.txt |
Q:
Django Subprocess live/unbuffered reporting of stdout from batch scripts
Basically the back story is that i've built a selecting of python scripts for a client to process importing and exporting batch jobs between their operations database and their ecomms site database. this works fine. these scripts write to stdout to update the user on the status of the batch script.
I'm trying to produce a framework for these scripts to be run via a django view and to post the stdout to the webpage to show the user the progress of these batch processes.
the plan was to
- call the batch script as a subprocess and then save stdout and stderr to a file.
- return a redirect to a display page that will reload every 2 seconds and display line by line the contents of the file that stdout is being written to.
however the problem is, that the stdout/stderr file is not being actually written to until the entire batch script has finished running or errors out.
i've tried a number of things, but none seem to work.
heres the current view code.
def long_running(app, filename):
"""where app is ['command', 'arg1', 'arg2'] and filename is the file used for output"""
# where to write the result (something like /tmp/some-unique-id)
fullname = temppath+filename
f = file(fullname, "a+")
# launch the script which outputs something slowly
subprocess.Popen(app, stdout=f, stderr=f)# .communicate()
# once the script is done, close the output
f.close()
def attributeexport(request):
filename = "%d_attribute" %(int(time.time())) #set the filename to be the current time stamp plus an identifier
app = ['python','/home/windsor/django/applications/attribute_exports.py']
#break thread for processing.
threading.Thread(target=long_running, args=(app,filename)).start()
return HttpResponseRedirect('/scripts/dynamic/'+filename+'/')
pass
def dynamic(request, viewfile):
fileobj = open(temppath+viewfile, 'r')
results = []
for line in fileobj:
results.append(line)
if '~END' in line:
#if the process has completed
return render_to_response('scripts/static.html', {'displaylist':results, 'filename':viewfile})
return render_to_response('scripts/dynamic.html', {'displaylist':results, 'filename':viewfile})
pass
A:
It helps if you use the following:
['python','-u','path/to/python/script.py']
| Django Subprocess live/unbuffered reporting of stdout from batch scripts | Basically the back story is that i've built a selecting of python scripts for a client to process importing and exporting batch jobs between their operations database and their ecomms site database. this works fine. these scripts write to stdout to update the user on the status of the batch script.
I'm trying to produce a framework for these scripts to be run via a django view and to post the stdout to the webpage to show the user the progress of these batch processes.
the plan was to
- call the batch script as a subprocess and then save stdout and stderr to a file.
- return a redirect to a display page that will reload every 2 seconds and display line by line the contents of the file that stdout is being written to.
however the problem is, that the stdout/stderr file is not being actually written to until the entire batch script has finished running or errors out.
i've tried a number of things, but none seem to work.
heres the current view code.
def long_running(app, filename):
"""where app is ['command', 'arg1', 'arg2'] and filename is the file used for output"""
# where to write the result (something like /tmp/some-unique-id)
fullname = temppath+filename
f = file(fullname, "a+")
# launch the script which outputs something slowly
subprocess.Popen(app, stdout=f, stderr=f)# .communicate()
# once the script is done, close the output
f.close()
def attributeexport(request):
filename = "%d_attribute" %(int(time.time())) #set the filename to be the current time stamp plus an identifier
app = ['python','/home/windsor/django/applications/attribute_exports.py']
#break thread for processing.
threading.Thread(target=long_running, args=(app,filename)).start()
return HttpResponseRedirect('/scripts/dynamic/'+filename+'/')
pass
def dynamic(request, viewfile):
fileobj = open(temppath+viewfile, 'r')
results = []
for line in fileobj:
results.append(line)
if '~END' in line:
#if the process has completed
return render_to_response('scripts/static.html', {'displaylist':results, 'filename':viewfile})
return render_to_response('scripts/dynamic.html', {'displaylist':results, 'filename':viewfile})
pass
| [
"It helps if you use the following:\n['python','-u','path/to/python/script.py']\n\n"
] | [
1
] | [] | [] | [
"django",
"django_views",
"mod_python",
"python",
"subprocess"
] | stackoverflow_0004222035_django_django_views_mod_python_python_subprocess.txt |
Q:
Can PyPy/RPython be used to produce a small standalone executable?
(Or, "Can PyPy/RPython be used to compile/translate Python to C/C++ without requiring the Python runtime?")
I have tried to comprehend PyPy with its RPython and its Python, its running and its compiling and its translating, and have somewhat failed.
I have a hypothetical Python project (for Windows); I would like to keep its size down, in the order of a hundred kilobytes (O.N.O.) rather than the several megabytes that using py2exe entails (after UPX). Can I use PyPy1 in any way to produce a standalone executable which does not depend on Python26.dll? If I can, does it need to follow the RPython restrictions like for only working on builtin types, or is it full Python syntax?
I do realise that if this can be done I almost certainly couldn't use C modules from Python directly.
1 (Since the time of asking, the situation has become clearer, and this part of the toolchain is more clearly branded as RPython rather than PyPy; it wasn't so in 2010.)
A:
Yes, PyPy can produce standalone executables from RPython code. That means, you need to follow all the awkward RPython rules when it comes to writing code. Your Python code is completely unlikely to function out of the box and porting existing Python code is usually not fun. It won't make executables as small as C, but for example rpystone target (from pypy/translator/goal) using boehm GC is 80k on 64bit after stripping.
| Can PyPy/RPython be used to produce a small standalone executable? | (Or, "Can PyPy/RPython be used to compile/translate Python to C/C++ without requiring the Python runtime?")
I have tried to comprehend PyPy with its RPython and its Python, its running and its compiling and its translating, and have somewhat failed.
I have a hypothetical Python project (for Windows); I would like to keep its size down, in the order of a hundred kilobytes (O.N.O.) rather than the several megabytes that using py2exe entails (after UPX). Can I use PyPy1 in any way to produce a standalone executable which does not depend on Python26.dll? If I can, does it need to follow the RPython restrictions like for only working on builtin types, or is it full Python syntax?
I do realise that if this can be done I almost certainly couldn't use C modules from Python directly.
1 (Since the time of asking, the situation has become clearer, and this part of the toolchain is more clearly branded as RPython rather than PyPy; it wasn't so in 2010.)
| [
"Yes, PyPy can produce standalone executables from RPython code. That means, you need to follow all the awkward RPython rules when it comes to writing code. Your Python code is completely unlikely to function out of the box and porting existing Python code is usually not fun. It won't make executables as small as C... | [
18
] | [] | [] | [
"compiler_construction",
"pypy",
"python",
"rpython",
"translate"
] | stackoverflow_0004251964_compiler_construction_pypy_python_rpython_translate.txt |
Q:
Sorting alphanumerical dictionary keys in python
I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ...
def sort_keys(dictionary):
keys = dictionary.keys()
keys.sort()
return map(dictionary.get, keys)
How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?
A:
keys.sort(key=lambda k:(k[0], int(k[1:])) )
Edit: This will fail in the keys are not like A23, e.g. AA12 will stop the program. In the general case, see Python analog of natsort function (sort a list using a "natural order" algorithm).
A:
dictionary.keys() return a list and you can sort list by your own function:
>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
>>> import operator
>>> a.sort(key = operator.itemgetter(1))
>>> a
[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]*
A:
You need OrderedDict from collections in 2.7 +
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
| Sorting alphanumerical dictionary keys in python | I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ...
def sort_keys(dictionary):
keys = dictionary.keys()
keys.sort()
return map(dictionary.get, keys)
How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?
| [
"keys.sort(key=lambda k:(k[0], int(k[1:])) )\n\nEdit: This will fail in the keys are not like A23, e.g. AA12 will stop the program. In the general case, see Python analog of natsort function (sort a list using a \"natural order\" algorithm).\n",
"dictionary.keys() return a list and you can sort list by your own f... | [
9,
1,
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0004253785_dictionary_python_sorting.txt |
Q:
How do you translate this to objective C?
class MyClass():
def printer(name="abc", description="123")
print name + description
This is python...how can you translate that to objective C?
A:
Something like this will get you started:
- (void)printName:(NSString *)name andDescription:(NSString *)description
{
if (name == nil) name = @"abc";
if (description == nil) description = @"123";
NSLog(@"%@%@", name, description);
}
| How do you translate this to objective C? | class MyClass():
def printer(name="abc", description="123")
print name + description
This is python...how can you translate that to objective C?
| [
"Something like this will get you started:\n- (void)printName:(NSString *)name andDescription:(NSString *)description\n{\n if (name == nil) name = @\"abc\";\n if (description == nil) description = @\"123\";\n NSLog(@\"%@%@\", name, description);\n}\n\n"
] | [
2
] | [] | [] | [
"objective_c",
"oop",
"python"
] | stackoverflow_0004254130_objective_c_oop_python.txt |
Q:
POST data has wrong value for Django template variable?
I have the following code in my template:
<form action="" method="post">{% csrf_token %}
{%for category, category_votes in votes%}
<p>{{category}}: {{category_votes}} <!-- displays as expected -->
<input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}>
<input type="submit" name="upvote" value="Vote for...">
<input type="submit" name="downvote" value="Vote against...">
</p>
{%endfor%}
</form>
The variable {{category}} displays as expected when rendered, but looking in the POST data, "votedCat" is always the last category value in votes.
For example, if votes=[('a',1),('b',2),('c',3)], then request.POST['votedCat'] returns 'c' regardless of which input button is used to submit the form. What did I do wrong?
A:
Because you only have one single form, with multiple inputs for votedCat. Clicking any of the buttons submits the whole form, with all the values for votedCat. If you were to access request.POST.getlist('votedCat') you would see that you actually have all the values.
There are two ways of fixing this. The first is to have separate form elements for each iteration through the loop - to do that, just move the <form> and </form> elements inside the loop.
The second is to have the votedCat input actually be the submit button:
<input type="submit" name="votedCat" value="Vote for {{category}}" id={{forloop.counter}}>
The disadvantage here is that now you have the words 'Vote for' in your variable, which you'll need to parse out in the view code.
Better than both of these would be to have a simple radio button set or select box with a single submit button, but I understand that design requirements sometimes get in the way.
Finally, you should really be using Django's forms framework, rather than using manual HTML and dealing with the POST directly.
A:
I'm not sure if this is the best solution, but you can create a new form inside the loop:
{%for category, category_votes in votes%}
<p>{{category}}: {{category_votes}} <!-- displays as expected -->
<form action="" method="post">{% csrf_token %}
<input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}>
<input type="submit" name="upvote" value="Vote for...">
<input type="submit" name="downvote" value="Vote against...">
</form>
</p>
{%endfor%}
You could consider using the django.forms.Form class to build and process your forms.
| POST data has wrong value for Django template variable? | I have the following code in my template:
<form action="" method="post">{% csrf_token %}
{%for category, category_votes in votes%}
<p>{{category}}: {{category_votes}} <!-- displays as expected -->
<input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}>
<input type="submit" name="upvote" value="Vote for...">
<input type="submit" name="downvote" value="Vote against...">
</p>
{%endfor%}
</form>
The variable {{category}} displays as expected when rendered, but looking in the POST data, "votedCat" is always the last category value in votes.
For example, if votes=[('a',1),('b',2),('c',3)], then request.POST['votedCat'] returns 'c' regardless of which input button is used to submit the form. What did I do wrong?
| [
"Because you only have one single form, with multiple inputs for votedCat. Clicking any of the buttons submits the whole form, with all the values for votedCat. If you were to access request.POST.getlist('votedCat') you would see that you actually have all the values.\nThere are two ways of fixing this. The first i... | [
3,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004254252_django_django_templates_python.txt |
Q:
django-sphinx: SphinxClient instance has no attribute 'SetFieldWeights'
In my models, when I refer to SphinxSearch with defaults like:
from djangosphinx.models import SphinxSearch
class Blog(models.Model):
...
search = SphinxSearh()
the fulltext search works fine. But when I give weights attribute as documented:
search = SphinxSearch(
weights={'title': 10, 'body': 5, 'tags': 10}
)
searches raise: SphinxClient instance has no attribute 'SetFieldWeights'
I must be missing something obvious as I seem to be the only one with this problem after Googling. Any help is much appreciated.
A:
This problem is coming due to version of sphinxapi, put
SPHINX_API_VERSION = 0x116
in your settings.py file. problem will get resolve.
Default version getting picked up is 0x107, which doesn't have implemented 'SetFieldWeights' function.
| django-sphinx: SphinxClient instance has no attribute 'SetFieldWeights' | In my models, when I refer to SphinxSearch with defaults like:
from djangosphinx.models import SphinxSearch
class Blog(models.Model):
...
search = SphinxSearh()
the fulltext search works fine. But when I give weights attribute as documented:
search = SphinxSearch(
weights={'title': 10, 'body': 5, 'tags': 10}
)
searches raise: SphinxClient instance has no attribute 'SetFieldWeights'
I must be missing something obvious as I seem to be the only one with this problem after Googling. Any help is much appreciated.
| [
"This problem is coming due to version of sphinxapi, put \n\nSPHINX_API_VERSION = 0x116\n\nin your settings.py file. problem will get resolve.\nDefault version getting picked up is 0x107, which doesn't have implemented 'SetFieldWeights' function.\n"
] | [
4
] | [] | [] | [
"django_sphinx",
"full_text_search",
"python"
] | stackoverflow_0004139208_django_sphinx_full_text_search_python.txt |
Q:
where to start programing a server application
Question: Where is a good starting point for learning to write server applications?
Info:
I'm looking in to writing a distributed computing system to harvest the idle cycles of the couple hundred computers sitting idle around my college's campus. There are systems that come close, but don't quite meet all the requirements I need. (most notable all transactions have to be made through SSH because the network blocks everything else) So I've decided to write my own application. partly to get exactly what I want, but also for experience.
Important features:
Written in python
All transaction made through ssh(this is solved through the simple use of pexpect)
Server needs to be able to take potentially hundreds of hits. I'll optimize later, the point being simulation sessions.
I feel like those aren't to ridiculous of things to try and accomplish. But with the last one I'm not certain where to even start. I've actually already accomplished the first 2 and written a program that will log into my server, and then print ls -l to a file locally. so that isn't hard. but how do i attach several clients asking the server for simulation data to crunch all at the same time? obviously it feels like threading comes in to play here, but more than that I'm sure.
This is where my problem is. Where does one even start researching how to write server applications? Am I even using the right wording? What information is there freely available on the internet and/or what books are there on such? again, specifically python, but a step in the right direction is one more than where i am now.
p.s. this seeemed more fitting for stackoverflow than serverfault. Correct me if I am wrong.
A:
Check out the following discussion on SO
Would twisted be a good choice for building a multi-threaded server?
Also check out the fantastic introductions at
Twisted Introduction : http://krondo.com/?page_id=1327
Twisted Web in 60 seconds : http://jcalderone.livejournal.com/50562.html
A:
Twisted is an event loop framework that is commonly used in Python for network handling.
A:
Here's an approach.
Write an "agent" in Python. The agent is installed on the various computers. It does whatever processing your need locally. It uses urllib2 to make RESTful HTTP requests of the server. It either posts data or requests work to do or whatever is supposed to go on.
Write a "server" in Python. The server is installed on one computer. This is written using wsgiref and is a simple WSGI-based server that serves requests from the various agents scattered around campus.
While this requires agent installation, it's very, very simple. It can be made very, very secure (use HTTP Digest Authentication). And the agent's privileges define the level of vulnerability. If the agent is running in an account with relatively few privileges, it's quite safe. The agent shouldn't run as root and the agent's account should not be allowed to su or sudo.
| where to start programing a server application | Question: Where is a good starting point for learning to write server applications?
Info:
I'm looking in to writing a distributed computing system to harvest the idle cycles of the couple hundred computers sitting idle around my college's campus. There are systems that come close, but don't quite meet all the requirements I need. (most notable all transactions have to be made through SSH because the network blocks everything else) So I've decided to write my own application. partly to get exactly what I want, but also for experience.
Important features:
Written in python
All transaction made through ssh(this is solved through the simple use of pexpect)
Server needs to be able to take potentially hundreds of hits. I'll optimize later, the point being simulation sessions.
I feel like those aren't to ridiculous of things to try and accomplish. But with the last one I'm not certain where to even start. I've actually already accomplished the first 2 and written a program that will log into my server, and then print ls -l to a file locally. so that isn't hard. but how do i attach several clients asking the server for simulation data to crunch all at the same time? obviously it feels like threading comes in to play here, but more than that I'm sure.
This is where my problem is. Where does one even start researching how to write server applications? Am I even using the right wording? What information is there freely available on the internet and/or what books are there on such? again, specifically python, but a step in the right direction is one more than where i am now.
p.s. this seeemed more fitting for stackoverflow than serverfault. Correct me if I am wrong.
| [
"Check out the following discussion on SO\n\nWould twisted be a good choice for building a multi-threaded server?\n\nAlso check out the fantastic introductions at\n\nTwisted Introduction : http://krondo.com/?page_id=1327\nTwisted Web in 60 seconds : http://jcalderone.livejournal.com/50562.html\n\n",
"Twisted is a... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004253557_python.txt |
Q:
Looking to write my own 'Application Whitelisting Tool' Something like Bit9?
Playing around with project ideas that I might actually use, figured I might try to write my own simple version of Bit9 Parity, in either C# or Python. My question is what is the best way to go about doing this. I've googled .Net functionality for prevent processes from executing, but I havn't really found what I'm looking for. What I'd like to do is monitory the system memory as a whole, and deny any process or application from starting unless specifically identified in a list. ProcessWatcher caught my eye, but is that not for a specific process ID. How do I block ALL other processes from starting? Is this possible in .Net? What about python?
A:
This blog post (Using WMI to monitor process creation, deletion and modification in .NET) shows how to do that. With a few changes, you should be able to do exactly what you want.
A:
How do I block ALL other processes from starting?
Deep, mysterious OS API magic. After all, you're interfering with how the OS works. You must, therefore patch or hook into the OS itself.
Is this possible in .Net? What about python?
It doesn't involve time-travel, anti-gravity or perpetual motion. It can be done.
It's a matter of figuring out (1) which OS API calls are required to put your new hook into the OS, and (2) implementing a call from the OS to your code.
Is really hard.
Is really easy.
| Looking to write my own 'Application Whitelisting Tool' Something like Bit9? | Playing around with project ideas that I might actually use, figured I might try to write my own simple version of Bit9 Parity, in either C# or Python. My question is what is the best way to go about doing this. I've googled .Net functionality for prevent processes from executing, but I havn't really found what I'm looking for. What I'd like to do is monitory the system memory as a whole, and deny any process or application from starting unless specifically identified in a list. ProcessWatcher caught my eye, but is that not for a specific process ID. How do I block ALL other processes from starting? Is this possible in .Net? What about python?
| [
"This blog post (Using WMI to monitor process creation, deletion and modification in .NET) shows how to do that. With a few changes, you should be able to do exactly what you want.\n",
"\nHow do I block ALL other processes from starting? \n\nDeep, mysterious OS API magic. After all, you're interfering with how t... | [
2,
1
] | [] | [] | [
"c#",
"process",
"python",
"whitelist"
] | stackoverflow_0004252725_c#_process_python_whitelist.txt |
Q:
Testing Google App Engine app from terminal (python cli)
I'm running from appname import model, which gives me:
ImportError: No module named google.appengine.api
So I add the following Python path (the only path I could find):
PYTHONPATH=/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/:~/src/appname/src/ python
And then I run the command again. But that tells me:
ImportError: No module named yaml
I'm running Mac OS X Snow Leopard and the latest GAE. Any tips? All I want to do is run some of the methods in my model.
A:
From dev_appserver.py:
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
# ...
EXTRA_PATHS = [
DIR_PATH,
os.path.join(DIR_PATH, 'lib', 'antlr3'),
os.path.join(DIR_PATH, 'lib', 'django'),
os.path.join(DIR_PATH, 'lib', 'fancy_urllib'),
os.path.join(DIR_PATH, 'lib', 'ipaddr'),
os.path.join(DIR_PATH, 'lib', 'webob'),
os.path.join(DIR_PATH, 'lib', 'yaml', 'lib'),
]
# ...
sys.path = EXTRA_PATHS + sys.path
I think it should work if you put these bits in a separate script, and import it before importing your own code.
Or, as you've pointed out, use the Appengine console in the SDK (but that's not there for Linux users).
| Testing Google App Engine app from terminal (python cli) | I'm running from appname import model, which gives me:
ImportError: No module named google.appengine.api
So I add the following Python path (the only path I could find):
PYTHONPATH=/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/:~/src/appname/src/ python
And then I run the command again. But that tells me:
ImportError: No module named yaml
I'm running Mac OS X Snow Leopard and the latest GAE. Any tips? All I want to do is run some of the methods in my model.
| [
"From dev_appserver.py:\nDIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))\n# ...\n\nEXTRA_PATHS = [\n DIR_PATH,\n os.path.join(DIR_PATH, 'lib', 'antlr3'),\n os.path.join(DIR_PATH, 'lib', 'django'),\n os.path.join(DIR_PATH, 'lib', 'fancy_urllib'),\n os.path.join(DIR_PATH, 'lib', 'ipaddr')... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004255380_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.