Monday, April 19, 2010

comp.lang.python - 25 new messages in 14 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* why pylint wants only capitals identifiers? - 3 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/bbc2dfdac68c4ad4?hl=en
* PLEASE HELP--Button images refuse to show. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/cba7861d7c274dc7?hl=en
* Python 2.6 SSL module: Fails on key file error, with Errno 336265225,
without a key file. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/aeac0c7c11623fb3?hl=en
* "ssl" module doesn't validate that domain of certificate is correct - 5
messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/5fea0f97c0bb1030?hl=en
* Tkinter scrollbar background color doesn't work - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/41d73c96ef992669?hl=en
* UnicodeEncodeError during repr() - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/e208e63e399ec52a?hl=en
* scipy error undefined symbol: lsame_ - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/dc569c8bcf83a9a6?hl=en
* Operations on sparse matrices - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d6a3158ab1d4aba3?hl=en
* pyconfig.h - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d434c1898c3b4a56?hl=en
* problems creating and adding class instances to a list: - 3 messages, 2
authors
http://groups.google.com/group/comp.lang.python/t/5197b1343f9da781?hl=en
* ANN: Oktest 0.2.1 released - a new style testing library. - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/da2cbfcf8906d0da?hl=en
* unexpected output from difflib.SequenceMatcher - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d5262c18d15d9dd0?hl=en
* cross-platform coloured text in terminal - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/1c1cb43fa8d7a8ac?hl=en
* any modules having a function to partition a list by predicate provided? - 2
messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/f6e5a5e615820980?hl=en

==============================================================================
TOPIC: why pylint wants only capitals identifiers?
http://groups.google.com/group/comp.lang.python/t/bbc2dfdac68c4ad4?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Apr 19 2010 8:32 am
From: Giacomo Boffi


Jean-Michel Pichavant <jeanmichel@sequans.com> writes:

> Giacomo Boffi wrote:
>> i have this code
>>
>> def example(a):
>> return lambda b: a+b+1
>>
>> fun = example(10)
>> k_1 = fun(7)
>> ...
>>
>> and pylint tells me
>>
>> [...]
>> C: 4: Invalid name "fun" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
>> C: 5: Invalid name "k_1" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
>> [...]
>> g
>>
> Pylint default rules need some tuning

ok, but maybe it's not my specific problem (see below)

> However, given you example, you should not insert code execution at
> you module level, unless it's required only at the module import. I
> dont know what is your module

module? this was not well specified in my OP, but i'd rather speak of
a "script" instead of a module...

maybe should i use the

if __name__ == "__main__":
main()

idiom to keep happy my pylint? oh, let's do it... it should be easy
isn't it?

thanks,
g
--
I wish we'd come to our senses and see there is no truth
In those who promote the confusion for this ever changing mood.
(people get ready people get ready people get ready people get ready)


== 2 of 3 ==
Date: Mon, Apr 19 2010 8:48 am
From: Giacomo Boffi


Giacomo Boffi <giacomo.boffi@polimi.it> writes:

>> However, given you example, you should not insert code execution at
>> you module level, unless it's required only at the module import. I
>> dont know what is your module
>
> module? this was not well specified in my OP, but i'd rather speak of
> a "script" instead of a module...
>
> maybe should i use the
>
> if __name__ == "__main__":
> main()
>
> idiom to keep happy my pylint? oh, let's do it... it should be easy
> isn't it?

well, it's not so easy... pylint complains (correctly) about too many
local variables in main(), and about other things for different
adjustments i tried

i think i will put some variable at top level, CAPITALIZED, with the
intention of making evident that those values are the data of the
problem, as well as other quantities that are computed once from base
data, and then use these capitalized global variables inside my main
function --- tonight, at home

thank you again,
g
--
l'amore e' un sentimento a senso unico. a volte una via comincia dove
finisce un'altra e viceversa -- Caldana, in IFQ


== 3 of 3 ==
Date: Mon, Apr 19 2010 9:30 am
From: Jean-Michel Pichavant


Giacomo Boffi wrote:
> Jean-Michel Pichavant <jeanmichel@sequans.com> writes:
>
>
>> Giacomo Boffi wrote:
>>
>>> i have this code
>>>
>>> def example(a):
>>> return lambda b: a+b+1
>>>
>>> fun = example(10)
>>> k_1 = fun(7)
>>> ...
>>>
>>> and pylint tells me
>>>
>>> [...]
>>> C: 4: Invalid name "fun" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
>>> C: 5: Invalid name "k_1" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
>>> [...]
>>> g
>>>
>>>
>> Pylint default rules need some tuning
>>
>
> ok, but maybe it's not my specific problem (see below)
>
>
>> However, given you example, you should not insert code execution at
>> you module level, unless it's required only at the module import. I
>> dont know what is your module
>>
>
> module? this was not well specified in my OP, but i'd rather speak of
> a "script" instead of a module...
>

If by "script" you mean quick-and-dirty, then why bother running pylint
on it ? Sounds out of topic to me.

But if you still care about how correctly structured you script should
be, then it should be written almost like a module.

- do not write executable code at the module level
- if a function needs an information, it should ask for it as a
parameter, not using a de-scoped variable (aka global variables)
- if a function ask for too many parameters, then it may ask for few
objects instead (e.g. plot(x,y,z) => plot(point), poor example though, 3
paramaters are acceptable)
- it's better if your script can be imported in a separate file and
tested there

the list could contain many more items, and the more item you implement
the closer to a module you get.

JM

==============================================================================
TOPIC: PLEASE HELP--Button images refuse to show.
http://groups.google.com/group/comp.lang.python/t/cba7861d7c274dc7?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 8:58 am
From: Barrett


I have been fighting the same bug for weeks now with zero success: I
am trying to get images to come up on my buttons, but they are way too
small. Regardless of whether I used my old Python 2.5.1 or now 2.6.5,
the following code:

====================
'''Minesweeper.'''

from Tkinter import *
#from PIL import Image
import Tkinter as tk
#import PIL as pil
import random
#import glob, os

BEGINNER = 1
INTERMEDIATE = 2
EXPERT = 3

