quickly read a formated file?
Hi, Is there a fine way to read a formated file like: %HEADER title = "Untilted" username = "User" %DATA .. .. The formated file may be very popularly, but the module ConfigPaser doesn't handle it. Is there a way to process it freely? -- http://mail.python.org/mailman/listinfo/python-list
PyQt4: Clickable links in QLabel?
Hi everyone, A short and sweet question: Is it possible to put a clickable link in a QLabel that will open in the systems default browser? I tried to put in some HTML but it did (of course?) simply display the code instead of a link. I also tried to set openExternalLinks 'true' but then pyuic4 bombed. I see that QLabel does not have a html text format but I'm still hoping it's possible. I really need a link on my main window form. Thanks Tina -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about raise and exceptions.
On 1 mar, 04:46, Daniel Klein <[EMAIL PROTECTED]> wrote: > On Wed, 28 Feb 2007 22:03:13 +0100, Bruno Desthuilliers > > > > <[EMAIL PROTECTED]> wrote: > >Daniel Klein a écrit : > >> The arguments for TransitionError must be a tuple, > > >Err... > > >> eg: > > >> msg = "Going to error state %d from state %d" % (self.curr_state, > >> newstate) > >> raise TransitionError(self, curr_state, newstate, msg) > > >Where did you see a tuple here ? You're code is *calling* > >TransitionError, passing it the needed arguments. > > >Note that it's the correct syntax - but not the correct explanation !-) > > My bad :-( > > Thanks for setting me straight. I had (wrongly) thought that the stuff > inside of () was a tuple. For the record, it's the ',' that makes the tuple. The () are (in this context) the call operator. >>> t = 1, 2, 3 >>> t (1, 2, 3) >>> type(t) >>> t2 = 1, >>> t2 (1,) >>> def toto(): >>> return "it's me" ... >>> toto >>> toto() "it's me" >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Curious UnboundLocalError Behavior
On 28 fév, 18:15, "Matthew Franz" <[EMAIL PROTECTED]> wrote: > I'm probably fundamentally misunderstanding the way the interpreter > works with regard to scope, but is this the intended behavior... > (snip traceback) > import os,sys > > SOMEGLOBAL=1 > > def foo(): > dome=False > if dome: > SOMEGLOBAL = 0 This makes SOMEGLOBAL local !-) Look for the 'global' statement. Or better, try to avoid rebinding globals from within a function. As as side note: by convention, ALL_UPPER names denote constants. -- http://mail.python.org/mailman/listinfo/python-list
Fwd: gmpy moving to code.google.com
> > Could you please tell me, on that 64-bit build, what happens with: > > > >>> importgmpy, sys, operator > > >>> sys.maxint > > ??? > > >>>gmpy.mpz(sys.maxint) > > ??? > > >>> operator.index(gmpy.mpz(sys.maxint)) > > ??? > > >>> sys.maxint+1 > > ??? > > >>>gmpy.mpz(sys.maxint+1) > > ??? > > >>> operator.index(gmpy.mpz(sys.maxint)+1) > > ??? > > > i.e., what are the values correspondiing to the ??? occurrences when > > you actually do that...? > > Here it goes (python 2.5 - 64bit): > > >>> importgmpy, sys, operator > >>> sys.maxint > 9223372036854775807 > >>>gmpy.mpz(sys.maxint) > mpz(-1) > >>> operator.index(gmpy.mpz(sys.maxint)) > -1 > >>> sys.maxint+1 > > 9223372036854775808L>>>gmpy.mpz(sys.maxint+1) > > mpz(9223372036854775808L)>>> operator.index(gmpy.mpz(sys.maxint)+1) > > 0 > > I don't pretent to fully understand what's going on, > butgmpy.mpz(sys.maxint)==gmpy.mpz(-1) is more than suspicious :) [directing Alex's message back to the list] Yes, clearly there is some 32-vs-64 bit assumption around. When I create an mpz from a Python int (a PyObject* i which passes Python's int typecheck) I do that by calling mpz_from_c_long(PyInt_AsLong(i)) -- depending on what "long" means in C, I guess that might be the root of the problem. There might be similar problems in creating mpq and mpf from Python ints > 2**31-1 on 64-bit platforms, I guess. I could try flailing around in the dark to fix it, but, without access to a 64-bit Python platform, I don't really see any chance of me fixing this. If somebody can give me ssh access to such a platform, I'll be glad to work to give it a try; of course, if anybody who does have access to such a platform wants to send me patches or join the gmpy project, that would also be great; failing either of these options, I don't see much that I could do beyond pointing out in the docs that gmpy does not correctly support 64-bits builds of Python, checking for them in the unittests, etc. Thanks, Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote: > Bruno Desthuilliers wrote: > >> class Toto(object): >> pass >> >> print Toto.__name__ > > Okay, I revoke my statement and assert the opposite. > > But what's it (__name__) good for? As objects don't know to which name they are bound, that's a good way to give some information in stack traces or when doing introspection. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Vector, matrix, normalize, rotate. What package?
Mattias Brändström wrote: > 1. Create 3d vectors. > 2. Normalize those vectors. > 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in > radians. > 4. Perform matrix multiplication. > > Meybe someone knows a way to use numpy for 2 and 3? Here's some code I wrote recently to do normalisation of vectors using Numeric: from Numeric import add, sqrt def dots(u, v): """Return array of dot products of arrays of vectors.""" return add.reduce(u * v, -1) def units(v): """Array of unit vectors from array of vectors.""" ds = 1.0 / sqrt(dots(v, v)) return ds * v These work best if you give them multiple vectors to work on at once, otherwise you don't get much advantage from using Numeric. I don't have anything to hand for rotation about a vector, but if you can find a formula, you should be able to use similar techniques to "vectorize" it using Numeric. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: quickly read a formated file?
lialie:
> The formated file may be very popularly, but the module ConfigPaser
> doesn't handle it. Is there a way to process it freely?
First try, assuming the input file can be read whole. The code isn't
much readable, it needs better variable names (name names?), comments,
etc.
data = """
%HEADER
title1 = "Untilted1"
username = "User1"
%DATA
title2 = "Untilted2"
username2 = "User2"
"""
l1 = (p.strip().splitlines() for p in data.split("%") if p.strip())
result = {}
for part in l1:
pairs1 = (pair.split('=') for pair in part[1:])
pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in pairs1)
result[part[0]] = dict(pairs2)
print result
All done lazily for your better comfort :-)
Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
Alan Isaac wrote: > class NothingNew: > a = 0 > def __init__(self): > self.b = 1 > self.initialized = True There's a problem with that when you want to subclass: class NothingElseNew(NothingNew): def __init__(self): NothingNew.__init__(self) self.c = 42 # <--- Not allowed! You could get around this by temporarily de-initializing it, i.e. def __init__(self): NothingNew.__init__(self) del self.__dict__['initialized'] self.c = 42 self.initialized = True but that's not very elegant. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
kevinliu23 wrote: > Just tried your solution Tim, worked like a charm. :) > > It's great because I don't even have to worry about the computer name. > A question regarding the rootPath parameter...how would I be passing > it? Would I be passing it as... > >tuple = win32api.GetDiskFreeSpace(r'C:') > or just leave it blank and the function will automatically use the > rootPath of where the .py file resides? > > Both have returned the correct result. The simple answer is: I'm not sure. If you experiment and find something which works, just use it! Something which SickMonkey made me return to your question. Are you trying to find the disk space available on a different machine (possibly on several different machines)? If so, then WMI is definitely your answer. You can run -- from your machine -- one piece of code which will attach to several different machines to give you the answer. (as per Sick Monkey's later post). If I've read too much into your question, well nothing's ever wasted on the internet. Here's some sample code which uses the wmi module from: http://timgolden.me.uk/python/wmi.html machines = ['mycomp', 'othercomp'] for machine in machines: print "Machine:", machine c = wmi.WMI (machine) # only consider local fixed disks for disk in c.Win32_LogicalDisk (DriveType=3): print disk.Name, disk.FreeSpace print Yes, you could even write: for disk in wmi.WMI (machine).Win32_LogicaDisk (DriveType=3): but I'd find it a touch unwieldy. YMMV. HTH TJG -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pylint 0.13 / astng 0.17
Hi there! I'm very pleased to announce new releases of pylint (0.13) and its underlying library astng (0.17). The PyLint release contains a bunch of bugs fixes, some new checks and command line changes, and a new checker dedicated to Restricted Python checking. If this doesn't sound familiar to you, visit the PyPy_ project web site for more information. The astng release contains a lot of inference fixes and enhancement, so even if pylint should still works with the old version you're strongly encouraged to upgrade. .. _PyPy: http://codespeak.net/pypy/ What is pylint ? Pylint is a python tool that checks if a module satisfy a coding standard. Pylint can be seen as another pychecker since nearly all tests you can do with pychecker can also be done with Pylint. But Pylint offers some more features, like checking line-code's length, checking if variable names are well-formed according to your coding standard, or checking if declared interfaces are truly implemented, and much more (see http://www.logilab.org/projects/pylint/ for the complete check list). The big advantage with Pylint is that it is highly configurable, customizable, and you can easily write a small plugin to add a personal feature. The usage it quite simple : $ pylint mypackage.mymodule This command will output all the errors and warnings related to the tested code (here : mypackage.mymodule), will dump a little summary at the end, and will give a mark to the tested code. Pylint is free software distributed under the GNU Public Licence. Home page - http://www.logilab.org/project/name/pylint http://www.logilab.org/project/name/logilab-astng Download ftp://ftp.logilab.org/pub/pylint ftp://ftp.logilab.org/pub/astng Mailing list mailto://[EMAIL PROTECTED] Enjoy ! -- Sylvain Thénault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
On Feb 26, 10:48 pm, "Alan Isaac" <[EMAIL PROTECTED]> wrote: > I have a class whose instances should only receive attribute > assignments for attributes that were created at inititialization. > If slots are not appropriate, what is the Pythonic design for this? > > Thanks, > Alan Isaac There is a Cookbook recipe for that: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote: > > > But what's it (__name__) good for? > > As objects don't know to which name they are bound, that's a good way to > give some information in stack traces or when doing introspection. Also, the name is used by pickle to find the class of pickled instances. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading csv files using SQL
Paul McGuire ha scritto: > Sqlite has an in-memory option, so that you can read in your csv, then > load into actual tables. Thanks, this could be the perfect solution. Paolo -- http://mail.python.org/mailman/listinfo/python-list
splitting perl-style find/replace regexp using python
Hi all
I have a file with a bunch of perl regular expressions like so:
/(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
bold
/(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
b>''$3/ # italic bold
/(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
italic
These are all find/replace expressions delimited as '/search/replace/
# comment' where 'search' is the regular expression we're searching
for and 'replace' is the replacement expression.
Is there an easy and general way that I can split these perl-style
find-and-replace expressions into something I can use with Python, eg
re.sub('search','replace',str) ?
I though generally it would be good enough to split on '/' but as you
see the <\/b> messes that up. I really don't want to learn perl
here :-)
Cheers
JP
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
Andi Clemens wrote: > I want to change the A-Record for some IPs, this shouldn't be too > hard. I looked at dnspython and twisted, but I really don't have a > clue how to do this. > Has anyone done this before? Read RFC 2136 (Dynamic updates in the DNS) and see if your server can be configured to do this. If not, you'll have to change the zone files manually and reload the DNS config. Regards, Björn -- BOFH excuse #203: Write-only-memory subsystem too slow for this machine. Contact your local dealer. -- http://mail.python.org/mailman/listinfo/python-list
Converting a c array to python list
Hi! I want to embed a function in my python application, that creates a two-dimensional array of integers and passes it as a list (preferably a list of lists, but that is not necessary, as the python function knows the dimensions of this array). As I read the reference, I see, that I must first initialize a list object and then item-by-item put the values to the list. Is there any faster way to do it? And is it worth to implement? The same problem is resolved in the current version by calling a smaller c function (that counts just one element of the array) many times. Will it add much performance to the process? zefciu -- http://mail.python.org/mailman/listinfo/python-list
Re: installing "pysqlite"
On Feb 28, 12:51 pm, "Paul Boddie" <[EMAIL PROTECTED]> wrote:
> On 28 Feb, 12:07, Nader Emami <[EMAIL PROTECTED]> wrote:
>
>
>
> > I am back with another problem. I suppose that I can tell it!
> > I have installed both, 'sqlite' and 'pysqlite' without any problem. But
> > If I try to test whether the 'pysqlite' interface works, I get the next
> > error message:
>
> [...]
>
> > /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so:
> > undefined symbol: sqlite3_set_authorizer
>
> > I don't understand it. Could you tell me how I can solve this last
> > point? I hope so!
>
> It looks like Python (although it's really the dynamic linker) can't
> locate the SQLite libraries. If you have installed SQLite into a non-
> standard place, which I'm guessing is the case, then you will need to
> set your LD_LIBRARY_PATH environment variable to refer to the
> directory where the libraries were installed.
>
> So, if you installed SQLite into /usr/people/emami and you see files
> like libsqlite3.so in /usr/people/emami/lib, then you need to change
> your LD_LIBRARY_PATH as follows:
>
> export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib
>
> (The actual directory should be the same as the one you specified for
> library_dirs in the setup.cfg file for pysqlite.)
>
> If you're not using bash as your shell, the syntax for the command may
> be different. Don't forget to add this command to your shell
> configuration file (eg. .bashrc) so that your system remembers this
> information.
>
> Paul
Hello
I have expanded the LD_LIBRARY_PATH to my home lib (export
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib).
I have built and installed the 'pysqlite-2.3.3' with the next
'setup.cfg' :
[build_ext]
define=
include_dirs=/usr/people/emami/include
library_dirs=/usr/people/emami/lib
#libraries=/usr/people/emami/lib/libsqlite3.so (this line as a
comment)
The resutl of this process was:
running install_lib
copying build/lib.linux-i686-2.4/pysqlite2/_sqlite.so -> /usr/people/
emami/lib/python2.4/site-packages/pysqlite2
running install_data
This message had given after installing. I have controll the '/usr/
people/emami/lib/python2.4/site-packages/pysqlite2' whether the
'_sqlite.so' has copied there. Yes it has. Okay!
I go to python and I give the next command:
>>> from pysqlite import test
and Unfortunately I get the next error message:
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/test/
__init__.py", line 25, in ?
from pysqlite2.test import dbapi, types, userfunctions, factory,
transactions,\
File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/test/
dbapi.py", line 26, in ?
import pysqlite2.dbapi2 as sqlite
File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/
dbapi2.py", line 27, in ?
from pysqlite2._sqlite import *
ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/
_sqlite.so: undefined symbol: sqlite3_set_authorizer
Do you know what option I have to give to if I want to use the
'easy_install" tool?
%easy_install pysqlite (with some optione with which it cab find the
installed 'libsqlite.so')
Nader
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dialog with a process via subprocess.Popen blocks forever
Hi, Thanks for your answer. I had a look into the fcntl module and tried to unlock the output-file, but >>> fcntl.lockf(x.stdout, fcntl.LOCK_UN) Traceback (most recent call last): File "", line 1, in IOError: [Errno 9] Bad file descriptor I wonder why it does work with the sys.stdin It's really a pity, it's the first time python does not work as expected. =/ Flushing the stdin did not help, too. Regards, -Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuples vs Lists: Semantic difference
Ben Finney wrote: > Bjoern Schliessmann <[EMAIL PROTECTED]> >> Explain. > > Well, since you ask so politely :-) I admit, sometimes I'm a little short-spoken ;) >> I know tuples as immutable lists ... > > That's a common misconception. > [...] Thanks for pointers, there's more to it than I suspected. Regards, Björn -- BOFH excuse #384: it's an ID-10-T error -- http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
Michele Simionato wrote: > On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> >> In <[EMAIL PROTECTED]>, Bjoern Schliessmann >>> But what's it (__name__) good for? >> >> As objects don't know to which name they are bound, that's a good >> way to give some information in stack traces or when doing >> introspection. > > Also, the name is used by pickle to find the class of pickled > instances. Mh. I suspect there's also more to it than I see now, but this __name__ seems quite useless to me. What if I rebind the class' name after definition? Or is it really just for some manual introspection? If it is, it seems a bit of an overkill to me. >>> class Spam(object): ... pass ... >>> Ham = Spam >>> Spam = 0 >>> test = Ham() >>> test.__class__ >>> test.__class__.__name__ 'Spam' >>> Spam 0 >>> Regards, Björn -- BOFH excuse #137: User was distributing pornography on server; system seized by FBI. -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
John Pye wrote:
> Hi all
>
> I have a file with a bunch of perl regular expressions like so:
>
> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
> bold
> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
> b>''$3/ # italic bold
> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
> italic
>
> These are all find/replace expressions delimited as '/search/replace/
> # comment' where 'search' is the regular expression we're searching
> for and 'replace' is the replacement expression.
>
> Is there an easy and general way that I can split these perl-style
> find-and-replace expressions into something I can use with Python, eg
> re.sub('search','replace',str) ?
>
> I though generally it would be good enough to split on '/' but as you
> see the <\/b> messes that up. I really don't want to learn perl
> here :-)
>
> Cheers
> JP
>
This could be more general, in principal a perl regex could end with a
"\", e.g. "\\/", but I'm guessing that won't happen here.
py> for p in perlish:
... print p
...
/(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/
/(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/
/(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/
py> import re
py> splitter = re.compile(r'[^\\]/')
py> for p in perlish:
... print splitter.split(p)
...
['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
"$1'''$2'''$", '']
['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
"$1''$2<\\/b>''$", '']
['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
"$1''$2''$", '']
(I'm hoping this doesn't wrap!)
James
--
http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
John Pye wrote:
> I have a file with a bunch of perl regular expressions like so:
>
> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
> bold
> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
> b>''$3/ # italic bold
> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
> italic
>
> These are all find/replace expressions delimited as '/search/replace/
> # comment' where 'search' is the regular expression we're searching
> for and 'replace' is the replacement expression.
>
> Is there an easy and general way that I can split these perl-style
> find-and-replace expressions into something I can use with Python, eg
> re.sub('search','replace',str) ?
>
> I though generally it would be good enough to split on '/' but as you
> see the <\/b> messes that up. I really don't want to learn perl
> here :-)
How about matching all escaped chars and '/', and then throwing away the
former:
def split(s):
breaks = re.compile(r"(\\.)|(/)").finditer(s)
left, mid, right = [b.start() for b in breaks if b.group(2)]
return s[left+1:mid], s[mid+1:right]
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
James Stroud wrote:
> John Pye wrote:
>> Hi all
>>
>> I have a file with a bunch of perl regular expressions like so:
>>
>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
>> bold
>> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
>> b>''$3/ # italic bold
>> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
>> italic
>>
>> These are all find/replace expressions delimited as '/search/replace/
>> # comment' where 'search' is the regular expression we're searching
>> for and 'replace' is the replacement expression.
>>
>> Is there an easy and general way that I can split these perl-style
>> find-and-replace expressions into something I can use with Python, eg
>> re.sub('search','replace',str) ?
>>
>> I though generally it would be good enough to split on '/' but as you
>> see the <\/b> messes that up. I really don't want to learn perl
>> here :-)
>>
>> Cheers
>> JP
>>
>
> This could be more general, in principal a perl regex could end with a
> "\", e.g. "\\/", but I'm guessing that won't happen here.
>
> py> for p in perlish:
> ... print p
> ...
> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/
> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/
> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/
> py> import re
> py> splitter = re.compile(r'[^\\]/')
> py> for p in perlish:
> ... print splitter.split(p)
> ...
> ['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
> "$1'''$2'''$", '']
> ['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
> "$1''$2<\\/b>''$", '']
> ['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
> "$1''$2''$", '']
>
> (I'm hoping this doesn't wrap!)
>
> James
I realized that threw away the closing parentheses. This is the correct
version:
py> splitter = re.compile(r'(? for p in perlish:
... print splitter.split(p)
...
['', '(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
"$1'''$2'''$3", '']
['', '(^|[\\s\\(])\\_\\_([^ ].*?[^
])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', "$1''$2<\\/b>''$3", '']
['', '(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
"$1''$2''$3", '']
James
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Source Code Beautifier
En Wed, 28 Feb 2007 19:09:09 -0300, [EMAIL PROTECTED] <[EMAIL PROTECTED]> escribió: > On Feb 28, 11:24 am, Alan Franzoni > <[EMAIL PROTECTED]> wrote: >> Il 27 Feb 2007 16:14:20 -0800, [EMAIL PROTECTED] ha scritto: >> >> > Those mean different things: >> >> a=[1] >> b=a >> a += [2] >> a >> > [1, 2] >> b >> > [1, 2] >> a=[1] >> b=a >> a = a + [2] >> a >> > [1, 2] >> b >> > [1] >> >> This is a really nasty one! I just answered to Tim above here, and then >> I >> saw your example... I had never realized that kind of list behaviour. >> That's probably because i never use + and += on lists (i prefer the more >> explicit append() or extend() and i do copy list explictly when I want >> to) >> , BTW I think this behaviour is tricky! > > Seems obvious and desirable to me. Bare "=" is the way you assign a > name to an object; saying "NAME =" will rebind the name, breaking the > connection between a and b. Without it, they continue to refer to the > same object; extending the list (via += or .extend) mutates the > object, but doesn't change which objects a and b are referencing. > > It would be very counterintuitive to me if "=" didn't change the > name's binding, or if other operators did. Note that a += b first tries to use __iadd__ if it is available, if not, behaves like a = a + b. And even if __iadd__ exists, there is no restriction on it to mutate the object in place; it may return a new instance if desired. So, a += b may involve a name rebinding anyway. Try the example above using immutable objects like tuples or strings. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
James Stroud wrote:
> James Stroud wrote:
>> John Pye wrote:
>>> Hi all
>>>
>>> I have a file with a bunch of perl regular expressions like so:
>>>
>>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
>>> bold
>>> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
>>> b>''$3/ # italic bold
>>> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
>>> italic
>>>
>>> These are all find/replace expressions delimited as '/search/replace/
>>> # comment' where 'search' is the regular expression we're searching
>>> for and 'replace' is the replacement expression.
>>>
>>> Is there an easy and general way that I can split these perl-style
>>> find-and-replace expressions into something I can use with Python, eg
>>> re.sub('search','replace',str) ?
>>>
>>> I though generally it would be good enough to split on '/' but as you
>>> see the <\/b> messes that up. I really don't want to learn perl
>>> here :-)
>>>
>>> Cheers
>>> JP
>>>
>>
>> This could be more general, in principal a perl regex could end with a
>> "\", e.g. "\\/", but I'm guessing that won't happen here.
>>
>> py> for p in perlish:
>> ... print p
>> ...
>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/
>> /(^|[\s\(])\_\_([^ ].*?[^
>> ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/ /(^|[\s\(])\_([^ ].*?[^
>> ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ py> import re
>> py> splitter = re.compile(r'[^\\]/')
>> py> for p in perlish:
>> ... print splitter.split(p)
>> ...
>> ['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>> "$1'''$2'''$", '']
>> ['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>> "$1''$2<\\/b>''$", '']
>> ['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>> "$1''$2''$", '']
>>
>> (I'm hoping this doesn't wrap!)
>>
>> James
>
> I realized that threw away the closing parentheses. This is the correct
> version:
>
> py> splitter = re.compile(r'(? py> for p in perlish:
> ... print splitter.split(p)
> ...
> ['', '(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
> "$1'''$2'''$3", '']
> ['', '(^|[\\s\\(])\\_\\_([^ ].*?[^
> ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', "$1''$2<\\/b>''$3", '']
> ['', '(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
> "$1''$2''$3", '']
There is another problem with escaped backslashes:
>>> re.compile(r'(?http://mail.python.org/mailman/listinfo/python-list
Re: finding out the precision of floats
On Feb 28, 10:29 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > On Mar 1, 4:19 am, "BartOgryczak" <[EMAIL PROTECTED]> wrote: > > > > > On Feb 28, 3:53 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > > > > On Feb 28, 10:38 pm, "BartOgryczak" <[EMAIL PROTECTED]> wrote: > > > > > [1] eg. consider calculating interests rate, which often is defined as > > > > math.pow(anualRate,days/365.0). > > > > More importantly, the formula you give is dead wrong. The correct > > > formula for converting an annual rate of interest to the rate of > > > interest to be used for n days (on the basis of 365 days per year) is: > > > > (1 + annual_rate) ** (n / 365.0) - 1.0 > > > or > > > math.pow(1 + annual_rate, n / 365.0) - 1.0 > > > if you prefer. > > > YPB? Anyone with half a brain knows, that you can either express rate > > as 0.07 and do all those ridiculous conversions above, or express it > > as 1.07 and apply it directly. > > A conversion involving an exponentiation is necessary. "All those"?? I > see only two. > > Please re-read your original post, and note that there are *TWO* plus- > or-minus 1.0 differences between your formula and mine. For an annual > rate of 10%, yours would calculate the rate for 6 months (expressed as > 182.5 days) as: > math.pow(0.10, 0.5) = 0.316... i.e. 31.6% You're assuming that I'd store annual rate as 0.1, while actually it'd stored as 1.1. Which is logical and applicable directly. -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
Peter Otten wrote:
> James Stroud wrote:
>
>> James Stroud wrote:
>>> John Pye wrote:
Hi all
I have a file with a bunch of perl regular expressions like so:
/(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ #
bold
/(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/
b>''$3/ # italic bold
/(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ #
italic
These are all find/replace expressions delimited as '/search/replace/
# comment' where 'search' is the regular expression we're searching
for and 'replace' is the replacement expression.
Is there an easy and general way that I can split these perl-style
find-and-replace expressions into something I can use with Python, eg
re.sub('search','replace',str) ?
I though generally it would be good enough to split on '/' but as you
see the <\/b> messes that up. I really don't want to learn perl
here :-)
Cheers
JP
>>> This could be more general, in principal a perl regex could end with a
>>> "\", e.g. "\\/", but I'm guessing that won't happen here.
>>>
>>> py> for p in perlish:
>>> ... print p
>>> ...
>>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/
>>> /(^|[\s\(])\_\_([^ ].*?[^
>>> ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/ /(^|[\s\(])\_([^ ].*?[^
>>> ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ py> import re
>>> py> splitter = re.compile(r'[^\\]/')
>>> py> for p in perlish:
>>> ... print splitter.split(p)
>>> ...
>>> ['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>>> "$1'''$2'''$", '']
>>> ['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>>> "$1''$2<\\/b>''$", '']
>>> ['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$',
>>> "$1''$2''$", '']
>>>
>>> (I'm hoping this doesn't wrap!)
>>>
>>> James
>> I realized that threw away the closing parentheses. This is the correct
>> version:
>>
>> py> splitter = re.compile(r'(?> py> for p in perlish:
>> ... print splitter.split(p)
>> ...
>> ['', '(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
>> "$1'''$2'''$3", '']
>> ['', '(^|[\\s\\(])\\_\\_([^ ].*?[^
>> ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', "$1''$2<\\/b>''$3", '']
>> ['', '(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)',
>> "$1''$2''$3", '']
>
> There is another problem with escaped backslashes:
>
re.compile(r'(? ['', 'abc/def', '']
>
> Peter
Yes, this would be a case of the expression (left side) ending with a
"\" as I mentioned above.
James
--
http://mail.python.org/mailman/listinfo/python-list
Re: Eric on XP for Newbie
Thanks guys Found this on another blog and it seems to work - you need to run the SPE.pyo file ... Stani said... In order to run SPE you need to install python from www.python.org and wxpython 2.6 from wxpython.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: installing "pysqlite"
On 1 Mar, 10:34, "Nader" <[EMAIL PROTECTED]> wrote:
>
> I have expanded the LD_LIBRARY_PATH to my home lib (export
> LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib).
> I have built and installed the 'pysqlite-2.3.3' with the next
> 'setup.cfg' :
>
> [build_ext]
> define=
> include_dirs=/usr/people/emami/include
> library_dirs=/usr/people/emami/lib
> #libraries=/usr/people/emami/lib/libsqlite3.so (this line as a
> comment)
This looks alright. Be sure to verify that libsqlite3.so is in /usr/
people/emami/lib, although I suppose you've done this, looking at your
comment.
> The resutl of this process was:
>
> running install_lib
> copying build/lib.linux-i686-2.4/pysqlite2/_sqlite.so -> /usr/people/
> emami/lib/python2.4/site-packages/pysqlite2
> running install_data
>
> This message had given after installing. I have controll the '/usr/
> people/emami/lib/python2.4/site-packages/pysqlite2' whether the
> '_sqlite.so' has copied there. Yes it has. Okay!
So pysqlite2 has installed properly at least.
> I go to python and I give the next command:
>
> >>> from pysqlite import test
>
> and Unfortunately I get the next error message:
[...]
> ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/
> _sqlite.so: undefined symbol: sqlite3_set_authorizer
I'm running out of ideas here, but you could try doing this:
ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so
This should show a list of references to libraries, but if one of them
is missing in some way then it means that it isn't found by the linker
and it's not on the LD_LIBRARY_PATH. Another thought is that
sqlite3_set_authorizer isn't found in the SQLite library - you can
test this by doing the following:
nm /usr/people/emami/lib/libsqlite3.so
I get something like this in response:
000110b0 T sqlite3_set_authorizer
If you don't get anything in response or if you see "U" instead of
"T", then this might indicate an problem with the way SQLite has been
configured.
> Do you know what option I have to give to if I want to use the
> 'easy_install" tool?
> %easy_install pysqlite (with some optione with which it cab find the
> installed 'libsqlite.so')
I'm no easy_install expert, I'm afraid. You might want to talk to the
pysqlite people directly if what I've suggested doesn't help you
further:
http://www.initd.org/tracker/pysqlite/wiki/pysqlite
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote: > Michele Simionato wrote: >> On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> >>> In <[EMAIL PROTECTED]>, Bjoern Schliessmann > But what's it (__name__) good for? >>> >>> As objects don't know to which name they are bound, that's a good >>> way to give some information in stack traces or when doing >>> introspection. >> >> Also, the name is used by pickle to find the class of pickled >> instances. > > Mh. I suspect there's also more to it than I see now, but this > __name__ seems quite useless to me. What if I rebind the class' > name after definition? Then it's a way to still get the name of the definition via `__name__`. Together with the name of the module where the definition took place which is also available as attribute on the objects it is very useful to find out where to look for the source code. Just see the default `repr()` of class objects. > Or is it really just for some manual introspection? If it is, it seems a > bit of an overkill to me. > class Spam(object): > ... pass > ... Ham = Spam Spam = 0 test = Ham() test.__class__ > What would you expect this to look like if there weren't a __name__ attribute? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Importing binary modules
How can I, in python (linux, python version >= 2.4.2), dynamically set
the path and import a binary module that depends on libraries which
are not declared in LD_LIBRARY_PATH or any other automated linker path
when python starts?
This is a an example:
Suppose I have a new python module, called MyNewModule.py. It resides
in '/my/module/dir'. Internally, it loads libMyNewModule.so, which
implements most of the functionality for MyNewModule, so the user can
say:
import sys
sys.path.append('/my/module/dir')
import MyNewModule
And everything works fine.
The problem appears when libMyNewModule.so depends on another library,
say libfoo.so, which sits also in /my/module/dir. In that case, '/my/
module/dir', needs to be preset in the LD_LIBRARY_PATH *before* the
python interpreter is set.
In this case, the snippet of code above will not work as one would
expect. It will normally give an ImportError saying it cannot find
libfoo.so. That happens, apparently, because the dynamic linker cannot
rescan LD_LIBRARY_PATH after the python interpreter has started.
So is there any other way to circumvent this?
import sys
sys.path.append('/my/module/dir')
#black magic to get the linker to reload the LD_LIBRARY_PATH
import MyNewModule
So this succeeds?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple)
George Sakkis, I agree with the things you say. Sometimes you may have a sequence of uniform data with unknown len (so its index doesn't have semantic meaning). You may want to use it as dict key, so you probably use a tuple meant as just an immutable list. I don't know Ruby, but I think it allows such purposes with a freezing function. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
James Stroud wrote: > Yes, this would be a case of the expression (left side) ending with a > "\" as I mentioned above. Sorry for not tracking the context. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting perl-style find/replace regexp using python
John Pye wrote:
> Is there an easy and general way that I can split these perl-style
> find-and-replace expressions into something I can use with Python, eg
> re.sub('search','replace',str) ?
Another candidate:
>>> re.compile(r"(?:/((?:\\.|[^/])*))").findall(r"/abc\\/def\/ghi//jkl")
['abc', 'def\\/ghi', '', 'jkl']
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
On 28 Feb 2007 13:53:37 -0800, Luis M. González <[EMAIL PROTECTED]> wrote: > Hmmm... not really. > The code above is supposed to be a shorter way of writing this: > > class Person: > def __init__(self, name, birthday, children): > self.name = name > self.birthday = birthday > self.children = children > > So the purpose of this question is finding a way to emulate this with > a single line and minimal typing. I believe this is what you are looking for: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 olle = attrdict(name = "Olle", birthday = date(, 12, 1), children = 329) print olle.name, olle.birthday, olle.children It is not identical to the Ruby recipe, but is IMHO better. Being able to instantiate objects on the fly, without having to explicitly declare the class, is a big advantage. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a technic to avoid this bug
On 2/27/07, hg <[EMAIL PROTECTED]> wrote: Michele Simionato wrote: > pychecker Thanks all ... pydev extension does not however ... will have to install pychecker also. Just as a note: pydev extensions 1.2.8 supports that... (just released) Cheers, Fabio -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question(file-delete trailing comma)
thanks,,,
i tried another way and it works,,,
f.writelines(','.join([('\"%s\"' % some[field]) for field in field_order]))
thanks a lot,,,
Gabriel Genellina <[EMAIL PROTECTED]> wrote:
En Wed, 28 Feb 2007 08:34:29 -0300, kavitha thankaian
escribió:
> thanks,,
> now i have one more problem,,,
> the strings should be seperated in an order,,,
> some={1:'a', 2:7, 3:'c', 4:'d'}
> i need the output to be a,c,d,7
> before my code was:
> field_order = [1,3,4,2]
> for field in field_order:
> f.writelines('\"%s\",' % someprt[field] )
> do you have an idea now how should it look like???
Proceed in small steps. First get the data you need to write, then, format
them and build a single line, then write the new line onto the file.
some = {1:'a', 2:7, 3:'c', 4:'d'}
# i need the output to be a,c,d,7
field_order = [1,3,4,2]
row = []
for field in field_order:
row.append(some[field])
# row contains ['a', 'c', 'd', 7]
# convert to string
row = ['%s' % item for item in row]
### alternative: convert to string, with "" around each value
##row = ['"%s"' % item for item in row]
# make a single line, using "," as separator
line = ','.join(row)
# write to file
f.write('%s\n' % line)
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
-
Heres a new way to find what you're looking for - Yahoo! Answers --
http://mail.python.org/mailman/listinfo/python-list
Re: Importing binary modules
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 [EMAIL PROTECTED] wrote: cut .. > > The problem appears when libMyNewModule.so depends on another > library, say libfoo.so, which sits also in /my/module/dir. In that > case, '/my/ module/dir', needs to be preset in the LD_LIBRARY_PATH > *before* the python interpreter is set. > > In this case, the snippet of code above will not work as one would > expect. It will normally give an ImportError saying it cannot find > libfoo.so. That happens, apparently, because the dynamic linker > cannot rescan LD_LIBRARY_PATH after the python interpreter has > started. Since you create a new module, you should try to link your module with - -rpath-link option. You can specify a path searched by linker when finding shared object required. - -- Thinker Li - [EMAIL PROTECTED] [EMAIL PROTECTED] http://heaven.branda.to/~thinker/GinGin_CGI.py -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5rcp1LDUVnWfY8gRAmLcAKCobvo06x84L0pj66amTBspTJ9nUwCg5sA+ MP7tLF/i8zqoZHl5Fxw2YsQ= =BNQy -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
On Feb 28, 7:26 pm, "Luis M. González" <[EMAIL PROTECTED]> wrote:
> I've come across a code snippet inwww.rubyclr.comwhere they show how
> easy it is to declare a class compared to equivalent code in c#.
> I wonder if there is any way to emulate this in Python.
>
> The code is as follows:
>
> Person = struct.new( :name, :birthday, :children)
>
> I tried something like this, but it's nothing close to what I'd like:
>
> def klass(table, *args):
> cls = new.classobj(table, (), {})
> for i in args:
> setattr(cls, i, i)
> return cls
>
> But this above is not what I want.
> I guess I should find a way to include the constructor code inside
> this function, but I don't know if this is possible.
> Also, I wonder if there is a way to use the variable name in order to
> create a class with the same name (as in "Person"above).
>
> Well, if anyone has an idea, I'd like to know...
>
> Luis
Perhaps something like:
class Struct(object):
def __init__(self, **vals):
for slot, val in vals.iteritems():
setattr(self, slot, val)
def __repr__(self):
return "%s(%s)" % (type(self).__name__,
", ".join("%s=%s" % (slot, repr(getattr(self, slot))) for
slot in self.__slots__ if hasattr(self, slot)))
def new_struct(name, *slots):
return type(name, (Struct,), {'__slots__': slots})
Then you can do:
>>> Point = new_struct('Point', 'x', 'y')
>>> p=Point(x=1, y=2)
>>> p
Point(x=1, y=2)
>>> p.x
1
>>> p.y
2
>>> p.x=7
>>> p
Point(x=7, y=2)
>>> Person = new_struct('Person', 'name', 'tel', 'email')
>>> jack = Person(name='Jack')
>>> jack
Person(name='Jack')
>>> jack.tel='555-132'
>>> jack
Person(name='Jack', tel='555-132')
>>>
etc...
Of course that's if you want a c-like struct. Otherwise there's not
much point at all!
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
En Wed, 28 Feb 2007 18:54:53 -0300, kevinliu23 <[EMAIL PROTECTED]>
escribió:
> It's great because I don't even have to worry about the computer name.
> A question regarding the rootPath parameter...how would I be passing
> it? Would I be passing it as...
>
>tuple = win32api.GetDiskFreeSpace(r'C:')
> or just leave it blank and the function will automatically use the
> rootPath of where the .py file resides?
For GetDiskFreeSpace, the argument *must* end in \, so you should use
GetDiskFreeSpace('C:\\')
Using GetDiskFreeSpaceEx, it can be any directory. If you leave it, the
current directory (or current disk) is used - this may or may not be the
directory where the .py resides.
About the 2GB limit, it only applies to Win98 and earlier. Since the ...Ex
function works on 98 too, unless you need to support Win95, it's easier to
use that function.
And you can use UNC paths too, so it may even be used for querying
available space on remote machines, but I've never tried it that way.
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
Alex Martelli wrote:
> You should probaby prepare before the loop a mapping from char to number
> of 1 bits in that char:
>
> m = {}
> for c in range(256):
> m[c] = countones(c)
Wouldn't a list be more efficient?
m = [countones(c) for c in xrange(256)]
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
[EMAIL PROTECTED] wrote: > HI, > > I am new to Python and wanted to know how to check for the remaining > disk space on my Windows machine using Python? I was thinking of using > the command line "dir" and trying to extract the output from there. > But I'm not sure how to extract command line strings using Python > either. And, just for the record, there's even a few other techniques outlined here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66455 TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: installing "pysqlite"
On Mar 1, 11:46 am, "Paul Boddie" <[EMAIL PROTECTED]> wrote:
> On 1 Mar, 10:34, "Nader" <[EMAIL PROTECTED]> wrote:
>
>
>
> > I have expanded the LD_LIBRARY_PATH to my home lib (export
> > LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib).
> > I have built and installed the 'pysqlite-2.3.3' with the next
> > 'setup.cfg' :
>
> > [build_ext]
> > define=
> > include_dirs=/usr/people/emami/include
> > library_dirs=/usr/people/emami/lib
> > #libraries=/usr/people/emami/lib/libsqlite3.so (this line as a
> > comment)
>
> This looks alright. Be sure to verify that libsqlite3.so is in /usr/
> people/emami/lib, although I suppose you've done this, looking at your
> comment.
>
> > The resutl of this process was:
>
> > running install_lib
> > copying build/lib.linux-i686-2.4/pysqlite2/_sqlite.so -> /usr/people/
> > emami/lib/python2.4/site-packages/pysqlite2
> > running install_data
>
> > This message had given after installing. I have controll the '/usr/
> > people/emami/lib/python2.4/site-packages/pysqlite2' whether the
> > '_sqlite.so' has copied there. Yes it has. Okay!
>
> So pysqlite2 has installed properly at least.
>
> > I go to python and I give the next command:
>
> > >>> from pysqlite import test
>
> > and Unfortunately I get the next error message:
>
> [...]
>
> > ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/
> > _sqlite.so: undefined symbol: sqlite3_set_authorizer
>
> I'm running out of ideas here, but you could try doing this:
>
> ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so
>
> This should show a list of references to libraries, but if one of them
> is missing in some way then it means that it isn't found by the linker
> and it's not on the LD_LIBRARY_PATH. Another thought is that
> sqlite3_set_authorizer isn't found in the SQLite library - you can
> test this by doing the following:
>
> nm /usr/people/emami/lib/libsqlite3.so
>
> I get something like this in response:
>
> 000110b0 T sqlite3_set_authorizer
>
> If you don't get anything in response or if you see "U" instead of
> "T", then this might indicate an problem with the way SQLite has been
> configured.
>
> > Do you know what option I have to give to if I want to use the
> > 'easy_install" tool?
> > %easy_install pysqlite (with some optione with which it cab find the
> > installed 'libsqlite.so')
>
> I'm no easy_install expert, I'm afraid. You might want to talk to the
> pysqlite people directly if what I've suggested doesn't help you
> further:
>
> http://www.initd.org/tracker/pysqlite/wiki/pysqlite
>
> Paul
Hello
ldd returens the next result:
ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so
linux-gate.so.1 => (0xe000)
libpthread.so.0 => /lib/tls/libpthread.so.0 (0x4004)
libc.so.6 => /lib/tls/libc.so.6 (0x4005)
and the 'nm' gives this:
nm usr/people/emami/lib/libsqlite3.so | grep sqlite3_set_authorize
ce40 T sqlite3_set_authorizer
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x8000)
--
http://mail.python.org/mailman/listinfo/python-list
Re: quickly read a formated file?
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]:
> lialie:
>> The formated file may be very popularly, but the module
>> ConfigPaser doesn't handle it. Is there a way to process it
>> freely?
>
> First try, assuming the input file can be read whole. The code
> isn't much readable, it needs better variable names (name
> names?), comments, etc.
>
> data = """
> %HEADER
> title1 = "Untilted1"
> username = "User1"
>
> %DATA
> title2 = "Untilted2"
> username2 = "User2"
> """
>
> l1 = (p.strip().splitlines() for p in data.split("%") if
> p.strip()) result = {}
> for part in l1:
> pairs1 = (pair.split('=') for pair in part[1:])
> pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in
pairs1) result[part[0]] = dict(pairs2)
> print result
>
>
If there could be embedded perecent signs in the data, that will
produce some unexpected results, though. Here's another shot:
data = """
%HEADER
title1 = "Untilted1"
username = "User1"
%DATA
title2 = "The 7% Solution"
username2 = "User2"
"""
# Assumes there may be embedded percent signs in data
# and all data lines are of the form key = value
def parseData(data):
pd = {}
idata = iter(data)
for line in idata:
line = line.strip()
if line.startswith('%'):
tname = line[1:]
cd = pd[tname] = {}
line = idata.next().strip()
while line != '':
if line.find('=') > 0:
id,val = line.split('=',1)
cd[id.strip()] = val.strip().strip('"')
line = idata.next().strip()
return pd
print parseData(data.split('\n'))
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading csv files using SQL
>> You could maybe use SQLite to load the CSV file and process in an >> actual DBMS... Pablo> Ok, this is the solution I'm using actually (with PostGres). My Pablo> hope is to find a way to do the same thing without using a DBMS Pablo> but working directly with the files. If you want to work directly with the files why not just use Python's csv module? Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
On Mar 1, 10:33 am, Bjoern Schliessmann wrote: > Read RFC 2136 (Dynamic updates in the DNS) and see if your server > can be configured to do this. If not, you'll have to change the > zone files manually and reload the DNS config. It worked before with a perl script, but now I'm using django for all our web services so I want to implement this update function in Python as well. I don't know how to do this in Python, right now I'm trying it with twisted, but I don't what to do exactly. It would be nice if somebody has an example for doing this. Andi -- http://mail.python.org/mailman/listinfo/python-list
Re: Dialog with a process via subprocess.Popen blocks forever
En Wed, 28 Feb 2007 18:27:43 -0300, <[EMAIL PROTECTED]> escribió:
> Hi,
>
> I am trying to communicate with a subprocess via the subprocess
> module. Consider the following example:
>
from subprocess import Popen, PIPE
Popen("""python -c 'input("hey")'""", shell=True)
>
hey
>
> Here hey is immediately print to stdout of my interpreter, I did not
> type in the "hey". But I want to read from the output into a string,
> so I do
>
x = Popen("""python -c 'input("hey\n")'""", shell=True, stdout=PIPE,
bufsize=2**10)
x.stdout.read(1)
> # blocks forever
Blocks, or is the child process waiting for you to input something in
response?
> Is it possible to read to and write to the std streams of a
> subprocess? What am I doing wrong?
This works for me on Windows XP. Note that I'm using a tuple with
arguments, and raw_input instead of input (just to avoid a traceback on
stderr)
py> x=Popen(("python", "-c", "raw_input('hey')"), shell=True, stdout=PIPE)
py> x.stdout.read(1)
1234
'h'
py> x.stdout.read()
'ey'
I typed that 1234 (response to raw_input).
You may need to use python -u, or redirect stderr too, but what your real
problem is?
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: urlDecode()
En Wed, 28 Feb 2007 22:45:40 -0300, gert <[EMAIL PROTECTED]> escribió:
> import re
>
> def htc(m):
> return chr(int(m.group(1),16))
>
> def urldecode(url):
> rex=re.compile('%([0-9a-hA-H][0-9a-hA-H])',re.M)
> return rex.sub(htc,url)
>
> if __name__ == '__main__':
> print urldecode('adasasdasd%20asdasdasdas')
>
> Ok thats it enough googeling around i make one my self :)
You reinvented urllib.unquote
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python installation problem (sorry if this is a dup)
On 1 mar, 06:22, Ray Buck <[EMAIL PROTECTED]> wrote: > I've been trying to install Mailman, which requires a newer version > of the Python language compiler (p-code generator?) It's actually the whole thing : (byte-code) compiler, virtual machine, and stdlib. > than the one I > currently have on my linux webserver/gateway box. > > It's running a ClarkConnect 2.01 package based on Red Hat 7.2 linux. > > I downloaded the zipped tarball (Python-2.4.4.tgz), ran gunzip, then > un-tarred it in /usr/local. Then (logged in as root) from > /usr/local/Python-2.4.4 I ran the configure script which appeared to > run properly. At least there were no error messages that I > saw. Then I attempted to run "make install" and ended up with an > error "make *** Error 1". It was right at the "libinstall" section > of the make, so I did some googling and came up with the following command: > [EMAIL PROTECTED] Python-2.4.4]# make libinstall inclinstall > > After thrashing for about 5 minutes, I got basically the same message: > Compiling /usr/local/lib/python2.4/zipfile.py ... > make: *** [libinstall] Error 1 Nothing else between these two lines ? > I dunno if this is relevant, but I have Python 2.2.2 in the > /usr/Python-2.2.2 directory. Do I have to blow this away in order to > install the newer distro? I don't know your distrib, but it may depend on this specific python version. You may want to specify the --prefix before running configure, and use make altinstall instead of make install. > Or do I need to install the new one in/usr > instead of /usr/local? The old one is in /usr/local ? If so, it may not be part of your linux distro. FWIW, you should perhaps post the same question on your linux distro's mailing list. > Although I'm a retired programmer (mainframes), I'm still learning > this linux stuff. I guess that makes me a noob...I hope you'll take > that into consideration. We're all newbies one way or another !-) -- http://mail.python.org/mailman/listinfo/python-list
Pydev 1.2.8 Released
Hi All, Pydev and Pydev Extensions 1.2.8 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: - * Code-analysis: when a compare statement is found out of a test scope, that's reported as a warning * Mark Occurrences: new option to choose whether strings and comments should be highlighted * Simple Completions: some keywords were removed from the default list (the 2-letter ones because they're barely worth it and those related to 'try', as there's already an assistant that creates 'try' blocks) * Rename refactoring / Mark Occurrences: matches in multi-line strings are now correct Release Highlights in Pydev: -- * Refactoring: integration of the PEPTIC refactoring engine * Package Explorer: many fixes (special thanks for Don Taylor for the bug reports) * Debugger: a number of small optimizations * Code-completion: works in emacs mode * Code-completion: added the possibility of auto-completing for all letter chars and '_' (so, it starts completing once you start writing) * Code-completion: code-completion for epydoc inside strings * Code-completion: assigns after global statement considered added to the global namespace * Code-completion: now works when a class is declared in a nested scope * Code-completion: if multiple assigns are found to some variable, the completion will be a merge of them * Code-completion: functions are analyzed for their return values for code-completion purposes * Code-completion: working on multi-line imports * Code-completion: can discover instance variables not declared in the class (in the scope where the class was instanced) * Auto-edit: adds 'self', 'cls' or no parameter based on the @clasmethod, @staticmethod declaration on previous line * Auto-edit: doesn't add 'self' if a method is declared in a method inner scope * Fix: BRM Refactoring: wrong column was being passed to the BRM refactoring engine * Code-folding: added for comments and strings * Fix: sometimes the 'create docstring' assistant was not recognizing method definitons What is PyDev? --- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny -- Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing binary modules
On 1 mar, 12:21, Thinker <[EMAIL PROTECTED]> wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > [EMAIL PROTECTED] wrote: > > cut .. > > > The problem appears when libMyNewModule.so depends on another > > library, say libfoo.so, which sits also in /my/module/dir. In that > > case, '/my/ module/dir', needs to be preset in the LD_LIBRARY_PATH > > *before* the python interpreter is set. > > > In this case, the snippet of code above will not work as one would > > expect. It will normally give an ImportError saying it cannot find > > libfoo.so. That happens, apparently, because the dynamic linker > > cannot rescan LD_LIBRARY_PATH after the python interpreter has > > started. > > Since you create a new module, you should try to link your module with > - -rpath-link option. > You can specify a path searched by linker when finding shared object > required. > > - -- > Thinker Li - [EMAIL PROTECTED] [EMAIL > PROTECTED]://heaven.branda.to/~thinker/GinGin_CGI.py > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF5rcp1LDUVnWfY8gRAmLcAKCobvo06x84L0pj66amTBspTJ9nUwCg5sA+ > MP7tLF/i8zqoZHl5Fxw2YsQ= > =BNQy > -END PGP SIGNATURE- Well, unfortunately I don't have access to the binary like that. It is given me, I just wanted to use it the way it was compiled. What could be done then? -- http://mail.python.org/mailman/listinfo/python-list
pattern matching
can someone give me good links for pattern matching in images using python -- http://mail.python.org/mailman/listinfo/python-list
Questions about app design - OOP with python classes
Hi I am working on a python app, an outliner(a window with a TreeCtrl on the left to select a document, and a RichTextBox at the right to edit the current doc). I am familiarized with OOP concepts and terms but I lack practical experience , so any comment/tip/pointer to docs will be welcome. So far, I have created a separated class for each important element of my app - the main Frame (cFrmMain) - the TreeCtrl - the TextCtrl at the right - a cDocument class that contains the entire file with all docs and manages creation/deletion/saving to disk, etc - classes for the toolbar, the menubar, etc With this design, pretty much everything is encapsulated in it respective class. However, that means that the main program logic is in the Frame class. >From there, it instantiates the other classes and is responsable of the communication between them. For example, the user deletes a node on the Tree, this raises an event on cFrmMain (the main Frame class). In the event handler, cFrmMain notifies cDocument that a node (and the associated text) has been deleted so the master file is modified accordingly. The problem is, I have been implementing some funcionalities to test this design, I have less than a dozen operations implemented and cFrmMain has grown more than acceptable, starting to get confusing. This design feels "not quite right" to me, I've been considering allowing the different classes to know of the existence of each other and pass messages between them. I would lose encapsulation (I think), and I don't know if that would be (very) bad... and I'm not sure if with this design I will gain or lose clarity on the code. My questions ( at last :-) ) are: ¿Should I stick to my first design idea, eventually moving code from the main Frame to modules to gain clarity? ¿Is the second idea I present "correct" (I know it'll work, what I want to know is the clearest way of organize my code)? ¿Am I doing this wrong from the start and have to use another design? Thanks for reading this long post. Any comment, hint or pointer to docs will be greatly appreciated. Regards Adrián Garrido -- http://mail.python.org/mailman/listinfo/python-list
Python Tutorial
Hi, is Guido van Rossum's "Python Tutorial" in non-HTML formats (e.g. PDF or PS) avaiable for free? Regards, Timm -- http://mail.python.org/mailman/listinfo/python-list
django learn
HI folks! I want to learn to make web pages with django. I dont know nothing about HTML. How much of HTML I need to know to be able to learn django well? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: installing "pysqlite"
On 1 Mar, 12:46, "Nader" <[EMAIL PROTECTED]> wrote: > > ldd returens the next result: > ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so > linux-gate.so.1 => (0xe000) > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x4004) > libc.so.6 => /lib/tls/libc.so.6 (0x4005) I think you pasted the nm result in here, but you seem to be missing libsqlite3.so.0 (from what I see myself). From what I've just read about linux-gate.so, the linker can't seem to find the SQLite libraries. More on linux-gate.so here: http://www.trilithium.com/johan/2005/08/linux-gate/ > and the 'nm' gives this: > > nm usr/people/emami/lib/libsqlite3.so | grep sqlite3_set_authorize > ce40 T sqlite3_set_authorizer That looks alright. > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x8000) I guess this was the end of the ldd result. I'm out of ideas, unfortunately. I think you should experiment with LD_LIBRARY_PATH and run ldd again to see if you can get it to show libsqlite3.so.0. The pysqlite mailing list might be the best place to ask for help if that doesn't work. Sorry! Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
On Mar 1, 7:52 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> It seems like this would be easy but I'm drawing a blank.
>
> What I want to do is be able to open any file in binary mode, and read
> in one byte (8 bits) at a time and then count the number of 1 bits in
> that byte.
>
> I got as far as this but it is giving me strings and I'm not sure how
> to accurately get to the byte/bit level.
>
> f1=file('somefile','rb')
> while 1:
> abyte=f1.read(1)
import struct
buf = open('somefile','rb').read()
count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
(x&64>0)+(x&128>0)
byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
byteOnes[n] is number is number of ones in byte n.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Tutorial
On 3/1/07, Timm Florian Gloger <[EMAIL PROTECTED]> wrote: > is Guido van Rossum's "Python Tutorial" in non-HTML formats (e.g. PDF > or PS) avaiable for free? Yes. Download one of the PDF documentation zips from here: http://docs.python.org/download and extract the tut.pdf file. AFAIK it's not available as a seperate download. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: django learn
Hi Gigs_ schrieb: > I want to learn to make web pages with django. > I dont know nothing about HTML. > > How much of HTML I need to know to be able to learn django well? You need to get a profound knowledge of it, unless you have someone else who does the HTML/Templating for your project. In that case, you could probably get away with learning just the basics. -- René -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I Color a QTableView row in PyQt4
On Feb 28, 5:08 pm, David Boddie <[EMAIL PROTECTED]> wrote:
> On Wednesday 28 February 2007 18:55, Mel wrote:
>
>
>
> > I am currently porting an SQL centered Visual Basic application to run
> > on Linux, Python, and Qt4. Currently I am stumped on changing row
> > colors in the QTableView widget. My test code is based on code from
> > the PyQt4 examples and looks like this:
>
> > *** Start Code ***
>
> > import sys
> > from PyQt4 import QtCore, QtGui, QtSql
>
> > import connection
>
> > class CustomSqlModel(QtSql.QSqlQueryModel):
> > def data(self, index, role):
> > value = QtSql.QSqlQueryModel.data(self, index, role)
> > if value.isValid() and role == QtCore.Qt.DisplayRole:
> > if index.column() == 0:
> > return QtCore.QVariant(value.toString().prepend("#"))
> > elif index.column() == 2:
> > return QtCore.QVariant(value.toString().toUpper())
> > if role == QtCore.Qt.TextColorRole and index.column() == 1:
> > return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
> > return value
>
> [Snipping the rest of the code to keep this post short.]
>
> > Column 18 in the table shows a number from 1 to 3. I would like to
> > change the color of the row based on the value in column 18 but I have
> > not been able to find any resources that show me how. Can anyone lend
> > a hand?
>
> It's interesting to see that you subclassed QSqlQueryModel instead of
> using a custom delegate to display the data. It's usually recommended
> that you subclass QItemDelegate if you want to customize the way items
> are represented, but you can also customize the model if you want.
>
> What you can do is to check to see if the requested role is the
> Qt.BackgroundRole and, if so, query the base class for the data in
> column 18 in the same row. Then you can supply a different colour
> (as a brush, actually) depending on the value you obtained.
>
> if role == QtCore.Qt.BackgroundRole:
> # Get the data from column 18.
> column18_data = index.sibling(index.row(), 18).data()
> # The data is stored in a QVariant, so we unpack it.
> integer_value = column18_data.toInt()[0] # just the value
> # Look up the associated color in a dictionary which you
> # have already defined, and return it.
> color = self.colors.get(integer_value, self.default_color)
> return QtCore.QVariant(QtGui.QBrush(color))
>
> You might also find the following pages useful:
>
> http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html#ItemDataRol...http://doc.trolltech.com/4.2/model-view-model.html
>
> Good luck!
>
> David
Thanks David, that did work as I had hoped. I just need to work on
the colors a bit and make them more appealing.
Here is my final code that works for the custom Sql Model.
class CustomSqlModel(QtSql.QSqlQueryModel):
def data(self, index, role):
value = QtSql.QSqlQueryModel.data(self, index, role)
if value.isValid() and role == QtCore.Qt.DisplayRole:
if index.column() == 0:
return QtCore.QVariant(value.toString().prepend("#"))
elif index.column() == 2:
return QtCore.QVariant(value.toString().toUpper())
if role == QtCore.Qt.TextColorRole and index.column() == 1:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
if role == QtCore.Qt.BackgroundRole:
# Get the data from column 18.
column18_data = index.sibling(index.row(), 18).data()
# The data is stored in a QVariant, so we unpack it.
integer_value = column18_data.toInt()[0] # just the value
# Look up the associated color in a dictionary which you
# have already defined, and return it.
if integer_value == 1:
return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.red)))
if integer_value == 2:
return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.yellow)))
if integer_value == 3:
return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.green)))
return value
Mel
--
http://mail.python.org/mailman/listinfo/python-list
Re: quickly read a formated file?
rzed kirjoitti:
> [EMAIL PROTECTED] wrote in
> news:[EMAIL PROTECTED]:
>
>> lialie:
>>> The formated file may be very popularly, but the module
>>> ConfigPaser doesn't handle it. Is there a way to process it
>>> freely?
>> First try, assuming the input file can be read whole. The code
>> isn't much readable, it needs better variable names (name
>> names?), comments, etc.
>>
>> data = """
>> %HEADER
>> title1 = "Untilted1"
>> username = "User1"
>>
>> %DATA
>> title2 = "Untilted2"
>> username2 = "User2"
>> """
>>
>> l1 = (p.strip().splitlines() for p in data.split("%") if
>> p.strip()) result = {}
>> for part in l1:
>> pairs1 = (pair.split('=') for pair in part[1:])
>> pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in
> pairs1) result[part[0]] = dict(pairs2)
>> print result
>>
>>
>
> If there could be embedded perecent signs in the data, that will
> produce some unexpected results, though. Here's another shot:
>
>
>
>
>
The solution of bearophile only needs 2 small modifications to handle this:
#=
data = """
%HEADER
title1 = "Untilted1"
username = "User1 20 %"
%DATA
title2 = "Untilted2"
username2 = "User2 10 %"
"""
# Ensure data starts with a newline
data = '\n' + data
# Split using '\n%' instead of '%'
l1 = (p.strip().splitlines() for p in data.split("\n%") if p.strip())
result = {}
for part in l1:
pairs1 = (pair.split('=') for pair in part[1:])
pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in pairs1)
result[part[0]] = dict(pairs2)
print result
#=
Cheers,
Jussi
--
http://mail.python.org/mailman/listinfo/python-list
Re: installing "pysqlite"
On Mar 1, 2:40 pm, "Paul Boddie" <[EMAIL PROTECTED]> wrote: > On 1 Mar, 12:46, "Nader" <[EMAIL PROTECTED]> wrote: > > > > > ldd returens the next result: > > ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so > > linux-gate.so.1 => (0xe000) > > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x4004) > > libc.so.6 => /lib/tls/libc.so.6 (0x4005) > > I think you pasted the nm result in here, but you seem to be missing > libsqlite3.so.0 (from what I see myself). From what I've just read > about linux-gate.so, the linker can't seem to find the SQLite > libraries. More on linux-gate.so here: > > http://www.trilithium.com/johan/2005/08/linux-gate/ > > > and the 'nm' gives this: > > > nm usr/people/emami/lib/libsqlite3.so | grep sqlite3_set_authorize > > ce40 T sqlite3_set_authorizer > > That looks alright. > > > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x8000) > > I guess this was the end of the ldd result. > > I'm out of ideas, unfortunately. I think you should experiment with > LD_LIBRARY_PATH and run ldd again to see if you can get it to show > libsqlite3.so.0. The pysqlite mailing list might be the best place to > ask for help if that doesn't work. Sorry! > > Paul Hello Paul, I have returnd to the begining and have installed everthing again. Fortunately now I have the 'pysqlite2' module, because the test.test() workd after importing of 'pysqlite2' >>> from pysqlite2 import test >>> test.test >>> test.test() . -- Ran 173 tests in 0.585s OK >>> And the result of running of 'ldd' is : [EMAIL PROTECTED]:~> ldd lib/python2.4/site-packages/pysqlite2/_sqlite.so linux-gate.so.1 => (0xe000) libsqlite3.so.0 => /usr/people/emami/lib/libsqlite3.so.0 (0x4001) libpthread.so.0 => /lib/tls/libpthread.so.0 (0x40096000) libc.so.6 => /lib/tls/libc.so.6 (0x400a7000) Now I can ggo on with TurboGears! I have at home a Laptop and I have installed the 'gentoo' on it, and have no problem. But I would like to experiment with TurboGears at my work and It was a problem that I had no 'root' password. However I appreciate well your help in this case. I you like Indian or oriental music I can send you some! With regards, Nader -- http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I don't share your definition of "reasonable". But you should have > guessed by now My view may be shaped by a different experience. I have found dynamic attribute creation convenient when doing something "quick and dirty", but I have never wanted it as a design feature in a more serious project. Can you give me an example where design considerations make dynamic attribute creation particularly desirable? Thank you, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
[EMAIL PROTECTED] wrote: > It worked before with a perl script, but now I'm using django for > all our web services so I want to implement this update function > in Python as well. > I don't know how to do this in Python, right now I'm trying it > with twisted, but I don't what to do exactly. It would be nice if > somebody has an example for doing this. No one here knows how the server is configured or how the perl script did it before, so there's little chance someone will have an example that works for you. Regards, Björn -- BOFH excuse #280: Traceroute says that there is a routing problem in the backbone. It's not our problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
On 1 Mar 2007 04:14:23 -0800, [EMAIL PROTECTED] wrote: >On Mar 1, 10:33 am, Bjoern Schliessmann [EMAIL PROTECTED]> wrote: >> Read RFC 2136 (Dynamic updates in the DNS) and see if your server >> can be configured to do this. If not, you'll have to change the >> zone files manually and reload the DNS config. > >It worked before with a perl script, but now I'm using django for all >our web services so I want to implement this update function in Python >as well. >I don't know how to do this in Python, right now I'm trying it with >twisted, but I don't what to do exactly. It would be nice if somebody >has an example for doing this. > You need to provide more details. There is no one way to change the configuration of a DNS server. Different servers have different features and different interfaces. A start would be to specify which DNS server software needs to be reconfigured. You might also want to include an example of what kind of change you want to make. For example, do you want to add and delete records? Do you want to change the address of associated with an existing A record? Are all your changes in a single zone? etc. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
imagemagick
Hy did anyone manage to work with imahemagick through python. I've been googling like a crazy for some instalation instructions, but i cant find anything. please help. thnx -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract String From Enclosing Tuple
On 2007-02-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
import itertools
tuple(itertools.chain((t[0], t2[0].encode('ascii')), t[2:]))
> ('eco', 'Roads', 0.073969887301348305)
Steven,
As suggested in the previous article, I handled it where the values are
read from the list retrieved from the database. By adding an additional
index of [0] the format is correct.
Thank you all very much,
Rich
--
http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
"greg" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> There's a problem with that when you want to subclass:
Agreed. The following addresses that and, I think, some
of the other objections that have been raised.
Alan
class Lockable:
a = 0
def __init__(self, lock=False):
self.b = 1
self.lock = lock
def __setattr__(self, attr, val):
if not hasattr(self,attr) and hasattr(self,'lock') and self.lock:
raise ValueError("This object accepts no new attributes.")
self.__dict__[attr] = val
--
http://mail.python.org/mailman/listinfo/python-list
Re: django learn
On 1 mar, 14:36, Gigs_ <[EMAIL PROTECTED]> wrote: > HI folks! > > I want to learn to make web pages with django. > I dont know nothing about HTML. > > How much of HTML I need to know to be able to learn django well? > Anyway : 1/ you'll obviously need to have a good knowledge of html (plus css and possibly javascript too) to 'make web pages'. 2/ you'll also need to have a good knowledge of the HTTP protocol to write web apps 3/ and since Django is using Python, you'll need to know Python too !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
Thanks Tim, I only need to run the get hard drive space function on one drive for one machine so I'll stick to GetDiskFreeSpace. If I need to expand this feature to multiple harddrives/machines, I'll be sure to come back to this thread. :) Kevin On Mar 1, 4:17 am, Tim Golden <[EMAIL PROTECTED]> wrote: > kevinliu23 wrote: > > Just tried your solution Tim, worked like a charm. :) > > > It's great because I don't even have to worry about the computer name. > > A question regarding the rootPath parameter...how would I be passing > > it? Would I be passing it as... > > >tuple = win32api.GetDiskFreeSpace(r'C:') > > or just leave it blank and the function will automatically use the > > rootPath of where the .py file resides? > > > Both have returned the correct result. > > The simple answer is: I'm not sure. If you experiment and find > something which works, just use it! > > Something which SickMonkey made me return to your question. > Are you trying to find the disk space available on a > different machine (possibly on several different machines)? > If so, then WMI is definitely your answer. You can > run -- from your machine -- one piece of code which > will attach to several different machines to give > you the answer. (as per Sick Monkey's later post). > > If I've read too much into your question, well nothing's > ever wasted on the internet. Here's some sample code > which uses the wmi module from: > >http://timgolden.me.uk/python/wmi.html > > > machines = ['mycomp', 'othercomp'] > > for machine in machines: >print "Machine:", machine >c = wmi.WMI (machine) ># only consider local fixed disks >for disk in c.Win32_LogicalDisk (DriveType=3): > print disk.Name, disk.FreeSpace >print > > > > Yes, you could even write: > >for disk in wmi.WMI (machine).Win32_LogicaDisk (DriveType=3): > > but I'd find it a touch unwieldy. YMMV. > > HTH > TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: imagemagick
azrael wrote: > Hy > did anyone manage to work with imahemagick through python. I've been > googling like a crazy for some instalation instructions, but i cant > find anything. please help. There have been a few wrappers for ImageMagick over the last few years. There was once something called "PythonMagick", for example. However AFAIK, they are all currently defunct. There was a later version using Boost, but it apparently required a lot of system resources to compile for some reason, and I don't think I was able to. Apparently ImageMagick has gone through a lot of API changes and people get disgusted with supporting it (?). There is also, of course the Python Imaging Library (PIL) that competes with it pretty effectively for most use cases (of course ImageMagick has unparalleled image conversion support). If you really want ImageMagick, though, you might want to consider writing your own wrapper (perhaps using ctypes, now that it is included in the standard library). I have used 'popen' to run it as a separate process in the past. The 'subprocess' module would be the smart way to do that today, and that might be your fastest solution. Cheers, Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
On 28 Feb, 15:39, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > However I will observe that > > - entire languages are structured on the premise that dynamic > > attribute creation can be hazardous > > Yup, and you are free to use one of them. And as an additional benefit, they > will be more performant because you then can optimize the code further. I think that's something many people miss: it can be desirable to declare the range of attributes on instances "up front" for optimisation purposes (in various languages other than Python), but the advantages of not risking the occasional AttributeError shouldn't be too readily discarded either. I'm not sure where the different tools stand on this front, but second-guessing invalid accesses to attributes is a completely different level to just identifying dodgy accesses to globals or locals, along with dubious imports and "bad practice" programming styles consisting of one or more of those more detectable things. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing binary modules
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 > Well, unfortunately I don't have access to the binary like that. It > is given me, I just wanted to use it the way it was compiled. What > could be done then? You have better set LD_LIBRARY_PATH environment variable, or use ldconfig (plz, man ldconfig) to add the directory, where you shared object is in, to the search path of dynamic linker. - -- Thinker Li - [EMAIL PROTECTED] [EMAIL PROTECTED] http://heaven.branda.to/~thinker/GinGin_CGI.py -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5uWt1LDUVnWfY8gRAs52AKDLkGkNaPo2NgjdjFelNOx5KWG0KQCfT1RN l6WqAWcutwPtmJPleSdkrr4= =Ov/a -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Eric on XP for Newbie
[EMAIL PROTECTED] wrote: > I'm starting on the path of freeing myself from proprietory software > but I need to migrate, not make one huge jump. > > I'm looking at using Python and Eric for programming > > I've got Python up and running but can someone please point me to a > simple step by step guide for installing Eric? I've downloaded the tar > files, but what do I do with them? > > Thanks > Take a look at PyScripter also. I REALLY like it a lot on Windows: http://mmm-experts.com/Products.aspx?ProductId=4 -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
Bart Ogryczak kirjoitti:
> On Mar 1, 7:52 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> wrote:
>> It seems like this would be easy but I'm drawing a blank.
>>
>> What I want to do is be able to open any file in binary mode, and read
>> in one byte (8 bits) at a time and then count the number of 1 bits in
>> that byte.
>>
>> I got as far as this but it is giving me strings and I'm not sure how
>> to accurately get to the byte/bit level.
>>
>> f1=file('somefile','rb')
>> while 1:
>> abyte=f1.read(1)
>
> import struct
> buf = open('somefile','rb').read()
> count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
> (x&64>0)+(x&128>0)
> byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
>
> byteOnes[n] is number is number of ones in byte n.
>
>
>
I guess struct.unpack is not necessary, because:
byteOnes2 = map(count1, (ord(ch) for ch in buf))
seems to do the trick also.
Cheers,
Jussi
--
http://mail.python.org/mailman/listinfo/python-list
Re: starship.python.net is down
On Feb 26, 3:46 pm, Tom Bryan <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Any news onstarship.python.net? It still seems to bedown. > > Yes. Unfortunately, there may be a hardware problem. Stefan, the admin > who owns the hosted machine, is working with the host company to > determine what's going on. I think that they are still in the > "investigation" stage at the moment, so it's hard to give an estimate of > when the problem will be fixed. > > Thanks for your patience, > ---Tom I appreciate the update. Thanks, Matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
Hi,
I'm just a trainee working here and I don't really know how the old
Perl script worked.
But I can post the function, maybe you can recognize what is going on
there:
my $domain = "wiv-dom.com";
my $nameserver = "bldc01.wiv-dom.com";
sub makeDNSEntry {
my $res = new Net::DNS::Resolver;
my $query = $res->query("$domain", "NS");
if ($query) {
print "\nMaking entries into nameserver...\nSearching for
nameservers...\n\n" if $opt{d};
foreach my $rr ($query->answer) {
next unless $rr->type eq "NS";
print $rr->nsdname, "\n" if $opt{d};
}
}
else {
print "query for Nameserver for $domain failed: ", $res-
>errorstring, "\n";
}
my $update = new Net::DNS::Update("$domain");
$update->push("pre", yxrrset("$snmpHostName.$domain. A"));
$update->push("update", rr_del("$snmpHostName.$domain. A"));
$update->push("update", rr_add("$snmpHostName.$domain. 3600 A
$outbound"));
$res = new Net::DNS::Resolver;
$res->nameservers("$nameserver");
print "\nNameserver for $domain :" . $nameserver, "\n" if $opt{d};
my $reply = $res->send($update);
if (defined $reply) {
if ($reply->header->rcode eq "NOERROR") {
print "Update for $snmpHostName.$domain. OK\n" if $opt{d};
} else {
print "Update for $snmpHostName.$domain. ERROR : ". $reply-
>header->rcode. "\n" if $opt{d};
}
} else {
print "RESERROR : No reply: ". $res->errorstring. "\n";
}
}
What I want to do is change the A-Record of existing entries in the
DNS server.
I'm getting all the IPs from a django database and ask them via SNMP
what their outbound address is, then I want to change those settings
in our DNS server like in the perl script above.
Sorry for my bad explanation, but I never worked with DNS before...
Andi
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Tutorial
Thanks. And excuse this now so obviously foolish question. It seems that my so-called "brain" was not able to recognise "Downloads" as a valueable possibility to dive into when searching some non-HTML content. Sorry for wasting your time, and thanks even more for answering nevertheless. Regards, Timm (ashamed) On 3/1/07, Jerry Hill <[EMAIL PROTECTED]> wrote: > On 3/1/07, Timm Florian Gloger <[EMAIL PROTECTED]> wrote: > > is Guido van Rossum's "Python Tutorial" in non-HTML formats (e.g. PDF > > or PS) avaiable for free? > > Yes. Download one of the PDF documentation zips from here: > http://docs.python.org/download and extract the tut.pdf file. AFAIK > it's not available as a seperate download. > > -- > Jerry > -- http://mail.python.org/mailman/listinfo/python-list
Re: imagemagick
i need to use some common filters lik the edge, blur. it was pretty easy and fast to use python magick. but now as I want to use it with python, it is impossible. there is the PIL_usm, but also no installation instrucions. Is there a way to blur the image using the PIL by a specific radius. On Mar 1, 4:12 pm, Terry Hancock <[EMAIL PROTECTED]> wrote: > azrael wrote: > > Hy > > did anyone manage to work with imahemagick through python. I've been > > googling like a crazy for some instalation instructions, but i cant > > find anything. please help. > > There have been a few wrappers for ImageMagick over the last few years. > > There was once something called "PythonMagick", for example. However > AFAIK, they are all currently defunct. There was a later version using > Boost, but it apparently required a lot of system resources to compile > for some reason, and I don't think I was able to. > > Apparently ImageMagick has gone through a lot of API changes and people > get disgusted with supporting it (?). There is also, of course the > Python Imaging Library (PIL) that competes with it pretty effectively > for most use cases (of course ImageMagick has unparalleled image > conversion support). > > If you really want ImageMagick, though, you might want to consider > writing your own wrapper (perhaps using ctypes, now that it is included > in the standard library). > > I have used 'popen' to run it as a separate process in the past. The > 'subprocess' module would be the smart way to do that today, and that > might be your fastest solution. > > Cheers, > Terry > > -- > Terry Hancock ([EMAIL PROTECTED]) > Anansi Spaceworkshttp://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> Alex Martelli wrote:
> > You should probaby prepare before the loop a mapping from char to number
> > of 1 bits in that char:
> >
> > m = {}
> > for c in range(256):
> > m[c] = countones(c)
>
> Wouldn't a list be more efficient?
>
> m = [countones(c) for c in xrange(256)]
Yes, or an array.array -- actually I meant to use m[chr(c)] above (so
you could use the character you're reading directly to index m, rather
than calling ord(byte) a bazillion times for each byte you're reading),
but if you're using the numbers (as I did before) a list or array is
better.
Alex
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
On Mar 1, 8:53 am, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote:
> On Mar 1, 7:52 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> wrote:
>
> > It seems like this would be easy but I'm drawing a blank.
>
> > What I want to do is be able to open any file in binary mode, and read
> > in one byte (8 bits) at a time and then count the number of 1 bits in
> > that byte.
>
> > I got as far as this but it is giving me strings and I'm not sure how
> > to accurately get to the byte/bit level.
>
> > f1=file('somefile','rb')
> > while 1:
> > abyte=f1.read(1)
>
> import struct
> buf = open('somefile','rb').read()
> count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
> (x&64>0)+(x&128>0)
> byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
>
> byteOnes[n] is number is number of ones in byte n.
This solution looks nice, but how does it work? I'm guessing
struct.unpack will provide me with 8 bit bytes (will this work on any
system?)
How does count1 work exactly?
Thanks for the help.
-Greg
--
http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
Arnaud Delobelle wrote:
> On Feb 28, 7:26 pm, "Luis M. González" <[EMAIL PROTECTED]> wrote:
>> I've come across a code snippet inwww.rubyclr.comwhere they show how
>> easy it is to declare a class compared to equivalent code in c#.
>> I wonder if there is any way to emulate this in Python.
>>
>> The code is as follows:
>>
>> Person = struct.new( :name, :birthday, :children)
>>
>> I tried something like this, but it's nothing close to what I'd like:
>>
>> def klass(table, *args):
>> cls = new.classobj(table, (), {})
>> for i in args:
>> setattr(cls, i, i)
>> return cls
>>
>> But this above is not what I want.
>> I guess I should find a way to include the constructor code inside
>> this function, but I don't know if this is possible.
>> Also, I wonder if there is a way to use the variable name in order to
>> create a class with the same name (as in "Person"above).
>>
>> Well, if anyone has an idea, I'd like to know...
>>
>> Luis
>
> Perhaps something like:
>
> class Struct(object):
> def __init__(self, **vals):
> for slot, val in vals.iteritems():
> setattr(self, slot, val)
> def __repr__(self):
> return "%s(%s)" % (type(self).__name__,
> ", ".join("%s=%s" % (slot, repr(getattr(self, slot))) for
> slot in self.__slots__ if hasattr(self, slot)))
>
> def new_struct(name, *slots):
> return type(name, (Struct,), {'__slots__': slots})
>
>
> Then you can do:
>
Point = new_struct('Point', 'x', 'y')
p=Point(x=1, y=2)
p
> Point(x=1, y=2)
p.x
> 1
p.y
> 2
p.x=7
p
> Point(x=7, y=2)
Person = new_struct('Person', 'name', 'tel', 'email')
jack = Person(name='Jack')
jack
> Person(name='Jack')
jack.tel='555-132'
jack
> Person(name='Jack', tel='555-132')
This does pretty much the same thing as the recipe I posted:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
Note that your approach requires repetition of the 'Person' and quotes
around each attribute name, which the OP complained about. The recipe at
least gets rid of the repetition of 'Person'.
You might also want to check out Raymond Hettinger's NamedTuple recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261
STeVe
--
http://mail.python.org/mailman/listinfo/python-list
Re: pattern matching
azrael wrote: > can someone give me good links for pattern matching in images using > python There is a python-binding available for the OpenCV library, a collection of state-of-the-art CV algorithms. And it comes with a free manual Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: finding out the precision of floats
On Mar 1, 9:33 pm, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote: > On Feb 28, 10:29 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > > > > > On Mar 1, 4:19 am, "BartOgryczak" <[EMAIL PROTECTED]> wrote: > > > > On Feb 28, 3:53 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > > > > > On Feb 28, 10:38 pm, "BartOgryczak" <[EMAIL PROTECTED]> wrote: > > > > > > [1] eg. consider calculating interests rate, which often is defined as > > > > > math.pow(anualRate,days/365.0). > > > > > More importantly, the formula you give is dead wrong. The correct > > > > formula for converting an annual rate of interest to the rate of > > > > interest to be used for n days (on the basis of 365 days per year) is: > > > > > (1 + annual_rate) ** (n / 365.0) - 1.0 > > > > or > > > > math.pow(1 + annual_rate, n / 365.0) - 1.0 > > > > if you prefer. > > > > YPB? Anyone with half a brain knows, that you can either express rate > > > as 0.07 and do all those ridiculous conversions above, or express it > > > as 1.07 and apply it directly. > > > A conversion involving an exponentiation is necessary. "All those"?? I > > see only two. > > > Please re-read your original post, and note that there are *TWO* plus- > > or-minus 1.0 differences between your formula and mine. For an annual > > rate of 10%, yours would calculate the rate for 6 months (expressed as > > 182.5 days) as: > > math.pow(0.10, 0.5) = 0.316... i.e. 31.6% > > You're assuming that I'd store annual rate as 0.1, while actually it'd > stored as 1.1. > Which is logical and applicable directly. Storing 1.1 and using it in calculations may save you a few microseconds a day in your real-time apps. However the annual rate of interest is 10% aka 0.1; naming 1.1 as "anualRate" (sic) is utterly ludicrous. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
On Mar 2, 12:53 am, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote:
>
> import struct
> buf = open('somefile','rb').read()
> count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
> (x&64>0)+(x&128>0)
> byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
byteOnes = map(count1,struct.unpack('%dB'%len(buf),buf))
--
http://mail.python.org/mailman/listinfo/python-list
GIS Shape file upload FTP server
HI Group,
As I am very new in python field so this question might be very silly
but If I get any help that is highly appreciated.
Problem:
I have a python script which is working fine to upload files to the ftp
server but the problem is it is reducing the actual size after
transferring. I need to upload a GIS Shape file to the ftp server but
want to keep the same size and format. Any idea or help is highly
appreciated.
Thanks
Shakir
Staff Geographer
Sfwmd.gov
The code is as follows:
# Import system modules
import os
import sys
import win32com.client
import zipfile
import os.path
import ftplib
from ftplib import FTP
ftp=ftplib.FTP("ftp.sfwmd.gov","","")
ftp.login('sahmed','sa1lf1sh')
#ftp.cwd("/export/pub/sahmed")
ffile = open('c:\\test\\wuppnt.shp', 'r')
ftp.storbinary("stor wuppnt.shp", ffile)
ffile.close()
print "OK"
ftp.quit()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple)
On Mar 1, 5:02 am, [EMAIL PROTECTED] wrote: > I don't know Ruby, but I think it allows such purposes with a freezing > function. In ruby all objects can be frozen (freeze is a method on Object, from which all other objects derive), not just Arrays (Arrays == lists in python; ruby has no built-in container equiv. to tuple). But that's more of an implementation detail rather than anthing to do with the structure/semantics of a certain type of object (e.g., a String can be frozen, a Hash can be frozen, &c). Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading csv files using SQL
[EMAIL PROTECTED] ha scritto: > If you want to work directly with the files why not just use Python's csv > module? Now, with Java, I use the same class to read several databases and csv files (with SQL instructions). I'd like to find a library for using the same approach in Python. Thank you, Paolo -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Tkinter GUI building
Adam wrote:
> On Feb 28, 9:13 pm, Adonis Vargas <[EMAIL PROTECTED]>
> wrote:
>> Adam wrote:
>>
>>
>>
>>> I think my main questions are:
>>> 1. How can I get the Window to be sized the way I want it?
>>> 2. How can I get the Scrollbars to fill the side of the text box
>>> instead of being small? (like .pack(fill= tk.Y)
>>
>>
>>> I have only posted the code relevant to the GUI.
>>> TIA
>>> Adam
>> To size the window use Tk's geometry method
>>
>> self.top.geometry("%dx%d%+d%+d" % (800, 600, 0, 0)) # (width,
>> height, x, y)
>>
>> For the scrollbar to fill vertically, use the sticky grid option.
>>
>> self.scrlr1.grid(row=0, column=1, sticky=tk.N + tk.S)
>>
>> Hope this helps.
>>
>> Adonis
>
> Can't test now as its late in th UK and I'm going to bed. Looks good
> though.
> So remove the size from the frames etc and use the geometry method
> instead? Then use grid to "pack" them for want of a better word?
>
No, the geometry method is used to set the size of your main application
window. This is what I understood from your first question, and please
correct me if I am wrong. The grid method (or the pack method) are used
to layout the widgets.
In other words, after line 8 of the code you provided you would add this
line:
self.top.geometry("%dx%d%+d%+d" % (800, 600, 0, 0))
Hope this helps.
Adonis
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading csv files using SQL
Pablo was Paolo wrote: > [EMAIL PROTECTED] ha scritto: >> If you want to work directly with the files why not just use Python's csv >> module? > > Now, with Java, I use the same class to read several databases and csv > files (with SQL instructions). > I'd like to find a library for using the same approach in Python. I vaguely remember that you can get an ODBC driver for CSV. If I'm right, you could access it using one of the several Python ODBC DBAPI modules... just a thought. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Dialog with a process via subprocess.Popen blocks forever
Okay, here is what I want to do: I have a C Program that I have the source for and want to hook with python into that. What I want to do is: run the C program as a subprocess. The C programm gets its "commands" from its stdin and sends its state to stdout. Thus I have some kind of dialog over stdin. So, once I start the C Program from the shell, I immediately get its output in my terminal. If I start it from a subprocess in python and use python's sys.stdin/sys.stdout as the subprocess' stdout/stdin I also get it immediately. BUT If I use PIPE for both (so I can .write() on the stdin and .read() from the subprocess' stdout stream (better: file descriptor)) reading from the subprocess stdout blocks forever. If I write something onto the subprocess' stdin that causes it to somehow proceed, I can read from its stdout. Thus a useful dialogue is not possible. Regards, -Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
On Mar 1, 4:58 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> On Mar 1, 8:53 am, "Bart Ogryczak" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 1, 7:52 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> > wrote:
>
> > > It seems like this would be easy but I'm drawing a blank.
>
> > > What I want to do is be able to open any file in binary mode, and read
> > > in one byte (8 bits) at a time and then count the number of 1 bits in
> > > that byte.
>
> > > I got as far as this but it is giving me strings and I'm not sure how
> > > to accurately get to the byte/bit level.
>
> > > f1=file('somefile','rb')
> > > while 1:
> > > abyte=f1.read(1)
>
> > import struct
> > buf = open('somefile','rb').read()
> > count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
> > (x&64>0)+(x&128>0)
> > byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
>
> > byteOnes[n] is number is number of ones in byte n.
>
> This solution looks nice, but how does it work? I'm guessing
> struct.unpack will provide me with 8 bit bytes
unpack with 'B' format gives you int value equivalent to unsigned char
(1 byte).
> (will this work on any system?)
Any system with 8-bit bytes, which would mean any system made after
1965. I'm not aware of any Python implementation for UNIVAC, so I
wouldn't worry ;-)
> How does count1 work exactly?
1,2,4,8,16,32,64,128 in binary are
1,10,100,1000,1,10,100,1000
x&1 == 1 if x has first bit set to 1
x&2 == 2, so (x&2>0) == True if x has second bit set to 1
... and so on.
In the context of int, True is interpreted as 1, False as 0.
--
http://mail.python.org/mailman/listinfo/python-list
Python on a mac: how to build pythonw?
I'm trying to run the Python examples distributed with XCode and they all give me the same error: Traceback (most recent call last): File "checktext.py", line 35, in main() File "checktext.py", line 8, in main pathname = EasyDialogs.AskFileForOpen(message='File to check end-of-lines in:') File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 650, in AskFileForOpen _interact() File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 53, in _interact AE.AEInteractWithUser(5000) MacOS.Error: (-1713, 'no user interaction is allowed') Googling reveals that the answer is to use pythonw, but there is no such thing installed on my system: [EMAIL PROTECTED]:~]$ pythonw -bash: pythonw: command not found Apparently, pythonw didn't get built when I installed Python 2.5, and I can't find any instructions on how to build it. (The installation instructions don't seem to mention it.) If anyone could spare a clue I would be most grateful. Thank, rg -- http://mail.python.org/mailman/listinfo/python-list
Re: How to update DNS record
Andi Clemens wrote: > Hi, > > I want to update our DNS servers periodically with some IP addresses. But I > don't know how to do this. > I searched the Internet quite a while but I haven't found a good example how > to do this. > I want to change the A-Record for some IPs, this shouldn't be too hard. > I looked at dnspython and twisted, but I really don't have a clue how to do > this. > Has anyone done this before? > > Andi I'll looked at the perl function you mentioned and it seems to me (but I'm not a pearl coder) that it uses the dynamic update procedure, which is explained by the RFC 2136 (Bjoern mentioned that already). So I googled for "Python DNS dynamic update" and in the results the following site looked promising, http://www.dnspython.org/. hth -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: Dialog with a process via subprocess.Popen blocks forever
[EMAIL PROTECTED] wrote: > Okay, here is what I want to do: > > I have a C Program that I have the source for and want to hook with > python into that. What I want to do is: run the C program as a > subprocess. > The C programm gets its "commands" from its stdin and sends its state > to stdout. Thus I have some kind of dialog over stdin. > > So, once I start the C Program from the shell, I immediately get its > output in my terminal. If I start it from a subprocess in python and > use python's sys.stdin/sys.stdout as the subprocess' stdout/stdin I > also get it immediately. > > BUT If I use PIPE for both (so I can .write() on the stdin and .read() > from the subprocess' stdout stream (better: file descriptor)) reading > from the subprocess stdout blocks forever. If I write something onto > the subprocess' stdin that causes it to somehow proceed, I can read > from its stdout. > > Thus a useful dialogue is not possible. > > Regards, > -Justin > > > Have you considered using pexpect: http://pexpect.sourceforge.net/ ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on a mac: how to build pythonw?
Ron Garret wrote: > I'm trying to run the Python examples distributed with XCode and they > all give me the same error: > > Traceback (most recent call last): > File "checktext.py", line 35, in > main() > File "checktext.py", line 8, in main > pathname = EasyDialogs.AskFileForOpen(message='File to check > end-of-lines in:') > File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 650, in > AskFileForOpen > _interact() > File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 53, in > _interact > AE.AEInteractWithUser(5000) > MacOS.Error: (-1713, 'no user interaction is allowed') > > Googling reveals that the answer is to use pythonw, but there is no such > thing installed on my system: > > [EMAIL PROTECTED]:~]$ pythonw > -bash: pythonw: command not found > > Apparently, pythonw didn't get built when I installed Python 2.5, and I > can't find any instructions on how to build it. (The installation > instructions don't seem to mention it.) It looks like you built Python yourself. The default build does not allow you to communicate with the Apple GUI. You need a framework build. I highly recommend that you simply use the binary on www.python.org instead of building from source. If you do want to build from source, please read the file Mac/README for instructions. Note that in recent versions of Python, I believe that the pythonw executable is no longer necessary as a workaround. -- 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: Vector, matrix, normalize, rotate. What package?
On Feb 27, 4:49 pm, "Mattias Brändström" <[EMAIL PROTECTED]> wrote: > Hello! > > I'm trying to find what package I should use if I want to: > > 1. Create 3d vectors. > 2. Normalize those vectors. > 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in > radians. > 4. Perform matrix multiplication. > > It seems to me that perhaps numpy should be able to help me with this. > However, I can only figure out how to do 1 and 4 using numpy. Meybe > someone knows a way to use numpy for 2 and 3? If not, what Python > package helps me with geometry related tasks such as 2 and 3? Try Alex Holkner's euclid.py module: http://cheeseshop.python.org/pypi/euclid/0.01 Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon blogs?
On Feb 27, 6:36 pm, [EMAIL PROTECTED] wrote: > Was anybody blogging about PyCon (talks and/or sprints)? Got any pointers? Have you tried Planet Python? http://planet.python.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: class declaration shortcut
On Mar 1, 4:01 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Arnaud Delobelle wrote:
[...]
> This does pretty much the same thing as the recipe I posted:
Not at all. My new_struct create returns a new class which is similar
to a C struct (notice the __slots__). The recipe you refer to is
nothing more a class which can be initialised with some attributes. It
does not address the OP's question at all.
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
>
> Note that your approach requires repetition of the 'Person' and quotes
> around each attribute name, which the OP complained about. The recipe at
> least gets rid of the repetition of 'Person'.
The 'name' argument is not necessary. It is just here to give a user-
friendly name to the newly created class.
One could just as well write the new_struct function so that
>>> Person = new_struct('name', 'tel', ...)
Of course it would be impossible for the function written as above to
name the class in a user-meaningful way. The recipe you refer to does
not face this problem because it is not a method to quickly create a
new class, it is merely a class whose __init__ method allows you to
initialise some attribute at instance-creation time.
As for the quotes around the attribute names, well... Let's say that
if it was possible to do without, I don't think I would be using
python...
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
