Re: Testing if a global is defined in a module

2011-07-06 Thread Waldek M.
Dnia Wed, 06 Jul 2011 03:36:24 +1000, Steven D'Aprano napisał(a):
 Because unless you are extremely disciplined, code and the comments
 describing them get out of sync. [...]
True, but that gets far worse with external docs.
Do you have in mind any better replacement?

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Gregory Ewing

rantingrick wrote:


What he means is that On Mac, if you close all windows, the application is
still running.


Then that is NOT closing windows that is only ICONIFIYING/HIDING them.


No, the windows really are closed. They no longer exist
in any way. The application is still running, though, and
its menu bar will appear if you bring it to the front
(in MacOSX this is done by clicking on its dock icon;
in classic MacOS it was done by selecting from the menu
of running applications that was available in the top right
corner of the screen).

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Gregory Ewing

rantingrick wrote:


And how do you EXPLICITY quit the application?


Using its Quit menu command.

But that's Mac-specific, and not central to the discussion.
On Linux and Windows, an application will usually exit when
its last window is closed. Either way, there is no need for
a privileged main window.

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Chris Rebert
On Tue, Jul 5, 2011 at 10:54 PM, Phlip phlip2...@gmail.com wrote:
 Pythonistas:

 Consider this hashing code:

  import hashlib
  file = open(path)
  m = hashlib.md5()
  m.update(file.read())
  digest = m.hexdigest()
  file.close()

 If the file were huge, the file.read() would allocate a big string and
 thrash memory. (Yes, in 2011 that's still a problem, because these
 files could be movies and whatnot.)

 So if I do the stream trick - read one byte, update one byte, in a
 loop, then I'm essentially dragging that movie thru 8 bits of a 64 bit
 CPU. So that's the same problem; it would still be slow.

 So now I try this:

  sum = os.popen('sha256sum %r' % path).read()

 Those of you who like to lie awake at night thinking of new ways to
 flame abusers of 'eval()' may have a good vent, there.

Indeed (*eyelid twitch*). That one-liner is arguably better written as:
sum = subprocess.check_output(['sha256sum', path])

 Does hashlib have a file-ready mode, to hide the streaming inside some
 clever DMA operations?

Barring undocumented voodoo, no, it doesn't appear to. You could
always read from the file in suitably large chunks instead (rather
than byte-by-byte, which is indeed ridiculous); see
io.DEFAULT_BUFFER_SIZE and/or the os.stat() trick referenced therein
and/or the block_size attribute of hash objects.
http://docs.python.org/library/io.html#io.DEFAULT_BUFFER_SIZE
http://docs.python.org/library/hashlib.html#hashlib.hash.block_size

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Thomas Rachel

Am 06.07.2011 07:54 schrieb Phlip:

Pythonistas:

Consider this hashing code:

   import hashlib
   file = open(path)
   m = hashlib.md5()
   m.update(file.read())
   digest = m.hexdigest()
   file.close()

If the file were huge, the file.read() would allocate a big string and
thrash memory. (Yes, in 2011 that's still a problem, because these
files could be movies and whatnot.)

So if I do the stream trick - read one byte, update one byte, in a
loop, then I'm essentially dragging that movie thru 8 bits of a 64 bit
CPU. So that's the same problem; it would still be slow.


Yes. That is why you should read with a reasonable block size. Not too 
small and not too big.


def filechunks(f, size=8192):
while True:
s = f.read(size)
if not s: break
yield s
#f.close() # maybe...

import hashlib
file = open(path)
m = hashlib.md5()
fc = filechunks(file)
for chunk in fc:
m.update(chunk)
digest = m.hexdigest()
file.close()

So you are reading in 8 kiB chunks. Feel free to modify this - maybe use 
os.stat(file).st_blksize instead (which is AFAIK the recommended 
minimum), or a value of about 1 MiB...




So now I try this:

   sum = os.popen('sha256sum %r' % path).read()


This is not as nice as the above, especially not with a path containing 
strange characters. What about, at least,


def shellquote(*strs):
return  .join([
'+st.replace(','\\'')+'
for st in strs
])

sum = os.popen('sha256sum %r' % shellquote(path)).read()


or, even better,