OFFSET = 2

BUTTON_SIZE = 2

class Board(Frame, object):
def __init__(self, master, difficulty, photo):
Frame.__init__(self, master)
if difficulty == BEGINNER:
self.x = 9
self.y = 9
self.mines = 10
elif difficulty == INTERMEDIATE:
self.x = 16
self.y = 16
self.mines = 40
elif difficulty == EXPERT:
self.x = 30
self.y = 16
self.mines = 99

self.grid()
self.photo = photo
self.create_widgets()

def create_widgets(self):
#Create the grid.
self.square = []
self.isAMine = []
self.selected = []
for i in range(self.x):
squareColumn = []
mineColumn = []
selectedColumn = []
for j in range(self.y):
squareColumn.append(Button(self, width = 3, height =
2,\
padx = -1, pady = -1))
squareColumn[j].grid(row = j + OFFSET, column = i)
mineColumn.append(False)
selectedColumn.append(False)
self.square.append(squareColumn)
self.isAMine.append(mineColumn)
self.selected.append(selectedColumn)

#Plant the mines.
print 'Dimensions:', self.x, self.y
for i in range(self.mines):
mineSquare = random.randrange(self.x * self.y)
mine_y = mineSquare / self.x
mine_x = mineSquare % self.x
self.isAMine[mine_x][mine_y] = True
self.square[mine_x][mine_y]['text'] = 'X' #temp line;
shows mines
#photo = tk.PhotoImage(file="1.gif")
#self.square[mine_x][mine_y]['image'] = photo #temp line;
shows mines


for i in range(self.y):
for j in range(self.x):
self.square[j][i]['command'] = lambda x=j, y=i:
self.hit(x, y)

#Runs when a button (square) is clicked.
def hit(self, x, y):
self.selected[x][y] = True
self.square[x][y].config(relief=SUNKEN)

#print x, y
if self.isAMine[x][y]:
print 'Mine found. Location:', x, y
else:
#Look at all eight neighbors and see if they are mines.
#x>0, etc. avoid looking off the edge of the map.
adjMines = 0
if (x > 0 and y > 0) and self.isAMine[x-1][y-1]: #NW
adjMines+=1
if y > 0 and self.isAMine[x][y-1]: #N
adjMines+=1
if (x < self.x-1 and y > 0) and self.isAMine[x+1][y-1]:
#NE
adjMines+=1
if x > 0 and self.isAMine[x-1][y]: #W
adjMines+=1
if x < self.x-1 and self.isAMine[x+1][y]: #E
adjMines+=1
if (x > 0 and y < self.y-1) and self.isAMine[x-1][y+1]:
#SW
adjMines+=1
if y < self.y-1 and self.isAMine[x][y+1]: #S
adjMines+=1
if (x < self.x-1 and y < self.y-1) and\
self.isAMine[x+1][y+1]: #SE
adjMines+=1

if adjMines != 0 and adjMines < 3:
self.square[x][y]['text'] = ''
self.square[x][y]['image'] = self.photo[adjMines]

elif adjMines>0: #temp line until the pix are ready
self.square[x][y]['text'] = adjMines

else: #adjMines == 0
#If none of the adjacent squares have mines, it is
safe to hit
#them all. Just like the official game, this game
does
#precisely that.
if (x > 0 and y > 0) and not self.selected[x-1][y-1]:
Board.hit(self, x-1, y-1) #NW
if y > 0 and not self.selected[x][y-1]: #N
Board.hit(self, x, y-1)
if (x < self.x-1 and y > 0) and not self.selected[x+1]
[y-1]: #NE
Board.hit(self, x+1, y-1)
if x > 0 and not self.selected[x-1][y]: #W
Board.hit(self, x-1, y)
if x < self.x-1 and not self.selected[x+1][y]: #E
Board.hit(self, x+1, y)
if (x > 0 and y < self.y-1) and not self.selected[x-1]
[y+1]: #SW
Board.hit(self, x-1, y+1)
if y < self.y-1 and not self.selected[x][y+1]: #S
Board.hit(self, x, y+1)
if (x < self.x-1 and y < self.y-1) and\
not self.selected[x+1][y+1]:
Board.hit(self, x+1, y+1) #SE

self.square[x][y]['command'] = ''

def main():
root = Tk()
root.title('Minesweeper')
root.geometry('450x300')
diff = int(raw_input( 'Select your difficulty level: '))
try:
photo = []
photo.append(None)
photo.append(tk.PhotoImage(file="1.gif"))
photo.append(tk.PhotoImage(file="2.gif"))
#photo[1] = photo[1].resize((15, 15))
except (IOError):
print 'File missing.'
else:
theBoard = Board(root, diff, photo)

root.mainloop()

main()
====================

Results in the following:

http://img194.yfrog.com/img194/237/weirdness3.jpg

("3" and above, I have not coded the pix for. I want to get the "1"
and "2" right before proceeding.)

I am completely at wit's end. I have tried using PIL, I have tried
resizing the buttons, and zooming the images, and saving the images
as .gif's and .jpeg's and .bmp's and you name it. Absolutely nothing
is working. I have a major assignment due TOMORROW and absolutely MUST
figure this out. Someone please show me what the heck I am doing wrong
and what I can do to fix it.

==============================================================================
TOPIC: Python 2.6 SSL module: Fails on key file error, with Errno 336265225,
without a key file.
http://groups.google.com/group/comp.lang.python/t/aeac0c7c11623fb3?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 9:35 am
From: John Nagle


Antoine Pitrou wrote:
> Perhaps you are using the wrong parameters and looking for ca_certs
> instead:

That's right. Thanks.

John Nagle

==============================================================================
TOPIC: "ssl" module doesn't validate that domain of certificate is correct
http://groups.google.com/group/comp.lang.python/t/5fea0f97c0bb1030?hl=en
==============================================================================

== 1 of 5 ==
Date: Mon, Apr 19 2010 9:51 am
From: John Nagle


I'm converting some code from M2Crypto to the new "ssl" module, and
I've found what looks like a security hole. The "ssl" module will
validate the certificate chain, but it doesn't check that the certificate
is valid for the domain.

