SQLite date fields
Hi, I am having design problems with date storage/retrieval using Python and SQLite. I understand that a SQLite date column stores dates as text in ISO format (ie. '2010-05-25'). So when I display a British date (eg. on a web-page) I convert the date using datetime.datetime.strptime(mydate,'%Y-%m-%d').strftime('%d/%m/%Y'). However, when it comes to writing-back data to the table, SQLite is very forgiving and is quite happy to store '25/06/2003' in a date field, but this is not ideal because a) I could be left with a mixture of date formats in the same column, b) SQLite's date functions only work with ISO format. Therefore I need to convert the date string back to ISO format before committing, but then I would need a generic function which checks data about to be written in all date fields and converts to ISO if necessary. That sounds a bit tedious to me, but maybe it is inevitable. Are there simpler solutions? Would it be easier to change the date field to a 10-character field and store 'dd/mm/' throughout the table? This way no conversion is required when reading or writing from the table, and I could use datetime() functions if I needed to perform any date-arithmetic. How have other developers overcome this problem? Any help would be appreciated. For the record, I am using SQLite3 with Python 3.1. Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python dict as unicode
On 11/24/2010 5:58 PM, Brendon wrote: Hi all, I am trying to convert a dictionary to a unicode string and it fails with an exception. I am awfully surprised but searching the web has not turned up anything useful. I understand why the exception ocurrs, but am not sure why this is the default behaviour of python and if there is anything I can do to fix the problem. I have a python dictionary: d = { ..} It contains both primitive and complex objects. I want a unicode representation of that dict: s = unicode(d) Doing this I get an exception: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 71: ordinal not in range(128) Now, it seems that unicode(d) is the same as unicode(str(d)). I was expecting there to be a __unicode__ method in the dictionary that in turn calls unicode() on each of the keys/values in the dict, but apparently not. Instead it seems to call the equivalent of str() on each key/value and then after adding them together, calls unicode() on the resulting string. Is this really the default behaviour? If so is there any way around it? Use 3.x I am using python 2.6.6 on a Linux system. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Needed: Real-world examples for Python's Cooperative Multiple Inheritance
On 2010-11-24 12:08:04 -0800, Raymond Hettinger said: I'm writing-up more guidance on how to use super() and would like to point at some real-world Python examples of cooperative multiple inheritance. The SocketServer module (http://docs.python.org/library/socketserver.html) uses cooperative multiple inheritance to implement threading / async using a ThreadingMixIn class and multi-processing using a ForkingMixIn class, which may not be as complicated a use case as you are looking for. One thing that caught me up was the attribute resolution order; it's a FIFO, with the first superclass being examined preferentially over later superclasses in the declaration. (Mixins go before the class they extend.) — Alice. -- http://mail.python.org/mailman/listinfo/python-list
a regexp riddle: re.search(r'(?:(\w+), |and (\w+))+', 'whatever a, bbb, and c') =? ('a', 'bbb', 'c')
HypoNt: I need to turn a human-readable list into a list(): print re.search(r'(?:(\w+), |and (\w+))+', 'whatever a, bbb, and c').groups() That currently returns ('c',). I'm trying to match "any word \w+ followed by a comma, or a final word preceded by and." The match returns 'a, bbb, and c', but the groups return ('bbb', 'c'). What do I type for .groups() to also get the 'a'? Please go easy on me (and no RTFM!), because I have only been using regular expressions for about 20 years... -- Phlip http://bit.ly/ZeekLand -- http://mail.python.org/mailman/listinfo/python-list
Re: Pypi (Cheeseshop) Score - derivation of ?
On Nov 25, 11:57 am, shearichard wrote: > Hi - Anyone know how the score offered by Pypi is derived ? > > For instance in ... > > http://pypi.python.org/pypi?%3Aaction=search&term=spam&submit=search > > ... 'bud.nospam 1.0.1' has a score of 9 but 'pydspam 1.1.9' has a > score of 7. If you hover over the Score header in the results list, it says: Occurrence of search term weighted by field (name, summary, keywords, description, author, maintainer) I thought PyPI used to offer a 'kwality' score for packages, based on the presence of installers, doc files, tests etc. Does anyone know what happened to that? -- http://mail.python.org/mailman/listinfo/python-list
Re: Pypi (Cheeseshop) Score - derivation of ?
On Nov 25, 3:54 pm, Ben Finney wrote: > shearichard writes: > > Hi - Anyone know how the score offered by Pypi is derived ? > > Specifically, the score offered in response to a search query. > > > For instance in ... > > >http://pypi.python.org/pypi?%3Aaction=search&term=spam&submit=search > > > ... 'bud.nospam 1.0.1' has a score of 9 but 'pydspam 1.1.9' has a > > score of 7. > > > Where are those numbers from and what do they mean ? > > They are the relevance of the result to that particular search query. I > don't know the scale of the score or how it's derived, but that's the > intended meaning AFAIK. > > I think a better term than “score” could be chosen; perhaps you could > submit a bug report against PyPI. > OK that makes sense. I thought it was some comment on how 'good' the package in question was ! I will do as you say and submit a bug report to get the literal altered to something a little more self-explanatory. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pypi (Cheeseshop) Score - derivation of ?
shearichard writes: > Hi - Anyone know how the score offered by Pypi is derived ? Specifically, the score offered in response to a search query. > For instance in ... > > http://pypi.python.org/pypi?%3Aaction=search&term=spam&submit=search > > ... 'bud.nospam 1.0.1' has a score of 9 but 'pydspam 1.1.9' has a > score of 7. > > Where are those numbers from and what do they mean ? They are the relevance of the result to that particular search query. I don't know the scale of the score or how it's derived, but that's the intended meaning AFAIK. I think a better term than “score” could be chosen; perhaps you could submit a bug report against PyPI. -- \ “One of the most important things you learn from the internet | `\ is that there is no ‘them’ out there. It's just an awful lot of | _o__)‘us’.” —Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Pypi (Cheeseshop) Score - derivation of ?
Hi - Anyone know how the score offered by Pypi is derived ? For instance in ... http://pypi.python.org/pypi?%3Aaction=search&term=spam&submit=search ... 'bud.nospam 1.0.1' has a score of 9 but 'pydspam 1.1.9' has a score of 7. Where are those numbers from and what do they mean ? Thanks R. -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
On Nov 25, 7:43 am, Paul Rubin wrote: > Gerald Britton writes: > > if v: > > f() > > > I might, however, think more in a functional-programming direction. > > Then I might write: > > > v and f() > > Python has conditional expressions. The above would be: > > f() if v else None > > using "and" is bug-prone. Using 'and' is indeed bug-prone when used in combination with 'or' to achieve a ternary conditional op, as was done the pre PEP308 days, eg "val = cond and a or b" because of the possibility that 'a' was itself not true, (thus requiring the ugly 'val = (cond and [a] or [b])[0]'). But no such bug could occur with this particular idiom. What could possibly go wrong here? :) That being said, I agree with previous posters that "if cond : fn()" wins in terms of readability. -- http://mail.python.org/mailman/listinfo/python-list
Re: Needed: Real-world examples for Python's Cooperative Multiple Inheritance
On Wed, 24 Nov 2010 12:08:04 -0800 (PST) Raymond Hettinger wrote: > I'm writing-up more guidance on how to use super() and would like to > point at some real-world Python examples of cooperative multiple > inheritance. > > Google searches take me to old papers for C++ and Eiffel, but that > don't seem to be relevant to most Python programmers (i.e. a > WalkingMenu example where a submenu is both a Entry in a Menu and a > Menu itself). Another published example is in a graphic library where > some widgets inherit GraphicalFeature methods such as location, size > and NestingGroupingFeatures such as finding parents, siblings, and > children. I don't find either of those examples compelling because > there is no particular reason that they would have to have overlapping > method names. > > So far, the only situation I can find where method names necessarily > overlap is for the basics like __init__(), close(), flush(), and > save() where multiple parents need to have their own initialization > and finalization. > > If you guys know of good examples, I would appreciate a link or a > recap. I have never seen a good use of cooperative multiple inheritance in Python. My own experience trying to use it suggests me that I would have been better with independent "handler" classes (urllib2-style). Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Matlab equivalent syntax in Python
Can anyone please suggest me what will be the good way to use matlab equivalent of "profile clear, profile on, profile off, profile resume and profile viewer" in Python? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Python dict as unicode
Hi all, I am trying to convert a dictionary to a unicode string and it fails with an exception. I am awfully surprised but searching the web has not turned up anything useful. I understand why the exception ocurrs, but am not sure why this is the default behaviour of python and if there is anything I can do to fix the problem. I have a python dictionary: d = { ..} It contains both primitive and complex objects. I want a unicode representation of that dict: s = unicode(d) Doing this I get an exception: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 71: ordinal not in range(128) Now, it seems that unicode(d) is the same as unicode(str(d)). I was expecting there to be a __unicode__ method in the dictionary that in turn calls unicode() on each of the keys/values in the dict, but apparently not. Instead it seems to call the equivalent of str() on each key/value and then after adding them together, calls unicode() on the resulting string. Is this really the default behaviour? If so is there any way around it? I am using python 2.6.6 on a Linux system. -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
On 11/24/10 12:30 PM, Robert Kern wrote: On 11/24/10 12:07 PM, Daniel Fetchinson wrote: The whole story is that I have a matrix A and matrix B both of which have rational entries and they both have pretty crazy entries too. Their magnitude spans many orders of magnitude, but inverse(A)*B is an okay matrix and I can deal with it using floating point numbers. I only need this exact fraction business for inverse(A)*B (yes, a preconditioner would be useful :)) And I wouldn't want to write the whole matrix into a file, call Maple on it, parse the result, etc. So after all I might just code the inversion via Gauss elimination myself in a way that can deal with fractions, shouldn't be that hard. +1000. This is almost always the right thing to do whether you have floats or rationals. By this I meant that you should using Gaussian elimination to *solve* the problem A^-1*B is the right thing to do rather than explicitly forming the inverse of A (no matter which algorithm you use). I hope that's what you meant too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Collect output to string
Burton Samograd writes: > Terry Reedy writes: > >> On 11/23/2010 3:02 PM, Chris Rebert wrote: >> If you are using print or print(), you can redirect output to the >> StringIO object with >>sfile or file=sfile. I use the latter in a >> custom test function where I normally want output to the screen but >> occasionally want to capture test reports. > > Thanks for the info, but I was looking for a way to collect output > without modifying the original function, similar to > with-output-to-string in some schemes. Redirecting output like with-output-to-string does is achieved by assigning to sys.stdout. Using contextlib you can make it even closer to with-output-to-string by deploying the actual with statement. Unfortunately python's with cannot return a value, so you must expose the StringIO to the caller. The result is still quite nice: import sys, contextlib, cStringIO @contextlib.contextmanager def output_to_string(): oldout = sys.stdout sys.stdout = cStringIO.StringIO() try: yield sys.stdout finally: sys.stdout = oldout >>> with output_to_string() as out: ... print 'foo' ... print 'bar' ... >>> out.getvalue() 'foo\nbar\n' -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
>> So after all I might just code the inversion via Gauss elimination >> myself in a way that can deal with fractions, shouldn't be that hard. > > I wouldn't do it that way. Let M be your matrix. Work out the LCM l of > the denominators, and multiply the matrix by that to make it an integer > matrix N = l M. Then work out the determinant d of that integer matrix. > Next, the big step: use Gaussian elimination to find a matrix A (the > `adjugate matrix') such that A N = d I. This should be doable entirely > using integer arithmetic, and I think without needing any divisions. > Finally, we have l A M = d I, so (l/d A) M = I and l/d A is the inverse > you seek. > > Does that make sense? Absolutely! But there is nothing wrong with working out the inverse directly using fractions.Fraction arithmetic, I'd think. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
PyQt Installation Problem on Windows
Hi, I've been trying to install PyQt on Windows XP Pro so that I can try out eric ide. I used the binary windows installer for PyQt. I can run eric as administrator, but not with my ordinary user account. By running eric.bat with the --debug flag, I found that he crux of the problem is that if I type import PyQt4 in the python shell, it works for both users, but if I type import PyQt4.QtCore it works for the administrator, but the non-privileged account gets the message ImportError: DLL load failed: The specified module could not be found. In the file the file pyqtconfig.py from Python26\Lib\site-packages \PyQt4 I have the line 'pyqt_config_args': '--confirm-license -b C:\\Python26\\Lib\\site- packages\\PyQt4\\bin', I checked with a friend who uses eric, and his file does not have the --confirm-license parameter. As far as we can tell, we followed the same installation procedures. By the way, I have tried this with python 3.1 on the same machine with similar results. I've blown a whole day playing with this, so I'd really appreciate any help you can give me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with module 'evolution' after moving system
tinn...@isbd.co.uk wrote: > tinn...@isbd.co.uk wrote: > [snip] > > > Using 'help' reveals basic information for evolution but reports "no > > documentation " for evolution.ebook. On the old system (exactly > > the same version of python, same OS, same everything just about) > > "help(evolution.ebook)" shows the expected documentation. > > > > So, what's wrong, is some python module missing that the evolution > > module needs? (It's quite likely that there are far more modules > > installed on the old system than the new one) > > > A bit further trying to see what's wrong it seems that Python is > failing to load .so libraries for some reason on the system where it > doesn't work. > > The initialisation code in the evolution module has:- > > import ebook > > So, obviously this works on the old system but not on the new system. > The ebook.so file is present on both systems in exactly the same place. > and I've finally found what was missing, I tried:- import evolution.ebook and it told me that 'import bonobo' was failing. A little searching and I found that python-gnome2 (which includes bonobo) was installed on the old system but not on the new one. Installing it has fixed my problem. -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensuring symmetry in difflib.SequenceMatcher
On Nov 24, 8:43 pm, Peter Otten <__pete...@web.de> wrote: > John Yeung wrote: > > I'm generally pleased with difflib.SequenceMatcher: It's probably not > > the best available string matcher out there, but it's in the standard > > library and I've seen worse in the wild. One thing that kind of > > bothers me is that it's sensitive to which argument you pick as "seq1" > > and which you pick as "seq2": > > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > > (Intel)] on > > win32 > > Type "help", "copyright", "credits" or "license" for more information. > import difflib > difflib.SequenceMatcher(None, 'BYRD', 'BRADY').ratio() > > 0.2 > difflib.SequenceMatcher(None, 'BRADY', 'BYRD').ratio() > > 0.3 > > > Is this a bug? I am guessing the algorithm is implemented correctly, > > and that it's just an inherent property of the algorithm used. It's > > certainly not what I'd call a desirably property. Are there any > > simple adjustments that can be made without sacrificing (too much) > > performance? > > def symmetric_ratio(a, b, S=difflib.SequenceMatcher): > return (S(None, a, b).ratio() + S(None, b, a).ratio())/2.0 > > I'm expecting 50% performance loss ;) > > Seriously, have you tried to calculate the ratio with realistic data? > Without looking into the source I would expect the two ratios to get more > similar. > > Peter Surnames are extremely realistic data. The OP should consider using Levenshtein distance, which is "symmetric". A good (non-naive) implementation should be much faster than difflib. ratio = 1.0 - levenshtein(a, b) / float(max(len(a), len(b))) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with module 'evolution' after moving system
tinn...@isbd.co.uk wrote: [snip] > Using 'help' reveals basic information for evolution but reports "no > documentation " for evolution.ebook. On the old system (exactly > the same version of python, same OS, same everything just about) > "help(evolution.ebook)" shows the expected documentation. > > So, what's wrong, is some python module missing that the evolution > module needs? (It's quite likely that there are far more modules > installed on the old system than the new one) > A bit further trying to see what's wrong it seems that Python is failing to load .so libraries for some reason on the system where it doesn't work. The initialisation code in the evolution module has:- import ebook So, obviously this works on the old system but not on the new system. The ebook.so file is present on both systems in exactly the same place. -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
No rule to make target `Parser/printgrammar.o'
I'm trying to compile Python from source and get the same error on RedHat and Mac OS X. I did not pass any options to configure. The error occurs immediately. Redhat:~/Downloads/Python-2.7$ make gcc -pthread -c -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 - Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE - o Modules/python.o ./Modules/python.c make: *** No rule to make target `Parser/printgrammar.o', needed by `Parser/pgen'. Stop. MacOSX:Python-2.7$ make gcc -c -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c make: *** No rule to make target `Parser/printgrammar.o', needed by `Parser/pgen'. Stop. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scheme as a virtual machine?
On Nov 24, 1:10 pm, Raffael Cavallaro wrote: > On 2010-11-23 11:34:14 -0500, Keith H Duggar said: > > > You don't understand the implications of your own words: > > > "having a financial interest in the outcome of a debate makes > > anything that person says an advertisement for his financial > > interests, not a fair assessment." > > > is substantially different from > > > "render his arguments in the debate inherently suspect." > > They are substantially the same, your jesuitical nit-picking > notwithstanding; JH is an untrustworthy source on matters relating to > the languages he sells training for. > And furthermore, he has cooties. --T > warmest regards, > > Ralph > > -- > Raffael Cavallaro -- http://mail.python.org/mailman/listinfo/python-list
collect2: library libpython2.6 not found while building extensions (--enable-shared)
All, When I configure python to enable shared libraries, none of the extensions are getting built during the make step due to this error. building 'cStringIO' extension gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I/u01/home/apli/wm/GDD/Python-2.6.6/./Include -I. -IInclude -I./Include -I/opt/freeware/include -I/opt/freeware/include/readline -I/opt/freeware/include/ncurses -I/usr/local/include -I/u01/home/apli/wm/GDD/Python-2.6.6/Include -I/u01/home/apli/wm/GDD/Python-2.6.6 -c /u01/home/apli/wm/GDD/Python-2.6.6/Modules/cStringIO.c -o build/temp.aix-5.3-2.6/u01/home/apli/wm/GDD/Python-2.6.6/Modules/cStringIO.o ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/temp.aix-5.3-2.6/u01/home/apli/wm/GDD/Python-2.6.6/Modules/cStringIO.o -L/usr/local/lib *-lpython2.6* -o build/lib.aix-5.3-2.6/cStringIO.so *collect2: library libpython2.6 not found* building 'cPickle' extension gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I/u01/home/apli/wm/GDD/Python-2.6.6/./Include -I. -IInclude -I./Include -I/opt/freeware/include -I/opt/freeware/include/readline -I/opt/freeware/include/ncurses -I/usr/local/include -I/u01/home/apli/wm/GDD/Python-2.6.6/Include -I/u01/home/apli/wm/GDD/Python-2.6.6 -c /u01/home/apli/wm/GDD/Python-2.6.6/Modules/cPickle.c -o build/temp.aix-5.3-2.6/u01/home/apli/wm/GDD/Python-2.6.6/Modules/cPickle.o ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/temp.aix-5.3-2.6/u01/home/apli/wm/GDD/Python-2.6.6/Modules/cPickle.o -L/usr/local/lib *-lpython2.6* -o build/lib.aix-5.3-2.6/cPickle.so *collect2: library libpython2.6 not found* This is on AIX 5.3, GCC 4.2, Python 2.6.6 I can confirm that there is a libpython2.6.a file in the top level directory from where I am doing the configure/make etc Here are the options supplied to the configure command ./configure --enable-shared --disable-ipv6 --with-gcc=gcc CPPFLAGS="-I /opt/freeware/include -I /opt/freeware/include/readline -I /opt/freeware/include/ncurses" Please guide me in getting past this error. Thanks for your help on this. Regards, Anurag -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
Gerald Britton writes: > if v: > f() > > I might, however, think more in a functional-programming direction. > Then I might write: > > v and f() Python has conditional expressions. The above would be: f() if v else None using "and" is bug-prone. -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
Gerald Britton writes: > Writing in Python gives me the luxury of choosing different paradigms > for similar operations. Lately I've been thinking about a minor > detail that peaked my interest and am curious what others think: > > Say that I have some function "f" that I will execute if some variable > "v" evaluates true. Using a classical procedural approach, I might > write: > > if v: > f() > > I might, however, think more in a functional-programming direction. > Then I might write: > > v and f() > > Interestingly, this second expression compiles smaller (though only by > a little) in both Python 2.6 and 3.1, which I currently have > installed. If I had thousands of such expressions, I could boast > about a measurable difference but practically speaking, it is not > significant. > > What I _am_ interested in, however, is feedback from a style perspective. > > What do the rest of you think about this? > > Have you used the second approach and, if so, what was your motivation? > > Is there a good/bad reason to choose one over the other? I would use the if: form every time but it's interesting that the "JUMP_FORWARD 0" instruction below doesn't get optimised away. If it did, both forms would be the same compiled lengths. >>> def g(): ... if v: f() ... >>> dis.dis(g2) 2 0 LOAD_GLOBAL 0 (v) 3 POP_JUMP_IF_FALSE 16 6 LOAD_GLOBAL 1 (f) 9 CALL_FUNCTION0 12 POP_TOP 13 JUMP_FORWARD 0 (to 16) >> 16 LOAD_CONST 0 (None) 19 RETURN_VALUE -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
Daniel Fetchinson writes: > So after all I might just code the inversion via Gauss elimination > myself in a way that can deal with fractions, shouldn't be that hard. I wouldn't do it that way. Let M be your matrix. Work out the LCM l of the denominators, and multiply the matrix by that to make it an integer matrix N = l M. Then work out the determinant d of that integer matrix. Next, the big step: use Gaussian elimination to find a matrix A (the `adjugate matrix') such that A N = d I. This should be doable entirely using integer arithmetic, and I think without needing any divisions. Finally, we have l A M = d I, so (l/d A) M = I and l/d A is the inverse you seek. Does that make sense? -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Needed: Real-world examples for Python's Cooperative Multiple Inheritance
I'm writing-up more guidance on how to use super() and would like to point at some real-world Python examples of cooperative multiple inheritance. Google searches take me to old papers for C++ and Eiffel, but that don't seem to be relevant to most Python programmers (i.e. a WalkingMenu example where a submenu is both a Entry in a Menu and a Menu itself). Another published example is in a graphic library where some widgets inherit GraphicalFeature methods such as location, size and NestingGroupingFeatures such as finding parents, siblings, and children. I don't find either of those examples compelling because there is no particular reason that they would have to have overlapping method names. So far, the only situation I can find where method names necessarily overlap is for the basics like __init__(), close(), flush(), and save() where multiple parents need to have their own initialization and finalization. If you guys know of good examples, I would appreciate a link or a recap. Thanks, Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
Both paradigms are in the bash shell. Using a test switch (like -x for executiable) mixed with an && or ||. Example: [-x /usr/bin/firefox ] || exit I think it's very clear, to old hands, but not so much for a new or intermediate users. It certainly is the 'cleaner' form. Like the C style increment " x++ " or the insidious " x += 4 ". However I often found myself looking for places to use "x += 4" instead of just using the clear: "x = x + 4 ". Unless there is a significant compiler/executable improvement it just there to amuse yourself. The if v: f() structure is clearer. Which is the only reason to use indents, braces and the like. I suppose that's my vote/opinion. Given a choice between clean or clear, take clear. sph On 11/24/2010 10:46 AM, Gerald Britton wrote: Writing in Python gives me the luxury of choosing different paradigms for similar operations. Lately I've been thinking about a minor detail that peaked my interest and am curious what others think: Say that I have some function "f" that I will execute if some variable "v" evaluates true. Using a classical procedural approach, I might write: if v: f() I might, however, think more in a functional-programming direction. Then I might write: v and f() Interestingly, this second expression compiles smaller (though only by a little) in both Python 2.6 and 3.1, which I currently have installed. If I had thousands of such expressions, I could boast about a measurable difference but practically speaking, it is not significant. What I _am_ interested in, however, is feedback from a style perspective. What do the rest of you think about this? Have you used the second approach and, if so, what was your motivation? Is there a good/bad reason to choose one over the other? -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
On Nov 24, 2010, at 1:46 PM, Gerald Britton wrote: > Say that I have some function "f" that I will execute if some variable > "v" evaluates true. Using a classical procedural approach, I might > write: > >if v: >f() > > I might, however, think more in a functional-programming direction. > Then I might write: > >v and f() > > Interestingly, this second expression compiles smaller (though only by > a little) in both Python 2.6 and 3.1, which I currently have > installed. If I had thousands of such expressions, I could boast > about a measurable difference but practically speaking, it is not > significant. > > What I _am_ interested in, however, is feedback from a style perspective. > > What do the rest of you think about this? Readability is key. The first is instantly understandable; the second only if you are familiar with that particular programming construct. Explicit is better than implicit, so I'd go with the first form. -- Ed Leafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
On Nov 24, 11:46 am, Gerald Britton wrote: > Say that I have some function "f" that I will execute if some variable > "v" evaluates true. Using a classical procedural approach, I might > write: > > if v: > f() > > I might, however, think more in a functional-programming direction. > Then I might write: > > v and f() The idea that "if" is inherently procedural is mistaken. Functional programming emphasizes the use of functions (in the mathematical sense) over changes in state. Assuming that f has no side effects, either of the above could equally be viewed as functional. (Of course, the fact that the return value is simply discarded in both of the above cases suggests that f *does* have side effects, in which case neither of the above should be viewed as functional.) That said, the 'if' version is clearer, so I would nearly always go with that. The rare exception would be if I were genuinely interested in capturing the value of "v" if it evaluated false. I can't remember the last time that was the case. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Style question for conditional execution
Writing in Python gives me the luxury of choosing different paradigms for similar operations. Lately I've been thinking about a minor detail that peaked my interest and am curious what others think: Say that I have some function "f" that I will execute if some variable "v" evaluates true. Using a classical procedural approach, I might write: if v: f() I might, however, think more in a functional-programming direction. Then I might write: v and f() Interestingly, this second expression compiles smaller (though only by a little) in both Python 2.6 and 3.1, which I currently have installed. If I had thousands of such expressions, I could boast about a measurable difference but practically speaking, it is not significant. What I _am_ interested in, however, is feedback from a style perspective. What do the rest of you think about this? Have you used the second approach and, if so, what was your motivation? Is there a good/bad reason to choose one over the other? -- Gerald Britton -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
On 11/24/10 12:07 PM, Daniel Fetchinson wrote: The whole story is that I have a matrix A and matrix B both of which have rational entries and they both have pretty crazy entries too. Their magnitude spans many orders of magnitude, but inverse(A)*B is an okay matrix and I can deal with it using floating point numbers. I only need this exact fraction business for inverse(A)*B (yes, a preconditioner would be useful :)) And I wouldn't want to write the whole matrix into a file, call Maple on it, parse the result, etc. So after all I might just code the inversion via Gauss elimination myself in a way that can deal with fractions, shouldn't be that hard. +1000. This is almost always the right thing to do whether you have floats or rationals. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Collect output to string
Terry Reedy writes: > On 11/23/2010 3:02 PM, Chris Rebert wrote: > If you are using print or print(), you can redirect output to the > StringIO object with >>sfile or file=sfile. I use the latter in a > custom test function where I normally want output to the screen but > occasionally want to capture test reports. Thanks for the info, but I was looking for a way to collect output without modifying the original function, similar to with-output-to-string in some schemes. -- Burton Samograd -- http://mail.python.org/mailman/listinfo/python-list
Problem with module 'evolution' after moving system
I have just moved my desktop system (running xubuntu 10.04) to new hardware. I have an almost trivial python program that uses the evolution module which no longer works and I'm having trouble working out why. The program is:- #!/usr/bin/python # # # # import evolution import sys addrs = evolution.ebook.open_addressbook('default') result = addrs.search(sys.argv[1]) print "Found ", len(result), " matches" if len(result) > 0: for nm in result: print nm.get_property('email-1'), "\t", nm.get_property('full-name') exit(0) else: exit(1) When I run it I get the error:- chris$ getEvoAddress.py zelma Traceback (most recent call last): File "/home/chris/bin/getEvoAddress.py", line 10, in addrs = evolution.ebook.open_addressbook('default') AttributeError: 'NoneType' object has no attribute 'open_addressbook' Using 'help' reveals basic information for evolution but reports "no documentation " for evolution.ebook. On the old system (exactly the same version of python, same OS, same everything just about) "help(evolution.ebook)" shows the expected documentation. So, what's wrong, is some python module missing that the evolution module needs? (It's quite likely that there are far more modules installed on the old system than the new one) -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: unittests with different parameters
Apologies if this is a bit off the wall but I've only just started getting into unit testing (in Python) this morning. Would generators help you in any way? You might be able to have a generator which would yield an attribute set combination each time it is called. I'm not sure if it would still stop at the first fail but I was reading this morning that the Py.test framework utilises generators, and is apparently compatible with the python unittest module. I could be wrong though... -- http://mail.python.org/mailman/listinfo/python-list
Re: Scheme as a virtual machine?
On 2010-11-23 11:34:14 -0500, Keith H Duggar said: You don't understand the implications of your own words: "having a financial interest in the outcome of a debate makes anything that person says an advertisement for his financial interests, not a fair assessment." is substantially different from "render his arguments in the debate inherently suspect." They are substantially the same, your jesuitical nit-picking notwithstanding; JH is an untrustworthy source on matters relating to the languages he sells training for. warmest regards, Ralph -- Raffael Cavallaro -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
>> It's a mathematical problem so no uncertainty is present in the >> initial values. And even if there was, if there are many orders of >> magnitude differences between the entries in the matrix floating point >> does not suffice for various things like eigenvalue calculation and >> stuff like that. > > Well, if you want to do eigenvalue calculations, you are going to have to > start > doing numerical approximations anyways. There is no analytical solution for > matrices larger than 4x4. Sure! (I didn't explain the whole thing yet, see the other reply where I actually do.) > Sympy will do inverses of matrices over rationals for you, though: > > |4> from sympy import * > > |6> m = Matrix([[S(1)/2, S(1)/3], [S(1)/4, S(1)/5]]) > > |7> m > [1/2, 1/3] > [1/4, 1/5] > > |8> m.inv() > [ 12, -20] > [-15, 30] Thanks a lot! This sounds like the simplest solution so far. I don't need to call Maple after all :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
>> I'm using fractions.Fraction as entries in a matrix because I need to >> have very high precision and fractions.Fraction provides infinite >> precision . . . >> >> Probably it doesn't matter but the matrix has all components non-zero >> and is about a thousand by thousand in size. > > I wonder how big the numerators and denominators in those > fractions are going to get during the matrix inversion. Would > it be surprising if the elements of the inverse matrix had > numerators and denominators a million times longer than the > original matrix? I've checked this with Maple for matrix size 150 x 150 and the numerators and denominators do get pretty long. But that's okay as long as it is kept exact. The whole story is that I have a matrix A and matrix B both of which have rational entries and they both have pretty crazy entries too. Their magnitude spans many orders of magnitude, but inverse(A)*B is an okay matrix and I can deal with it using floating point numbers. I only need this exact fraction business for inverse(A)*B (yes, a preconditioner would be useful :)) And I wouldn't want to write the whole matrix into a file, call Maple on it, parse the result, etc. So after all I might just code the inversion via Gauss elimination myself in a way that can deal with fractions, shouldn't be that hard. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
I guess this is a question to folks with some numpy background (but not necessarily). I'm using fractions.Fraction as entries in a matrix because I need to have very high precision and fractions.Fraction provides infinite precision (as I've learned from advice from this list). >>> >>> "Infinite" precision only for values that can be expressed as a fraction: >>> >> Fraction(2)**Fraction(1, 2) >>> 1.4142135623730951 >> type(_) >>> >> >> True, but I only need to add, multiply and divide my fractions in >> order to end up with the entries in the matrix. >> Now I need to calculate its inverse. Can numpy help in this regard? Can I tell numpy that the inverse matrix should also have entries in fractions.Fraction? Or numpy can only do floating point calculations? >>> >>> I tried it, and numpy.linalg.inv() converted the Fraction values to >>> float. If you aren't concerned about efficiency it should be easy to do >>> it yourself, in pure python. >> >> If there is no other way, that's what I'll try to do. >> >>> You could also ask on the numpy mailing list. >>> Probably it doesn't matter but the matrix has all components non-zero and is about a thousand by thousand in size. >>> >>> Hmm, where did you get that million of exact fractions from? >> >> The million of exact fractions are coming from a recursion relation. >> This recursion relation only adds, multiplies and divides numbers so >> the end result is always a rational number. >> >>> If some real >>> world data is involved the error introduced by the floating point >>> calculation may be negligable in comparison with the initial measurement >>> uncertainty. >> >> It's a mathematical problem so no uncertainty is present in the >> initial values. And even if there was, if there are many orders of >> magnitude differences between the entries in the matrix floating point >> does not suffice for various things like eigenvalue calculation and >> stuff like that. > > It may be worthwhile to have a look at http://www.sagemath.org/ > > sage: Matrix([[1,2],[3,4]])**-1 > > [ -21] > [ 3/2 -1/2] > sage: a = Matrix([[1,2],[3,4]]) > sage: b = Matrix([[1,2],[3,4]])**-1 > sage: a*b > > [1 0] > [0 1] > sage: type(b[1,1]) > This sounds like a good idea! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
On 11/24/10 9:10 AM, Daniel Fetchinson wrote: It's a mathematical problem so no uncertainty is present in the initial values. And even if there was, if there are many orders of magnitude differences between the entries in the matrix floating point does not suffice for various things like eigenvalue calculation and stuff like that. Well, if you want to do eigenvalue calculations, you are going to have to start doing numerical approximations anyways. There is no analytical solution for matrices larger than 4x4. Sympy will do inverses of matrices over rationals for you, though: |4> from sympy import * |6> m = Matrix([[S(1)/2, S(1)/3], [S(1)/4, S(1)/5]]) |7> m [1/2, 1/3] [1/4, 1/5] |8> m.inv() [ 12, -20] [-15, 30] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
On Wed, 24 Nov 2010 14:02:21 +0100, Daniel Fetchinson wrote: [snip] > I'm using fractions.Fraction as entries in a matrix because I need to > have very high precision and fractions.Fraction provides infinite > precision . . . [snip] > > Probably it doesn't matter but the matrix has all components non-zero > and is about a thousand by thousand in size. I wonder how big the numerators and denominators in those fractions are going to get during the matrix inversion. Would it be surprising if the elements of the inverse matrix had numerators and denominators a million times longer than the original matrix? -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: efficient way of splitting a list in to lists where the sum of the values in each does not exceed n
Thanks for the reply Ian, I've looked in to the bin-packing problem in a general sense now, and I think my ugly algorithm is actually not too bad (although not too efficient either!) :) It was only for a quick job any how. Thanks again. Tom. On 24/11/10 16:16, Ian Kelly wrote: On Wed, Nov 24, 2010 at 8:34 AM, Tom Boland wrote: I'm trying to find a _nice_ way of taking a list of integers, and splitting them in to lists where the sum of the values does not exceed a threshold. for instance: l = [1, 2, 3, 4, 5, 6] n = 6 nl = [1,2,3], [4], [5], [6] I don't mind if it's done like playing blackjack/pontoon (the card game where you try not to exceed a total of 21), ie. going through the list sequentially, and splitting off the list as soon as the running total would exceed n. A way of efficiently making all lists as close to n as possible would be nice however. You've described the bin-packing problem [1]. It's known to be NP-hard, so you won't find a solution that is both efficient and optimal, although the Wikipedia page mentions some polynomial-time approximate algorithms that you might want to take a look at. Cheers, Ian [1] http://en.wikipedia.org/wiki/Bin_packing_problem -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
Daniel Fetchinson wrote: >>> I guess this is a question to folks with some numpy background (but >>> not necessarily). >>> >>> I'm using fractions.Fraction as entries in a matrix because I need to >>> have very high precision and fractions.Fraction provides infinite >>> precision (as I've learned from advice from this list). >> >> "Infinite" precision only for values that can be expressed as a fraction: >> > Fraction(2)**Fraction(1, 2) >> 1.4142135623730951 > type(_) >> > > True, but I only need to add, multiply and divide my fractions in > order to end up with the entries in the matrix. > >>> Now I need to >>> calculate its inverse. Can numpy help in this regard? Can I tell numpy >>> that the inverse matrix should also have entries in >>> fractions.Fraction? Or numpy can only do floating point calculations? >> >> I tried it, and numpy.linalg.inv() converted the Fraction values to >> float. If you aren't concerned about efficiency it should be easy to do >> it yourself, in pure python. > > If there is no other way, that's what I'll try to do. > >> You could also ask on the numpy mailing list. >> >>> Probably it doesn't matter but the matrix has all components non-zero >>> and is about a thousand by thousand in size. >> >> Hmm, where did you get that million of exact fractions from? > > The million of exact fractions are coming from a recursion relation. > This recursion relation only adds, multiplies and divides numbers so > the end result is always a rational number. > >> If some real >> world data is involved the error introduced by the floating point >> calculation may be negligable in comparison with the initial measurement >> uncertainty. > > It's a mathematical problem so no uncertainty is present in the > initial values. And even if there was, if there are many orders of > magnitude differences between the entries in the matrix floating point > does not suffice for various things like eigenvalue calculation and > stuff like that. It may be worthwhile to have a look at http://www.sagemath.org/ sage: Matrix([[1,2],[3,4]])**-1 [ -21] [ 3/2 -1/2] sage: a = Matrix([[1,2],[3,4]]) sage: b = Matrix([[1,2],[3,4]])**-1 sage: a*b [1 0] [0 1] sage: type(b[1,1]) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: efficient way of splitting a list in to lists where the sum of the values in each does not exceed n
On Wed, Nov 24, 2010 at 8:34 AM, Tom Boland wrote: > I'm trying to find a _nice_ way of taking a list of integers, and splitting > them in to lists where the sum of the values does not exceed a threshold. > > for instance: > > l = [1, 2, 3, 4, 5, 6] > n = 6 > > nl = [1,2,3], [4], [5], [6] > > > I don't mind if it's done like playing blackjack/pontoon (the card game > where you try not to exceed a total of 21), ie. going through the list > sequentially, and splitting off the list as soon as the running total would > exceed n. A way of efficiently making all lists as close to n as possible > would be nice however. You've described the bin-packing problem [1]. It's known to be NP-hard, so you won't find a solution that is both efficient and optimal, although the Wikipedia page mentions some polynomial-time approximate algorithms that you might want to take a look at. Cheers, Ian [1] http://en.wikipedia.org/wiki/Bin_packing_problem -- http://mail.python.org/mailman/listinfo/python-list
Re: extensive scatter plot
On 11/24/10 9:12 AM, Johannes Korn wrote: Hi, I would like to produce a scatter plot with roughly 200 mio points. Because the points are so numerous I rather need a point density plot. I use numpy. Right now I loop over the individual data points and make a where query on a meshgrid. ind = where((x_grid == x_points[i])& (y_grid == y_points[i]) ) counter_grid[ind] += 1 This is really slow. I'm sure there's a better solution already out there. Kind regards! You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists If you are using a particular plotting package like matplotlib, you will want to ask your plotting questions on their mailing lists. E.g. https://lists.sourceforge.net/lists/listinfo/matplotlib-users If you are doing your own plotting, you will want to use the numpy.histogram2d() function to make a 2D histogram that can be plotted using a colormapped image. If you are using matplotlib, try matplotlib.pyplot.hexbin(). http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hexbin -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
efficient way of splitting a list in to lists where the sum of the values in each does not exceed n
I'm trying to find a _nice_ way of taking a list of integers, and splitting them in to lists where the sum of the values does not exceed a threshold. for instance: l = [1, 2, 3, 4, 5, 6] n = 6 nl = [1,2,3], [4], [5], [6] I don't mind if it's done like playing blackjack/pontoon (the card game where you try not to exceed a total of 21), ie. going through the list sequentially, and splitting off the list as soon as the running total would exceed n. A way of efficiently making all lists as close to n as possible would be nice however. I have an algorithm, but it's very ugly. I don't want to paste it, as it's a bit more complicated than I have made out, and wouldn't make too much sense out of context. It's a very ugly blight on my code as well! I wonder if anyone out there has some crazy one-line list comprehension or idiomatic way of doing this beautifully :) Many thanks. Tom. -- http://mail.python.org/mailman/listinfo/python-list
extensive scatter plot
Hi, I would like to produce a scatter plot with roughly 200 mio points. Because the points are so numerous I rather need a point density plot. I use numpy. Right now I loop over the individual data points and make a where query on a meshgrid. ind = where((x_grid == x_points[i]) & (y_grid == y_points[i]) ) counter_grid[ind] += 1 This is really slow. I'm sure there's a better solution already out there. Kind regards! -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
>> I guess this is a question to folks with some numpy background (but >> not necessarily). >> >> I'm using fractions.Fraction as entries in a matrix because I need to >> have very high precision and fractions.Fraction provides infinite >> precision (as I've learned from advice from this list). > > "Infinite" precision only for values that can be expressed as a fraction: > Fraction(2)**Fraction(1, 2) > 1.4142135623730951 type(_) > True, but I only need to add, multiply and divide my fractions in order to end up with the entries in the matrix. >> Now I need to >> calculate its inverse. Can numpy help in this regard? Can I tell numpy >> that the inverse matrix should also have entries in >> fractions.Fraction? Or numpy can only do floating point calculations? > > I tried it, and numpy.linalg.inv() converted the Fraction values to float. > If you aren't concerned about efficiency it should be easy to do it > yourself, in pure python. If there is no other way, that's what I'll try to do. > You could also ask on the numpy mailing list. > >> Probably it doesn't matter but the matrix has all components non-zero >> and is about a thousand by thousand in size. > > Hmm, where did you get that million of exact fractions from? The million of exact fractions are coming from a recursion relation. This recursion relation only adds, multiplies and divides numbers so the end result is always a rational number. > If some real > world data is involved the error introduced by the floating point > calculation may be negligable in comparison with the initial measurement > uncertainty. It's a mathematical problem so no uncertainty is present in the initial values. And even if there was, if there are many orders of magnitude differences between the entries in the matrix floating point does not suffice for various things like eigenvalue calculation and stuff like that. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Read time and date from a text file
On Nov 24, 2:45 pm, Peter Otten <__pete...@web.de> wrote: > huisky wrote: > > I see the problem of year. But the question is the source file does > > NOT provide the year information. > > for instance if i have one record as ['Dec','6','21:01:17'], and the > > other as ['Jan','6','21:01:17'] > > these two records may be in different year. Will it be a problem to > > use the 'datetime' do the time difference calculation? > > You have a problem that is independent of Python. You have to guess the > correct year to get the correct time interval. One approach would be to use > the year from the file's timestamp, then calculate the differences, and > whenever you get a negative interval add one year to the end date. > > This will still result in rare ValueErrors (Feb 29 in non-leapyears) and > some silent miscalculations; I fear you'll have to live with that. > > Peter I see, what i'm doing is only for personal usage. should be no problem at all. thanks a lot, Peter! -- http://mail.python.org/mailman/listinfo/python-list
Re: I got a ImportError,help~!
On 11/24/2010 3:59 AM, xlizzard wrote: HI, I am a newer to python(my version is 3.1.2),recently I got a IDE named Eric(http://eric-ide.python-projects.org/index.html) to study and on this main page I downloaded a tutorial named "**minibrowser". http://eric-ide.python-projects.org/tutorials/MiniBrowser/index.html But when I run this source ,I got the follow Error: Traceback (most recent call last): File "C:\minibrowser\minibrowser\minibrowser.py", line 3, in from ui.mainwindow import MainWindow File "C:\minibrowser\minibrowser\ui\mainwindow.py", line 10, in from Ui_mainwindow import Ui_MainWindow ImportError: No module named Ui_mainwindow I don't understand what's wrong?! The folder structure of the source just like this A.py+ -B.py -C.py A call B,B call C in the same folder ,and "not found"? Can anyone help me,thanks a lot~! That tutorial was probably written for Python 2.X. In Python 3, it is no longer possible to do relative imports using that syntax. If you change the import line to read: from .Ui_mainwindow import Ui_MainWindow or better (making it an absolute import, which is preferred): from ui.mainwindow.Ui_mainwindow import Ui_MainWindow then Python will interpret it as a relative import, and it should work. There could still be other incompatibilities due to the version difference, however. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: I got a ImportError,help~!
2010/11/24 xlizzard : > HI, > I am a newer to python(my version is 3.1.2),recently I got a IDE named > Eric(http://eric-ide.python-projects.org/index.html) to study > and on this main page I downloaded a tutorial named "minibrowser". > http://eric-ide.python-projects.org/tutorials/MiniBrowser/index.html > But when I run this source ,I got the follow Error: > Traceback (most recent call last): > File "C:\minibrowser\minibrowser\minibrowser.py", line 3, in > from ui.mainwindow import MainWindow > File "C:\minibrowser\minibrowser\ui\mainwindow.py", line 10, in > from Ui_mainwindow import Ui_MainWindow > ImportError: No module named Ui_mainwindow > > I don't understand what's wrong?! > The folder structure of the source just like this > A.py+ >-B.py >-C.py > A call B,B call C in the same folder ,and "not found"? > Can anyone help me,thanks a lot~! > How is that a folder structure? Is A.py a folder? Also, you didn't give us enough information to help. If your files are called A.py, B.py, and C.py, then of course it can't find the Ui_MainWindow module (aside: modules are usually lowercase) > > > 网易163/126邮箱百分百兼容iphone ipad邮件收发 > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: pyqt4: multi-threaded database access
Adrian Casey writes: > I have a PyQt4 multi-threaded application which accesses many hosts > concurrently via ssh. I would like each thread to have access to a > database so that it can look up details about the particular system it > is connected to. > > The easy way is to have each thread create a connection to the database. > However, this is wasteful and likely to exhaust the maximum number of > connections the database (postgresql) allows. Instead, I would like to > share a single database connection between all threads. In PyQt4, this > is not possible since the database connection can only be used by the > thread which created it. > > So, I'm thinking I'll create a thread to just handle database queries. > The worker threads will communicate with the database thread using > signals and slots. > > My question is, if I have 20 worker threads who have emitted a signal > which results in a database query, how do I ensure that the query > results are sent back to the originating thread? > > Ideas, examples anyone? First of all, do you *know* it will exhaust the connections, or is that just some gut feeling? Because postgres can easily handle a few hundered connections, and unless you really are exhausting these, it's the easiest solution. The next advice would be to create a pool of connections (pure python, not Qt). Then you lose the "can only be used by the thread which created it" restriction. Of course you should only use a connection from within one thread at a time, but that shouldn't be an issue. So all you have to make sure is that you fetch & return the connections properly. I would use a context-manager for that: with connection_pooll as connection: do_some_queries(connection) HTH, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI FieldStorage instances?
On Nov 23, 7:22 pm, Ian Kelly wrote: > Try Django[1] or TurboGears[2]. > > [1]http://www.djangoproject.com/ > [2]http://www.turbogears.org/ Thanks, never understood what those programs were for. -- Gnarlie -- http://mail.python.org/mailman/listinfo/python-list
Re: inverse of a matrix with Fraction entries
Daniel Fetchinson wrote: > I guess this is a question to folks with some numpy background (but > not necessarily). > > I'm using fractions.Fraction as entries in a matrix because I need to > have very high precision and fractions.Fraction provides infinite > precision (as I've learned from advice from this list). "Infinite" precision only for values that can be expressed as a fraction: >>> Fraction(2)**Fraction(1, 2) 1.4142135623730951 >>> type(_) > Now I need to > calculate its inverse. Can numpy help in this regard? Can I tell numpy > that the inverse matrix should also have entries in > fractions.Fraction? Or numpy can only do floating point calculations? I tried it, and numpy.linalg.inv() converted the Fraction values to float. If you aren't concerned about efficiency it should be easy to do it yourself, in pure python. You could also ask on the numpy mailing list. > Probably it doesn't matter but the matrix has all components non-zero > and is about a thousand by thousand in size. Hmm, where did you get that million of exact fractions from? If some real world data is involved the error introduced by the floating point calculation may be negligable in comparison with the initial measurement uncertainty. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: unittests with different parameters
Short update on what I've settled for generating test functions for various input data: # test case with common test function class MyTest(unittest.TestCase): def _test_invert_flags(self, input, flags, expected): res = do_invert(input, flags) self.assertEqual(res, expected) # test definitions for the various invert flags tests = [((10, 20), INVERT_NONE, (10, 20)), ((10, 20), INVERT_X, (-10, 20)), ((10, 20), INVERT_Y, (10, -20))] # add test to the test case class for input, flags, expected in tests: def test(self): self._test_invert_flags(input, flags, expected) test.__doc__ = "testing invert flags %s" % flags setattr(MyTest, "test_invert_flags_%s" % flags, test) Yes, the names of the test functions would clash if I tested the same flags twice, in the real code that doesn't happen (enumerate is my friend!). Thanks all! Uli -- Domino Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Re: Read time and date from a text file
huisky wrote: > I see the problem of year. But the question is the source file does > NOT provide the year information. > for instance if i have one record as ['Dec','6','21:01:17'], and the > other as ['Jan','6','21:01:17'] > these two records may be in different year. Will it be a problem to > use the 'datetime' do the time difference calculation? You have a problem that is independent of Python. You have to guess the correct year to get the correct time interval. One approach would be to use the year from the file's timestamp, then calculate the differences, and whenever you get a negative interval add one year to the end date. This will still result in rare ValueErrors (Feb 29 in non-leapyears) and some silent miscalculations; I fear you'll have to live with that. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Read time and date from a text file
On Nov 24, 2:09 pm, Peter Otten <__pete...@web.de> wrote: > huisky wrote: > > As a newbie, I posted my question here again. > > say i have two dics read from a text file by 'split'. > > Please don't start a new thread when you are still asking about the same > topic. > > cstart > > > defaultdict(, {15424: ['Dec', '6', '18:57:40'], 552: > > ['Dec', '7', '09:31:00'], 15500: ['Dec', '6', '20:17:02'], 18863: > > ['Dec', '7', '13:14:47'], 18291: ['Dec', '6', '21:01:17'], 18969: > > ['Dec', '7', '14:28:42'], 18937: ['Dec', '7', '14:21:34']}) > ccompl > > > defaultdict(, {15424: ['Dec', '6', '19:42:55'], 18291: > > ['Dec', '6', '21:01:28'], 15500: ['Dec', '6', '20:26:03'], 18863: > > ['Dec', '7', '13:24:07']}) > > I think you should use a normal dict. A default value of 0 doesn't make much > sense here. > > > and I need to calculate the difference time if the key value is the > > same in both dics. > > > Someone suggested me to use the module 'datetime', but I'm still > > wondering how to make it work. > > I mean how to assign ['Dec','6','21:01:17'] to a 'datetime' object and > > then do the datetime operation. > time=datetime.datetime(cstart[18291]) does NOT work. > > Chris Rebert also suggested that you use the strptime() method. To spell it > out a bit: > > >>> s = " ".join(cstart[18291]) > >>> s > 'Dec 6 21:01:17' > >>> datetime.datetime.strptime(s, "%b %d %H:%M:%S") > > datetime.datetime(1900, 12, 6, 21, 1, 17) > > You can learn about the format codes here: > > http://docs.python.org/library/time.html#time.strftime > > Note that strptime() assumes 1900 as the year which may lead to errors in > leapyears and when start and completion time are in different years. > > Peter Thanks a lot, Peter. It helps a lot! I see the problem of year. But the question is the source file does NOT provide the year information. for instance if i have one record as ['Dec','6','21:01:17'], and the other as ['Jan','6','21:01:17'] these two records may be in different year. Will it be a problem to use the 'datetime' do the time difference calculation? regards Huisky Huisky -- http://mail.python.org/mailman/listinfo/python-list
Re: Read time and date from a text file
huisky wrote: > As a newbie, I posted my question here again. > say i have two dics read from a text file by 'split'. Please don't start a new thread when you are still asking about the same topic. cstart > > defaultdict(, {15424: ['Dec', '6', '18:57:40'], 552: > ['Dec', '7', '09:31:00'], 15500: ['Dec', '6', '20:17:02'], 18863: > ['Dec', '7', '13:14:47'], 18291: ['Dec', '6', '21:01:17'], 18969: > ['Dec', '7', '14:28:42'], 18937: ['Dec', '7', '14:21:34']}) ccompl > > defaultdict(, {15424: ['Dec', '6', '19:42:55'], 18291: > ['Dec', '6', '21:01:28'], 15500: ['Dec', '6', '20:26:03'], 18863: > ['Dec', '7', '13:24:07']}) I think you should use a normal dict. A default value of 0 doesn't make much sense here. > and I need to calculate the difference time if the key value is the > same in both dics. > > Someone suggested me to use the module 'datetime', but I'm still > wondering how to make it work. > I mean how to assign ['Dec','6','21:01:17'] to a 'datetime' object and > then do the datetime operation. time=datetime.datetime(cstart[18291]) does NOT work. Chris Rebert also suggested that you use the strptime() method. To spell it out a bit: >>> s = " ".join(cstart[18291]) >>> s 'Dec 6 21:01:17' >>> datetime.datetime.strptime(s, "%b %d %H:%M:%S") datetime.datetime(1900, 12, 6, 21, 1, 17) You can learn about the format codes here: http://docs.python.org/library/time.html#time.strftime Note that strptime() assumes 1900 as the year which may lead to errors in leapyears and when start and completion time are in different years. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Read time and date from a text file
On Nov 24, 7:45 am, huisky wrote: > Hi, > > As a newbie, I posted my question here again. > say i have two dics read from a text file by 'split'. > > >>> cstart > > defaultdict(, {15424: ['Dec', '6', '18:57:40'], 552: > ['Dec', '7', '09:31:00'], 15500: ['Dec', '6', '20:17:02'], 18863: > ['Dec', '7', '13:14:47'], 18291: ['Dec', '6', '21:01:17'], 18969: > ['Dec', '7', '14:28:42'], 18937: ['Dec', '7', '14:21:34']}) > > >>> ccompl > > defaultdict(, {15424: ['Dec', '6', '19:42:55'], 18291: > ['Dec', '6', '21:01:28'], 15500: ['Dec', '6', '20:26:03'], 18863: > ['Dec', '7', '13:24:07']}) > > and I need to calculate the difference time if the key value is the > same in both dics. > > Someone suggested me to use the module 'datetime', but I'm still > wondering how to make it work. > I mean how to assign ['Dec','6','21:01:17'] to a 'datetime' object and > then do the datetime operation. > > >>>time=datetime.datetime(cstart[18291]) does NOT work. > > thanks in advance > Huisky You can use datetime.datetime.strptime() to create a datetime object from a string representing a date >>> import datetime >>> datetime.datetime.strptime('Dec 7 13:24:07','%b %d %H:%M:%S') datetime.datetime(1900, 12, 7, 13, 24, 7) Of course, you need to put in the correct year. datetime.strptime(date_string, format) Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])). ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. -- http://mail.python.org/mailman/listinfo/python-list
inverse of a matrix with Fraction entries
I guess this is a question to folks with some numpy background (but not necessarily). I'm using fractions.Fraction as entries in a matrix because I need to have very high precision and fractions.Fraction provides infinite precision (as I've learned from advice from this list). Now I need to calculate its inverse. Can numpy help in this regard? Can I tell numpy that the inverse matrix should also have entries in fractions.Fraction? Or numpy can only do floating point calculations? Probably it doesn't matter but the matrix has all components non-zero and is about a thousand by thousand in size. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Read time and date from a text file
Hi, As a newbie, I posted my question here again. say i have two dics read from a text file by 'split'. >>> cstart defaultdict(, {15424: ['Dec', '6', '18:57:40'], 552: ['Dec', '7', '09:31:00'], 15500: ['Dec', '6', '20:17:02'], 18863: ['Dec', '7', '13:14:47'], 18291: ['Dec', '6', '21:01:17'], 18969: ['Dec', '7', '14:28:42'], 18937: ['Dec', '7', '14:21:34']}) >>> ccompl defaultdict(, {15424: ['Dec', '6', '19:42:55'], 18291: ['Dec', '6', '21:01:28'], 15500: ['Dec', '6', '20:26:03'], 18863: ['Dec', '7', '13:24:07']}) and I need to calculate the difference time if the key value is the same in both dics. Someone suggested me to use the module 'datetime', but I'm still wondering how to make it work. I mean how to assign ['Dec','6','21:01:17'] to a 'datetime' object and then do the datetime operation. >>>time=datetime.datetime(cstart[18291]) does NOT work. thanks in advance Huisky -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays
Garland Fulton, 24.11.2010 06:55: Is there a way I can define an Array of and unknown size so I can add and remove to or from it? Are arrays immutable? Python has lists and tuples as basic data structures. Tuples are completely immutable, lists are completely mutable. If you want a container that has a fixed size but allows changing items, use a list and avoid calling .append() and .remove() to change items in favour of direct item assignments. If you want a completely mutable container, use a list and use it as you see fit. If you want a stack, a list will do. If you want a queue, a deque is a better option. In any case, if you tell us more about what you actually want to do, we can give better suggestions. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensuring symmetry in difflib.SequenceMatcher
John Yeung wrote: > I'm generally pleased with difflib.SequenceMatcher: It's probably not > the best available string matcher out there, but it's in the standard > library and I've seen worse in the wild. One thing that kind of > bothers me is that it's sensitive to which argument you pick as "seq1" > and which you pick as "seq2": > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. import difflib difflib.SequenceMatcher(None, 'BYRD', 'BRADY').ratio() > 0.2 difflib.SequenceMatcher(None, 'BRADY', 'BYRD').ratio() > 0.3 > > Is this a bug? I am guessing the algorithm is implemented correctly, > and that it's just an inherent property of the algorithm used. It's > certainly not what I'd call a desirably property. Are there any > simple adjustments that can be made without sacrificing (too much) > performance? def symmetric_ratio(a, b, S=difflib.SequenceMatcher): return (S(None, a, b).ratio() + S(None, b, a).ratio())/2.0 I'm expecting 50% performance loss ;) Seriously, have you tried to calculate the ratio with realistic data? Without looking into the source I would expect the two ratios to get more similar. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: factorial of negative one (-1)
On Tue, Nov 2, 2010 at 12:57 PM, Terry Reedy wrote: > On 11/2/2010 6:11 AM, Hrvoje Niksic wrote: > > 1.1 .hex() > '0x1.1999ap+0' >> >> Here it is immediately obvious that the final digit of the infinite >> sequence "1.1999..." is rounded from 9 to a. Printing the number with >> any more digits would just reveal zeros, as expected. >> >> Does anyone know why Python doesn't accept hex float literals in source >> code? >> > > Assuming that the parser would have no problem with them: > 1. the format is relatively recent > 2. you can write float.fromhex('') > 3. it never occurred to anyone to do so > 4. literals are values supplied by the programmer; hex float values are > rare and when they do occur, they are usually the stored output of a > previous .hex() in Python or similar in other languages. > 5. too easy to confuse in quick reading with normal float literals > 6. the format is a bit weird and too esoteric for most programmers; they > should not be part of the basic syntax that everyone has to learn; someone > who reads float.fromhex(something) can look it up. > > -- > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > I have just realized that there is a program called PyNum that would be of great help to me, but I can't seem to figure out how to use it after installing, or how to build it with Python 2.7 -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensuring symmetry in difflib.SequenceMatcher
On Mittwoch 24 November 2010, John Yeung wrote: > Are there any > simple adjustments that can be made without sacrificing (too > much) performance? >>> difflib.SequenceMatcher(None,*sorted(('BYRD','BRADY'))).ratio() 0.3 -- Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
pyqt4: multi-threaded database access
I have a PyQt4 multi-threaded application which accesses many hosts concurrently via ssh. I would like each thread to have access to a database so that it can look up details about the particular system it is connected to. The easy way is to have each thread create a connection to the database. However, this is wasteful and likely to exhaust the maximum number of connections the database (postgresql) allows. Instead, I would like to share a single database connection between all threads. In PyQt4, this is not possible since the database connection can only be used by the thread which created it. So, I'm thinking I'll create a thread to just handle database queries. The worker threads will communicate with the database thread using signals and slots. My question is, if I have 20 worker threads who have emitted a signal which results in a database query, how do I ensure that the query results are sent back to the originating thread? Ideas, examples anyone? Thanks. Adrian. -- http://mail.python.org/mailman/listinfo/python-list