import subprocess
sp = subprocess.Popen(['sha256sum', path'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
sp.stdin.close() # generate EOF
sum = sp.stdout.read()
sp.wait()

?



Does hashlib have a file-ready mode, to hide the streaming inside some
clever DMA operations?


AFAIK not.


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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Gregory Ewing

rantingrick wrote:


I was thinking more about this comment and it occurred to me that
Python does have user controlled data structures. Just because there
is no top level syntax like ruby does not mean these do not exists.


Syntax is what it's really about, though. There's no clear
dividing line, but when Guido says he's opposed to user
defined syntax he's talking about things like Lisp macros,
which let you effectively extend the grammar with new
keywords and syntactic structures.

Compared to that, Python's grammar is very much fixed.
Anything you want to do has to be done within the existing
framework of function calls, attribute references etc.

If Python truly had user-defined syntax, it wouldn't have
been necessary to modify the compiler to implement features
such as list comprehensions and with-statements -- those
features could have been implemented, with the *same
syntax* or something close to it, in the base language.

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


Re: embedding: how do I redirect print output?

2011-07-06 Thread Ulrich Eckhardt
Steven D'Aprano wrote:
 Why do you think it [sink for use as sys.stdout] needs to be in C? As
 far as I can tell, so long as it quacks like a file object (that is,
 has a write method), it should work.

Good point  thanks for the example fish!

Uli


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

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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Ulrich Eckhardt
rantingrick wrote:
 On Jul 5, 10:26 am, Steven D'Aprano steve
 Since you can't do anything without a root window, I don't see the
 benefit in forcing the user to do so [create one explicitly].
 
 The reason is simple. It's called order. It's called learning from day
 one how the order of things exists. Widgets are part of windows, not
 the other way around. Saving a few keystrokes is not acceptable if you
 jumble the understanding of a new student. To understand and use
 Tkinter properly you must understand the order of window-widget.
 
 When they need to learn about root windows,
 they will in their own good time.
 
 So you would start drivers education class with road construction? Or
 the history of the internal combustion engine? Who cares about
 actually *driving* the car.

Ahem, you are the one that suggests that in order to drive a car you should 
first build a road, not Steven!

That said, why should I care about the choices and steps I have for creating 
main windows and the possibilities I get from doing this myself? A basic 
default main window is enough for me! Further, choice implies I can make 
wrong choices, too, so forcing someone to make a decision might cause 
errors.

Uli

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

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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Ulrich Eckhardt
Mel wrote:
 In wx, many of the window classes have Create methods, for filling in
 various attributes in two-step construction.  I'm not sure why, because
 it works so well to just supply all the details when the class is called
 and an instance is constructed.  Maybe there's some C++ strategy that's
 being supported there.

Just guessing, is it legacy, C-with-classes code rather than C++ code 
perhaps? Haven't looked at wx for a while. Such code typically lacks 
understanding of exceptions, which are the only way to signal failure from 
e.g. constructors.

Uli

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

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Gregory Ewing

rantingrick wrote:

Something to replace Python, Ruby, Perl,
JavaScript, etc, etc not some pie-in-the-sky,  single-answer-to-all-
our-problems pipe dream language.


So it's just a single-answer-to-all-our-glue-programming
pipe dream language, then? :-)

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


Error while downloading webpages

2011-07-06 Thread TimB
Hi everyone, new to python. I'm attempting to download a large amount
of webpages (about 600) to disk and for some reason a few of them
fail.

I'm using this in a loop where pagename and urlStr change each time:
import urllib
try:
urllib.urlretrieve(urlStr, 'webpages/'+pagename+'.htm')
except IOError:
print 'Cannot open URL %s for reading' % urlStr
str1 = 'error!'

Out of all the webpages, it does not work for these three:
http://exoplanet.eu/planet.php?p1=WASP-11/HAT-P-10p2=b
http://exoplanet.eu/planet.php?p1=HAT-P-27/WASP-40p2=b
http://exoplanet.eu/planet.php?p1=HAT-P-30/WASP-51p2=b
giving Cannot open URL http://exoplanet.eu/planet.php?p1=WASP-11/HAT-P-10p2=b
for reading etc.

however copying and pasting the URL from the error message
successfully opens in firefox

it successfully downloads the 500 or so other pages such as:
http://exoplanet.eu/planet.php?p1=HD+88133p2=b

I guess it has something to do with the forward slash in the names
(e.g. HAT-P-30/WASP-51 compared to HD+88133 in the examples above)

Is there a way I can fix this? Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Not able to store data to dictionary because of memory limitation

2011-07-06 Thread Rama Rao Polneni
Hi All,

I am facing a problem when I am storing cursor fetched(Oracle 10G)
data in to a dictionary.
As I don't have option to manipulate data in oracle10G, I had to stick
to python to parse the data for some metrics.

After storing 1.99 GB data in to the dictionary, python stopped to
store the remaining data in to dictionary.

Memory utilization is 26 GB/34GB. That means, still lot memory is left
as unutilized.

Can please share your experices/ideas to resolve this issue.
Is this prople mbecasue of large memory utlization.
Is there any alternate solution to resolve this issue. Like splitting
the dictionaries or writing the data to hard disk instead of writing
to memory.
How efficiently we can use  memory when we are going for dictionaries.

Thanks in advacne,
Rama
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web browsing short cut

2011-07-06 Thread Thomas Jollans
On 07/06/2011 03:30 AM, Dustin Cheung wrote:
 I am looking into Tkinter. But i am not sure if it will actually work.
 This maybe a crazy idea but i was wondering if i can put a web browser
 in the frame. I have tried to use Tkinter to resize and place the
 windows to certain areas of the screen but that's not working or the way
 im approaching this problem is completely wrong. I want to make a
 program that will have websites displayed in specific areas of the
 screen. I was planning on using the program on the big screen. So is it
 possible to put the web browser inside the frame in Tkinter?

What you could do, in effect, is write your own web browser, using an
existing rendering engine. I do not know which rendering engines are how
easily used in Tkinter code (possibly none of them).

This isn't a job for (traditional, cross-platform) Python. It *may* be
possible with pyWin32. It may be easier with the Windows Script Host
(which apparently can support Python). I personally would use
browser-side JavaScript; it's certainly possible to open a popup of a
specific size in JS, not sure about specific position on-screen. Maybe
you have to write an extension for Firefox or Chrome.

 
 
 On Sat, Jul 2, 2011 at 7:10 PM, Chris Rebert c...@rebertia.com
 mailto:c...@rebertia.com wrote:
 
 On Sat, Jul 2, 2011 at 6:21 PM, Dustin Cheung dustin...@gmail.com
 mailto:dustin...@gmail.com wrote:
  Hey guys,
  I am new to python. I want to make a shortcut that opens my websites
  and re-sizes them to  display on different areas on the screen. I
 looked
  around but i had no luck. Is that possible with python? if so can
 someone
  point to to the right direction? Here is what I came up with so far..
 
 The window positioning+resizing bit will likely require using
 platform-specific APIs. Since you appear to be on Windows, the
 relevant library would be pywin32 (http://pypi.python.org/pypi/pywin32
 ). You would use it to invoke some COM API that does window
 positioning+resizing. I am unable to give more details as I'm on a
 Mac.
 
 Sidenote: Have you tried Firefox's Bookmark All Tabs feature?
 
 Cheers,
 Chris
 
 
 
 
 -- 
 Dustin Cheung
 
 

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


Re: Error while downloading webpages

2011-07-06 Thread TimB
On Jul 6, 5:39 pm, TimB timbova...@gmail.com wrote:
 Hi everyone, new to python. I'm attempting to download a large amount
 of webpages (about 600) to disk and for some reason a few of them
 fail.

 I'm using this in a loop where pagename and urlStr change each time:
 import urllib
     try:
         urllib.urlretrieve(urlStr, 'webpages/'+pagename+'.htm')
     except IOError:
         print 'Cannot open URL %s for reading' % urlStr
         str1 = 'error!'

 Out of all the webpages, it does not work for these 
 three:http://exoplanet.eu/planet.php?p1=WASP-11/HAT-P-10p2=bhttp://exoplanet.eu/planet.php?p1=HAT-P-27/WASP-40p2=bhttp://exoplanet.eu/planet.php?p1=HAT-P-30/WASP-51p2=b
 giving Cannot open URLhttp://exoplanet.eu/planet.php?p1=WASP-11/HAT-P-10p2=b
 for reading etc.

 however copying and pasting the URL from the error message
 successfully opens in firefox

 it successfully downloads the 500 or so other pages such 
 as:http://exoplanet.eu/planet.php?p1=HD+88133p2=b

 I guess it has something to do with the forward slash in the names
 (e.g. HAT-P-30/WASP-51 compared to HD+88133 in the examples above)

 Is there a way I can fix this? Thanks.

sorry, I was attempting to save the page to disk with the forward
slash in the name, disreguard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Not able to store data to dictionary because of memory limitation

2011-07-06 Thread Chris Angelico
On Wed, Jul 6, 2011 at 5:49 PM, Rama Rao Polneni ram...@gmail.com wrote:
 Hi All,

 I am facing a problem when I am storing cursor fetched(Oracle 10G)
 data in to a dictionary.
 As I don't have option to manipulate data in oracle10G, I had to stick
 to python to parse the data for some metrics.

 After storing 1.99 GB data in to the dictionary, python stopped to
 store the remaining data in to dictionary.

Is the data one row from the table, or could you work with it row-by-row?

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


Re: web browsing short cut

2011-07-06 Thread Chris Angelico
On Wed, Jul 6, 2011 at 11:30 AM, Dustin Cheung dustin...@gmail.com wrote:
 Hey,
 I am looking into Tkinter. But i am not sure if it will actually work. This
 maybe a crazy idea but i was wondering if i can put a web browser in the
 frame. I have tried to use Tkinter to resize and place the windows to
 certain areas of the screen but that's not working or the way im approaching
 this problem is completely wrong. I want to make a program that will have
 websites displayed in specific areas of the screen. I was planning on using
 the program on the big screen. So is it possible to put the web browser
 inside the frame in Tkinter?

Thinking along a quite different line here, is it possible for you to
use regular frames? Create an HTML file with:

frameset rows=50%,50%
frameset cols=50%,50%
frame src=http://blah/blah;
frame src=http://another/blah;
/frameset
frameset cols=50%,50%
frame src=http://third/blah;
frame src=http://final/blah;
/frameset
/frameset

That should divide your screen four ways (if I haven't botched my HTML
- ages since I've used frames).

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


Re: Secure ssl connection with wrap_socket

2011-07-06 Thread AndDM
On Jul 5, 4:08 pm, Jean-Paul Calderone calderone.jeanp...@gmail.com
wrote:
 On Jul 5, 4:52 am, Andrea Di Mario anddima...@gmail.com wrote:

  Hi, I'm a new python user and I'm writing a small web service with ssl.
  I want use a self-signed certificate like in 
  wiki:http://docs.python.org/dev/library/ssl.html#certificates
  I've used wrap_socket, but if i try to use
  cert_reqs=ssl.CERT_REQUIRED, it doesn't work with error:

  urllib2.URLError: urlopen error _ssl.c:326: No root certificates
  specified for verification of other-side certificates.

  It works only with CERT_NONE (the default) but with this option i
  could access to the service in insicure mode.

  Have you some suggestions for my service?

 Also specify some root certificates to use in verifying the peer's
 certificate.  Certificate verification works by proceeding from a
 collection of root certificates which are explicitly trusted.  These
 are used to sign other certificates (which may in turn be used to sign
 others, which in turn...).  The process of certificate verification is
 the process of following the signatures from the certificate in use by
 the server you connect to back up the chain until you reach a root
 which you have either decided to trust or not.  If the signatures are
 all valid and the root is one you trust, then you have established a
 connection to a trusted entity.  If any signature is invalid, or the
 root is not one you trust, then you have not.

 The root certificates are also called the ca certificates or
 certificate authority certificates.  `wrap_socket` accepts a
 `ca_certs` argument.  
 Seehttp://docs.python.org/library/ssl.html#ssl-certificates
 for details about that argument.

 Jean-Paul

Hi Jean-Paul, i thought that with self-signed certificate i shouldn't
use ca_certs option. Now, i've created a ca-authority and i use this
command:

 self.sock = ssl.wrap_socket(sock, certfile = ca/certs/
myfriend.cert.pem, keyfile = ca/private/myfriend.key.pem,
ca_certs=/home/andrea/ca/certs/cacert.pem,
cert_reqs=ssl.CERT_REQUIRED)

When i use the some machine as client-server it works, but, when i use
another machine as client, i've this:

Traceback (most recent call last):
  File loginsender.py, line 48, in module
    handle = url_opener.open('https://debian.andrea.it:10700/%s+%s' %
(DATA,IPIN))
  File /usr/lib/python2.6/urllib2.py, line 391, in open
    response = self._open(req, data)
  File /usr/lib/python2.6/urllib2.py, line 409, in _open
    '_open', req)
  File /usr/lib/python2.6/urllib2.py, line 369, in _call_chain
    result = func(*args)
  File loginsender.py, line 33, in https_open
    return self.do_open(self.specialized_conn_class, req)
  File /usr/lib/python2.6/urllib2.py, line 1145, in do_open
    raise URLError(err)
urllib2.URLError: urlopen error [Errno 185090050] _ssl.c:328: error:
0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

I see that i should create a certificate with server, client and ca
autority, but i haven't clear the ca_certs option and which path i
should use.
Have you any suggestion?

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


Extracting property getters from dir() results

2011-07-06 Thread Gnarlodious
Using introspection, is there a way to get a list of property
getters?

Does this:

vars=property(getVars(), Dump a string of variables and values)

have some parsable feature that makes it different from other
functions? Or would I need to use some naming scheme to parse them
out?

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


Re: Not able to store data to dictionary because of memory limitation

2011-07-06 Thread Rama Rao Polneni

Yes the data is from table. which is retrieved using some queries in
to cx_oracel cursor.  I am able to read the data row by row.
One more information, I am Able to load the data in to dictionary by
removing some some data from table.

-Ram

 Is the data one row from the table, or could you work with it row-by-row?

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


On 7/6/11, Chris Angelico ros...@gmail.com wrote:
 On Wed, Jul 6, 2011 at 5:49 PM, Rama Rao Polneni ram...@gmail.com wrote:
 Hi All,

 I am facing a problem when I am storing cursor fetched(Oracle 10G)
 data in to a dictionary.
 As I don't have option to manipulate data in oracle10G, I had to stick
 to python to parse the data for some metrics.

 After storing 1.99 GB data in to the dictionary, python stopped to
 store the remaining data in to dictionary.


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


Re: Not able to store data to dictionary because of memory limitation

2011-07-06 Thread Ulrich Eckhardt
Rama Rao Polneni wrote:
 After storing 1.99 GB data in to the dictionary, python stopped to
 store the remaining data in to dictionary.

Question here:
 - Which Python?
 - stopped to store (you mean stopped storing, btw), how does it behave? 
Hang? Throw exceptions? Crash right away?


 Memory utilization is 26 GB/34GB. That means, still lot memory is left
 as unutilized.

2GiB is typically the process limit for memory allocations on 32-bit 
systems. So, if you are running a 32-bit system or running a 32-bit process 
on a 64-bit system, you are probably hitting hard limits. With luck, you 
could extend this to 3GiB on a 32-bit system.


 Is this proplem becasue of large memory utlization.

I guess yes.


 Is there any alternate solution to resolve this issue. Like splitting
 the dictionaries or writing the data to hard disk instead of writing
 to memory.

If you have lost of equal strings, interning them might help, both in size 
and speed. Doing in-memory compression would be a good choice, too, like 
e.g. if you have string fields in the DB that can only contain very few 
possible values, converting them to an integer/enumeration.

Otherwise, and this is a more general approach, prefer making a single sweep 
over the data. This means that you read a chunk of data, perform whatever 
operation you need on it, possibly write the results and then discard the 
chunk. This keeps memory requirements low. At first, it doesn't look as 
clean as reading the whole data in one step, calculations as a second and 
writing results as a third, but with such amounts of data as yours, it is 
the only viable step.

Good luck, and I'd like to hear how you solved the issue!

Uli

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

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


Re: Extracting property getters from dir() results

2011-07-06 Thread Christian Heimes
Am 06.07.2011 11:02, schrieb Gnarlodious:
 Using introspection, is there a way to get a list of property
 getters?
 
 Does this:
 
 vars=property(getVars(), Dump a string of variables and values)
 
 have some parsable feature that makes it different from other
 functions? Or would I need to use some naming scheme to parse them
 out?

dir() won't help you much here. The inspect module has several tools to
make inspection easier.

 import inspect
 class Example(object):
... @property
... def method(self):
... return 1
...
 inspect.getmembers(Example, inspect.isdatadescriptor)
[('__weakref__', attribute '__weakref__' of 'Example' objects),
('method', property object at 0xec0520)]


inspect.getmembers() with isdatadescriptor predicate works only on
classes, not on instances.

 inspect.getmembers(Example(), inspect.isdatadescriptor)
[]


Property instances have the attributes fget, fset and fdel that refer to
their getter, setter and delete method.

 for name, obj in inspect.getmembers(Example, inspect.isdatadescriptor):
... if isinstance(obj, property):
... print name, obj, obj.fget
...
method property object at 0xec0520 function method at 0xec1a28



Christian

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


Python Packaging

2011-07-06 Thread Benji Benjokal
Can someone show me how to package with py2exe?
Every time I tried  it says the file does not exist.
Can you help?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Anssi Saari
Phlip phlip2...@gmail.com writes:

 If the file were huge, the file.read() would allocate a big string and
 thrash memory. (Yes, in 2011 that's still a problem, because these
 files could be movies and whatnot.)

I did a crc32 calculator like that and actually ran into some kind of
string length limit with large files. So I switched to 4k blocks and
the speed is about the same as a C implementation in the program
cksfv. Well, of course crc32 is usually done with a table lookup, so
it's always fast.

I just picked 4k, since it's the page size in x86 systems and also a
common block size for file systems. Seems to be big enough.
io.DEFAULT_BUFFER_SIZE is 8k here. I suppose using that would be the
proper way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Packaging

2011-07-06 Thread Thomas Jollans
On 07/06/2011 11:44 AM, Benji Benjokal wrote:
 
 Can someone show me how to package with py2exe?
 Every time I tried  it says the file does not exist.


If you show us how you're trying to do it, somebody may be able to spot
your error.

PS: http://www.catb.org/~esr/faqs/smart-questions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


hiiiiiiiiiiii see this webpage

2011-07-06 Thread covai exxon
http://123maza.com/65/papaya846/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Adam Tauno Williams
On Tue, 2011-07-05 at 22:54 -0700, Phlip wrote:
 Pythonistas
 Consider this hashing code:
   import hashlib
   file = open(path)
   m = hashlib.md5()
   m.update(file.read())
   digest = m.hexdigest()
   file.close()
 If the file were huge, the file.read() would allocate a big string and
 thrash memory. (Yes, in 2011 that's still a problem, because these
 files could be movies and whatnot.)

Yes, the simple rule is do not *ever* file.read().  No matter what the
year this will never be OK.  Always chunk reading a file into reasonable
I/O blocks.

For example I use this function to copy a stream and return a SHA512 and
the output streams size:

def write(self, in_handle, out_handle):
m = hashlib.sha512()
data = in_handle.read(4096)
while True:
if not data:
break
m.update(data)
out_handle.write(data)
data = in_handle.read(4096)
out_handle.flush()
return (m.hexdigest(), in_handle.tell())

 Does hashlib have a file-ready mode, to hide the streaming inside some
 clever DMA operations?

Chunk it to something close to the block size of your underlying
filesystem.

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Steven D'Aprano
rantingrick wrote:

 On Jul 5, 11:04 am, Corey Richardson kb1...@aim.com wrote:
 
 How is giving the sort method a function by which to determine the
 relative value of objects a control structure? Do you know what a control
 structure is? It's something that you use to modify control flow:

 if foo = bar:
 foo += 1
 else:
 bar += 1
 
 Interesting, corey. Very interesting. However the fun is yet to come
 so stay tuned...
 
 That's a control structurem the if-else. I don't know what Ruby calls a
 control structure, but that's what it is. for and while are in there too.
 When you run lst.sort(lambda x, y: cmp(x[1], y[1])), what happens?
 
 So are you suggesting that a control structure must have at minimum
 one of for, while, or if? 

A control structure is a structure which controls the program flow. Control
structures include:

* jumps (goto, gosub, comefrom, exceptions, break, continue)

* loops (for, while, repeat...until)

* conditional branches (if, case/switch)

There may be others, although I can't think of any of hand. Jumping, looping
and branching pretty much covers all the bases, I think.

It excludes expressions such as ternary-if, because that doesn't control
program flow, it's just an expression.

A function which includes a control structure inside it is not itself a
control structure, in the same way that the existence of bones inside you
does not make you a bone.


[...]
 Yes there IS and if in there and IF you look closely enough you may
 see two for's also. So by your own definition this (naive) code
 qualifies as a control structure. 

I see what you did there. First you put words into Cory's mouth that he did
not say, they you try to criticise him based on those words -- YOUR words.

No Rick, that's your definition, not Cory's. Please do not treat us as
stupid.



 But wait just a second Corey. My statement has nothing to do with
 sort. sort is just the vehicle. My statement is that the cmp argument
 to sort IS a user defined control structure (the code block to be
 exact). 

The cmp argument to sort is not a control structure because it is not a
structure and it does not control the program flow.


-- 
Steven

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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Steven D'Aprano
Stefaan Himpe wrote:

 Now, I have an ulterior motive in raising this issue... I can't find the
 original article I read! My google-fu has failed me (again...). I don't
 suppose anyone can recognise it and can point me at it?
 
 My sarcasm detector warns me not to add a link, although perhaps it's
 time for recalibration (after all, summer season started) :-)

