Re: Free chapter about Python and databases (MySQL and SQLite)

2010-05-31 Thread christian schulze
On 28 Mai, 18:09, Peter Otten <[email protected]> wrote:
> christian schulze wrote:
> > On 28 Mai, 17:12, Sebastian Bassi  wrote:
> >> On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain 
> >> wrote:
> >> > Did you consider adding a part dealing with postgresql too?
> >> > (Especially interesting in the way you can write stored functions
> >> > in python there)
>
> >> That is a good idea for the next version/edition. But meanwhile I
> >> could write something in my blog atwww.py4bio.com
> >> Best,
> >> SB
>
> > Indeed a style like
> >> user="root"
> > is not that nice.
>
> > I had no look at the chapter but recommend you to read the PEP 8 -
> > Python style guides (code conventions for python).
>
> > Imo a book have to be kinda exemplary. And bad style sucks anyway ...
>
> > PS:
> >> user = 'root' or user = "root"
> > ... would be much more beautyful.
>
> My crystal ball says that the post you are not quoting is concerned about
> the security implications of accessing a database as the superuser rather
> than about spaces surrounding the assignment operator.
>
> My crystal ball then starts nitpicking and adds that in the sample chapter
> user="root" occurs within an argument list where its format is actually
> required by the PEP:
>
> """
> - Don't use spaces around the '=' sign when used to indicate a
>       keyword argument or a default parameter value.
>
>       Yes:
>
>           def complex(real, imag=0.0):
>               return magic(r=real, i=imag)
> """
>
> Cheers,
> Peter

Oh, I'm sorry. As I said, i didn't even had a look on the chapter. I
assumed it was a regular variable declaration. So just ignore what I
said :P

best regards
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xrange issue 7721

2010-05-31 Thread Martin v. Loewis

For the record, the issue you were looking at was a complaint that the
documentation is incorrect. This had been fixed by correcting the
documentation.


I think Mark's point is that the code snippet given isn't a full
replacement for xrange, since it doesn't support negative step sizes, nor
does it raise an exception on step=0.


Still, that issue is different from 7721. 7721 was about a 
completely-nonworking example in the documentation. This error has been 
fully

corrected. So this issue *is* fixed, reopining it would be
inappropriate.

There may be another issue with this example, which should be reported 
separately.



Since the docs are read by people with vastly different levels of
experience, skill and nous, I think it's a reasonable complaint to make.


That may well be. The proposed approach (reopen the issue) is what I 
consider unreasonable.


Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUI programs

2010-05-31 Thread eb303
On May 30, 5:21 pm, "Alf P. Steinbach"  wrote:
> PS: Tkinter on its own does not provide image resizing and does not on its own
> support common image formats like JPEG or PNG (it does support GIF).

"Native" PNG support in tcl/tk and hence Tkinter is planned for the
next release (8.6), which is in beta stage, so should be official
soon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter function outout to text widget

2010-05-31 Thread eb303
On May 29, 10:51 pm, Johan Lans  wrote:
> Hi
> I'm totally new on python and I'm doing an assignement where I'm doing
> a class that manipulates a text. The program is also supposed to have
> a GUI, for which I have used tkinter.
> So far I have entry widgets for file names and buttons, its all
> working like I want it to.
> What is missing is a way to output the changes to the text. I was
> thinking that a text-widget would be suitable. Is there a reasonably
> easy way to do this?
> I tried inserting a string to the textwidget and letting the class
> method change this string, but the inserted string isn't updated in
> the text-widget.
> Would be very happy for any hints.

You won't be able to do exactly what you want with the text widget.
There is a possibility to have to auto-updating in the GUI indeed, but
it can only be made via other widgets than the text.

Here is an example of what you can do:

from Tkinter import *
root = Tk()
var = StringVar()
var.set('aaa')
lbl = Label(root, textvariable=var)
lbl.pack(side=LEFT)
def next():
  var.set(''.join(chr(ord(c) + 1) for c in var.get()))
Button(root, text='Next', command=next).pack()
root.mainloop()


As you can see, I'm using a Label here. This should be enough if the
text you want to display is read-only. The Label will also adapt its
size if there are several lines in your text. The biggest limitation
is probably that you can't make it scrollable (not easily, at least…).

HTH
 - Eric -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter library reference

2010-05-31 Thread eb303
On May 29, 3:11 pm, Pradeep B  wrote:
> Do we have a standard reference library for Tkinter available?
>
> --
> Pradeep

Short answer: no, at least not a complete one for Tkinter itself.

However, there is a complete reference for tcl/tk here: 
http://www.tcl.tk/man/tcl8.5/
Once you're used to converting tcl/tk's commands and options into
Tkinter classes and methods, it is the best one around.

If you really need Python/Tkinter syntax, there are some good
documents here:
http://www.tkdocs.com/widgets/index.html
http://effbot.org/tkinterbook/
But these are not complete or rather old. However, you can use them as
a starting point before diving into the tcl/tk reference above.

HTH
 - Eric -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a single list

2010-05-31 Thread Astley Le Jasper
On May 29, 4:10 pm, superpollo  wrote:
> Astley Le Jasper ha scritto:
>
>
>
> > This is probably a really silly question but, given the example code
> > at the bottom, how would I get a single list?
>
> > What I currently get is:
>
> > ('id', 20, 'integer')
> > ('companyname', 50, 'text')
> > [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30,
> > 'text'), ('puma', 30, 'text')]
> > ('contact', 50, 'text')
> > ('email', 50, 'text')
>
> > what I would like is:
>
> > ('id', 20, 'integer')
> > ('companyname', 50, 'text')
> > ('focus', 30, 'text'),
> > ('fiesta', 30, 'text'),
> > ('mondeo', 30, 'text'),
> > ('puma', 30, 'text'),
> > ('contact', 50, 'text')
> > ('email', 50, 'text')
>
> > SAMPLE CODE>>>
> > def getproducts():
> >     temp_list=[]
> >     product_list=['focus','fiesta','mondeo','puma'] #usually this
> > would come from a db
> >     for p in product_list:
> >         temp_list.append((p,30,'text'))
> >     return temp_list
>
> > def createlist():
> >     column_title_list = (
> >                                     ("id",20,"integer"),
> >                                     ("companyname",50,"text"),
> >                                     getproducts(),
> >                                     ("contact",50,"text"),
> >                                     ("email",50,"text"),
> >                                 )
> >     return column_title_list
>
> > for item in createlist():
> >     print item
>
>  >>> def createlist():
> ...     column_title_list = [
> ...                                     ("id",20,"integer"),
> ...                                     ("companyname",50,"text")]
> ...     column_title_list += getproducts()
> ...     column_title_list += [
> ...                                     ("contact",50,"text"),
> ...                                     ("email",50,"text")]
> ...     return column_title_list
> ...
>  >>> for item in createlist():
> ...     print item
> ...
> ('id', 20, 'integer')
> ('companyname', 50, 'text')
> ('focus', 30, 'text')
> ('fiesta', 30, 'text')
> ('mondeo', 30, 'text')
> ('puma', 30, 'text')
> ('contact', 50, 'text')
> ('email', 50, 'text')
>  >>>
>
> bye

Cheers for that. I was thinking there might be something clever, but
as usual, simple is better.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py_single_input and the side-effects...

2010-05-31 Thread moerchendiser2k3
Hi Carl,

thanks for your help!!

> The only foolproof way to ensure that an object has been finalized is
> to do it manually (i.e., provide a finalize method to releases
> resources).

Yes, you are right, thats what I thought, too. So I wanted to
manually delete the reference, but browsing the sources, seems that
I cant really free it, because its wrapped somewhere
in Py_Finalize() and PyGC_Collect and Py_FreeModules. Any ideas?

Thanks a lot!

Cheers, moerchendiser2k3
-- 
http://mail.python.org/mailman/listinfo/python-list


reading help() - newbie question

2010-05-31 Thread Payal
Hi,
I am trying to learn Python (again) and have some basic doubts which I
hope someone in the list can address. (English is not my first language and I
have no CS background except I can write decent shell scripts)

When I type help(something) e.g. help(list), I see many methods like,
__methodname__(). Are these something special? How do I use them and why
put "__" around them?