Here's the basic code:

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,443))
cert = sock.getpeercert()
print('SSL cert for "%s":' % (domain,))
for fieldname in cert :
print(' %s = %s' % (fieldname, cert[fieldname]))

Note that I'm sending a CA cert list and am specifying CERT_REQUIRED,
so I should get a proper cert check.

Now let's try a host that presents the wrong SSL cert. Try, in
a browser,

https://www.countrysidecabinetry.com

You'll get an error. But the "ssl" module is happy with this cert:

SSL cert for "www.countrysidecabinetry.com":
notAfter = Dec 8 23:30:48 2010 GMT
subject = ((('serialNumber', u'E5gMXaDjnqfFPID2KNdLTVNEE6PjtqOr'),),
(('countryName', u'US'),), (('organizationName', u'customla
serengravings.com'),), (('organizationalUnitName', u'GT57631608'),),
(('organizationalUnitName', u'See www.rapidssl.com/resources/cp
s (c)09'),), (('organizationalUnitName', u'Domain Control Validated -
RapidSSL(R)'),), (('commonName', u'customlaserengravings.com')
,))

Note that the cert is for "customlaserengravings.com", but is being
presented by "countrysidecabinetry.com". Fail.

When I try this with M2Crypto, I get an SSL.Checker.WrongHost exception.
That's what should happen.

John Nagle


== 2 of 5 ==
Date: Mon, Apr 19 2010 9:50 am
From: exarkun@twistedmatrix.com


On 04:51 pm, nagle@animats.com wrote:
> I'm converting some code from M2Crypto to the new "ssl" module, and
>I've found what looks like a security hole. The "ssl" module will
>validate the certificate chain, but it doesn't check that the
>certificate
>is valid for the domain.
>
> Here's the basic code:
>
> 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,443))
> cert = sock.getpeercert()
> print('SSL cert for "%s":' % (domain,))
> for fieldname in cert :
> print(' %s = %s' % (fieldname, cert[fieldname]))
>
>Note that I'm sending a CA cert list and am specifying CERT_REQUIRED,
>so I should get a proper cert check.
>
>Now let's try a host that presents the wrong SSL cert. Try, in
>a browser,
>
> https://www.countrysidecabinetry.com
>
>You'll get an error. But the "ssl" module is happy with this cert:
>
>SSL cert for "www.countrysidecabinetry.com":
> notAfter = Dec 8 23:30:48 2010 GMT
> subject = ((('serialNumber',
>u'E5gMXaDjnqfFPID2KNdLTVNEE6PjtqOr'),), (('countryName', u'US'),),
>(('organizationName', u'customla
>serengravings.com'),), (('organizationalUnitName', u'GT57631608'),),
>(('organizationalUnitName', u'See www.rapidssl.com/resources/cp
>s (c)09'),), (('organizationalUnitName', u'Domain Control Validated -
>RapidSSL(R)'),), (('commonName', u'customlaserengravings.com')
>,))
>
>Note that the cert is for "customlaserengravings.com", but is being
>presented by "countrysidecabinetry.com". Fail.
>
>When I try this with M2Crypto, I get an SSL.Checker.WrongHost
>exception.
>That's what should happen.

It's a bit debatable. There probably should be a way to make this
happen, but it's far from clear that it's the only correct behavior.
And, as it turns out, there is a way to make it happen - call
getpeercert() and perform the check yourself. ;)

Here's some related discussion for an equivalent API in a different
module:

http://twistedmatrix.com/trac/ticket/4023

At the very least, the documentation for this should be very clear about
what is and is not being checked.

Jean-Paul


== 3 of 5 ==
Date: Mon, Apr 19 2010 10:49 am
From: John Nagle


exarkun@twistedmatrix.com wrote:
> On 04:51 pm, nagle@animats.com wrote:
>> I'm converting some code from M2Crypto to the new "ssl" module, and
>> I've found what looks like a security hole. The "ssl" module will
>> validate the certificate chain, but it doesn't check that the certificate
>> is valid for the domain.
>>
...
> It's a bit debatable. There probably should be a way to make this
> happen, but it's far from clear that it's the only correct behavior.
> And, as it turns out, there is a way to make it happen - call
> getpeercert() and perform the check yourself. ;)

"Checking it yourself" is non-trivial. The checking code has to
understand DNS wildcards and additional domains in cert extensions.
The SSL module doesn't seem to let you read all the cert extensions,
(in particular, you don't get "certificatePolicies", so you can't
tell if a cert is an "extended validation" cert) but it looks like
you do get the subjectAltName fields present in the extensions, like this:

subjectAltName = (('DNS', 'www.chapinfurniture.com'),
('DNS', 'chapinfurniture.com')))

So it's at least possible to check. Almost.

(DNS wildcards look like this: "*.example.com". It's also possible
to have "*.*.example.com". However, no DNS wildcard cert should cover
more than one second-level domain (huge security hole if you allow that)
and no extended validation cert should have a wildcard.)

There may also be issues with internationalized domain names.

It's very bad for the "ssl" module to both ignore this check and
not have that mentioned prominently in the documentation. This is
a security-critical function. Somewhere, there's a Python program that
can be exploited due to this bug.

Here's a comparison of what M2Crypto and the SSL module return, for
"verisign.com", which uses most cert features.

Trying domain "www.verisign.com"
Host: www.verisign.com Port: 443

Info from "M2Crypto: module:

Cipher = DHE-RSA-AES256-SHA
Subject info: [('CN', 'verisign.com'),
('OU', 'production Security Services '),
('O', 'VeriSign, Inc.'),
('streetAddress', '487 East Middlefield Road'),
('L', 'Mountain View'),
('ST', 'California'),
('postalCode', '94043'),
('C', 'US'),
('serialNumber', '2497886'),
('2.5.4.15', 'V1.0, Clause 5.(b)'),
('jurisdictionOfIncorporationStateOrProvinceName', 'Delaware'),
('jurisdictionOfIncorporationCountryName', 'US')]

Certificate has 10 extensions.
Extension #0: subjectAltName = DNS:verisign.com, DNS:www.verisign.com,
DNS:verisign.mobi, DNS:www.verisign.mobi, DNS:verisign.eu, DN
S:www.verisign.eu
Extension #1: basicConstraints = CA:FALSE
Extension #2: subjectKeyIdentifier =
0F:75:C5:F7:06:11:CE:74:FC:5F:DA:B6:2A:53:CE:39:1C:D6:7D:19
Extension #3: keyUsage = Digital Signature, Key Encipherment
Extension #4: crlDistributionPoints =
URI:http://EVIntl-crl.verisign.com/EVIntl2006.crl

Extension #5: certificatePolicies = Policy: 2.16.840.1.113733.1.7.23.6
CPS: https://www.verisign.com/rpa

Extension #6: extendedKeyUsage = TLS Web Server Authentication, TLS Web Client
Authentication, Netscape Server Gated Crypto
Extension #7: authorityKeyIdentifier =
keyid:4E:43:C8:1D:76:EF:37:53:7A:4F:F2:58:6F:94:F3:38:E2:D5:BD:DF

Extension #8: authorityInfoAccess = OCSP - URI:http://EVIntl-ocsp.verisign.com
CA Issuers - URI:http://EVIntl-aia.verisign.com/EVIntl2006.cer

Extension #9: UNDEF = None

Info from "ssl" module:

SSL cert for "www.verisign.com":
notAfter = Apr 2 23:59:59 2012 GMT
subject = ((('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
(('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
(('2.5.4.15', u'V1.0, Clause 5.(b)'),),
(('serialNumber', u'2497886'),),
(('countryName', u'US'),),
(('postalCode', u'94043'),),
(('stateOrProvinceName', u'California'),),
(('localityName', u'Mountain View'),),
(('streetAddress', u'487 East Middlefield Road'),),
(('organizationName', u'VeriSign, Inc.'),),
(('organizationalUnitName', u'production Security Services '),),
(('commonName', u'verisign.com'),))


John Nagle


== 4 of 5 ==
Date: Mon, Apr 19 2010 11:59 am
From: geremy condra


On Mon, Apr 19, 2010 at 1:49 PM, John Nagle <nagle@animats.com> wrote:
> exarkun@twistedmatrix.com wrote:
>>
>> On 04:51 pm, nagle@animats.com wrote:
>>>
>>>   I'm converting some code from M2Crypto to the new "ssl" module, and
>>> I've found what looks like a security hole.  The "ssl" module will
>>> validate the certificate chain, but it doesn't check that the certificate
>>> is valid for the domain.
>>>
> ...
>>
>> It's a bit debatable.  There probably should be a way to make this happen,
>> but it's far from clear that it's the only correct behavior. And, as it
>> turns out, there is a way to make it happen - call getpeercert() and perform
>> the check yourself. ;)
>
>   "Checking it yourself" is non-trivial. The checking code has to
> understand DNS wildcards and additional domains in cert extensions.
> The SSL module doesn't seem to let you read all the cert extensions,
> (in particular, you don't get "certificatePolicies", so you can't
> tell if a cert is an "extended validation" cert) but it looks like
> you do get the subjectAltName fields present in the extensions, like this:
>
>  subjectAltName = (('DNS', 'www.chapinfurniture.com'),
>        ('DNS', 'chapinfurniture.com')))
>
>   So it's at least possible to check.  Almost.
>
>   (DNS wildcards look like this: "*.example.com".  It's also possible
> to have "*.*.example.com".  However, no DNS wildcard cert should cover
> more than one second-level domain (huge security hole if you allow that)
> and no extended validation cert should have a wildcard.)
>
>   There may also be issues with internationalized domain names.
>
>   It's very bad for the "ssl" module to both ignore this check and
> not have that mentioned prominently in the documentation.  This is
> a security-critical function.  Somewhere, there's a Python program that
> can be exploited due to this bug.
>
>   Here's a comparison of what M2Crypto and the SSL module return, for
> "verisign.com", which uses most cert features.
>
> Trying domain "www.verisign.com"
> Host: www.verisign.com Port: 443
>
> Info from "M2Crypto: module:
>
> Cipher = DHE-RSA-AES256-SHA
>   Subject info: [('CN', 'verisign.com'),
>        ('OU', 'production Security Services  '),
>        ('O', 'VeriSign, Inc.'),
>        ('streetAddress', '487 East Middlefield Road'),
>        ('L', 'Mountain View'),
>        ('ST', 'California'),
>        ('postalCode', '94043'),
>        ('C', 'US'),
>        ('serialNumber', '2497886'),
>        ('2.5.4.15', 'V1.0, Clause 5.(b)'),
>        ('jurisdictionOfIncorporationStateOrProvinceName', 'Delaware'),
>        ('jurisdictionOfIncorporationCountryName', 'US')]
>
>  Certificate has 10 extensions.
> Extension #0: subjectAltName = DNS:verisign.com, DNS:www.verisign.com,
> DNS:verisign.mobi, DNS:www.verisign.mobi, DNS:verisign.eu, DN
> S:www.verisign.eu
> Extension #1: basicConstraints = CA:FALSE
> Extension #2: subjectKeyIdentifier =
> 0F:75:C5:F7:06:11:CE:74:FC:5F:DA:B6:2A:53:CE:39:1C:D6:7D:19
> Extension #3: keyUsage = Digital Signature, Key Encipherment
> Extension #4: crlDistributionPoints =
> URI:http://EVIntl-crl.verisign.com/EVIntl2006.crl
>
> Extension #5: certificatePolicies = Policy: 2.16.840.1.113733.1.7.23.6
>  CPS: https://www.verisign.com/rpa
>
> Extension #6: extendedKeyUsage = TLS Web Server Authentication, TLS Web
> Client Authentication, Netscape Server Gated Crypto
> Extension #7: authorityKeyIdentifier =
> keyid:4E:43:C8:1D:76:EF:37:53:7A:4F:F2:58:6F:94:F3:38:E2:D5:BD:DF
>
> Extension #8: authorityInfoAccess = OCSP -
> URI:http://EVIntl-ocsp.verisign.com
> CA Issuers - URI:http://EVIntl-aia.verisign.com/EVIntl2006.cer
>
> Extension #9: UNDEF = None
>
> Info from "ssl" module:
>
> SSL cert for "www.verisign.com":
>    notAfter = Apr  2 23:59:59 2012 GMT
>    subject = ((('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
>                (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
>                (('2.5.4.15', u'V1.0, Clause 5.(b)'),),
>                (('serialNumber', u'2497886'),),
>                (('countryName', u'US'),),
>                (('postalCode', u'94043'),),
>                (('stateOrProvinceName', u'California'),),
>                (('localityName', u'Mountain View'),),
>                (('streetAddress', u'487 East Middlefield Road'),),
>                (('organizationName', u'VeriSign, Inc.'),),
>                (('organizationalUnitName', u'production Security Services
>  '),),
>                (('commonName', u'verisign.com'),))
>
>
>                                John Nagle
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I talked about this in my pycon lighting talk- it's actually been
known for some time, and in fact there's some comments in
Zope core that mention this problem being a motivation for
rewriting SSL support from scratch. IIRC (I seem to recall
this, but I seem to have lost my test harness for it) it also
impacts higher level libraries like urllib, but I would verify that
before taking it as gospel. Several of the other members of
python-crypto would know more about it than I.

As a side note, it also impacts IronPython.

Geremy Condra


== 5 of 5 ==
Date: Mon, Apr 19 2010 1:37 pm
From: exarkun@twistedmatrix.com


On 05:49 pm, nagle@animats.com wrote:
>exarkun@twistedmatrix.com wrote:
>>On 04:51 pm, nagle@animats.com wrote:
>>> I'm converting some code from M2Crypto to the new "ssl" module,
>>>and
>>>I've found what looks like a security hole. The "ssl" module will
>>>validate the certificate chain, but it doesn't check that the
>>>certificate
>>>is valid for the domain.
>...
>>It's a bit debatable. There probably should be a way to make this
>>happen, but it's far from clear that it's the only correct behavior.
>>And, as it turns out, there is a way to make it happen - call
>>getpeercert() and perform the check yourself. ;)
>
> "Checking it yourself" is non-trivial.

Yes. It'd be nice to having something in the stdlib which accepted a
hostname and a certificate and told you if they line up or not.
>The SSL module doesn't seem to let you read all the cert extensions,

Yes. That sucks. It was argued about on python-dev and ultimately the
people writing the code didn't want to expose everything. I don't
remember the exact argument for that position.
> It's very bad for the "ssl" module to both ignore this check and
>not have that mentioned prominently in the documentation.

I agree. As I said, I think the behavior should be well documented.

Jean-Paul

==============================================================================
TOPIC: Tkinter scrollbar background color doesn't work
http://groups.google.com/group/comp.lang.python/t/41d73c96ef992669?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 9:35 am
From: KL


Tkinter scrollbar widget's "background" and "relief" options seem not
work.

The below is the codes I tried and the python/tk information:
===================

ActivePython 2.6.4.8 (ActiveState Software Inc.) based on
Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit
(Intel)] on
win32
>>> from Tkinter import *
>>> r=Tk()
>>> s=Scrollbar(r,bg="#000")
>>> s.grid()
>>> s['activebackground'] = "#000"
>>> s['relief'] = "sunken"
>>>
>>> TkVersion
8.5
>>> import sys
>>> sys.version
'2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit
(Intel)]'
>>>

==============================================================================
TOPIC: UnicodeEncodeError during repr()
http://groups.google.com/group/comp.lang.python/t/e208e63e399ec52a?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 10:08 am
From: gb345


In <hqguja$tt$1@online.de> "Martin v. Loewis" <martin@v.loewis.de> writes:

>> Do I need to do something especial to get repr to work strictly
>> with unicode?

>Yes, you need to switch to Python 3 :-)

>> Or should __repr__ *always* return bytes rather than unicode?

>In Python 2.x: yes.

>> What about __str__ ?

>Likewise.

>> If both of these are supposed to return bytes,
>> then what method should I use to define the unicode representation
>> for instances of a class?

>__unicode__.

Thanks!


==============================================================================
TOPIC: scipy error undefined symbol: lsame_
http://groups.google.com/group/comp.lang.python/t/dc569c8bcf83a9a6?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Apr 19 2010 10:15 am
From: gerardob

I installed scipy (and all the required libraries) and the following error
appears when i tried run a simple example which uses the optimize package of
scipy. I tried also numpy alone and it works ( at least for printing
numpy.array([10,20,10]))

error:

Traceback (most recent call last):
File "main_test.py", line 2, in <module>
from scipy import optimize
File
"/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/__init__.py",
line 11, in <module>
from lbfgsb import fmin_l_bfgs_b
File
"/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/lbfgsb.py",
line 30, in <module>
import _lbfgsb
ImportError:
/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/_lbfgsb.so:
undefined symbol: lsame_
gberbeglia@actarus:~/python/mycodes>

Any ideas on how to solve this problem? Thanks.

PS: the example is below:

import numpy
from scipy import optimize

a = numpy.array([10,20,10])
print a

def f_(x):
return x*x

x,f,d = optimize.fmin_l_bfgs_b(f_,[0.1],fprime=None, approx_grad = True,
bounds = [(-10000,10000)], iprint=30, maxfun=150000)


--
View this message in context: http://old.nabble.com/scipy-error-undefined-symbol%3A-lsame_-tp28287715p28287715.html
Sent from the Python - python-list mailing list archive at Nabble.com.

== 2 of 3 ==
Date: Mon, Apr 19 2010 10:38 am
From: Joaquin Abian


On Apr 19, 7:15 pm, gerardob <gberbeg...@gmail.com> wrote:
> I installed scipy (and all the required libraries) and the following error
> appears when i tried run a simple example which uses the optimize package of
> scipy. I tried also numpy alone and it works ( at least for printing
> numpy.array([10,20,10]))
>
> error:
>
> Traceback (most recent call last):
>   File "main_test.py", line 2, in <module>
>     from scipy import optimize
>   File
> "/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/__init__.py",
> line 11, in <module>
>     from lbfgsb import fmin_l_bfgs_b
>   File
> "/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/lbfgsb.py",
> line 30, in <module>
>     import _lbfgsb
> ImportError:
> /home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/_lbfgsb.so:
> undefined symbol: lsame_
> gberbeglia@actarus:~/python/mycodes>
>
> Any ideas on how to solve this problem? Thanks.
>
> PS: the example is below:
>
> import numpy
> from scipy import optimize
>
> a = numpy.array([10,20,10])
> print a
>
> def f_(x):
>         return x*x
>
> x,f,d = optimize.fmin_l_bfgs_b(f_,[0.1],fprime=None, approx_grad = True,
> bounds = [(-10000,10000)], iprint=30, maxfun=150000)
>
> --
> View this message in context:http://old.nabble.com/scipy-error-undefined-symbol%3A-lsame_-tp282877...
> Sent from the Python - python-list mailing list archive at Nabble.com.

Um... The snip works perfect on my computer. Just copy and paste.
What libraries are you talking about you had to download? Are you on
windows or linux? On windows you dont need to download anything but
numpy and scipy packages.
joaquin


== 3 of 3 ==
Date: Mon, Apr 19 2010 12:16 pm
From: Robert Kern


On 4/19/10 12:15 PM, gerardob wrote:
>
> I installed scipy (and all the required libraries) and the following error
> appears when i tried run a simple example which uses the optimize package of
> scipy. I tried also numpy alone and it works ( at least for printing
> numpy.array([10,20,10]))
>
> error:
>
> Traceback (most recent call last):
> File "main_test.py", line 2, in<module>
> from scipy import optimize
> File
> "/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/__init__.py",
> line 11, in<module>
> from lbfgsb import fmin_l_bfgs_b
> File
> "/home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/lbfgsb.py",
> line 30, in<module>
> import _lbfgsb
> ImportError:
> /home/gberbeglia/python/Python-2.6.5/lib/python2.6/site-packages/scipy/optimize/_lbfgsb.so:
> undefined symbol: lsame_

This is a FORTRAN symbol. It means that this extension module was not
linked correctly to the FORTRAN standard library appropriate for your
system.

If you need more help, please ask scipy questions on the scipy mailing list.

http://www.scipy.org/Mailing_Lists

--
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


==============================================================================
TOPIC: Operations on sparse matrices
http://groups.google.com/group/comp.lang.python/t/d6a3158ab1d4aba3?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 12:14 pm
From: Robert Kern


On 4/19/10 1:03 AM, pp wrote:
> I am currently dealing with sparse matrices and have doubts on whether
> we can use
> 1.) dot (for matrix multiplication) and inv (inverse) operations of
> numpy on sparse matrices of CSR format.
>
> I initially constructed my sparse matrix using COO format and then
> converted it to CSR format now I want to know whether normal inverse
> and matrix multiplications work with sparse csr matrices.
>
> Also can these operations be applied directly to csr matrices

You will want to ask scipy questions on the scipy mailing list.

http://www.scipy.org/Mailing_Lists

--
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


==============================================================================
TOPIC: pyconfig.h
http://groups.google.com/group/comp.lang.python/t/d434c1898c3b4a56?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 2:18 pm
From: "Martin v. Loewis"


omnia neo wrote:
> Hi All,
>
> I am working on porting python on vxworks and hence was updating the PC
> \pyconfig.h file for configurng python. As I am reading the file and
> updating manually I come across lot many preprocessor directives which
> I dont understand e.g. HAVE_NICE etc. May be this is standard
> nomenclature and I am not aware of it.
> My point and qwery is that how can I get info about all these
> directives. I am perplexed to enable or disable any of them with half
> knowledge.

See the main pyconfig.h.in for comments when to define each of these
macros. HAVE_NICE should be defined if you have (i.e. your system has)
the nice() function.

Regards,
Martin

NICE(P) POSIX Programmer's Manual NICE(P)

NAME
nice - change the nice value of a process

SYNOPSIS
#include <unistd.h>

int nice(int incr);

DESCRIPTION
The nice() function shall add the value of incr to the nice
value of the calling process. A process' nice value is a non-
negative number for which a more positive value shall result
in less favorable scheduling.

A maximum nice value of 2*{NZERO}-1 and a minimum nice value
of 0 shall be imposed by the system. Requests for values above
or below these limits shall result in the nice value being set
to the corresponding limit. Only a process with appropriate
privileges can lower the nice value.

Calling the nice() function has no effect on the priority of
processes or threads with policy SCHED_FIFO or SCHED_RR. The
effect on processes or threads with other scheduling policies
is implementation-defined.

The nice value set with nice() shall be applied to the
process. If the process is multi-threaded, the nice value
shall affect all system scope threads in the process.

As -1 is a permissible return value in a successful situation,
an application wishing to check for error situations should
set errno to 0, then call nice(), and if it returns -1, check
to see whether errno is non-zero.

RETURN VALUE
Upon successful completion, nice() shall return the new nice
value -{NZERO}. Otherwise, -1 shall be returned, the process'
nice value shall not be changed, and errno shall be set to
indicate the error.
indicate the error.

ERRORS
The nice() function shall fail if:

EPERM The incr argument is negative and the calling process
does not have appropriate privileges.

The following sections are informative.

EXAMPLES
Changing the Nice Value
The following example adds the value of the incr argument,
-20, to the nice value of the calling process.

#include <unistd.h>
...
int incr = -20;
int ret;

ret = nice(incr);

APPLICATION USAGE
None.

RATIONALE
None.

FUTURE DIRECTIONS
None.

SEE ALSO
getpriority() , setpriority() , the Base Definitions volume of
IEEE Std 1003.1-2001, <limits.h>, <unistd.h>

COPYRIGHT
Portions of this text are reprinted and reproduced in elec‐
tronic form from IEEE Std 1003.1, 2003 Edition, Standard for
Information Technology -- Portable Operating System Interface
(POSIX), The Open Group Base Specifications Issue 6, Copyright
(C) 2001-2003 by the Institute of Electrical and Electronics
Engineers, Inc and The Open Group. In the event of any dis‐
crepancy between this version and the original IEEE and The
Open Group Standard, the original IEEE and The Open Group
Standard is the referee document. The original Standard can be
obtained online at http://www.opengroup.org/unix/online.html .

IEEE/The Open Group 2003 NICE(P)

==============================================================================
TOPIC: problems creating and adding class instances to a list:
http://groups.google.com/group/comp.lang.python/t/5197b1343f9da781?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Apr 19 2010 2:21 pm
From: Robert Somerville


I am trying to create a list of consisting of multiple instances of the
same class, The Problems i am having is that i seem to be accessing the
same memory.. How should i solve this Python problem ?

Here is some sample code demonstraing my problem (same memory) :
from copy import copy as cp

class ctest():
x = int
y = [1,2,3]

def return_class(i):
d = ctest()
d.y[1] = i*10
return (d)

if __name__ == '__main__':
c_list= []
print 'len-a =',len(c_list)
for i in range(5):
e = cp(return_class(i))
c_list.append(e)
print 'i= ',i,c_list[i].y[1]
if ( i > 0):
print 'i-1= ',i-1,c_list[i-1].y[1]

print 'len = ' , len(c_list)
for i in range(5):
print 'i= ',i,c_list[i].y[1]


here is the output demonstrating that i am addressing the same memory:

rsomerville@galena:~/workspace/CSIRO_gui/trunk/src$ python test4.py
len-a = 1
i= 0 0
i= 1 10
i-1= 0 10
i= 2 20
i-1= 1 20
i= 3 30
i-1= 2 30
i= 4 40
i-1= 3 40
len = 6
i= 0 40
i= 1 40
i= 2 40
i= 3 40
i= 4 40

== 2 of 3 ==
Date: Mon, Apr 19 2010 2:38 pm
From: Chris Rebert


On Mon, Apr 19, 2010 at 2:29 PM, Xavier Ho <contact@xavierho.com> wrote:
> On Tue, Apr 20, 2010 at 7:21 AM, Robert Somerville
> <rsomerville@sjgeophysics.com> wrote:
>>
>> class ctest():
>>   x = int
>>   y = [1,2,3]
>
> Variables defined directly under the class are known as "static variables"
> in many other languages. Here in Python it's called a class variable, but
> they're still the same concept.
>
> What you want is "instance variables", which are not shared by the class
> instances, but different depending on each instance instead. That said,
>
> class ctest():
>     def __init__(self):
>         self.x = int

Additionally, `self.x = int` might not do what you thought it does. It
does *not* create a new instance variable of type 'int'. Instead, it
literally assigns to a new instance variable x the *function*† that
converts values into integers.

Cheers,
Chris
--
† This isn't entirely accurate; I'm oversimplifying for ease of understanding.
http://blog.rebertia.com


== 3 of 3 ==
Date: Mon, Apr 19 2010 3:58 pm
From: Chris Rebert


On Mon, Apr 19, 2010 at 3:41 PM, Xavier Ho <contact@xavierho.com> wrote:
> On Tue, Apr 20, 2010 at 7:38 AM, Chris Rebert <clp2@rebertia.com> wrote:
>> Additionally, `self.x = int` might not do what you thought it does. It
>> does *not* create a new instance variable of type 'int'. Instead, it
>> literally assigns to a new instance variable x the *function*† that
>> converts values into integers.
>
> Thanks, Chris. I'm well aware of that. =]

It was obviously directed at the OP. :-)

Cheers,
Chris

==============================================================================
TOPIC: ANN: Oktest 0.2.1 released - a new style testing library.
http://groups.google.com/group/comp.lang.python/t/da2cbfcf8906d0da?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 3:25 pm
From: kwatch


Hi,

I released Oktest 0.2.1.

homepage: http://packages.python.org/Oktest/
download: http://pypi.python.org/pypi/Oktest/
repository: http://bitbucket.org/kwatch/oktest/

Oktest is a new-style testing library for Python.

from oktest import ok
ok (x) > 0 # same as assert_(x > 0)
ok (s) == 'foo' # same as assertEqual(s, 'foo')
ok (s) != 'foo' # same as assertNotEqual(s, 'foo')
ok (f).raises(ValueError) # same as assertRaises(ValueError, f)
ok (u'foo').is_a(unicode) # same as assert_(isinstance(u'foo',
ode))
not_ok (u'foo').is_a(int) # same as assert_(not
isinstance(u'foo', )
ok ('A.txt').is_file() # same as
assert_(os.path.isfile('A.txt'))
not_ok ('A.txt').is_dir() # same as assert_(not
os.path.isdir('A.txt'))