No! I was serious. I've spent *ages* trying to find the link to the
article... if you know it, please share.


-- 
Steven

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Steven D'Aprano
sal migondis wrote:

 How could a belief be wrong?

I believe you are a small glass of beer. Are you *actually* a small glass of
beer in reality? If so, my belief is right. If you are a human being, then
my belief is wrong.



-- 
Steven

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Steven D'Aprano
rantingrick wrote:

 Define best for all, and try not to make it what Rick wants.
 
 You want features? And remember i am talking about scripting/glue
 level languages here. Something to replace Python, Ruby, Perl,
 JavaScript, etc, etc not some pie-in-the-sky,  single-answer-to-all-
 our-problems pipe dream language.
 
  * Intuitive syntax.

Intuitive to who? 

Newbies? Then you get a language like Hypertalk, that experienced
programmers hate.

Experienced C programmers? Then you get something like Java.

Forth programmers? Then you get something like Arc, that nobody except Paul
Graham uses. (Not literally, no offence to anyone who likes Arc.)

System administrators? They you get something like Perl. (It's like bash
scripting only better!)

Mathematicians? Then you get something like Haskell.

Non-programmers? Then you could get anything from Inform7, to Applescript,
to Resolver's Python-in-a-spreadsheet, to Pascal, to FoxPro, to Flash, to
Javascript, to Mathematica... depending on *which* non-programmers you are
aiming at.


  * Productivity friendly.

That covers everything from Excel to Lisp, depending on who you ask.


  * Complex enough to solve large problems but simple enough for simple
 problems (that does include extending into C when needed)

But if you are designing the perfect language, what do you need C for? C
will no longer exist, except in museums, because Rick's perfect language
will be used for everything.

  * Multi paradigm (problem

Which is guaranteed to annoy those who believe that paradigms A, C, D and E
are harmful and should be avoided... the only problem is that there is no
broad agreement on which paradigm B is non-harmful.


  * Promotes a culture of code readability (because people read source;
 not just machines!).

Define readability.

Hypertalk, Python, Inform7 and Pascal are all readable, in radically
different ways.


 No, Python is not a monoculture. There are the Stackless, Jython, PyPy
 and IronPython sub-cultures, all with their own needs, wants and desires.
 There are sub-cultures for embedded devices and smart phones,
 sub-cultures for those who use Python as a teaching language, for web
 development, for GUI development, and for system administration. There
 are the Numpy and Scipy sub-cultures, sub-cultures in the fields of
 linguistics and biology.
 
 Hmm. Just think how far ahead we would be if these folks would stop
 trying to support petty differences and focus on a singular Python
 language?

These are not petty differences, but real differences that are important
to people who have actually work to do.

A sushi chef needs a different sort of knife to a brain surgeon, both of
which are different to that needed by a special forces soldier deep in
enemy territory, which is different again to the sort of knife is needed by
some guy working in a warehouse unpacking boxes. Different jobs need
different tools.

There is no perfect language because different tasks need different tools,
and any compromise tool that tries to do everything will be weaker than a
specialist tool.


-- 
Steven

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


Re: Not able to store data to dictionary because of memory limitation

2011-07-06 Thread Tim Chase

On 07/06/2011 02:49 AM, Rama Rao Polneni wrote:

After storing 1.99 GB data in to the dictionary, python stopped to
store the remaining data in to dictionary.

Is there any alternate solution to resolve this issue. Like splitting
the dictionaries or writing the data to hard disk instead of writing
to memory.


Without details on the specifics of what you're storing in your 
dictionary, you might investigate the anydbm module which would 
allow you to have a disk-backed dictionary, but it really only 
works for string-string mappings.  You can use shelve/pickle to 
marshal other data-types into strings for use in such a mapping, 
but there are some odd edge-cases to be aware of (updating an 
instance of a class doesn't change the pickled object, so you 
have to intentionally re-store it after you change it; I've hit 
unexpected scoping issues with class-names; etc).  But for the 
general case, it might do exactly what you need to remove the 2GB 
cap.


-tkc


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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Stefaan Himpe



No! I was serious. I've spent *ages* trying to find the link to the
article... if you know it, please share.


Ok - I thought you were referring to some troll's rant with similar 
title. I'm probably way off, but were you referring to the RAII technique?


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




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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread rantingrick
On Jul 6, 6:44 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 A control structure is a structure which controls the program flow. Control
 structures include:

 * jumps (goto, gosub, comefrom, exceptions, break, continue)

 * loops (for, while, repeat...until)

 * conditional branches (if, case/switch)

---
THIS CODE RESULTS IN A CONTROL STRUCTURE!

-- lst.sort(lambda x,y: cmp(x[1], y[1]))
---

I am using a user defined spec as an argument to the cmp function.
That spec then modifies the body of the compare function and creates a
user defined control structure. You can argue all day that it is not a
user defined control structure but no one is going to believe you.

 A function which includes a control structure inside it is not itself a
 control structure,

Of course the FUNCTION is not a control structure (not directly). No
wonder you are confused. It's the FUNCTION BODY that is the control
structure. The function body that has been modified by my arguments to
the cmp function. But in a way, you can say the function OWNS the code
block so it is itself a control structure. Still confused? Read on...

  in the same way that the existence of bones inside you
 does not make you a bone.

Bad analogy. See last comment.

 I see what you did there. First you put words into Cory's mouth that he did
 not say, they you try to criticise him based on those words -- YOUR words.

I quoted Corey exactly. And why do you feel the need to answer for
him?

 The cmp argument to sort is not a control structure because it is not a
 structure and it does not control the program flow.

Again you lack simple reading and comprehension skills. It's not the
argument that is the control structure itself. The argument is just
the SPEC for creating a control structure. The control structure is
the modified CODE BLOCK owned by the CMP function.

The modified code block owned by the cmp function-- defined by the
user through an argument spec--  controls the return value to the list
sort method. USER DEFINED CONTROL STRUCTURE. Plain and simple. I don't
think i can use any simpler terms to describe it.

Give it up man and admit i am correct and you are wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Chris Angelico
On Wed, Jul 6, 2011 at 11:41 PM, rantingrick rantingr...@gmail.com wrote:
 Give it up man and admit i am correct and you are wrong.


Sorry. A Lawful Good character cannot tell a lie.

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 1:12 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote:
 rantingrick wrote:
 What he means is that On Mac, if you close all windows, the application is
 still running.

  Then that is NOT closing windows that is only ICONIFIYING/HIDING them.

 No, the windows really are closed. They no longer exist
 in any way. The application is still running, though, and
 its menu bar will appear if you bring it to the front
 (in MacOSX this is done by clicking on its dock icon;
 in classic MacOS it was done by selecting from the menu
 of running applications that was available in the top right
 corner of the screen).

Yes but what benefit does that gain over say, Tkinter's design
(because that has been your argument). I see no benefit at all. I can
destroy a GUI and still have a script run, but what's the point?

If you design a GRAPHICAL user interface, then once the GRAPHICAL part
is removed (window), why do need the main code to stick around? And if
you do, that fact has nothing to do with Tkinter and window hierarchy.
I think we've gone completely off topic here.

Is this another community strawman contest?
Are we mass producing these things now?

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
wow, tx y'all!

I forgot to mention that hashlib itself is not required; I could also
use Brand X. But y'all agree that blocking up the file in python adds
no overhead to hashing each block in C, so hashlib in a loop it is!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Secure ssl connection with wrap_socket

2011-07-06 Thread Jean-Paul Calderone
On Jul 6, 4:44 am, AndDM anddima...@gmail.com wrote:
 On Jul 5, 4:08 pm, Jean-Paul Calderone calderone.jeanp...@gmail.com
 wrote:



  On Jul 5, 4:52 am, Andrea Di Mario anddima...@gmail.com wrote:

   Hi, I'm a new python user and I'm writing a small web service with ssl.
   I want use a self-signed certificate like in 
   wiki:http://docs.python.org/dev/library/ssl.html#certificates
   I've used wrap_socket, but if i try to use
   cert_reqs=ssl.CERT_REQUIRED, it doesn't work with error:

   urllib2.URLError: urlopen error _ssl.c:326: No root certificates
   specified for verification of other-side certificates.

   It works only with CERT_NONE (the default) but with this option i
   could access to the service in insicure mode.

   Have you some suggestions for my service?

  Also specify some root certificates to use in verifying the peer's
  certificate.  Certificate verification works by proceeding from a
  collection of root certificates which are explicitly trusted.  These
  are used to sign other certificates (which may in turn be used to sign
  others, which in turn...).  The process of certificate verification is
  the process of following the signatures from the certificate in use by
  the server you connect to back up the chain until you reach a root
  which you have either decided to trust or not.  If the signatures are
  all valid and the root is one you trust, then you have established a
  connection to a trusted entity.  If any signature is invalid, or the
  root is not one you trust, then you have not.

  The root certificates are also called the ca certificates or
  certificate authority certificates.  `wrap_socket` accepts a
  `ca_certs` argument.  
  Seehttp://docs.python.org/library/ssl.html#ssl-certificates
  for details about that argument.

  Jean-Paul

 Hi Jean-Paul, i thought that with self-signed certificate i shouldn't
 use ca_certs option. Now, i've created a ca-authority and i use this
 command:

  self.sock = ssl.wrap_socket(sock, certfile = ca/certs/
 myfriend.cert.pem, keyfile = ca/private/myfriend.key.pem,
 ca_certs=/home/andrea/ca/certs/cacert.pem,
 cert_reqs=ssl.CERT_REQUIRED)

 When i use the some machine as client-server it works, but, when i use
 another machine as client, i've this:

 Traceback (most recent call last):
   File loginsender.py, line 48, in module
     handle = url_opener.open('https://debian.andrea.it:10700/%s+%s'%
 (DATA,IPIN))
   File /usr/lib/python2.6/urllib2.py, line 391, in open
     response = self._open(req, data)
   File /usr/lib/python2.6/urllib2.py, line 409, in _open
     '_open', req)
   File /usr/lib/python2.6/urllib2.py, line 369, in _call_chain
     result = func(*args)
   File loginsender.py, line 33, in https_open
     return self.do_open(self.specialized_conn_class, req)
   File /usr/lib/python2.6/urllib2.py, line 1145, in do_open
     raise URLError(err)
 urllib2.URLError: urlopen error [Errno 185090050] _ssl.c:328: error:
 0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

 I see that i should create a certificate with server, client and ca
 autority, but i haven't clear the ca_certs option and which path i
 should use.
 Have you any suggestion?

You need to have the CA certificate on any machine that is going to
verify the certificate used on the SSL connection.  The path just
needs to be the path to that CA certificate on the client machine.

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Steven D'Aprano
rantingrick wrote:

 If you design a GRAPHICAL user interface, then once the GRAPHICAL part
 is removed (window), why do need the main code to stick around? 

Open your mind to ideas that go beyond your simple window-centric paradigm!
There is more to graphical user interfaces than windows!

In the Mac OS GUI, an application can have a menubar and no windows. Windows
come and go as needed, but the menubar stays until the users quits the
application.

In the Unix/Linux world, there is a graphical application called xkill which
has no menus and no windows, all it has is a mouse cursor! No, it does not
run in the background: it is a foreground app.

An extreme case, but telling. There is no absolute need for any windows at
all, let alone for one privileged window to rule all the others.


-- 
Steven

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


Re: Extracting property getters from dir() results

2011-07-06 Thread Gnarlodious
On Jul 6, 3:35 am, Christian Heimes wrote:

Thank you! Exactly what I wanted.

-- Gnarlie
http://Gnarlodious.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx MenuItem - icon is missing

2011-07-06 Thread Laszlo Nagy



Under windows, this displays the icon for the popup menu item. Under GTK it 
doesn't and there is no error message, no exception.


I get different results than you.

Under Ubuntu 9.04 w with wx 2.8.9.1, when I right click I see a menu item 
called test with little icon of a calculator or something.

Under OS X 10.6 with wx 2.8.12.0 and Win XP with wx 2.8.10.1, when I right 
click I get this --