One more simple query. Many times I see something like this,
|  D.iteritems() -> an iterator over the (key, value) items of D
What is this iterator they are talking about and how do I use these
methods because simly saying D.iteritems() does not work?

Thanks a lot in advance.
With warm regards,
-Payal
-- 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading help() - newbie question

2010-05-31 Thread Xavier Ho
On 31 May 2010 20:19, Payal  wrote:

> Hi,
> I am trying to learn Python (again) and have some basic doubts which I
> hope someone in the list can address. (English is not my first language and
> I
> have no CS background except I can write decent shell scripts)
>
>
Welcome (back) to the Python-List!


> When I type help(something) e.g. help(list), I see many methods like,
> __methodname__(). Are these something special?


They're very special. You can think of them as "Python internal functions",
and are called internally by other functions.


> How do I use them and why
> put "__" around them?
>

You call them as if they were any other function. 99% of the time though,
you don't need to call them, as there are better, cleaner ways.


>
> One more simple query. Many times I see something like this,
> |  D.iteritems() -> an iterator over the (key, value) items of D
> What is this iterator they are talking about <...>
>

See http://docs.python.org/library/stdtypes.html#iterator-types . Just a
peek, nothing big.


> and how do I use these
>

You can use iterators by ... iterating through the items! Like this:

>>> for i in [1, 3, 6, 10, 15]:
... print i
...
1
3
6
10
15

and, in your specific example:

>>> x = {1: 2, 3: 4}
>>> for key, value in x.iteritems():
... print key, "->", value
...
1 -> 2
3 -> 4


> methods because simly saying D.iteritems() does not 
> work?


It does work - it returns you an iterator you can use later:

>>> x_items = x.iteritems()
>>> for k, v in x_items:
... print k + v
...
3
7

Have fun with Python!

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading help() - newbie question

2010-05-31 Thread Colin J. Williams

On 31-May-10 06:19 AM, Payal wrote:

Hi,
I am trying to learn Python (again) and have some basic doubts which I
hope someone in the list can address. (English is not my first language and I
have no CS background except I can write decent shell scripts)

When I type help(something) e.g. help(list), I see many methods like,
__methodname__(). Are these something special? How do I use them and why
put "__" around them?

One more simple query. Many times I see something like this,
|  D.iteritems() ->  an iterator over the (key, value) items of D
What is this iterator they are talking about and how do I use these
methods because simly saying D.iteritems() does not work?

Thanks a lot in advance.
With warm regards,
-Payal


Here is an extract from the docs for Python 2.6.5.

I hope that this clarifies things.

Colin W.

2.3.2. Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special meanings. 
These classes are identified by the patterns of leading and trailing 
underscore characters:


_*
Not imported by from module import *. The special identifier _ is used 
in the interactive interpreter to store the result of the last 
evaluation; it is stored in the __builtin__ module. When not in 
interactive mode, _ has no special meaning and is not defined. See 
section The import statement.


Note
The name _ is often used in conjunction with internationalization; refer 
to the documentation for the gettext module for more information on this 
convention.


__*__
System-defined names. These names are defined by the interpreter and its 
implementation (including the standard library); applications should not 
expect to define additional names using this convention. The set of 
names of this class defined by Python may be extended in future 
versions. See section Special method names.

__*
Class-private names. Names in this category, when used within the 
context of a class definition, are re-written to use a mangled form to 
help avoid name clashes between “private” attributes of base and derived 
classes. See section Identifiers (Names).



--
http://mail.python.org/mailman/listinfo/python-list


Re: reading help() - newbie question

2010-05-31 Thread Chris Rebert
On Mon, May 31, 2010 at 3:41 AM, Xavier Ho  wrote:
> On 31 May 2010 20:19, Payal  wrote:

>> When I type help(something) e.g. help(list), I see many methods like,
>> __methodname__(). Are these something special?
>
> They're very special. You can think of them as "Python internal functions",
> and are called internally by other functions.
>
>>
>> How do I use them and why
>> put "__" around them?
>
> You call them as if they were any other function. 99% of the time though,
> you don't need to call them, as there are better, cleaner ways.


To be a bit more specific, double-underscore methods are called
internally by Python to implement various operators.
For example, `a + b` is usually equivalent to `a.__add__(b)`, and
`len(a)` calls `a.__len__()` internally.
For more info, see
http://docs.python.org/reference/datamodel.html#special-method-names

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py_single_input and the side-effects...

2010-05-31 Thread moerchendiser2k3
Hi Carl,

you are right, Python still holds the last
reference. I just set a dummy and thats it :)

Can you tell me where did you get the information from?

Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. Fedora and CentOS

2010-05-31 Thread Jason D

  The major Red Hat based Linux distros are still shipping with
Python 2.4.
As a result, almost all hosting providers are running obsolete
versions of
Python.

  The big problem seems to be that "cPanel" and
"yum" still use older versions
of Python, and those programs are more important to distro builders
than Python
itself.

  Is anybody trying to do something about this?

John Nagle


I am not sure of Fedora, 
CentOs 5.x ships with Python 2.5 . 
The version of python depends a lot on everything else that is packed into 
the system and uses python. e.g. GUI based tools, system scripts etc.


There is however never been an issue to locate different version of python 
in your system as you deem fit without problems. 
So I dont understand why your concern.


regards
Jason




posted via Grepler.com -- poster is authenticated.
--
http://mail.python.org/mailman/listinfo/python-list


how to generate a csr in python?

2010-05-31 Thread holmes86
hi,everyone

I want generate a Certificate signing request in python,but I don't
how to realize this function.I don't find any method after read the
python-openssl manual.Any help will appreciate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter library reference

2010-05-31 Thread Pradeep B
On Mon, May 31, 2010 at 2:46 PM, eb303  wrote:
> On May 29, 3:11 pm, Pradeep B  wrote:
>> Do we have a standard reference library for Tkinter available?
>>
>> --
>> Pradeep
>
> Short answer: no, at least not a complete one for Tkinter itself.
>
> However, there is a complete reference for tcl/tk here: 
> http://www.tcl.tk/man/tcl8.5/
> Once you're used to converting tcl/tk's commands and options into
> Tkinter classes and methods, it is the best one around.
>
> If you really need Python/Tkinter syntax, there are some good
> documents here:
> http://www.tkdocs.com/widgets/index.html
> http://effbot.org/tkinterbook/
> But these are not complete or rather old. However, you can use them as
> a starting point before diving into the tcl/tk reference above.
>
> HTH
>  - Eric -
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I think, generating it using the 'pydoc' seems to be much better.
-pradeep

-- 

|_|0|_|
|_|_|0|
|0|0|0|

http://picasaweb.google.com/pradeepbpin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Programming by John Grayson

2010-05-31 Thread Pradeep B
On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer  wrote:

> Tkinter doesn't wrap native printing API's. There are a few extensions that
> do it, but they are platform specific and not complete.
>
> The usual ways of printing are like this:
>
> 1. If you're outputting data from the text widget, write that to a temporary
> text file and print via lpr.
>
> 2. If you're outputting data from the canvas, write that to a temporary
> postscript file and print via lpr.
>
> This is on Unix/MacOS. Not sure what the equivalent API on Windows is.
>
> --Kevin
>
> --
> Kevin Walzer
> Code by Kevin
> http://www.codebykevin.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thanx Kevin.

Anybody can throw light on how to do the same in Windows ?

-pradeep


-- 

|_|0|_|
|_|_|0|
|0|0|0|

http://picasaweb.google.com/pradeepbpin
-- 
http://mail.python.org/mailman/listinfo/python-list


parsing question

2010-05-31 Thread Mag Gam
I have a file with bunch of nfsstat -c (on AIX) which has all the
hostnames, for example

r1svr==
Client rpc:
Connection oriented
calls badcalls  badxids  timeouts  newcreds badverfs  timers
0  0  0  0  0  0  0
nomem cantconn interrupts
0  0  0
Connectionless
calls badcalls retrans   badxids   timeouts newcreds  badverfs
6553   0  0  0  0  0  0
timersnomem cantsend
0  0  0