You can use ok() instead of 'assertXxx()' in unittest.

Oktest requires Python 2.3 or later. Oktest is ready for Python 3.

NOTICE!! Oktest is a young project and specification may change in the
future.

See http://packages.python.org/Oktest/ for details.

--
regards,
makoto kuwata

==============================================================================
TOPIC: unexpected output from difflib.SequenceMatcher
http://groups.google.com/group/comp.lang.python/t/d5262c18d15d9dd0?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 4:47 pm
From: Vlastimil Brom


From: Vlastimil Brom <vlastimil.brom@gmail.com>
Date: 2010/4/16
Subject: unexpected output from difflib.SequenceMatcher

...
Instead of just reporting the insertion and deletion of these single
characters ... the output of the
SequenceMatcher decides to delete a large part of the string in
between the differences and to insert the almost same text after that.
...

Just for the record, althought it seemed unlikely to me first, it
turns out, that this may have the same cause like several difflib
items in the issue tracker regarding unexpected outputs for long
sequences with relatively highly repetitive items, e.g.

http://bugs.python.org/issue2986
http://bugs.python.org/issue1711800
http://bugs.python.org/issue4622
http://bugs.python.org/issue1528074

In my case, disabling the "popular" heuristics as mentioned in
http://bugs.python.org/issue1528074#msg29269
i.e. modifying the difflib source (around line 314 for py.2.5.4) to