Traceback (most recent call last):
   File x.py, line 46, in onPopupMenu
 item = wx.MenuItem(None,-1,uTest)
   File 
/usr/local/lib/wxPython-unicode-2.8.12.0/lib/python2.6/site-packages/wx-2.8-mac-unicode/wx/_core.py,
 line 11481, in __init__
 _core_.MenuItem_swiginit(self,_core_.new_MenuItem(*args, **kwargs))
wx._core.PyAssertionError: C++ assertion parentMenu != NULL failed at 
/BUILD/wxPython-src-2.8.12.0/src/common/menucmn.cpp(389) in wxMenuItemBase(): menuitem 
should have a menu
I guess I'll have to write to the wxPython mailing list. Seriously, 
adding a simple menu to something is supposed to be platform 
independent, but we got four different results on four systems. :-(


Thank you for trying out though.


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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Steven D'Aprano
rantingrick wrote:

 On Jul 6, 6:44 am, Steven D'Aprano steve
 +comp.lang.pyt...@pearwood.info wrote:
 
 A control structure is a structure which controls the program flow.
 Control structures include:

 * jumps (goto, gosub, comefrom, exceptions, break, continue)

 * loops (for, while, repeat...until)

 * conditional branches (if, case/switch)
 
 ---
 THIS CODE RESULTS IN A CONTROL STRUCTURE!
 
 -- lst.sort(lambda x,y: cmp(x[1], y[1]))

No it doesn't.

How does it change the program flow? You call the sort method, it sorts, and
execution continues at the next statement. Regardless of whether you supply
a cmp function or not, the program flow is identical:

ENTER SORT ROUTINE
PERFORM SORTING
EXIT SORT ROUTINE

There is no control transferred. It is a linear program flow: in, do the
job, out again. Since it doesn't modify the program flow, it is not a
control structure.

Perform sorting is a black box. It could have loops, branches,
unconditional exists. It could have COMEFROM statements up the wazoo, if it
were implemented in a language with COMEFROM (like Intercal). None of that
matters two bits: the caller cannot use sort to modify the execution
sequence around it, therefore it's not a control structure. No matter how
much the sort routine jumps around internally, you can't use that change
program flow around it.

print surely is implemented with a loop: it has to loop over a string and
write it to stdout. Would you say that therefore print is a control
structure:

ENTER PRINT STATEMENT
PERFORM PRINTING
EXIT PRINT STATEMENT

One entry, one exit.



-- 
Steven

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


interactive plots

2011-07-06 Thread Mihai Badoiu
How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
and I want in the plot to be able to click on f and make it disappear.  Any
python library that does this?

thanks,

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


trouble creating tooltips using Wx in Tk canvas

2011-07-06 Thread Ravikanth
Hi all,
Hi all,

I am having a trouble creating tooltips. I am trying to embed a
matplotlib graph inside  a TkInter canvas. After some search over the
net, I found out a way to create tooltips using the WXbackend.
But when I embed my matplotlib figure inside a Tk and  the tooltips
are not getting displayed.
The error I am getting is below.

Traceback (most recent call last):
  File U:\graphing_tool\plotinsideTkInter\plotInTk.py, line 12, in
module
tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n'
% (' '*100)) # needs to be added to getover the bug with tooltip.
  File C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_misc.py,
line 771, in __init__
_misc_.ToolTip_swiginit(self,_misc_.new_ToolTip(*args, **kwargs))
PyNoAppError: The wx.App object must be created first!

I am not able to figure out the reason. I am trying to use IDLE for
running the script using python 2.7. I tried running from commandline
as well but still i face the same error. Following is the piece of
code I have used.
I created a simple 'sin' wave using matplotlib. and a  button. Added
them to a TkFrame.
and then binded the code using

self.f.canvas.mpl_connect('motion_notify_event',_onMotion)

to '_onMotion' function, where I am printing the toooltip.

Can somebody please help me solving the issue.

Code I have used is below.

#!/usr/apps/Python/bin/python
import matplotlib, sys
matplotlib.use('WXAgg')
matplotlib.interactive(False)
import numpy as np
from numpy import arange, sin, pi
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import wx
import Tkinter
tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n' %
(' '*100))
 # needs to be added to getover the bug with tooltip.

def alt():
print 'My Button'

def _onMotion(event):
print Xvalue:,event.xdata, Yvalue:,event.ydata
tip= Xvalue:{0}, Yvalue: {1}.format(event.xdata,event.ydata)
tooltip.SetTip(tip)
tooltip.Enable(True)

class  myClass(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
#global _onMotion
self.parent=parent

self.buildFigure()

def buildFigure(self):

self.f=plt.figure()
self.f = plt.figure(figsize=(5,4))
self.a = self.f.add_subplot(111)
self.t =
np.array([0.01,0.02,0.03,0.04,0.05,0.07,0.09,1.7,1.9,2.3,2.5,2.7,2.9])
self.s = sin(2*pi*self.t)
self.a.plot(self.t,self.s)


self.dataPlot = FigureCanvasTkAgg(self.f, master=self)
self.f.canvas.mpl_connect('motion_notify_event',_onMotion)
self.dataPlot.get_tk_widget().pack(side='top', fill='both')
self.toolbar = NavigationToolbar2TkAgg( self.dataPlot, self )
self.toolbar.update()
self.toolbar.pack()


self.btn=Tkinter.Button(self, text='btton',command=alt)
self.btn.pack(ipadx=250)

def alt (self):
print 9

if __name__ == __main__:
app = myClass(None)
app.title('Embedding in Tk')
app.mainloop()

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 9:32 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 rantingrick wrote:
  If you design a GRAPHICAL user interface, then once the GRAPHICAL part
  is removed (window), why do need the main code to stick around?

 Open your mind to ideas that go beyond your simple window-centric paradigm!

Correction: Window-Centric GUI paradigm! BIG DIFFERENCE.

 There is more to graphical user interfaces than windows!

OMG, you mean like, widgets? Whoa! Tell me more, Tell me more!

 In the Mac OS GUI, an application can have a menubar and no windows. Windows
 come and go as needed, but the menubar stays until the users quits the
 application.

That's just window visibility (whether by hiding or destroying) under
the veil of a detached UI window manager bar and has nothing to do
with window hierarchy. Your half stuffed straw men are leaking like a
sieve Steven.

 In the Unix/Linux world, there is a graphical application called xkill which
 has no menus and no windows, all it has is a mouse cursor! No, it does not
 run in the background: it is a foreground app.

Wow nice corner case. Can you come up with at least five of them
though? You and I both know that the vast majority of GUI's require
visible windows.

But wait! What is a GUI WINDOW exactly?

I'll tell you in the simplest terms i can muster... GUI windows are
an abstraction and nothing more. A GUI window is nothing more than an
imaginary area of the screen that can be drawn to. This area has
borders that define it. No not visible borders but two dimensional
spacial borders. THAT'S IT! The area could be 1x1 pixels OR the entire
screen space, OR even larger!

Most time you want the user to see the boundaries of this abstraction
(window) space and so the GUI library draws borders that represent
this boundary. Your supposedly windowless xkill application is not
windowless at all; THE WINDOW BOUNDARIES ARE JUST NOT DRAWN! The
window is the entire screen space OR IS JUST THE DESKTOP SPACE (same
thing)

 An extreme case, but telling. There is no absolute need for any windows at
 all, let alone for one privileged window to rule all the others.

Again your fear of losing imaginary freedoms is acting out again.
And your veiled attempts to link root GUI windows and Sauron (the
great antagonist of LOTH) is quite entertaining. Next you'll suggest
that root windows are really just a great eye, lidless,  and wreathed
in flame and that i am Saruman building an army of Orc followers hell
bent on destroying the freedom to believe self serving fantasies.

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Neil Cerutti
On 2011-07-06, Chris Angelico ros...@gmail.com wrote:
 On Wed, Jul 6, 2011 at 11:41 PM, rantingrick
 rantingr...@gmail.com wrote:
 Give it up man and admit i am correct and you are wrong.

 Sorry. A Lawful Good character cannot tell a lie.

Lawful Good characters have a hard time coexisting with the
Chaotic Neutrals.

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


Re: wx MenuItem - icon is missing

2011-07-06 Thread Philip Semanchuk

On Jul 6, 2011, at 2:25 AM, Laszlo Nagy wrote:

 
 Under windows, this displays the icon for the popup menu item. Under GTK it 
 doesn't and there is no error message, no exception.
 
 I get different results than you.
 
 Under Ubuntu 9.04 w with wx 2.8.9.1, when I right click I see a menu item 
 called test with little icon of a calculator or something.
 
 Under OS X 10.6 with wx 2.8.12.0 and Win XP with wx 2.8.10.1, when I right 
 click I get this --
 
 Traceback (most recent call last):
   File x.py, line 46, in onPopupMenu
 item = wx.MenuItem(None,-1,uTest)
   File 
 /usr/local/lib/wxPython-unicode-2.8.12.0/lib/python2.6/site-packages/wx-2.8-mac-unicode/wx/_core.py,
  line 11481, in __init__
 _core_.MenuItem_swiginit(self,_core_.new_MenuItem(*args, **kwargs))
 wx._core.PyAssertionError: C++ assertion parentMenu != NULL failed at 
 /BUILD/wxPython-src-2.8.12.0/src/common/menucmn.cpp(389) in 
 wxMenuItemBase(): menuitem should have a menu
 I guess I'll have to write to the wxPython mailing list. Seriously, adding a 
 simple menu to something is supposed to be platform independent, but we got 
 four different results on four systems. :-(

I can understand why it's frustrating but a menu items with icons on them 
aren't exactly common, so you're wandering into territory that's probably not 
so throughly explored (nor standard across platforms). Now that I think about 
it, I don't know that I've ever seen one under OSX, and I don't even know if 
it's supported at all.

Me, I would start by addressing the error in the traceback. wx doesn't seem 
happy with an orphan menu item; why not create a wx.Menu and assign the menu 
item to that? It might solve your icon problem; you never know.

In defense of wxPython, we have three wx apps in our project and they contain 
very little platform-specific code. To be fair, we've had to rewrite some code 
after we found that it worked on one platform but not another, but generally 
we're able to find code that works on all platforms. We have only a couple of 
places where we were forced to resort to this kind of thing:

   if wx.Platform == __WXGTK__:
  do X
   elif wx.Platform == __WXMAC__:
  do Y
   etc.


 Thank you for trying out though.

You're welcome. VirtualBox helped.


bye
Philip



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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread rantingrick
On Jul 6, 9:55 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 rantingrick wrote:
  ---
  THIS CODE RESULTS IN A CONTROL STRUCTURE!

  -- lst.sort(lambda x,y: cmp(x[1], y[1]))

 No it doesn't.

 How does it change the program flow? You call the sort method, it sorts, and
 execution continues at the next statement. Regardless of whether you supply
 a cmp function or not, the program flow is identical:

Not identical. The sort called WITHOUT a cmp argument will sort in a
predefined manner. The sort called WITH a cmp argument can modify the
existing code block in a way that suits a users desired result. A USER
DEFINED CONTROL STRUCTURE. Just because this realization breaks the
mold of everything you hold dear about user defined control structures
does not mean it is incorrect. For some reason you are religious about
this subject. Could it be that you are wrong?

 ENTER SORT ROUTINE
 PERFORM SORTING
 EXIT SORT ROUTINE

True for the non-modified case.

False for the modified one...

 ENTER SORT ROUTINE
 PERFORM SORTING BASED ON USER DEFINED CONTROL
 EXIT SORT ROUTINE

 There is no control transferred. It is a linear program flow: in, do the
 job, out again. Since it doesn't modify the program flow, it is not a
 control structure.

So you are telling me that calling cmp(itemsA[idx], itemsB[idx]) is
exactly the same as cmp(itemsA[idx][-1], itemsB[idx[-1])? Please show
proof of this in code. You have just witnessed the power of user
defined control structures and it has rocked your little world. You
believed UDCS to be evil, all the while oblivious to your own everyday
usage of them. Now that's ironic. Cruel or poetic, you be the judge.

 Perform sorting is a black box. It could have loops, branches,
 unconditional exists. It could have COMEFROM statements up the wazoo, if it
 were implemented in a language with COMEFROM (like Intercal). None of that
 matters two bits: the caller cannot use sort to modify the execution
 sequence around it, therefore it's not a control structure. No matter how
 much the sort routine jumps around internally, you can't use that change
 program flow around it.

The jumping(sic) around is controlled by a user defined spec. The
user is in control. The user made the definition. The cmp function
just implemented it.

 print surely is implemented with a loop: it has to loop over a string and
 write it to stdout. Would you say that therefore print is a control
 structure:

 ENTER PRINT STATEMENT
 PERFORM PRINTING
 EXIT PRINT STATEMENT

Nope. Print only takes an argument and spits out the result to
stdout.write. Print is an abstraction API for system.stdout.write, and
nothing more.

 One entry, one exit.
As evident from all the BS you spew on a daily basis, apparently YOU
have one entry and one exit!

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
Tx, all!. But...

 For example I use this function to copy a stream and return a SHA512 and
 the output streams size:

     def write(self, in_handle, out_handle):
         m = hashlib.sha512()
         data = in_handle.read(4096)
         while True:
             if not data:
                 break
             m.update(data)
             out_handle.write(data)
             data = in_handle.read(4096)
         out_handle.flush()
         return (m.hexdigest(), in_handle.tell())

The operation was a success but the patient died.

My version of that did not return the same hex digest as the md5sum
version:


def file_to_hash(path, m = hashlib.md5()):

with open(path, 'r') as f:

s = f.read(8192)

while s:
m.update(s)
s = f.read(8192)

return m.hexdigest()

You'll notice it has the same control flow as yours.

That number must eventually match an iPad's internal MD5 opinion of
that file, after it copies up, so I naturally cannot continue working
this problem until we see which of the two numbers the iPad likes!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-06 Thread Steven D'Aprano
rantingrick wrote:

 In the Mac OS GUI, an application can have a menubar and no windows.
 Windows come and go as needed, but the menubar stays until the users
 quits the application.
 
 That's just window visibility (whether by hiding or destroying) under
 the veil of a detached UI window manager bar and has nothing to do
 with window hierarchy.

If all the windows are destroyed, and the application still is running and
active, where is your window hierarchy?



The Dead Window Sketch
==

(with apologies to Monty Python)

Customer enters a pet shop.
Customer:  'Ello, I wish to register a complaint.
Owner: We're closin' for lunch.
Customer:  Never mind that, my lad. I wish to complain about this GUI 
   window what I purchased not half an hour ago from this very
   boutique.
Owner: Oh yes, the Norwegian Blue. What's wrong with it?
Customer:  I'll tell you what's wrong with it, my lad. It's deleted, 
   that's what's wrong with it!
Owner: No, no, it's resting!
Customer:  Look, matey, I know a deleted window when I see one, and I'm 
   looking at one right now.
Owner: No no it's not deleted, it's restin'! Remarkable window, the
   Norwegian Blue. Beautiful widgets!
Customer:  The widgets don't enter into it. It's completely destroyed.
Owner: Nononono, no, no! It's resting!
Customer:  All right then, if it's restin', I'll wake it up!
   (shouting at the screen) 'Ello, Mister Wally Window! I've got
   a lovely fresh icon for you if you show...
(owner hits the screen)
Owner: There, it refreshed!
Customer:  No, it didn't, that was you hitting the screen!
Owner: I never!!
Customer:  Yes, you did!
Owner: I never, never did anything...
Customer:  (yelling and hitting the screen repeatedly) 'ELLO WINDOW!!!
   WAKEY WAKEY! This is your notification signal!!!
   (takes the window out of the screen and thumps its title bar 
   on the counter. Throws it up in the air and watches it plummet 
   to the floor.)
Customer:  Now that's what I call a dead window.
Owner: No, no... No, it's stunned!
Customer:  STUNNED?!?
Owner: Yeah! You stunned it, just as it was maximising! Norwegian 
   Blues stun easily.
Customer:  Now look, mate, I've definitely 'ad enough of this! That 
   window is definitely deleted, and when I purchased it not 
   'alf an hour ago, you assured me that its lack of an entry 
   in the task bar was due to it bein' tired and shagged out 
   following a long refresh!
Owner: Well, it's... probably pining for the fjords.
Customer:  PININ' for the FJORDS?!?!?!? What kind of talk is that? Look,
   why did it fall flat on its back the moment I got it home?
Owner: The Norwegian Blue prefers being minimised on its back! 
   Remarkable bird, i'nit, squire? Lovely scroll bars!
Customer:  Look, I took the liberty of examining that window when I 
   got it home, and I discovered the only reason that the 
   window was still visible in the first place was that it 
   had been NAILED there.
(pause)
Owner: Well, o'course it was nailed there! If I hadn't nailed that 
   window down, it would have nuzzled up to those pixels, bent 
   'em apart with its cursor, and VOOM! Feeweeweewee!
Customer:  VOOM?!? Mate, this window wouldn't voom if you put four 
   million volts through it! Its bleedin' memory is reclaimed!
Owner: No no! It's pining!
Customer:  It's not pinin'! It's purged! This window is no more! It's
   pointer has ceased to be! It's expired and gone to meet the
   memory manager! Bereft of bytes, it rests in peace! If you 
   hadn't nailed it to the screen it'd be a Flash animation in 
   a browser by now! It's callbacks are now 'istory! Its ref 
   count is zero! It's called the garbage collector, its blocks
   have been cleared, shuffled off this mortal coil, run down 
   the curtain and joined the bleedin' choir invisibile!! THIS 
   IS AN EX-WINDOW!!
(pause)
Owner: Well, I'd better replace it, then.
(he takes a quick peek behind the counter)
Owner: Sorry squire, I've had a look 'round the back of the shop, and 
   uh, we're right out of windows.
Customer:  I see. I see, I get the picture.
Owner: I got a DOS batch file.
(pause)
Customer:  (sweet as sugar) Pray, does it talk?
Owner: Yes.
Customer:  Right, I'll have that one then.




-- 
Steven

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Chris Angelico
On Thu, Jul 7, 2011 at 1:10 AM, rantingrick rantingr...@gmail.com wrote:
 On Jul 6, 9:32 am, Steven D'Aprano steve
 +comp.lang.pyt...@pearwood.info wrote:
 Open your mind to ideas that go beyond your simple window-centric paradigm!

 Correction: Window-Centric GUI paradigm! BIG DIFFERENCE.

 There is more to graphical user interfaces than windows!

 OMG, you mean like, widgets? Whoa! Tell me more, Tell me more!

Okay, Window-Centric GUI Paradigm. There's still more to it than
windows and widgets and mouse cursors and so on. Underneath it all is
CODE.

In some graphical applications, the code is relatively trivial. A
desktop calculator is just there to get input graphically and give
output graphically. In those, once you destroy the window, you may as
well terminate the application.

But in others the code drastically outweighs the windowing work. I
don't have a good example handy, but I have a bad example; our
(antique) accounting package has an hours-long year end process that
we do at the beginning of each July, and it chugs through its database
work while painting a pretty animation of a hand scribing a book. It
would be far more efficient to simply close the window and proceed
with the work; but the window was necessary for collecting certain
parameters from the user, prior to the start of the long job.

There's more to a windowed program than its window.

 In the Mac OS GUI, an application can have a menubar and no windows. Windows
 come and go as needed, but the menubar stays until the users quits the
 application.

 That's just window visibility (whether by hiding or destroying) under
 the veil of a detached UI window manager bar and has nothing to do
 with window hierarchy. Your half stuffed straw men are leaking like a
 sieve Steven.

It can be implemented with window visibility. That's not the same
thing. If I want to be in Sydney tomorrow, I want to cease existing
here and begin existing there. That can be implemented by burning
petrol in an internal combustion engine and turning some rubber
wheels. If I turn up in Sydney tomorrow, and argue vehemently that I
did not drive, are you going to insist that I did, or would you accept
that perhaps I took a train instead?

 In the Unix/Linux world, there is a graphical application called xkill which
 has no menus and no windows, all it has is a mouse cursor! No, it does not
 run in the background: it is a foreground app.

 Wow nice corner case. Can you come up with at least five of them
 though? You and I both know that the vast majority of GUI's require
 visible windows.

Five corner cases. Okay. One is xkill; if I can find four more, we run
out of corners and they're not corner cases any more - is that it?

1) See above.
2) Win2VNC. Doesn't actually paint a window on the screen, it just
watches where the mouse goes - move the mouse off the edge of the
screen, and it wraps and hides it. Very cool.
3) Firewall software with a graphical config notebook. I think
ZoneAlarm actually just hides its window, but that's not strictly
necessary. (My preferred firewall setup, though, has no GUI at all -
iptables etc is all I need.)
4) Clipboard Converter. An old app that I wrote a while ago that,
whenever you copy anything to the clipboard, runs it through a script
and puts the result back on the clipboard. Handier than you might
think.
5) Hotkey manager. It watches for keystrokes and replaces them with
other actions. Implemented as an input hook with injection facilities.

Enjoy.

 But wait! What is a GUI WINDOW exactly?

 I'll tell you in the simplest terms i can muster... GUI windows are
 an abstraction and nothing more.

*Everything* in a computer is an abstraction. People are fond of
saying that computers only work with 1s and 0s - that's not strictly
true, those numbers represent electrical signals. And those electrical
signals represent data which usually carries information. It's turtles
all the way down.

 A GUI window is nothing more than an
 imaginary area of the screen that can be drawn to. This area has
 borders that define it. No not visible borders but two dimensional
 spacial borders. THAT'S IT! The area could be 1x1 pixels OR the entire
 screen space, OR even larger!

Leaving off the imaginary, all you're saying is that a window is a
rectangular area of screen. That's not quite true; not all
windows/widgets have a painting area. A window is an object - and that
object can choose to request certain resources, including a portion of
its parent window's painting area if desired. (A top-level window's
parent is either a Screen or a Desktop, depending on your
implementation.)

 Most time you want the user to see the boundaries of this abstraction
 (window) space and so the GUI library draws borders that represent
 this boundary. Your supposedly windowless xkill application is not
 windowless at all; THE WINDOW BOUNDARIES ARE JUST NOT DRAWN! The
 window is the entire screen space OR IS JUST THE DESKTOP SPACE (same
 thing)

Boundaries have nothing to 

Re: Does hashlib support a file mode?

2011-07-06 Thread Peter Otten
Phlip wrote:

 Tx, all!. But...
 
 For example I use this function to copy a stream and return a SHA512 and
 the output streams size:

 def write(self, in_handle, out_handle):
 m = hashlib.sha512()
 data = in_handle.read(4096)
 while True:
 if not data:
 break
 m.update(data)
 out_handle.write(data)
 data = in_handle.read(4096)
 out_handle.flush()
 return (m.hexdigest(), in_handle.tell())
 
 The operation was a success but the patient died.
 
 My version of that did not return the same hex digest as the md5sum
 version:
 
 
 def file_to_hash(path, m = hashlib.md5()):
 
 with open(path, 'r') as f:
 
 s = f.read(8192)
 
 while s:
 m.update(s)
 s = f.read(8192)
 
 return m.hexdigest()
 
 You'll notice it has the same control flow as yours.
 
 That number must eventually match an iPad's internal MD5 opinion of
 that file, after it copies up, so I naturally cannot continue working
 this problem until we see which of the two numbers the iPad likes!

- Open the file in binary mode.
- Do the usual dance for default arguments:
def file_to_hash(path, m=None):
if m is None:
m = hashlib.md5()


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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 12:49 AM, Ulrich Eckhardt
ulrich.eckha...@dominolaser.com wrote:
 Mel wrote:
 In wx, many of the window classes have Create methods, for filling in
 various attributes in two-step construction.  I'm not sure why, because
 it works so well to just supply all the details when the class is called
 and an instance is constructed.  Maybe there's some C++ strategy that's
 being supported there.

 Just guessing, is it legacy, C-with-classes code rather than C++ code
 perhaps? Haven't looked at wx for a while. Such code typically lacks
 understanding of exceptions, which are the only way to signal failure from
 e.g. constructors.

No, wx is C++ through and through.  For the why of it, see:

http://wiki.wxpython.org/TwoStageCreation

The More Details section is particularly illuminating.
-- 
http://mail.python.org/mailman/listinfo/python-list


Javacv / google apps

2011-07-06 Thread PyNewbie
Hi,

Is it possible to use JavaCV with Google apps engine?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Mel
Ian Kelly wrote:

 On Wed, Jul 6, 2011 at 12:49 AM, Ulrich Eckhardt
 ulrich.eckha...@dominolaser.com wrote:
 Mel wrote:
 In wx, many of the window classes have Create methods, for filling in
 various attributes in two-step construction.  I'm not sure why,
 because it works so well to just supply all the details when the class
 is called and an instance is constructed.  Maybe there's some C++
 strategy that's being supported there.

 Just guessing, is it legacy, C-with-classes code rather than C++ code
 perhaps? Haven't looked at wx for a while. Such code typically lacks
 understanding of exceptions, which are the only way to signal failure
 from e.g. constructors.
 
 No, wx is C++ through and through.  For the why of it, see:
 
 http://wiki.wxpython.org/TwoStageCreation
 
 The More Details section is particularly illuminating.

Yes, it is.  Many thanks.

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
 - Open the file in binary mode.

I had tried open(path, 'rb') and it didn't change the wrong number.

And I added --binary to my evil md5sum version, and it didn't change
the right number!

Gods bless those legacy hacks that will never die, huh? But I'm using
Ubuntu (inside VMWare, on Win7, on a Core i7, because I rule), so that
might explain why binary mode is a no-op.

 - Do the usual dance for default arguments:
     def file_to_hash(path, m=None):
         if m is None:
             m = hashlib.md5()

Not sure why if that's what the defaulter does? I did indeed get an
MD5-style string of what casually appeared to be the right length, so
that implies the defaulter is not to blame...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-06 Thread Andrew Berg
On 2011.07.06 11:11 AM, Steven D'Aprano wrote:
 The Dead Window Sketch
 ==
As much as I hate it when people feed trolls, that was pretty funny.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread Teemu Likonen
* 2011-07-06T06:41:52-07:00 * rantingr...@gmail.com wrote:

 I am using a user defined spec as an argument to the cmp function.
 That spec then modifies the body of the compare function and creates a
 user defined control structure. You can argue all day that it is not a
 user defined control structure but no one is going to believe you.

I won't argue all day, I'll just show you an example of a user defined
control structure. This is like the standard (DOTIMES (VAR COUNT) BODY)
macro expect that it executes BODY forms first forwards and then
backwards. The iterator variable VAR goes first up from 0 and then down
to 0.


(defmacro ping-pong-iterator ((var count optional result)
  body body)
  `(progn (loop for ,var from 0 below ,count
do (progn ,@body))
  (loop for ,var from (1- ,count) downto 0
do (progn ,@(reverse body))
finally (return ,result


CL-USER (ping-pong-iterator (i 3 ready)
   (format t form 1: ~A~% i)
   (format t form 2: ~A~% i)
   (format t form 3: ~A~% i)
   (format t ~%))
form 1: 0
form 2: 0
form 3: 0

form 1: 1
form 2: 1
form 3: 1

form 1: 2
form 2: 2
form 3: 2


form 3: 2
form 2: 2
form 1: 2

form 3: 1
form 2: 1
form 1: 1

form 3: 0
form 2: 0
form 1: 0
= ready
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-06 Thread Waldek M.
Dnia Wed, 6 Jul 2011 08:10:27 -0700 (PDT), rantingrick napisał(a):
 In the Unix/Linux world, there is a graphical application called xkill which
 has no menus and no windows, all it has is a mouse cursor! No, it does not
 run in the background: it is a foreground app.
 
 Wow nice corner case. Can you come up with at least five of them
 though? You and I both know that the vast majority of GUI's require
 visible windows.

- 90% of MS DOS games; should I list them here? ;-)
- M$ Windows taskbar-only applications
- Linux apps using framebuffer but not X

One could argue that the second and the third case are - in one
way or another - using windows. But not the first case, and I don't think
you'd call them GUI-less.

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


Re: interactive plots

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 9:04 AM, Mihai Badoiu mbad...@gmail.com wrote:
 How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
 and I want in the plot to be able to click on f and make it disappear.  Any
 python library that does this?

Matplotlib can be integrated with either wxPython or PyQt to create
GUI applications with interactive plots.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Peter Otten
Phlip wrote:

 - Open the file in binary mode.
 
 I had tried open(path, 'rb') and it didn't change the wrong number.
 
 And I added --binary to my evil md5sum version, and it didn't change
 the right number!
 
 Gods bless those legacy hacks that will never die, huh? But I'm using
 Ubuntu (inside VMWare, on Win7, on a Core i7, because I rule), so that
 might explain why binary mode is a no-op.

Indeed. That part was a defensive measure mostly meant to make your function 
Windows-proof.

 - Do the usual dance for default arguments:
 def file_to_hash(path, m=None):
 if m is None:
 m = hashlib.md5()
 
 Not sure why if that's what the defaulter does? I did indeed get an
 MD5-style string of what casually appeared to be the right length, so
 that implies the defaulter is not to blame...

The first call will give you the correct checksum, the second: not. As the 
default md5 instance remembers the state from the previous function call 
you'll get the checksum of both files combined. 

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Tim Chase

On 07/06/2011 11:24 AM, Chris Angelico wrote:

On Thu, Jul 7, 2011 at 1:10 AM, rantingrickrantingr...@gmail.com  wrote:

Wow nice corner case. Can you come up with at least five of them
though? You and I both know that the vast majority of GUI's require
visible windows.


Five corner cases. Okay. One is xkill; if I can find four more, we run
out of corners and they're not corner cases any more - is that it?

1) See above.
2) Win2VNC. Doesn't actually paint a window on the screen, it just
watches where the mouse goes - move the mouse off the edge of the
screen, and it wraps and hides it. Very cool.
3) Firewall software with a graphical config notebook. I think
ZoneAlarm actually just hides its window, but that's not strictly
necessary. (My preferred firewall setup, though, has no GUI at all -
iptables etc is all I need.)
4) Clipboard Converter. An old app that I wrote a while ago that,
whenever you copy anything to the clipboard, runs it through a script
and puts the result back on the clipboard. Handier than you might
think.
5) Hotkey manager. It watches for keystrokes and replaces them with
other actions. Implemented as an input hook with injection facilities.


6) possibly xneko (just mouse-cursor amusements)

7) screen-shot/print-screen software (several such as scrot 
don't have an actual window, just a process that interacts with 
the other windows)


8) AutoHotkey and other keystroke-monitors (or 
mouse-gesture-monitors) to expand text, send key-sequences, 
launch programs, reconfigure windows, signal changes in 
display-configuration, etc


9) other clipboard utilities such as xclip or multi-clipboard 
functionality


10) DPMI screen-savers (that only listen for key/mouse activity 
and send a blank-screen signal to the monitor after a given 
period of inactivity)


I think there are sufficiently many edge cases this 
formerly-square room is starting to look round...




I regret that I am now in the position of following an awesome post
with a somewhat mediocre one. Steven, the Dead Window Sketch is
awesome!


agreed :)

-tkc


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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Steven D'Aprano
Andrew Berg wrote:

 On 2011.07.06 11:11 AM, Steven D'Aprano wrote:
 The Dead Window Sketch
 ==
 As much as I hate it when people feed trolls, that was pretty funny.

Thanks.

Re the troll-feeding, every few months I get a strange seizure in my brain
that compels me to interact with rantingrick and try to treat him
seriously. It never ends well, he always ends up back in my killfile.

Call it the triumph of hope over experience.



-- 
Steven

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Chris Angelico
Five more good entries (though I think #8 and #9 are mostly covered
already). But hey, we have at least an octagon to work in.

On Thu, Jul 7, 2011 at 3:37 AM, Tim Chase python.l...@tim.thechases.com wrote:
 I think there are sufficiently many edge cases this formerly-square room is
 starting to look round...

The room is starting to look round? Eek, it might see us!

*flees*

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
  def file_to_hash(path, m=None):
  if m is None:
  m = hashlib.md5()

 The first call will give you the correct checksum, the second: not. As the
 default md5 instance remembers the state from the previous function call
 you'll get the checksum of both files combined.

Ouch. That was it.

Python sucks. m = md5() looks like an initial assignment, not a
special magic storage mode. Principle of least surprise fail, and
principle of most helpful default behavior fail.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Chris Torek
 - Do the usual dance for default arguments:
 def file_to_hash(path, m=None):
 if m is None:
 m = hashlib.md5()

[instead of

def file_to_hash(path, m = hashlib.md5()):

]

In article b317226a-8008-4177-aaa6-3fdc30125...@e20g2000prf.googlegroups.com
Phlip  phlip2...@gmail.com wrote:
Not sure why if that's what the defaulter does?

For the same reason that:

def spam(somelist, so_far = []):
for i in somelist:
if has_eggs(i):
so_far.append(i)
return munch(so_far)

is probably wrong.  Most beginners appear to expect this to take
a list of things that pass my has_eggs test, add more things
to that list, and return whatever munch(adjusted_list) returns ...
which it does.  But then they *also* expect:

result1_on_clean_list = spam(list1)
result2_on_clean_list = spam(list2)
result3_on_partly_filled_list = spam(list3, prefilled3)

to run with a clean so_far list for *each* of the first two
calls ... but it does not; the first call starts with a clean
list, and the second one starts with so_far containing all
the results accumulated from list1.

(The third call, of course, starts with the prefilled3 list and
adjusts that list.)

I did indeed get an MD5-style string of what casually appeared
to be the right length, so that implies the defaulter is not to
blame...

In this case, if you do:

print('big1:', file_to_hash('big1'))
print('big2:', file_to_hash('big2'))

you will get two md5sum values for your two files, but the
md5sum value for big2 will not be the equivalent of md5sum big2
but rather that of cat big1 big2 | md5sum.  The reason is
that you are re-using the md5-sum-so-far on the second call
(for file 'big2'), so you have the accumulated sum from file
'big1', which you then update via the contents of 'big2'.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive plots

2011-07-06 Thread Steven Howe

On 07/06/2011 09:59 AM, Ian Kelly wrote:

On Wed, Jul 6, 2011 at 9:04 AM, Mihai Badoiumbad...@gmail.com  wrote:

How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
and I want in the plot to be able to click on f and make it disappear.  Any
python library that does this?

Matplotlib can be integrated with either wxPython or PyQt to create
GUI applications with interactive plots.

PyGTK interface too.

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 11:11 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 The Dead Window Sketch
 ==

 [snip]


##
 The Roman Stawman Sketch
##

[cmp.lang.python]:
(The trolls are gathered and a righteous man speaks.)

GRACCHUS: For your guidance TrollCaesar, the Senate has prepared a
series of protocols to address the many problems in the community,
beginning with basic understanding of USER DEFINED CONTROL STRUCTURES,
which is already propagated wildly throughout the community and people
are suffering gravely from a misunderstanding. So if TrollCaesar…

(Obviously bored, Commodus is spinning his sword on its tip on the
marble floor.  He interrupts.)

COMMODUS: Shhh.  Don’t you see Gracchus?  That’s the very problem,
isn’t it?  You've spent all your time at study, at books, learning and
programming.  All the while my self aggrandizing has been forgotten by
the people.

(He rises and brings his sword to rest across his shoulders.  He
begins to pace.)

GRACCHUS: But comp.lang.python is the people, Sire, chosen from among
the people, a place to speak for the people.
COMMODUS: I doubt if many people know as much as you do Gracchus, or
have such splendid code bases, Gaius. I think I understand my own
people.
GRACCHUS: Then perhaps TrollCaesar would be so kind as to teach us,
out of his own extensive experience about the nature of USER DEFINED
CONTROL STRUCTURES.

(Laughter is heard from the other group members.)

COMMODUS: I call it lies. The people are my children and I their
father. I shall hold them to my bosom and embrace them tightly with
lies and propaganda.
GRACCHUS(interrupting): Have you ever embraced someone dying of
exceptions, Sire?

(Commodus stops pacing and turns to face Gracchus bringing his sword
down from his shoulder.)

COMMODUS: No, but if you interrupt me again, I assure you, that you
shall!

[INT. PALACE – COMMODUS CHAMBERS]:
(He is struggling to clear his conscience. Lucilla assists him.)

COMMODUS: Who would deign to lecture me?
LUCILLA: Commodus, the community has its uses.
COMMODUS: What uses?  All they do is talk. It should be just you and
me, and Guido.
LUCILLA: Don’t even think it.  There has always been a community.
COMMODUS: The community has changed. It takes an emperor to rule an
empire.
LUCILLA: Of course, but leave the people their (She hesitates,
searching for the right word.)
COMMODUS: Illusions?
LUCILLA: Traditions.
COMMODUS: My war against the righteous, they said it themselves, it
achieved nothing. But the minions loved me!
LUCILLA: Minions always love victories.
COMMODUS: Why? They didn’t see all the work that went into stuffing
those straw-men.
LUCILLA: They care about the entertainment.
COMMODUS: The Entertainment?  Well what is that?
LUCILLA: It’s a way to waste time, entertainment. Entertainment is a
vision.
COMMODUS: Exactly! A vision. Do you not see, Lucilla? I will give the
people a vision, a false vision and they will love me for it. And
they’ll soon forget the tedious sermonizing of a few honest group
members.

(He extends his hand to her and without hesitation, she accepts it.
Commodus raises her hand to his lips and kisses it.)

COMMODUS: I will give the people the greatest false vision of their
lives... Strawmen! Legions of them!

(A hand reaches out and opens a mail reader. It is Usenet. And a
thread called the Dead Window Sketch.  The splendor of his false
victory.)

[EXT. Rome – MARKET]:
(Gaius approaches Gracchus at an outdoor café (starbucks).  Gaius is
waving a leaflet advertising
“Comp.lang.python.Gladiators_Violante.”)

GAIUS: Straw-men. 150 days of Straw-men!
GRACCHUS: He’s cleverer than I thought.
GAIUS: Clever? The whole of cmp.lang.python would be laughing at him
if they weren't so afraid of his forked tongue.
GRACCHUS: Fear and wonder. A powerful combination.
GAIUS: You really think the people will be seduced by that?
GRACCHUS: I think he knows what comp.lang.python is. Comp.lang.python
is the mob. He will conjure comedy for them and they will be
distracted. He will take away their freedom to think with half stuffed
straw-men, and still they will roar. The beating heart of
comp.lang.python is not the halls of righteousness; it is the den of
minions.  He will give them tripe, and they will love him for it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble creating tooltips using Wx in Tk canvas

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 9:12 AM, Ravikanth vvnrk.vanapa...@gmail.com wrote:
 Hi all,
 Hi all,

 I am having a trouble creating tooltips. I am trying to embed a
 matplotlib graph inside  a TkInter canvas. After some search over the
 net, I found out a way to create tooltips using the WXbackend.
 But when I embed my matplotlib figure inside a Tk and  the tooltips
 are not getting displayed.

That's pretty much what I would expect, since wxPython and Tkinter are
completely different GUI libraries.  Trying to use them together is a
bit like trying to call a .NET function from Java -- maybe possible,
but it's going to take a lot of work.

 The error I am getting is below.

 Traceback (most recent call last):
  File U:\graphing_tool\plotinsideTkInter\plotInTk.py, line 12, in
 module
    tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n'
 % (' '*100)) # needs to be added to getover the bug with tooltip.
  File C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_misc.py,
 line 771, in __init__
    _misc_.ToolTip_swiginit(self,_misc_.new_ToolTip(*args, **kwargs))
 PyNoAppError: The wx.App object must be created first!

 I am not able to figure out the reason.

As it says, you haven't created the wx.App object necessary for pretty
much all wxPython code.  You could create one, but your tooltip still
would not work correctly because you would be running the Tkinter
event loop rather than the wxPython event loop.  If you want to use
the wxToolTip widget, then you should write your program to use
wxPython only.  Alternatively, googling for tkinter tooltip turns up
a couple of recipes; you could try one of those.

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Andrew Berg
On 2011.07.06 01:19 PM, rantingrick wrote:
 ##
  The Roman Stawman Sketch
 ##
Nice try, but you have to use a Monty Python sketch (and you have to
spell correctly :-P ).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Andrew Berg
On 2011.07.06 12:38 PM, Phlip wrote:
 Python sucks. m = md5() looks like an initial assignment, not a
 special magic storage mode. Principle of least surprise fail, and
 principle of most helpful default behavior fail.
func() = whatever the function returns
func = the function object itself (in Python, everything's an object)

Maybe you have Python confused with another language (I don't know what
exactly you mean by initial assignment). Typically one does not need
more than one name for a function/method. When a function/method is
defined, it gets created as a function object and occupies the namespace
in which it's defined.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
On Jul 6, 11:42 am, Andrew Berg bahamutzero8...@gmail.com wrote:
 On 2011.07.06 12:38 PM, Phlip wrote: Python sucks. m = md5() looks like an 
 initial assignment, not a
  special magic storage mode. Principle of least surprise fail, and
  principle of most helpful default behavior fail.

 func() = whatever the function returns
 func = the function object itself (in Python, everything's an object)

 Maybe you have Python confused with another language (I don't know what
 exactly you mean by initial assignment). Typically one does not need
 more than one name for a function/method. When a function/method is
 defined, it gets created as a function object and occupies the namespace
 in which it's defined.

If I call m = md5() twice, I expect two objects.

I am now aware that Python bends the definition of call based on
where the line occurs. Principle of least surprise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread geremy condra
On Wed, Jul 6, 2011 at 3:07 PM, Phlip phlip2...@gmail.com wrote:
 On Jul 6, 11:42 am, Andrew Berg bahamutzero8...@gmail.com wrote:
 On 2011.07.06 12:38 PM, Phlip wrote: Python sucks. m = md5() looks like an 
 initial assignment, not a
  special magic storage mode. Principle of least surprise fail, and
  principle of most helpful default behavior fail.

 func() = whatever the function returns
 func = the function object itself (in Python, everything's an object)

 Maybe you have Python confused with another language (I don't know what
 exactly you mean by initial assignment). Typically one does not need
 more than one name for a function/method. When a function/method is
 defined, it gets created as a function object and occupies the namespace
 in which it's defined.

 If I call m = md5() twice, I expect two objects.

 I am now aware that Python bends the definition of call based on
 where the line occurs. Principle of least surprise.

Python doesn't do anything to the definition of call. If you call
hashlib.md5() twice, you get two objects:

 import hashlib
 m1 = hashlib.md5()
 m2 = hashlib.md5()
 id(m1)
139724897544712
 id(m2)
139724897544880

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 12:36 PM, Andrew Berg bahamutzero8...@gmail.com wrote:
 On 2011.07.06 01:19 PM, rantingrick wrote:
 ##
  The Roman Stawman Sketch
 ##
 Nice try, but you have to use a Monty Python sketch (and you have to
 spell correctly :-P ).

Seriously.  The source he borrowed from is the movie Gladiator, which
isn't even a comedy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-06 Thread MRAB

On 06/07/2011 20:15, Ian Kelly wrote:

On Wed, Jul 6, 2011 at 12:36 PM, Andrew Bergbahamutzero8...@gmail.com  wrote:

On 2011.07.06 01:19 PM, rantingrick wrote:

##
  The Roman Stawman Sketch
##

Nice try, but you have to use a Monty Python sketch (and you have to
spell correctly :-P ).


Seriously.  The source he borrowed from is the movie Gladiator, which
isn't even a comedy.


If it was from Life of Brian, then it would be OK:

What has Guido ever done for us...? :-)
--
http://mail.python.org/mailman/listinfo/python-list


Large number multiplication

2011-07-06 Thread Billy Mays
I was looking through the python source and noticed that long 
multiplication is done using the Karatsuba method (O(~n^1.5)) rather 
than using FFTs O(~n log n).  I was wondering if there was a reason the 
Karatsuba method was chosen over the FFT convolution method?


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


Re: trouble creating tooltips using Wx in Tk canvas

2011-07-06 Thread Ravikanth
On Jul 6, 1:32 pm, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Wed, Jul 6, 2011 at 9:12 AM, Ravikanth vvnrk.vanapa...@gmail.com wrote:
  Hi all,
  Hi all,

  I am having a trouble creating tooltips. I am trying to embed a
  matplotlib graph inside  a TkInter canvas. After some search over the
  net, I found out a way to create tooltips using the WXbackend.
  But when I embed my matplotlib figure inside a Tk and  the tooltips
  are not getting displayed.

 That's pretty much what I would expect, since wxPython and Tkinter are
 completely different GUI libraries.  Trying to use them together is a
 bit like trying to call a .NET function from Java -- maybe possible,
 but it's going to take a lot of work.

  The error I am getting is below.

  Traceback (most recent call last):
   File U:\graphing_tool\plotinsideTkInter\plotInTk.py, line 12, in
  module
     tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n'
  % (' '*100)) # needs to be added to getover the bug with tooltip.
   File C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_misc.py,
  line 771, in __init__
     _misc_.ToolTip_swiginit(self,_misc_.new_ToolTip(*args, **kwargs))
  PyNoAppError: The wx.App object must be created first!

  I am not able to figure out the reason.

 As it says, you haven't created the wx.App object necessary for pretty
 much all wxPython code.  You could create one, but your tooltip still
 would not work correctly because you would be running the Tkinter
 event loop rather than the wxPython event loop.  If you want to use
 the wxToolTip widget, then you should write your program to use
 wxPython only.  Alternatively, googling for tkinter tooltip turns up
 a couple of recipes; you could try one of those.

 Cheers,
 Ian

Thank you Ian for your insights to me on this.
I will migrate to wxPython to achieve the functionality.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Andrew Berg
On 2011.07.06 02:07 PM, Phlip wrote:
 If I call m = md5() twice, I expect two objects.
You get two objects because you make the function run again. Of course,
the first one is garbage collected if it doesn't have another reference.

 m1 = hashlib.md5()
 m2 = hashlib.md5()
 m1 is m2
False

Are you assuming Python acts like another language or is there something
confusing in the docs or something else?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does hashlib support a file mode?

2011-07-06 Thread Mel
Phlip wrote:

 If I call m = md5() twice, I expect two objects.
 
 I am now aware that Python bends the definition of call based on
 where the line occurs. Principle of least surprise.

Actually, in

def file_to_hash(path, m = hashlib.md5()):

hashlib.md5 *is* called once; that is when the def statement is executed.

Later on, when file_to_hash gets called, the value of m is either used as 
is, as the default parameter, or is replaced for the duration of the call by 
another object supplied by the caller.

Mel.



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


Re: Does hashlib support a file mode?

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 1:07 PM, Phlip phlip2...@gmail.com wrote:
 If I call m = md5() twice, I expect two objects.

 I am now aware that Python bends the definition of call based on
 where the line occurs. Principle of least surprise.

There is no definition-bending.  The code:


def file_to_hash(path, m = hashlib.md5()):
# do stuff...

file_to_hash(path1)
file_to_hash(path2)


does not call hashlib.md5 twice.  It calls it *once*, at the time the
file_to_hash function is defined.  The returned object is stored on
the function object, and that same object is passed into file_to_hash
as a default value each time the function is called.  See:

http://docs.python.org/reference/compound_stmts.html#function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large number multiplication

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 1:30 PM, Billy Mays no...@nohow.com wrote:
 I was looking through the python source and noticed that long multiplication
 is done using the Karatsuba method (O(~n^1.5)) rather than using FFTs O(~n
 log n).  I was wondering if there was a reason the Karatsuba method was
 chosen over the FFT convolution method?

According to Wikipedia:


In practice the Schönhage–Strassen algorithm starts to outperform
older methods such as Karatsuba and Toom–Cook multiplication for
numbers beyond 2**2**15 to 2**2**17 (10,000 to 40,000 decimal digits).


I think most Python users are probably not working with numbers that
large, and if they are, they are probably using specialized numerical
libraries anyway, so there would be little benefit in implementing it
in core.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large number multiplication

2011-07-06 Thread Christian Heimes
Am 06.07.2011 21:30, schrieb Billy Mays:
 I was looking through the python source and noticed that long 
 multiplication is done using the Karatsuba method (O(~n^1.5)) rather 
 than using FFTs O(~n log n).  I was wondering if there was a reason the 
 Karatsuba method was chosen over the FFT convolution method?

The Karatsuba algorithm uses just addition, subtraction and
multiplication, so you don't need to resort to floats and have no
rounding errors. On the other hand FFT are based on e, complex numbers
or trigonometric functions (=floats), which mean you'll get rounding errors.

We don't want rounding errors for large long multiplication.

Christian

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Ethan Furman

Phlip wrote:

On 2011.07.06 12:38 PM, Phlip wrote:

Python sucks. m = md5() looks like an initial assignment, not a
special magic storage mode. Principle of least surprise fail, and
principle of most helpful default behavior fail.




If I call m = md5() twice, I expect two objects.


You didn't call md5 twice -- you called it once when you defined the 
function.


Phlips naive code:
---
def file_to_hash(path, m = hashlib.md5()):
   \---/
happens once, when
def line is executed


If you want separate md5 objects, don't create just one when you create 
the function, create one inside the function:


def file_to_hash(path, m = None):
if m is None:
m = hashlib.md5()


You should try the Principle of Learning the Language.

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


Re: Large number multiplication

2011-07-06 Thread Billy Mays

On 07/06/2011 04:05 PM, Christian Heimes wrote:

Am 06.07.2011 21:30, schrieb Billy Mays:

I was looking through the python source and noticed that long
multiplication is done using the Karatsuba method (O(~n^1.5)) rather
than using FFTs O(~n log n).  I was wondering if there was a reason the
Karatsuba method was chosen over the FFT convolution method?


The Karatsuba algorithm uses just addition, subtraction and
multiplication, so you don't need to resort to floats and have no
rounding errors. On the other hand FFT are based on e, complex numbers
or trigonometric functions (=floats), which mean you'll get rounding errors.

We don't want rounding errors for large long multiplication.

Christian



I believe it is possible to do FFTs without significant rounding error. 
 I know that the GIMPS's Prime95 does very large multiplications using 
FFTs (I don't know if they use the integer based or double based 
version).  I also know they have guards to prevent rounding errors so I 
don't think it would be impossible to implement.


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


Re: Large number multiplication

2011-07-06 Thread Billy Mays

On 07/06/2011 04:02 PM, Ian Kelly wrote:

On Wed, Jul 6, 2011 at 1:30 PM, Billy Maysno...@nohow.com  wrote:

I was looking through the python source and noticed that long multiplication
is done using the Karatsuba method (O(~n^1.5)) rather than using FFTs O(~n
log n).  I was wondering if there was a reason the Karatsuba method was
chosen over the FFT convolution method?


According to Wikipedia:


In practice the Schönhage–Strassen algorithm starts to outperform
older methods such as Karatsuba and Toom–Cook multiplication for
numbers beyond 2**2**15 to 2**2**17 (10,000 to 40,000 decimal digits).


I think most Python users are probably not working with numbers that
large, and if they are, they are probably using specialized numerical
libraries anyway, so there would be little benefit in implementing it
in core.


You are right that not many people would gain significant use of it. 
The reason I ask is because convolution has a better (best ?) complexity 
class than the current multiplication algorithm.  I do like the idea of 
minimizing reliance on external libraries, but only if the changes would 
be useful to all the regular users of python.


I was more interested in finding previous discussion (if any) on why 
Karatsuba was chosen, not so much as trying to alter the current 
multiplication implementation.


Side note: Are Numpy/Scipy the libraries you are referring to?

--
Bill

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


Re: Large number multiplication

2011-07-06 Thread Ian Kelly
On Wed, Jul 6, 2011 at 2:21 PM, Billy Mays no...@nohow.com wrote:
 Side note: Are Numpy/Scipy the libraries you are referring to?

I was thinking more of gmpy or mpmath, but I'm not personally well
acquainted with any of them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large number multiplication

2011-07-06 Thread Christian Heimes
Am 06.07.2011 22:15, schrieb Billy Mays:
 I believe it is possible to do FFTs without significant rounding error. 
   I know that the GIMPS's Prime95 does very large multiplications using 
 FFTs (I don't know if they use the integer based or double based 
 version).  I also know they have guards to prevent rounding errors so I 
 don't think it would be impossible to implement.

It might work for medium large longs but how about really large longs
like 5 * 1,000**10,000? I'm not familiar with FFT based multiplication
but I guess that very large numbers are going to introduce rounding
errors if floating points are involved.

Python used to run on platforms without an FPU and floats. These days
Python might still run on platforms with just an emulated FPU. Unless
there is a way to implement FFT without floating point ops, an emulated
or missing FPU makes FFT slower than Karatsuba. There might be one but I
haven't learned a way in my numerics classes.

Christian

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Carl Banks
On Wednesday, July 6, 2011 12:07:56 PM UTC-7, Phlip wrote:
 If I call m = md5() twice, I expect two objects.
 
 I am now aware that Python bends the definition of call based on
 where the line occurs. Principle of least surprise.

Phlip:

We already know about this violation of the least surprise principle; most of 
us acknowledge it as small blip in an otherwise straightforward and clean 
language.  (Incidentally, fixing it would create different surprises, but 
probably much less common ones.)

We've helped you with your problem, but you risk alienating those who helped 
you when you badmouth the whole language on account of this one thing, and you 
might not get such prompt help next time.  So try to be nice.

You are wrong about Python bending the definition of call, though.  
Surprising though it be, the Python language is very explicit that the default 
arguments are executed only once, when creating the function, *not* when 
calling it.


Carl Banks

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


Re: web browsing short cut

2011-07-06 Thread Ian

On 03/07/2011 02:21, Dustin Cheung wrote:

Hey guys,

I am new to python. I want to make a shortcut that opens my websites 
and re-sizes them to  display on different areas on the screen. I 
looked around but i had no luck. Is that possible with python? if so 
can someone point to to the right direction? Here is what I came up 
with so far..



I suggest you create a dummy page on your disk with an onload event that 
uses javascript to open, size and load all the windows you want.


Then create a short cut to the dummy page.

Regards

Ian


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


Re: Does hashlib support a file mode?

2011-07-06 Thread Phlip
On Jul 6, 1:25 pm, Carl Banks pavlovevide...@gmail.com wrote:

 We already know about this violation of the least surprise principle; most of 
 us acknowledge it as small blip in an otherwise straightforward and clean 
 language.

Here's the production code we're going with - thanks again all:


def file_to_hash(path, hash_type=hashlib.md5):

Per: 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ea1c46f77ac1738c


hash = hash_type()

with open(path, 'rb') as f:

while True:
s = f.read(8192)  #  CONSIDER:  io.DEFAULT_BUFFER_SIZE
if not s:  break
hash.update(s)

return hash.hexdigest()

Note the fix also avoids comparing to None, which, as usual, is also
icky and less typesafe!

(And don't get me started about the extra lines needed to avoid THIS
atrocity!

while s = f.read(8192):
hash.update(s)

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


Re: interactive plots

2011-07-06 Thread Jeremy Sanders
Mihai Badoiu wrote:

 How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
 and I want in the plot to be able to click on f and make it disappear. 
 Any python library that does this?

You could try veusz, which is a python module and plotting program combined. 
You can also embed it in a PyQt program.

Jeremy


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


Re: interactive plots

2011-07-06 Thread Almar Klein
On 6 July 2011 17:04, Mihai Badoiu mbad...@gmail.com wrote:

 How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
 and I want in the plot to be able to click on f and make it disappear.  Any
 python library that does this?


Visvis is a plotting toolkit that has good support for interactive use and
picking: http://code.google.com/p/visvis/

I'll even give you an example:

 import visvis as vv


 # Create to lines, increase line width (lw) for easier clicking

f = vv.plot([1,2,3,2], lc='r', lw=3)

g = vv.plot([2,1,4,3], lc='b', lw=3)


 # Create callback function

def deleteLine(event):

event.owner.Destroy()

 # Enable picking and set callback

for fg in [f, g]:

fg.hitTest = True

fg.eventMouseDown.Bind(deleteLine)

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


Re: interactive plots

2011-07-06 Thread Almar Klein
On 7 July 2011 00:00, Almar Klein almar.kl...@gmail.com wrote:



 On 6 July 2011 17:04, Mihai Badoiu mbad...@gmail.com wrote:

 How do I do interactive plots in python?  Say I have to plot f(x) and g(x)
 and I want in the plot to be able to click on f and make it disappear.  Any
 python library that does this?


 Visvis is a plotting toolkit that has good support for interactive use and
 picking: http://code.google.com/p/visvis/

 I'll even give you an example:

 import visvis as vv


  # Create to lines, increase line width (lw) for easier clicking

 f = vv.plot([1,2,3,2], lc='r', lw=3)

 g = vv.plot([2,1,4,3], lc='b', lw=3)


  # Create callback function

 def deleteLine(event):

 event.owner.Destroy()

  # Enable picking and set callback

 for fg in [f, g]:

 fg.hitTest = True

 fg.eventMouseDown.Bind(deleteLine)


Except that the indentation got mangled when I pasted the code in. Sorry
about that.
  Almar
-- 
http://mail.python.org/mailman/listinfo/python-list


show() in pylab doesn't work if used twice

2011-07-06 Thread Ravikanth
Hi all,

I have been using python for just over a month now.
I am writing a program to plot some graph using the  show() twice in
the same program. The code snippet is shown below.
I am trying to plot a simple x vs y using ax.plot() then I get a
figure displayed. I close the figure displayed and then the execution
proceeds. Now If i try to call show second time with the updated
values of x and y, the second figure does not appear on my desktop.
but the second call to show() appears to work as the code also printed
'passed the second show' as well
Can someone help me figure out what the problem  here is.why is the
second figure not coming up on the desktop.

I am using python 2.7 .




from pylab import *
import scipy
import pylab as pl
import matplotlib.pyplot as plt
fig=pl.figure()
ax=fig.add_subplot(111)
x=arange(10)
y=x*2
ax.plot(x,y)
show()


print 'passed the first show()'
x=arange(10)
y=sin(x)
ax.plot(x,y)
show()
print 'passed the second show()'
-- 
http://mail.python.org/mailman/listinfo/python-list


multiple call to show not working in matplotlib

2011-07-06 Thread Ravikanth
Hi,

I am facing some problem. I have made multiple calls to show()
function in a sinlge program. as below. Before the first call I
plotted x vs y . then i called show. execution halted until i closed
the window. Once I closed the window, execution again progressed and
even passed second show(), but the dispaly did not appear.

Can anyone please suggest me how to go about solving this issue.


from pylab import *
from matplotlib import pyplot as p
import scipy
import pylab as pl
import matplotlib.pyplot as plt
fig=pl.figure()
ax=fig.add_subplot(111)
x=arange(10)
y=x*2
ax.plot(x,y)
show()


print 'passed the border'
x=arange(10)
y=sin(x)
ax.plot(x,y)
show()
print 'passed the second show'


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


multiple calls to show doesnot work for matplotlib

2011-07-06 Thread Ravikanth
Hi,

I am facing some problem. I have made multiple calls to show()
function in a sinlge program. as below. Before the first call I
plotted x vs y . then i called show. execution halted until i closed
the window. Once I closed the window, execution again progressed and
even passed second show(), but the dispaly did not appear.

Can anyone please suggest me how to go about solving this issue.


from pylab import *
from matplotlib import pyplot as p
import scipy
import pylab as pl
import matplotlib.pyplot as plt
fig=pl.figure()
ax=fig.add_subplot(111)
x=arange(10)
y=x*2
ax.plot(x,y)
show()


print 'passed the border'
x=arange(10)
y=sin(x)
ax.plot(x,y)
show()
print 'passed the second show'


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


multiple call to show not working in matplotlib

2011-07-06 Thread mru
Hi,

I am facing some problem. I have made multiple calls to show()
function in a sinlge program. as below. Before the first call I
plotted x vs y . then i called show. execution halted until i closed
the window. Once I closed the window, execution again progressed and
even passed second show(), but the dispaly did not appear.

Can anyone please suggest me how to go about solving this issue.


from pylab import *
from matplotlib import pyplot as p
import scipy
import pylab as pl
import matplotlib.pyplot as plt
fig=pl.figure()
ax=fig.add_subplot(111)
x=arange(10)
y=x*2
ax.plot(x,y)
show()


print 'passed the border'
x=arange(10)
y=sin(x)
ax.plot(x,y)
show()
print 'passed the second show'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web browsing short cut

2011-07-06 Thread Dustin Cheung
Okay thanks for the help guys, ill keep you guys posted.

On Wed, Jul 6, 2011 at 1:19 PM, Ian hobso...@gmail.com wrote:

 On 03/07/2011 02:21, Dustin Cheung wrote:

 Hey guys,

 I am new to python. I want to make a shortcut that opens my websites and
 re-sizes them to  display on different areas on the screen. I looked around
 but i had no luck. Is that possible with python? if so can someone point to
 to the right direction? Here is what I came up with so far..


  I suggest you create a dummy page on your disk with an onload event that
 uses javascript to open, size and load all the windows you want.

 Then create a short cut to the dummy page.

 Regards

 Ian



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




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


Re: multiple calls to show doesnot work for matplotlib

2011-07-06 Thread Steven D'Aprano
Ravikanth wrote:

 Hi,
 
 I am facing some problem. 


Yes, we heard you the first two times, there's no need to keep repeating the
question over and over again.

There is no Service Level Agreement for guaranteed response times for free
advice over the Internet. Be patient, and hopefully somebody with an answer
to your question will respond once they have read the question. Wait AT
LEAST a day before reposting the question.

In the meantime, you might like to Read the Fine Manual, which explains
everything you need to know about using show().

http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show

Does that answer your question?


-- 
Steven

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Steven D'Aprano
Phlip wrote:

 Note the fix also avoids comparing to None, which, as usual, is also
 icky and less typesafe!

Typesafe? Are you trying to make a joke?



-- 
Steven

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


Re: show() in pylab doesn't work if used twice

2011-07-06 Thread Robert Kern

On 7/6/11 5:05 PM, Ravikanth wrote:

Hi all,

I have been using python for just over a month now.
I am writing a program to plot some graph using the  show() twice in
the same program. The code snippet is shown below.


Please use the matplotlib-users list for matplotlib questions. By the way, four 
versions of your message made it to this list. I'm sure the repetition was an 
honest mistake, but there may be things you can do to prevent it in the future.


  https://lists.sourceforge.net/lists/listinfo/matplotlib-users

To answer your question, you are probably using an older version of matplotlib 
than 1.0.0. The ability to use show() more than once was only added in 1.0.0:


  http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show

--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


  1   2   >