Client nfs:
calls  badcalls   clgets cltoomany
6541   0  0  0
Version 2: (6541 calls)
null   getattrsetattrroot   lookup readlink   read
0 0%   590 9% 414 6% 0 0%   2308 35%   0 0%   0 0%
wrcachewrite  create remove rename link   symlink
0 0%   2482 37%   276 4% 277 4% 147 2% 0 0%   0 0%
mkdir  rmdir  readdirstatfs
6 0%   6 0%   30 0%  5 0%
Version 3: (0 calls)
null   getattrsetattrlookup access readlink   read
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
write  create mkdir  symlinkmknod  remove rmdir
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
rename link   readdirreaddir+   fsstat fsinfo pathconf
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
commit
0 0%

r2svr==
Client rpc:
Connection oriented
calls badcalls  badxids  timeouts  newcreds badverfs  timers
0  0  0  0  0  0  0
nomem cantconn interrupts
0  0  0
Connectionless
calls badcalls retrans   badxids   timeouts newcreds  badverfs
6553   0  0  0  0  0  0
timersnomem cantsend
0  0  0


Client nfs:
calls  badcalls   clgets cltoomany
6541   0  0  0
Version 2: (6541 calls)
null   getattrsetattrroot   lookup readlink   read
0 0%   590 9% 414 6% 0 0%   2308 35%   0 0%   0 0%
wrcachewrite  create remove rename link   symlink
0 0%   2482 37%   276 4% 277 4% 147 2% 0 0%   0 0%
mkdir  rmdir  readdirstatfs
6 0%   6 0%   30 0%  5 0%
Version 3: (0 calls)
null   getattrsetattrlookup access readlink   read
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
write  create mkdir  symlinkmknod  remove rmdir
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
rename link   readdirreaddir+   fsstat fsinfo pathconf
0 0%   0 0%   0 0%   0 0%   0 0%   0 0%   0 0%
commit
0 0%


and so on...
(http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=/com.ibm.aix.prftungd/doc/prftungd/nfsstat_c_command.htm)


Is there a an easy way to parse this file according to each host?

So,
r1svr.Connectionless.calls=6553
r1svr.Connectionless.badcalls=0

and so on...


I am currently using awk which I am able to get what I need, but
curious if in python how people handle block data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. Fedora and CentOS

2010-05-31 Thread Philip Semanchuk


On May 31, 2010, at 7:13 AM, Jason D wrote:


 The major Red Hat based Linux distros are still shipping with
Python 2.4.
As a result, almost all hosting providers are running obsolete
versions of
Python.

 The big problem seems to be that "cPanel" and
"yum" still use older versions
of Python, and those programs are more important to distro builders
than Python
itself.

 Is anybody trying to do something about this?

John Nagle


I am not sure of Fedora, CentOs 5.x ships with Python 2.5 . The  
version of python depends a lot on everything else that is packed  
into the system and uses python. e.g. GUI based tools, system  
scripts etc.


Hi Jason,
CentOS is based on RHEL SRPMs. How could it ship a more advanced  
version of Python than RHEL?


I have CentOS 5.4 installed, and it only offers Python 2.4.3.

And distrowatch.org backs this up -- the latest Python available for  
Centos 5.x is 2.4:

http://distrowatch.com/table.php?distribution=centos

Did you perhaps install Python 2.5 on your own by compiling the source  
tarball?



bye
Philip
--
http://mail.python.org/mailman/listinfo/python-list


Question about permutations (itertools)

2010-05-31 Thread Vincent Davis
As a note I am doing this in py3.

I am looking for the most efficient (speed) way to produce an an
iterator to of permutations.
One of the problem I am having it that neither combinations nor
permutations does not exactly what I want directly.
For example If I want all possible ordered lists of 0,1 of length 3
(0,0,0)
(0,0,1)
(0,1,1)
(1,1,1)
(1,0,1)
(1,1,0)
(1,0,0)
I don't see a way to get this directly from the itertools. But maybe I
am missing something. I see ways to get a bigger list and then remove
duplicates.

>>> list(permutations([0,1], 3))
[]

>>> list(combinations_with_replacement('01',3))
('0', '0', '0')
('0', '0', '1')
('0', '1', '1')
('1', '1', '1')

Is it possible to get combinations_with_replacement to return numbers
rather than strings? (see above)

Thanks
Vincent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about permutations (itertools)

2010-05-31 Thread Xavier Ho
> >>> list(combinations_with_replacement('01',3))
> ('0', '0', '0')
> ('0', '0', '1')
> ('0', '1', '1')
> ('1', '1', '1')
>
> Is it possible to get combinations_with_replacement to return numbers
> rather than strings? (see above)
>