if 0: # disable popular heuristics
if n >= 200 and len(indices) * 100 > n:
populardict[elt] = 1
del indices[:]

seems to work perfectly.
Anyway, I would appreciate comments, whether this is the appropriate
solution for the given task - i.e. the character-wise comparison of
strings; or are there maybe some drawbacks to be aware of? Wouldn't
some kind of control over the "pouplar" heuristics be useful in the
exposed interface of difflib?
Or is this just the inappropriate tool for the character-wise string
comparison, as is suggested e.g. in
http://bugs.python.org/issue1528074#msg29273 althought it seems to
work just right for the most part?

regards,
vbr

==============================================================================
TOPIC: cross-platform coloured text in terminal
http://groups.google.com/group/comp.lang.python/t/1c1cb43fa8d7a8ac?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Apr 19 2010 5:12 pm
From: Jonathan Hartley


On Apr 17, 11:52 am, Jonathan Hartley <tart...@tartley.com> wrote:
> On Apr 16, 5:59 pm, Lie Ryan <lie.1...@gmail.com> wrote:
>
>
>
> > On 04/16/10 19:28, Jonathan Hartley wrote:
>
> > > I'm playing with ideas of what API to expose. My favourite one is to
> > > simply embed ANSI codes in the stream to be printed. Then this will
> > > work as-is on Mac and *nix. To make it work on Windows, printing could
> > > be done to a file0-like object which wraps stdout:
>
> > The problem with that is you're simply reinventing ANSI.SYS device driver.
>
> > An alternative API is you could override .__add__(), like so (completely
> > untested):
>
> > classColor(object):
> >    def __init__(self,color):
> >        self.color=  map_the_color(color)
> >        self.string = ""
> >    def __add__(self, string):
> >        self.string += string
> >        return self
> >    def __str__(self):
> >        if terminal_can_do_ansi_color:
> >            return ansicolorescape(self.string, self.color)
> >        elif windows:
> >            syscalltocolor(self.color)
> >            print self.string
> >            syscalltocolor(reset thecolor)
> >            return ""
>
> > GREEN =Color('green')
> > print GREEN + "Great" + "Good"
>
> > you can even go a bit further and allow chained calls (again, completely
> > untested, but you get the idea):
>
> > classColor(object):
> >    def __init__(self,color):
> >        self.color=  map_the_color(color)
> >        self.stack = []
> >    def __add__(self, string):
> >        if isinstance(string,Color):
> >            # not a string, chain the calls
> >            self.stack.append((string.color, []]))
> >        else:
> >            # a string,
> >            self.stack[-1][1].append(string)
> >        return self
> >    def __radd__(self, string):
> >        self.stack.append([self.default, string])
> >        return self
>
> >    def __str__(self):
> >        if ansi_capable:
> >            return colorescape(format, string)
> >        elif windows:
> >            for format, string in self.stack:
> >                syscalltocolor(color)
> >                print string
> >                return ""
>
> > GREEN =Color('green')
> > RED =Color('red')
>
> > print "Fairly" + GREEN + "Great" + RED + "Poor"
>
> > or something like that, and you will have an API that works
> > transparently on all platforms. The downside is that you cannot call
> > str(GREEN + "foo") on windows.
>
> Hey Lie,
>
> Thanks heaps for the reply!
>
> >> The problem with that is you're simply reinventing ANSI.SYS device driver.
>
> I don't see that as a problem - in fact I think it's exactly my
> goal! :-)
>
> The difference is that the ANSI driver requires installation and a
> reboot on the end-user's computer, which is a fiddly and intrusive
> thing for a Python developer to achieve. Whereas doing the same job in
> a Python module is easy to use for the Python developer - they just
> import the module, maybe call an 'init()' function, and then the ANSI
> functionality works on all platforms.
>
> Your ideas about generating and chaining the ANSI code strings are
> great. I worry though, about intermingling the code that generates
> ANSI escape sequences with the code which makes them work on Windows.
> The problem is that then, only applications which use your ANSI-
> generation library will work on Windows. Whereas if these two things
> are kept separate, then applications which use any other ANSI-
> generation techniques, such as using 'termcolor', or manaully printing
> raw ANSI sequences, these can also all work on Windows too, simply by
> adding an import and an 'init()' call to the start of the application.
>
> Am I making sense? Many thanks for your thoughts.
>
>   Jonathan