>>> list(combinations_with_replacement(range(0,2), 3))
[(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]


Hopefully that'll give you some ideas.

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about permutations (itertools)

2010-05-31 Thread Peter Otten
Vincent Davis wrote:

> As a note I am doing this in py3.
> 
> I am looking for the most efficient (speed) way to produce an an
> iterator to of permutations.
> One of the problem I am having it that neither combinations nor
> permutations does not exactly what I want directly.
> For example If I want all possible ordered lists of 0,1 of length 3
> (0,0,0)
> (0,0,1)
> (0,1,1)
> (1,1,1)
> (1,0,1)
> (1,1,0)
> (1,0,0)
> I don't see a way to get this directly from the itertools. But maybe I
> am missing something.

>>> for t in itertools.product([0, 1], repeat=3):
... print(t)
...
(0, 0, 0)
(0, 0, 1)
(0, 1, 0) # Seems you missed one
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

> I see ways to get a bigger list and then remove
> duplicates.
> 
 list(permutations([0,1], 3))
> []
> 
 list(combinations_with_replacement('01',3))
> ('0', '0', '0')
> ('0', '0', '1')
> ('0', '1', '1')
> ('1', '1', '1')
> 
> Is it possible to get combinations_with_replacement to return numbers
> rather than strings? (see above)

>>> for t in itertools.combinations_with_replacement([0, 1], 3):
... print(t)
...
(0, 0, 0)
(0, 0, 1)
(0, 1, 1)
(1, 1, 1)

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about permutations (itertools)

2010-05-31 Thread Vincent Davis
On Mon, May 31, 2010 at 8:17 AM, Xavier Ho  wrote:
>
>> >>> list(combinations_with_replacement('01',3))
>> ('0', '0', '0')
>> ('0', '0', '1')
>> ('0', '1', '1')
>> ('1', '1', '1')
>>
>> Is it possible to get combinations_with_replacement to return numbers
>> rather than strings? (see above)
>
 list(combinations_with_replacement(range(0,2), 3))
> [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]

Thanks, for some reason I didn't combinations_with_replacement took a
list as an argument.

> Hopefully that'll give you some ideas.
>
> Cheers,
> Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about permutations (itertools)

2010-05-31 Thread Mark Dickinson
On May 31, 3:04 pm, Vincent Davis  wrote:
> For example If I want all possible ordered lists of 0,1 of length 3
> (0,0,0)
> (0,0,1)
> (0,1,1)
> (1,1,1)
> (1,0,1)
> (1,1,0)
> (1,0,0)
> I don't see a way to get this directly from the itertools. But maybe I
> am missing something.

In this case, you're missing itertools.product:

>>> list(itertools.product([0, 1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1,
1, 0), (1, 1, 1)]

--
Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parsing question

2010-05-31 Thread Tim Chase

On 05/31/2010 08:42 AM, Mag Gam wrote:

I have a file with bunch of nfsstat -c (on AIX) which has all the
hostnames, for example

...

Is there a an easy way to parse this file according to each host?

So,
r1svr.Connectionless.calls=6553
r1svr.Connectionless.badcalls=0

and so on...


I am currently using awk which I am able to get what I need, but
curious if in python how people handle block data.


Since you already profess to having an awk solution, I felt it 
was okay to at least take a stab at my implementation (rather 
than doing your job for you :).  Without a complete spec for the 
output, it's a bit of guesswork, but I got something fairly close 
to what you want.  It uses nested dictionaries which mean the 
keys and values have to be referenced like


  servers["r1svr"]["connectionless"]["calls"]

and the values are strings (I'm not sure what you want in the 
case of the data that has both a value and percentage) not 
ints/floats/percentages/etc.


That said, this should get you fairly close to what you describe:

###

import re
header_finding_re = re.compile(r'\b\w{2,}')
version_re = re.compile(r'^Version (\d+):\s*\(.*\)$', re.I)
CLIENT_HEADER = 'Client '
CONNECTION_HEADER = 'Connection'
servers = {}
server = client = orig_client = subtype = None
source = file('data.txt')
for line in source:
  line = line.rstrip('\r\n')
  if not line.strip(): continue
  if line.startswith('='*5) and line.endswith('='*5):
server = line.strip('=')
client = orig_client = subtype = None
  elif line.startswith(CLIENT_HEADER):
orig_client = client = line[len(CLIENT_HEADER):-1]
subtype = 'all'
  elif line.startswith(CONNECTION_HEADER):
subtype = line.replace(' ', '').lower()
  else: # it's a version or header row
m = version_re.match(line)
if m:
  subtype = "v" + m.group(1)
else:
  if None in (server, client, subtype):
print "Missing data", repr((server, client, subtype))
continue
  dest = servers.setdefault(server, {}
).setdefault(client, {}
).setdefault(subtype, {})
  data = source.next()
  row = header_finding_re.finditer(line)
  prev = row.next()
  for header in row:
key = prev.group(0)
value = data[prev.start():header.start()].strip()
prev = header
dest[key] = value
  key = prev.group(0)
  value = data[prev.start():].strip()
  dest[key] = value

for server, clients in servers.items():
  for client, subtypes in clients.items():
for subtype, kv in subtypes.items():
  for key, value in kv.items():
print ".".join([server, client, subtype, key]),
print '=', value

###

Have fun,

-tkc




--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about permutations (itertools)

2010-05-31 Thread Ulrich Eckhardt
Vincent Davis wrote:
> I am looking for the most efficient (speed) way to produce an an
> iterator to of permutations.
> One of the problem I am having it that neither combinations nor
> permutations does not exactly what I want directly.
> For example If I want all possible ordered lists of 0,1 of length 3
> (0,0,0)
> (0,0,1)
> (0,1,1)
> (1,1,1)
> (1,0,1)
> (1,1,0)
> (1,0,0)
> I don't see a way to get this directly from the itertools. But maybe I
> am missing something. I see ways to get a bigger list and then remove
> duplicates.

You have three digits where each digit can have two values (binary digits,
a.k.a. bits), so the number of combinations is 2*2*2 = 8. Even if the
possible values where unevenly distributed, you could calculate the number
of combinations by multiplying. Then, there are two different approaches:
1. count with an integer and then dissect into digits
# Note: Using // for integer division in Python3!
digit0 = n % base0
digit1 = (n // base0) % base1
digit2 = (n // base0 // base1) % base2

2. simulate digits and detect overflow
Here you simply count up the "ones" and if they overflow, you reset them to
zero and count up the "tens".


What I don't really understand is what you mean with "ordered lists".

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

-- 
http://mail.python.org/mailman/listinfo/python-list


writing numbers in binary file

2010-05-31 Thread eskandari
Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an "array of strings", I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  "offsetfile.write(offset)"
"TypeError: argument 1 must be string or read-only buffer, not int"

I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?
Thanks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. Fedora and CentOS

2010-05-31 Thread John Nagle

Philip Semanchuk wrote:

Hi Jason,
CentOS is based on RHEL SRPMs. How could it ship a more advanced version 
of Python than RHEL?


I have CentOS 5.4 installed, and it only offers Python 2.4.3.

And distrowatch.org backs this up -- the latest Python available for 
Centos 5.x is 2.4:

http://distrowatch.com/table.php?distribution=centos


Shared hosting services mostly run CentOS or RHEL; there's a trend away
from running Fedora Core.  So if you want to do anything in Python that
is intended to run on shared hosting, you have to target Python 2.4.

I have a dedicated server for a big site; there I can build
and install later Python versions.   That's not the problem.
It's the little sites, ones not big enough to need their own dedicated
server or virtual machine, where it's difficult to run Python.

The current RHEL beta has Python 2.6, and that should be out this
year.  Hosting providers should start cutting over to it in 2011.
RHEL and CentOS have a 7-year life cycle.  So we can expect mainstream
availability of Python 2.6 from 2011 to 2018.

John Nagle
--
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread MRAB

eskandari wrote:

Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an "array of strings", I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  "offsetfile.write(offset)"
"TypeError: argument 1 must be string or read-only buffer, not int"

I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?


You can't write ints to a file, but you can write bytestrings ('str' in
Python 2, 'bytes' in Python 3).

Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.
--
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread Tim Chase

On 05/31/2010 10:56 AM, eskandari wrote:

But when I try to write offset (number) in binary file, it raise
exception below in line  "offsetfile.write(offset)"
"TypeError: argument 1 must be string or read-only buffer, not int"

I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?


Well, you have at least two options:

1) use the pack/unpack functions in the "struct" module to 
convert a number to a byte representation that you can then write 
to a file


2) write the number to the file as a string and then use C++ 
libraries to parse a number from a string.


In both cases, you have to consider what happens when the number 
is outside the bounds of your C++ data-type (you don't mention 
what you're using...an int, a long, or "long long"; signed vs. 
unsigned).  Additionally in the first case, you have to make sure 
that your memory-architecture (big-endian vs. little-endian) 
matches on both sides; or that you marshal the data through a 
pre-defined format (in libraries, commonly called "network" 
format).  For such reasons, I'd stick with method #2 unless you 
have a strong reason not to.


-tkc




--
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread eskandari
On May 31, 12:30 pm, MRAB  wrote:
> eskandari wrote:
> > Hi,
> > I am a newbie in python. I have an data.pickle file which is
> > serialized form of an "array of strings", I want to write their
> > offsets in another binary file, so an C++ program can read and analyse
> > them.
> > But when I try to write offset (number) in binary file, it raise
> > exception below in line  "offsetfile.write(offset)"
> > "TypeError: argument 1 must be string or read-only buffer, not int"
>
> > I search the internet, find that all suggest converting number to
> > string ---with str()---and then write string to file.
> > But I shouldn't do this. because the above mentioned C++ function,
> > read file with this assumption that there are numbers in file.
> > So I want to know, Is there any way to produce an binary file
> > containing numbers same as the way C++ does?
> > Can anybody help me?
>
> You can't write ints to a file, but you can write bytestrings ('str' in
> Python 2, 'bytes' in Python 3).
>
> Use the 'struct' module to convert the int to a bytestring, and remember
> to open the file as a binary file.

Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)
Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Do you want the safety of the computer ?

2010-05-31 Thread ekr3d
Do you want the safety of the computer?
 Take this gift
Advanced SystemCare Free 3.3.1

http://free-ekramy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Programming by John Grayson

2010-05-31 Thread Arndt Roger Schneider

Pradeep B schrieb:


On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer  wrote:

 


Tkinter doesn't wrap native printing API's. There are a few extensions that
do it, but they are platform specific and not complete.

The usual ways of printing are like this:

1. If you're outputting data from the text widget, write that to a temporary
text file and print via lpr.

2. If you're outputting data from the canvas, write that to a temporary
postscript file and print via lpr.

This is on Unix/MacOS. Not sure what the equivalent API on Windows is.

--Kevin

--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list

   




Thanx Kevin.

Anybody can throw light on how to do the same in Windows ?

-pradeep


 


The conventional --crude-- way is to take the bitmap of a
window and to stretchDIBBitBlt it onto the printer device in windows
and osx. Native printer dialogs do exist for both platforms ...

When you do not need a printer dialog:
Convert the Tk-GUI to SVG, then wrap it into a fo-xml wrapper
--fo accepts inline SVG-- and use fop for printing.
This approach works cross-platform, albeit you need a Java
intallation (fop is a Java application).

You can use http://jeszra.sourceforge.net to generate SVG for a complete 
Tk-GUI.

In addition. there is a python/tkinter SVG export project for the Tk canvas
--search the tkinter wiki.


-roger

--
http://mail.python.org/mailman/listinfo/python-list


passing external data to web forms

2010-05-31 Thread M L
(Note: If you just skim this and can tell me how to pass data from an
external program to a web form, that's all I need, and the rest is
just what I'd like to have.)

This is probably extremely simple when you know what you're doing. I
figured I'd see if I could find a kind soul who
could give me some code samples. Here's what I need to do:

1. Receive email via IMAP-IDLE
2. Parse the email to see if it contains certain text
3. Open a browser window with the following variables based on what
that text is
  a. URL
  b. username
  c. password

Specifically, I'm needing to login to a particular website, and which
username I use varies based on it being specified in the email. I
tried to do this with a combination of message filters in Thunderbird
and command line arguments in Firefox, but it can't quite do
everything I need.

My real problem is how to get the username and password passed to the
browser. Also, you should know that the server to which I'm connecting
is a site to which I subscribe, not my own, so I can't run anything
sever-side. Also, if possible, having this just fill whatever the
first html form field it comes to with the username and the second
with the password would be great, though not necessary if that's
significantly more complicated than it filling them based on a
specific name. I don't anticipate the site changing the names of those
fields, but I'd like to not have to redo the code if it does.

Finally, and again just a preference not a requirement, I feel that it
would be easier to have an external file that stores the usernames and
passwords that could be referenced to load them based on the email
contents rather than having the usernames and passwords hardcoded.
However, I'm only needing about half a dozen, so if it's significantly
simpler, I'll go with that.

Thanks for any help!

-ML
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread Terry Reedy

On 5/31/2010 12:43 PM, eskandari wrote:

On May 31, 12:30 pm, MRAB  wrote:

eskandari wrote:



Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.


Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)


Tim Chase pretty well answered this. If you are not familiar with the 
problem of 'endianess', see

http://en.wikipedia.org/wiki/Endianess

--
http://mail.python.org/mailman/listinfo/python-list


Windows and Linux Tips

2010-05-31 Thread Pavel Haque
Hi Friends,

For Windows and Linux Tips, Please Visit:

www.windowsandlinuxtips.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with relative imports and pep 366

2010-05-31 Thread Gabriele Lanaro
I've yet asked this question on SO, I'll copy the contents:

I have a "canonical file structure" like that (I'm giving sensible names
to ease the reading):

mainpack/

  __main__.py
  __init__.py 

  - helpers/
 __init__.py
 path.py

  - network/
 __init__.py
 clientlib.py
 server.py

  - gui/
 __init__.py
 mainwindow.py
 controllers.py

In this structure, for example modules contained in each package may
want to access the helpers utilities through relative imports in
something like:

# network/clientlib.py
from ..helpers.path import create_dir

The program is runned "as a script" using the __main__.py file in this
way:

python mainpack/

Trying to follow the PEP 366 I've put in __main__.py these lines:

___package___ = "mainpack"
from .network.clientlib import helloclient 

But when running:

$ python mainpack 
Traceback (most recent call last):
  File "/usr/lib/python2.6/runpy.py", line 122, in _run_module_as_main
"__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.6/runpy.py", line 34, in _run_code
exec code in run_globals
  File "path/mainpack/__main__.py", line 2, in 
from .network.clientlib import helloclient
SystemError: Parent module 'mainpack' not loaded, cannot perform relative import

What's wrong? What is the correct way to handle and effectively use
relative imports?

I've tried also to add the current directory to the PYTHONPATH, nothing
changes.

link:
http://stackoverflow.com/questions/2943847/nightmare-with-relative-imports-how-does-pep-366-work


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritable Slots Metaclass

2010-05-31 Thread Aahz
In article <5a3a5737-f1b7-4419-9bb3-088c244a4...@c13g2000vbr.googlegroups.com>,
Carl Banks   wrote:
>
>However, Aahz will be by shortly to tell you never to use slots.

Please note that there is an important distinction between "don't use
slots" and "never use slots" -- if you can locate any instances where I
wrote the latter, I will be surprised and issue a retraction.  Obviously,
slots are an important element of Python, but they should be used only
when other approaches have proven impractical.

To quote Guido:

__slots__ is a terrible hack with nasty, hard-to-fathom side
effects that should only be used by programmers at grandmaster and
wizard levels. Unfortunately it has gained an enormous undeserved
popularity amongst the novices and apprentices, who should know
better than to use this magic incantation casually.

See also

http://www.dalkescientific.com/writings/diary/archive/2006/03/19/class_instantiation_performance.html
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: where are the program that are written in python?

2010-05-31 Thread Sandy Ydnas


 http://en.wikipedia.org/wiki/List_of_Python_software

 

 

 

 

 

 

 

 

List of Python software

>From Wikipedia, the free encyclopedia

Jump to:navigation, search 





This article needs additional citations for verification.
Please help improve this article by adding reliable references. Unsourced 
material may be challenged and removed. (March 2008)
The Python programming language is actively used by many people, both in 
industry and academia for a wide variety of purposes.






Contents[hide]

1 Integrated development environments
2 Applications
3 Web Applications
4 Video games
5 Web frameworks
6 Graphics frameworks
7 GUI frameworks
8 Scientific packages
9 Mathematical libraries
10 Additional development packages
11 Embedded as a scripting language
12 Commercial uses
13 Python implementations
14 References
15 External links


[edit] Integrated development environments

Boa Constructor, a cross-platform IDE for Python development
EasyEclipse, an open source IDE for Python and other languages
Eric, an IDE for Python and Ruby
PIDA, open source IDE written in Python capable of embedding other text 
editors, such as Vim
Stani's Python Editor (SPE), a cross-platform IDE for Python development
Webware for Python, a suite of programming tools for constructing web-based 
applications in Python
Wing IDE, an IDE for Python
NetBeans, is written in Java and runs everywhere where a JVM is installed.
[edit] Applications

Anki, a spaced repetition flashcard program
Bazaar, a free distributed revision control system
BitTorrent, original client, along with several derivatives
BuildBot, a continuous integration system
Calibre, an open source e-book management tool
Chandler, a personal information manager including calendar, email, tasks and 
notes support that is currently under development
Decibel Audio Player, an open source audio player
Deluge, a BitTorrent client for GNOME
emesene, a MSN/WLM substitute
Exaile, an open source audio player
Gajim, an instant messaging client for the XMPP protocol
GRAMPS, an open source genealogy software
Gwibber, a microblogging client
Impressive (ex. KeyJnote), a presentation software
Juice, a popular podcast downloader
Mercurial a cross-platform, distributed source management tool
Miro, a cross-platform internet television application
Morpheus, file-sharing client/server software operated by the company StreamCast
MusicBrainz Picard, a cross-platform MusicBrainz tag editor
Nicotine, a PyGTK Soulseek client
OpenLP, lyrics projection software
OpenShot Video Editor
PiTiVi, a non-linear video editor
Portage, the heart of Gentoo Linux, an advanced package management system based 
on the BSD-style ports system
Quake Army Knife, an environment for developing 3D maps for games based on the 
Quake engine
Resolver One, a spreadsheet
Sage (sagemath) combines more than 20 main opensource math packages and 
provides easy to use web interface with the help of Python
SCons, a tool for building software
Ubuntu Software Center, a graphical package manager, installed by default in 
Ubuntu 9.10 and higher
Wammu, a mobile phone management utility
Wicd, a network manager for Linux
YUM, a package management utility for RPM-compatible Linux operating systems
[edit] Web Applications

ERP5, a powerful open source ERP / CRM used in Aerospace, Apparel, Banking and 
for e-government
GNU Mailman, one of the more popular packages for running email mailing lists
MoinMoin, a popular wiki engine
Planet, a feed aggregator
Plone, a user-friendly and powerful open source content management system
Projectplace, Europe’s Leading Online Service for Project Collaboration
Roundup, a bug tracking system
ViewVC, a web-based interface for browsing CVS and SVN repositories
Trac, web-based bug/issue tracking database, wiki, and version control front-end
MediaCore Video CMS is an open source media focused content management system.
[edit] Video games

Civilization IV uses Python for most of its tasks
Battlefield 2 uses Python for all of its addons and a lot of its functionality
Eve Online uses Stackless Python
Freedom Force
Frets on Fire uses Python and Pygame
The Temple of Elemental Evil, a computer role-playing game based on the classic 
Greyhawk Dungeons & Dragons campaign setting
Vampire: The Masquerade – Bloodlines, a computer role-playing game based on the 
World of Darkness campaign setting
Vega Strike, an open source space simulator
[edit] Web frameworks

CherryPy, an object-oriented web application server and framework
Django, an MVC (model, view, controller) web framework
Pylons, a lightweight web framework emphasizing flexibility and rapid 
development
Quixote, a framework for developing Web applications in Python
Topsite Templating System, another Python-powered web framework
TurboGears, a web framework combining CherryPy, SQLObject, and Kid
web2py, a full-stack enterprise web application framework, following the MVC 
design
Zope, an application server, commonly used to build content management systems
[edi

Spawning console and piping the stdout into it

2010-05-31 Thread Leonhard Weber
Hi,

I'm stuck at a puzzle for quite some time.

Situation: (Linux environment)
I have a script that is invoked from an application (running my script as
part of embedded python). I have no power over that application, only supply
the script it executes. Now for development reasons I want that script to
spawn a console and show me the output through there. Though there is the
ugly way of writing to file and tailing it, it would be great if someone
could come up with a cleaner version.

The approach I've been taking is trying to start a child with the subprocess
module and pipe the sys.stdoout into the stdin of the child... hu. No
success so far.


Thanks,
~lwk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if, continuation and indentation

2010-05-31 Thread Lie Ryan
On 05/31/10 05:10, Colin J. Williams wrote:
> On 30-May-10 01:50 AM, Nathan Rice wrote:
>> On 27-May-10 08:48 AM, Xavier Ho wrote:
>>  >  On 27 May 2010 22:22, HH> > > >>  wrote:
>>
>>  >
>>  >   if (width == 0 and
>>  >   height == 0 and
>>  >   color == 'red' and
>>  >   emphasis == 'strong' or
>>  >   highlight>  100):
>>  >   raise ValueError("sorry, you lose")
>>  >
>>  >
>>  >  I've gotta say - I've bumped into this problem before,
>> and I'm sure many
>>  >  other have - this is a valid question. It just hasn't
>> bothered me enough
>>  >  to ask...
>>  >
>>  >  Correct me if I'm wrong, but I think the following is
>> equivalent, and
>>  >  looks better. Although this won't fix all ugly cases in
>> that problem..
>>  >
>>  >  if (width, height, color, emphasis) == (0, 0, 'red',
>> 'strong') or
>>  >  highlight>  100:
>>  >raise ValueError("sorry, you lose")
>>  >
>>  >  Cheers,
>>  >  Xav
>>
>> but nobody commented.
>>
>> Colin W.
>>
>>
>> Colin:
>> Sure, you can do it that way.  IMO, though, the OP was  wrong,
>> and so
>> is the PEP.  Source code is meant to communicate.  So it must
>> transmit
>> the correct information to the computer; it also must inform your
>> coworkers.  That means that you have a responsibility to care
>> what
>> they think, though you privately have your opinions.  Another
>> reason
>> the PEP is faulty in this circumstance is that a misplaced
>> backslash,
>> or a missing one, is easily found and fixed.  A misplaced
>> parentheses,
>> or just one of a pair, will transform your source code into
>> something
>> which may compile and then give faulty results:  a disaster.
>> So keep it simple, and make it legible.
>> Yours,
>> John
>>
>>
>> IMHO complete garbage, if your editor doesn't show misplaced or
>> missing parenthesis by highlighting you're using the wrong editor :)
>>
>>
> 
> Perhaps the arrangement below shows the matching a little better than
> the Xav suggestion.  The main point is that, to me, the tuple shows the
> item by item matching better than a series of and clauses:
> 
> # tif.py
> 
> (width, height, color, emphasis)= 0, 0, 'red', 'strong'
> highlight= 99
> if (width, height, color, emphasis) ==  \
>(0, 0,  'red', 'strong') or highlight>  100:
>raise ValueError("sorry, you lose")

How about:

all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'),
(emphasis, 'strong'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing external data to web forms

2010-05-31 Thread Tim Chase

On 05/31/2010 12:16 PM, M L wrote:

Specifically, I'm needing to login to a particular website,
and which username I use varies based on it being specified
in the email.


Are you in control of this email generation (that is, can you 
generate an email with an HTML form within, or is this email 
coming from a 3rd-party)?


Creating an HTML-email with a form to submit the 
username/password isn't a flawless solution because many folks 
(self included) configure their mail-reader to only display 
plain-text and ignore HTML components.



My real problem is how to get the username and password
passed to the browser.


If you can't create an HTML form in the source email, then it 
depends on what the web-server is expecting -- a GET (bad for 
users, good for you) or a POST (good web practice, but a pain for 
you).  If the web login form is maldesigned and uses a GET 
submission, you can just parse the email body for the fields and 
generate a link of the form


  http://example.com/login?user=jsmith&pass=SeKrEt

However, if the website creates expects a POST to login (good 
design so credentials don't get saved in history, or get 
bookmarked accidentally), then you have to either


1) do some dark browser-specific hackery, perhaps with a bit of 
urllib magic to kludge the session into an active browser.  Not a 
particularly inviting solution to implement.


2) generate a temporary HTML file with the prepopulated form in 
it, point the browser at that page and either (2a) have the user 
click on the [submit] button, and/or (2b) have a little 
JavaScript that clicks the [submit] button (or calls 
form.submit() more likely) after the temp-page is loaded.  I'd do 
both in the event the user has JS turned off in their browser 
(again, that'd be me, thanks to NoScript).  This temporary HTML 
file could be scraped (via urllib) from the login url itself, or 
hard-coded if you expect it to be of the same format for each 
website.


My crack at it looks something like
##
from sys import exit, stderr
from tempfile import NamedTemporaryFile
import email
import imaplib
import os
import re
import time
import urllib
import webbrowser

url_re = re.compile(r'\burl:\s*(http://.*)')
user_re = re.compile(r'\buser(?:name)?:\s*(.*)')
pass_re = re.compile(r'\bpass(?:word)?:\s*(.*)')

class MissingField(Exception): pass

IMAP = imaplib.IMAP4_SSL

def get_email(host, username, password):
  # ...
  for message in messages_I_care_about:
  yield message

def fields(msg):
  url_m = url_re.search(msg)
  if not url_m: raise MissingField("No URL")
  user_m = user_re.search(msg)
  if not user_m: raise MissingField("No username")
  pass_m = pass_re.search(msg)
  if not pass_m: raise MissingField("No password")
  return [m.group(1).strip() for m in (url_m, user_m, pass_m)]

def create_temp_html(url, username, password):
  f = NamedTemporaryFile(mode='w', suffix='.html')
  # HTML hard-coded here, but could be
  # scraped from the site, parsed with BeautifulSoup
  # searched for the form/uname/pwd values
  # and more programatically generated
  # but this is the lazy version you get for free ;-)
  f.write("""
  
  Some Title
  
  
   Hang on...time to log in...
   



   
  
  
""" % (
url,
urllib.quote_plus(username),
urllib.quote_plus(password),
)
  )
  f.flush()
  return f

if __name__ == "__main__":
  HOST = 'mail.example.com'
  USER = '[email protected]'
  PASS = 'SecretEmailPassword'
  EXPECTED_SENDER = '[email protected]'

  for message in get_email(HOST, USER, PASS):
msg = email.message_from_string(message)
# if you don't want to limit the sender
# delete/comment the next 3 lines
if EXPECTED_SENDER not in msg['from'].lower():
  print "Unexpected sender...ignoring %r" % msg['subject']
  continue

for part in msg.walk():
  # you may not want to skip HTML portions or other
  # MIME-types like attachments, but whatever
  if part.get_content_type() != 'text/plain': continue

  try:
url, username, password = fields(msg.get_payload())
print url, username, password
  except MissingField, e:
print e
continue
  f = create_temp_html(url, username, password)
  stderr.write(
"Opening %r in %s\n" %
(f.name, webbrowser.get().basename.title()))
  webbrowser.open(f.name)
  time.sleep(30) # wait for the browser to load the file
  # otherwise this .close() will delete it
  # before the web-browser could open it
  f.close()
##

Adjust regexps to find your URL/uname/pwd as desired, create the 
get_email() iterator that finds all the messages in your inbox 
that match your criteria (such as "not already seen, has XYZ in 
the subject, etc")


I'm not 100% sure of my JavaScript in the form.onload but you can 
also tweak that if your JS is enabled and you want to tinker with 
it for auto-login.


-tkc




--
http://mail.python.org/mailman/listinfo/py

Re: xrange issue 7721

2010-05-31 Thread Mark Lawrence

On 31/05/2010 09:22, Martin v. Loewis wrote:

For the record, the issue you were looking at was a complaint that the
documentation is incorrect. This had been fixed by correcting the
documentation.


I think Mark's point is that the code snippet given isn't a full
replacement for xrange, since it doesn't support negative step sizes, nor
does it raise an exception on step=0.


Still, that issue is different from 7721. 7721 was about a
completely-nonworking example in the documentation. This error has been
fully
corrected. So this issue *is* fixed, reopining it would be
inappropriate.

There may be another issue with this example, which should be reported
separately.


Since the docs are read by people with vastly different levels of
experience, skill and nous, I think it's a reasonable complaint to make.


That may well be. The proposed approach (reopen the issue) is what I
consider unreasonable.

Regards,
Martin


Just forget it, if anyone falls foul of the garbage that has been put 
into the documentation, you can accept responsibility.


Disgusted and offended.

Mark Lawrence.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Vote to Add Python Package "pubsub" to the Python Standard Library

2010-05-31 Thread Aahz
In article <6b9d2898-4166-40b4-9016-dc55dee77...@q33g2000vbt.googlegroups.com>,
Tom   wrote:
>
>I vote for adding the Python package "pubsub" to the Python standard
>library.  It has recently been added to wxpython (replacing the old
>wx.lib.pubsub package), but it has application to non-gui programs as
>well.

You should create a ticket on bugs.python.org
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread Dave Angel

eskandari wrote:

On May 31, 12:30 pm, MRAB  wrote:
  

eskandari wrote:


Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an "array of strings", I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  "offsetfile.write(offset)"
"TypeError: argument 1 must be string or read-only buffer, not int"
  
I search the internet, find that all suggest converting number to

string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?
  

You can't write ints to a file, but you can write bytestrings ('str' in
Python 2, 'bytes' in Python 3).

Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.



Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)
Thanks in advance

  
You talk as if C++ has a single way to write a file, or read a file.  It 
has dozens of possibilities, as does Python.  In another message, you 
refer to four bytes per number, so it's possible you're talking about 
reading directly from the file into an int variable.  If you know that 
the C++ program is reading a file in mode 'b' directly to an unsigned 
int, and is compiled in 32 bits, and has the same endian-ness as the 
Python program, chances are the struct will work correctly, if you're 
running Python under the same conditions.


DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: if, continuation and indentation

2010-05-31 Thread Colin J. Williams

On 31-May-10 17:15 PM, Lie Ryan wrote:

On 05/31/10 05:10, Colin J. Williams wrote:

On 30-May-10 01:50 AM, Nathan Rice wrote:

 On 27-May-10 08:48 AM, Xavier Ho wrote:
  >   On 27 May 2010 22:22, HHmailto:[email protected]>>  >>   wrote:

  >
  >if (width == 0 and
  >height == 0 and
  >color == 'red' and
  >emphasis == 'strong' or
  >highlight>   100):
  >raise ValueError("sorry, you lose")
  >
  >
  >   I've gotta say - I've bumped into this problem before,
 and I'm sure many
  >   other have - this is a valid question. It just hasn't
 bothered me enough
  >   to ask...
  >
  >   Correct me if I'm wrong, but I think the following is
 equivalent, and
  >   looks better. Although this won't fix all ugly cases in
 that problem..
  >
  >   if (width, height, color, emphasis) == (0, 0, 'red',
 'strong') or
  >   highlight>   100:
  > raise ValueError("sorry, you lose")
  >
  >   Cheers,
  >   Xav

 but nobody commented.

 Colin W.


 Colin:
 Sure, you can do it that way.  IMO, though, the OP was  wrong,
 and so
 is the PEP.  Source code is meant to communicate.  So it must
 transmit
 the correct information to the computer; it also must inform your
 coworkers.  That means that you have a responsibility to care
what
 they think, though you privately have your opinions.  Another
reason
 the PEP is faulty in this circumstance is that a misplaced
 backslash,
 or a missing one, is easily found and fixed.  A misplaced
 parentheses,
 or just one of a pair, will transform your source code into
 something
 which may compile and then give faulty results:  a disaster.
 So keep it simple, and make it legible.
 Yours,
 John


 IMHO complete garbage, if your editor doesn't show misplaced or
 missing parenthesis by highlighting you're using the wrong editor :)




Perhaps the arrangement below shows the matching a little better than
the Xav suggestion.  The main point is that, to me, the tuple shows the
item by item matching better than a series of and clauses:

# tif.py

(width, height, color, emphasis)= 0, 0, 'red', 'strong'
highlight= 99
if (width, height, color, emphasis) ==  \
(0, 0,  'red', 'strong') or highlight>   100:
raise ValueError("sorry, you lose")


How about:

all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'),
(emphasis, 'strong'


You need to add "or highlight > 100"



--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Regexp, \b

2010-05-31 Thread John Machin
On May 30, 1:30 am, andrew cooke  wrote:

>
> That's what I thought it did...  Then I read the docs and confused
> "empty string" with "space"(!) and convinced myself otherwise.  I
> think I am going senile.

Not necessarily. Conflating concepts like "string containing
whitespace", "string containing space(s)", "empty aka 0-length
string", None, (ASCII) NUL, and (SQL) NULL appears to be an age-
independent problem :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUI programs

2010-05-31 Thread Gregory Ewing

[email protected] wrote:
Has anyone had any luck getting 
PyGUI working on Snow Leopard?  I can't seem to get the blobedit 
example to work.


I've received reports that it seems to be problematic on
Snow Leopard. Unfortunately I don't have access to a Snow
Leopard system at the moment to troubleshoot it.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


problem with Descriptors

2010-05-31 Thread Steven W. Orr

I just discovered descriptors but what I want to do isn't working right.

I hope this isn't too long. :-(

Here's what I have that works:

class C(object):
  def g(self):
print "dir(g):",dir(self.g)

def f(self, ss):
  print "ss = ", ss

cc = C()

cc.ff = f.__get__(C,cc)
cc.ff('Round 3')

And when I run it, it prints out:

ss =  Round 3


That's the part that works. I'm trying to use the above construct to implement a 
new kind of dict().


The idea is that I want to create a dict that knows about certain values that 
can have dependencies on other values. If you change a value that is a 
dependency of another value within the dict, then the target value will 
automatically recompute itself. In the example below, the value of the key 
"range" is dependent on the value of the key "stop".


When I run the code, the function recalc_range seems to be successfully saved as 
a bound method. (The save happens in AddDep) But then when I try to invoke the 
saved bound method, it yells at me that the arg to __getitem__ is of the wrong type.


Does anyone see what I did wrong?

class BalancedDict(dict):
  def __init__( self, initval={}, depDesc=None ):
dict.__init__(self)
self.target = []
self.deplist = []
self.recalc_f = []
self.addDep( depDesc )
if isinstance(initval, dict):
  dict.update(self, initval)

  def __setitem__(self, key, value): # setting a keyword
dict.__setitem__(self, key, value)
for ii, deps in enumerate(self.deplist):
  if key in deps:
print '__setitem__:recalc_f[%d]'%ii,self.recalc_f[ii]
print '__setitem__:targ:',self.target[ii]
print '__setitem__:deplist:',self.deplist[ii]
self.recalc_f[ii](self.target[ii],self.deplist[ii])

  def addDep(self, depDesc=None):
if not depDesc:
  return
for jj in depDesc:
  self.target.append(jj[0])
  self.deplist.append(jj[1])
  self.recalc_f.append(None)
  idx = len(self.recalc_f) - 1
  self.recalc_f[idx] = jj[2].__get__(BalancedDict, self)
  print 'addDep:self.recalc_f[%d]:'%idx, self.recalc_f[idx]


if __name__ == "__main__":
  import pprint

  def recalc_range(self, target, deplist):
print 'recalc_range:type(self):', type(self), "self:",self
print 'recalc_range:target:', target
print 'recalc_range:deplist:', deplist
stop = None
for ii in deplist:
  if ii == 'stop':
print "ii:",ii
print "self:", self, type(self)
stop = self.__getitem__(ii)
if ( isinstance( stop, int ) ):
  self.__setitem__( self[target], range( stop ) )

  pp = pprint.PrettyPrinter()
  dd = BalancedDict()
  print 'dd: Init'
  pp.pprint(dd)
  dd.addDep([['range', ['stop'], recalc_range]])
  dd['stop'] = 40
  print 'dd: After start stop and step'
  pp.pprint(dd)

C:\Users\Steve\Documents\PythonSamples>python -i vfunc3.py
dd: Init
{}
addDep:self.recalc_f[0]: '__main__.BalancedDict'>>

__setitem__:recalc_f[0] >
__setitem__:targ: range
__setitem__:deplist: ['stop']
recalc_range:type(self):  self: 
recalc_range:target: range
recalc_range:deplist: ['stop']
ii: stop
self:  
Traceback (most recent call last):
  File "vfunc3.py", line 55, in 
dd['stop'] = 40
  File "vfunc3.py", line 20, in __setitem__
self.recalc_f[ii](self.target[ii],self.deplist[ii])
  File "vfunc3.py", line 46, in recalc_range
stop = self.__getitem__(ii)
TypeError: descriptor '__getitem__' requires a 'dict' object but received a 
'str'
>>>




--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Error building on cygwin

2010-05-31 Thread huangqiang.zhou
 
Hi All:

When i install wxPython on cygwin in windows xp, i get this error and can't 
continue...

my enviroment:

$ cygcheck -c cygwin
Cygwin Package Information
Package  VersionStatus
cygwin   1.7.5-1Incomplete

wxPython-src-2.8.11.0 

Following the build instructions on www.wxpython.org, before the installing of 
wxPython i have installed additional packages as :
autoconf
automake
gcc-core
gcc-g++
gcc-mingw
gcc-mingw-core
gcc-mingw-g++
make
mingw-runtime
mingw-zlib
patch
w32api// i can't find this package when i am installing cygwin, so it was 
not be installed

Then: i put the sourcecode to /usr/sr/wxPython-src-2.8.11.0 

$cd  /usr/sr/wxPython-src-2.8.11.0
$CC="gcc -mno-cygwin -mwindows"  \ 
CXX="g++ -mno-cygwin -mwindows" \
LDFLAGS="-mno-cygwin -mwindows" \
./configure \
--with-msw \
--build=i686-pc-mingw32 \
--prefix=/opt/wx/2.8 \
--enable-unicode \
--enable-debug \
--enable-debug_gdb \
--enable-geometry \
--enable-display \
--enable-shared \
--enable-optimise \
--with-expat=builtin \
--with-regex=builtin \
--with-zlib=builtin

$make $* \ 
&& make -C contrib/src/gizmos $* \
&& make -C contrib/src/stc $*

and then :
./src/msw/utils.cpp: In function ‘const wxChar* wxGetHomeDir(wxString*)’:
./src/msw/utils.cpp:392: error: cannot convert ‘const char*’ to ‘const wxChar
*’ for argument ‘1’ to ‘wxChar* wxGetenv(const wxChar*)’
./src/msw/utils.cpp:408: warning: ‘int cygwin_conv_to_full_win32_path(const cha
r*, char*)’ is deprecated (declared at /usr/include/sys/cygwin.h:52)
./src/msw/utils.cpp:408: error: cannot convert ‘wxString’ to ‘const char*’ f
or argument ‘1’ to ‘int cygwin_conv_to_full_win32_path(const char*, char*)’
./src/msw/utils.cpp: In function ‘wxChar* wxGetUserHome(const wxString&)’:
./src/msw/utils.cpp:472: error: new declaration ‘wxChar* wxGetUserHome(const wx
String&)’
./include/wx/utils.h:528: error: ambiguates old declaration ‘const wxWCharBuffe
r wxGetUserHome(const wxString&)’
make: *** [basedll_msw_utils.o] Error 1

please help!

regards.

2010-06-01 



huangqiang.zhou 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Vote to Add Python Package "pubsub" to the Python Standard Library

2010-05-31 Thread Terry Reedy

On 5/31/2010 5:37 PM, Aahz wrote:

In article<6b9d2898-4166-40b4-9016-dc55dee77...@q33g2000vbt.googlegroups.com>,
Tom  wrote:


I vote for adding the Python package "pubsub" to the Python standard
library.  It has recently been added to wxpython (replacing the old
wx.lib.pubsub package), but it has application to non-gui programs as
well.


You should create a ticket on bugs.python.org


But only if the author of pubsub has agreed to contribute and continue 
maintaining the package in the strdlib.



--
http://mail.python.org/mailman/listinfo/python-list


What timeouts are required when reading SSL certificates with Python 2.6.4?

2010-05-31 Thread John Nagle

   I'm converting some M2Crypto code to use the new "ssl" module, and
I'm concerned about protection against hung machines at the remote end.
With M2Crypto, getting timeout to work properly required much tweaking.

   Here's the code.  I've tried it on about fifteen domains, some of which
support SSL and some which don't.  So far, it hasn't hung.  Is there any further
protection I need?


port = httplib.HTTPS_PORT   
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = ssl.wrap_socket(sk, ca_certs=certfile, cert_reqs=ssl.CERT_REQUIRED)
sock.connect((domain,port)) 
cert = sock.getpeercert()   
#   ... process certificate data
del sock
del sk


   Note that this doesn't send or receive any data on the SSL connection
once the handshake has been completed.  It's just reading the remote
certificate as part of a host identity check.  Then it drops the connection.

John Nagle
--
http://mail.python.org/mailman/listinfo/python-list


Re: What timeouts are required when reading SSL certificates with Python 2.6.4?

2010-05-31 Thread John Nagle

   Is bug #5103 relevant here?  The one about the 30-minute connection hang?

http://bugs.python.org/issue5103

John Nagle

John Nagle wrote:

   I'm converting some M2Crypto code to use the new "ssl" module, and
I'm concerned about protection against hung machines at the remote end.
With M2Crypto, getting timeout to work properly required much tweaking.

   Here's the code.  I've tried it on about fifteen domains, some of which
support SSL and some which don't.  So far, it hasn't hung.  Is there any 
further

protection I need?


port = httplib.HTTPS_PORT   
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock = ssl.wrap_socket(sk, ca_certs=certfile, cert_reqs=ssl.CERT_REQUIRED)
sock.connect((domain,port))   
cert = sock.getpeercert()#... process 
certificate data

del sock
del sk


   Note that this doesn't send or receive any data on the SSL connection
once the handshake has been completed.  It's just reading the remote
certificate as part of a host identity check.  Then it drops the 
connection.


John Nagle

--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the largest python/django powered website in the world?

2010-05-31 Thread est
On May 31, 8:14 am, Benjamin Kaplan  wrote:
> On Sun, May 30, 2010 at 4:27 PM, est  wrote:
>
> > > I'm afraid you'll need to define what you mean by "python powered".
>
> > Except database, presentation layer, major business logic is done by
> > python.
>
> > Except Google/youtube, what's next?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> http://www.reddit.comhttp://github.com/reddit/reddit
>
> I believe they recently said that they're at 7.5 million users and 270
> million page views per month. And the repo is 71% Python with most of
> the rest as Javascript.

http://www.alexa.com/siteinfo/douban.com

is written in quixote, python 2.6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with Descriptors

2010-05-31 Thread Peter Otten
Steven W. Orr wrote:

> I just discovered descriptors but what I want to do isn't working right.

> That's the part that works. I'm trying to use the above construct to
> implement a new kind of dict().
> 
> The idea is that I want to create a dict that knows about certain values
> that can have dependencies on other values. If you change a value that is
> a dependency of another value within the dict, then the target value will
> automatically recompute itself. In the example below, the value of the key
> "range" is dependent on the value of the key "stop".
> 
> When I run the code, the function recalc_range seems to be successfully
> saved as a bound method. (The save happens in AddDep) But then when I try
> to invoke the saved bound method, it yells at me that the arg to
> __getitem__ is of the wrong type.
> 
> Does anyone see what I did wrong?

>self.recalc_f[idx] = jj[2].__get__(BalancedDict, self)

The __get__() method's signature is

__get__(self, obj, type=None)

not the other way round. But the real problem is that you are not heeding 
Kernighan's warning that debugging is twice as hard as writing the code in 
the first place...

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading help() - newbie question

2010-05-31 Thread Payal
On Mon, May 31, 2010 at 08:41:54PM +1000, Xavier Ho wrote:
> Welcome (back) to the Python-List!

Thanks a lot to all who replied. Special thanks to Xavier Ho for sample
examples on iterators. That cleared the doubt.

With warm regards,
-Payal
-- 

-- 
http://mail.python.org/mailman/listinfo/python-list