I have implemented these ideas here. It seems to work.
http://pypi.python.org/pypi/colorama

==============================================================================
TOPIC: any modules having a function to partition a list by predicate provided?

http://groups.google.com/group/comp.lang.python/t/f6e5a5e615820980?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Apr 19 2010 6:00 pm
From: knifenomad


i know it's not very hard to get that solution.
just by implementing simple function like below.

def partition(target, predicate):
"""
split a list into two partitions with a predicate
provided.
any better ideas? :)
"""
true = []
false= []
for item in target:
if predicates(item):
true.append(item)
else:
false.append(item)
return true, false

but i wonder if there's another way to do this with standard libraries
or .. built-ins.
if it's not, i'd like the list objects to have partition method like
string module has.

true, false = [1,2,3,4].partition(lambda x: x >1)

print true, false
[2,3,4] [1]

== 2 of 2 ==
Date: Mon, Apr 19 2010 6:16 pm
From: Chris Rebert


On Mon, Apr 19, 2010 at 6:00 PM, knifenomad <knifenomad@gmail.com> wrote:
> i know it's not very hard to get that solution.
> just by implementing simple function like below.
>
>      def partition(target, predicate):
>            """
>            split a list into two partitions with a predicate
> provided.
>            any better ideas? :)
>            """
>            true = []
>            false= []
>            for item in target:
>                if predicates(item):
>                    true.append(item)
>                else:
>                    false.append(item)
>            return true, false
>
> but i wonder if there's another way to do this with standard libraries
> or .. built-ins.
> if it's not, i'd like the list objects to have partition method like
> string module has.

(A) str.partition() has a /completely/ different meaning from your partition()
(B) You'd probably have better luck getting it added to the itertools
module since the concept is applicable to all iterables.
[http://docs.python.org/library/itertools.html]

Cheers,
Chris
--
http://blog.rebertia.com


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate