Re: displaying \n-less prompts in a pythonic way

2006-10-27 Thread Hendrik van Rooyen
"Steve Holden" <[EMAIL PROTECTED]> wrote:
8<---

>   >>> mystr = raw_input("Who is this? ")
> Who is this? Steve

how did you know how to answer that?

- Hendrik


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


Assertion failure on hotshot.stats.load()

2006-10-27 Thread Yang
Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks
several packages I depend on. I'm using Python 2.4.3.

I'm getting an AssertionError on "assert not self._stack" when calling
hotshot.stats.load() on my app's hotshot profile. The app consistently
causes hotshot to generate such a problematic profile, but I have no
idea what's causing it. Anybody know what's wrong?

Here's the profile:

http://www.filefactory.com/file/76fdbd/

Potentially relevant bugs:

http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470
http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470

Thanks in advance for any help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Matching Pure Numeric and '' with Python re

2006-10-27 Thread Wijaya Edward

Hi,
 
Given this list:
 
list = ['0123', '1A34' , '333-' , '' ]
 
I want to match only this element 
'0123' (pure numeric) and '' (empty element).
 
Why this construct doesn't work?
 
 p = re.compile("''+|[0-9]+")
   m = p.match(word)
   if m:
 print word,
 
Namely it doesn't print 0123 and ''.
What's wrong with my regex?
 
-- Edward WIJAYA
SINGAPORE

 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

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


Re: Matching Pure Numeric and '' with Python re

2006-10-27 Thread Steve Holden
Wijaya Edward wrote:
> Hi,
>  
> Given this list:
>  
> list = ['0123', '1A34' , '333-' , '' ]
>  
> I want to match only this element 
> '0123' (pure numeric) and '' (empty element).
>  
> Why this construct doesn't work?
>  
>  p = re.compile("''+|[0-9]+")
>m = p.match(word)
>if m:
>  print word,
>  
> Namely it doesn't print 0123 and ''.
> What's wrong with my regex?
>  
The first mistake is to assume that the single quotes are a part of the 
strings - they aren't. The second mistake was to over-complicate the 
pattern. All you actually need to match is zero or more digits - but you 
need a "$" at the ned of the pattern to make sure all the target string 
has been consumed in the match (otherwise *anything* will match, since 
all strings begin with zero or more digits). Here's my test:

  >>> import re
  >>> list = ['0123', '1A34' , '333-' , '' ]
  >>> p = re.compile("\d*$")
  >>> for word in list:
  ...   if p.match(word):
  ... print "[%s]" % word
  ...
[0123]
[]
  >>>

There is, however, an old saying to the effect that if you try to solve 
a problem with regular expressions you then have *two* problems. If this 
isn't just a learning exercise then consider:

  >>> for word in list:
  ...   if word.isdigit() or not word:
  ... print "[%s]" % word
  ...
[0123]
[]
  >>>

less-to-go-wrong-is-always-good-ly y'rs -  steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Assertion failure on hotshot.stats.load()

2006-10-27 Thread Yang
I fell back onto the old profile module, but got the following error
when trying to use zope.interface. I am now without any way to profile
my application.

Traceback (most recent call last):
  File "/home/yang/local/bin/profile.py", line 611, in ?
run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
  File "/home/yang/local/bin/profile.py", line 72, in run
prof = prof.run(statement)
  File "/home/yang/local/bin/profile.py", line 448, in run
return self.runctx(cmd, dict, dict)
  File "/home/yang/local/bin/profile.py", line 454, in runctx
exec cmd in globals, locals
  File "", line 1, in ?
  File 
"/.automount/nms.lcs.mit.edu/export/home/yang/proj/cartel/trunk/icedb/src/frontend/icedb-central.py",
line 5, in ?
from icedb import *
  File "/home/yang/local/lib/python2.4/site-packages/icedb/__init__.py",
line 4, in ?
import cafnet
  File "/home/yang/local/lib/python2.4/site-packages/cafnet/__init__.py",
line 269, in ?
class Cnl( object ):
  File "/opt/zope/lib/python/zope/interface/advice.py", line 132, in advise
return callback(newClass)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
485, in _implements_advice
classImplements(cls, *interfaces)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
462, in classImplements
spec.declared += tuple(_normalizeargs(interfaces))
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
1373, in _normalizeargs
_normalizeargs(v, output)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
1372, in _normalizeargs
for v in sequence:
TypeError: Error when calling the metaclass bases
iteration over non-sequence

On 10/27/06, Yang fer7msb02-at-sneakemail.com |python|
<...> wrote:
> Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks
> several packages I depend on. I'm using Python 2.4.3.
>
> I'm getting an AssertionError on "assert not self._stack" when calling
> hotshot.stats.load() on my app's hotshot profile. The app consistently
> causes hotshot to generate such a problematic profile, but I have no
> idea what's causing it. Anybody know what's wrong?
>
> Here's the profile:
>
> http://www.filefactory.com/file/76fdbd/
>
> Potentially relevant bugs:
>
> http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470
> http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470
>
> Thanks in advance for any help.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run subprocess in separate window

2006-10-27 Thread heracek


On Oct 15, 6:43 pm, "Radek" <[EMAIL PROTECTED]> wrote:
> Currently when using subprocess.Popen("mycommand") all output goes to
> the stdout of my launcher.
>

Hi,
the solution is:

p = subprocess.Popen(args=['command', 'arg1', 'arg2'],
 stdout=subprocess.PIPE,
 stderr=subprocess.STDOUT)
print p.stdout.read() # stderr and strout mix

or:

p = subprocess.Popen(args=['command', 'arg1', 'arg2'],
 stdout=subprocess.PIPE,
 stderr=subprocess.PIPE)
print p.stderr.read()
print p.stdout.read()

h.

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


Re: PyDev + Eclipse (Was: Re: What's the best IDE?)

2006-10-27 Thread olive

Michael B. Trausch wrote:

> Yep.  Still does it.

I'm running PyDev 1.2.4 without completion problem so far.

Are you up to date ?

Maybe you should install the latest from scratch.

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


Re: Assertion failure on hotshot.stats.load()

2006-10-27 Thread Christophe
Yang a écrit :
> Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks
> several packages I depend on. I'm using Python 2.4.3.
> 
> I'm getting an AssertionError on "assert not self._stack" when calling
> hotshot.stats.load() on my app's hotshot profile. The app consistently
> causes hotshot to generate such a problematic profile, but I have no
> idea what's causing it. Anybody know what's wrong?
> 
> Here's the profile:
> 
> http://www.filefactory.com/file/76fdbd/
> 
> Potentially relevant bugs:
> 
> http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470
>  
> 
> http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470
>  
> 
> 
> Thanks in advance for any help.

I had the exact same problem as the second bug in an embeded 
application. I solved it by ignoring any function return without a 
corresponding function start in the profiler but I'm sure it can be be 
made more precise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Search & Replace

2006-10-27 Thread Frederic Rentsch
DataSmash wrote:
> Hello,
> I need to search and replace 4 words in a text file.
> Below is my attempt at it, but this code appends
> a copy of the text file within itself 4 times.
> Can someone help me out.
> Thanks!
>
> # Search & Replace
> file = open("text.txt", "r")
> text = file.read()
> file.close()
>
> file = open("text.txt", "w")
> file.write(text.replace("Left_RefAddr", "FromLeft"))
> file.write(text.replace("Left_NonRefAddr", "ToLeft"))
> file.write(text.replace("Right_RefAddr", "FromRight"))
> file.write(text.replace("Right_NonRefAddr", "ToRight"))
> file.close()
>
>   

Here's a perfect problem for a stream editor, like 
http://cheeseshop.python.org/pypi/SE/2.2%20beta. This is how it works:

 >>> replacement_definitions = '''
   Left_RefAddr=FromLeft
   Left_NonRefAddr=ToLeft
   Right_RefAddr=FromRight
   Right_NonRefAddr=ToRight
'''
 >>> import SE
 >>> Replacements = SE.SE (replacement_definitions)
 >>> Replacements ('text.txt', 'new_text.txt')

That's all! Or in place:

 >>> ALLOW_IN_PLACE = 3
 >>> Replacements.set (file_handling_flag = ALLOW_IN_PLACE)
 >>> Replacements ('text.txt')

This should solve your task.

An SE object takes strings too, which is required for line-by-line 
processing and is very useful for development or verification:

 >>> print Replacements (replacement_definitions)   # Use definitions as 
test data

   FromLeft=FromLeft
   ToLeft=ToLeft
   FromRight=FromRight
   ToRight=ToRight

Checks out. All substitutions are made.


Regards

Frederic


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


Re: Slightly OT: Is pyhelp.cgi documentation search broken?

2006-10-27 Thread Thomas Heller
Joel Hedlund schrieb:
> Hi!
> 
> For a number of days I haven't been able to search the online python 
> docs at:
> 
> http://starship.python.net/crew/theller/pyhelp.cgi
> 
> that is the "search the docs with" link at this page:
> 
> http://www.python.org/doc/
> 
> Instead of the search engine, I get Error 404. This is a real bother for 
> me, since I rely heavily on it for my work.
> 

It works now again.  At the same time, I've added the ability to search the 
Python 2.5 docs,
(formerly they were exposed as 'current docs' only, and moved the code into an 
SVN repository.

Note that you can also download the module and use it locally.

Thomas

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


Simple problem with GUI!!

2006-10-27 Thread mohan
Hello Guys,

I am a beginner with Python programming and would like to implement
some GUI functionalities along with my main work. So I was trying to
implement one basic program (available from books).
Here is the code,


import Tkinter

TopLevelWindowObj = Tkinter.Tk() # Creating a root window
QuitObj = Tkinter.Button(TopLevelWindowObj, text = "QUIT", command =
TopLevelWindowObj.quit) #  Creating a Button
QuitObj.pack() # Positioning the button
Tkinter.mainloop()
#

So, this is a code to display a window with a "QUIT" button and by
clickign the button the entire window is closed. When I execute this
program, the window does not close down but the window is completely
disabled and after a few seconds I get the following message in a
message window,

**
Message box name - Microsoft Visual C++ Runtime Library

Runtime Error!

program...\Python22\core\lib\site-packages\Pythonwin\Pythonwin.exe

This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.


At the end I had to close down my entire python compiler. I am using
Python compiler with following specs in Windows XP OS.

Pythonwin - Python IDE and GUI Framework for Windows.
PythonWin 2.2.1 (#34, Feb 25 2003, 11:29:09) [MSC 32 bit (Intel)] on
win32.
Portions Copyright 1994-2001 Mark Hammond

Please let me know why is this happening and also if I am missing
something in the way of programming.

Thanks in advance.

Cheers,
Mohan.

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


Re: Simple problem with GUI!!

2006-10-27 Thread Fredrik Lundh
"mohan" wrote:

> At the end I had to close down my entire python compiler. I am using
> Python compiler with following specs in Windows XP OS.
>
> Pythonwin - Python IDE and GUI Framework for Windows.
> PythonWin 2.2.1 (#34, Feb 25 2003, 11:29:09) [MSC 32 bit (Intel)] on
> win32.
> Portions Copyright 1994-2001 Mark Hammond
>
> Please let me know why is this happening and also if I am missing
> something in the way of programming.

the PythonWin IDE doesn't work properly when you're running programs that
does their own Windows event handling.  this is a problem with PythonWin, not
with Tkinter or your program.  to solve this, you can either

1) check if you can make PythonWin run the program in a separate process

2) explicitly run the program in its own process (using "python.exe" or 
"pythonw.exe"),
   from the command line.

3) switch to an IDE that runs Python code in a separate process (such as IDLE,
   Wing, and most other modern IDE:s).

 



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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-26, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Wed, 25 Oct 2006 19:19:59 +, John Salerno wrote:
>
>> Oh!!! I get it now! I was thinking that
>> 
>> if s
>> 
>> was the same as
>> 
>> if s == True
>
> No. But you know that now :)
>
>> because I know sometimes you can write if statements this way (though 
>> it's wordy). 
>
> You can, but shouldn't.
>
>
>> But what I didn't realize was that in the cases I was 
>> thinking of, 's' was an expression that evaluated to a boolean value, 
>> not an actual value of some other type!
>> 
>> So I suppose
>> 
>> if (10 > 5)
>
> Is the same as:
>
> if True
>
> because (10 > 5) evaluates as True.
>
>  
>> would be the same as
>> 
>> if (10 > 5) == True
>
> Did you mean
>
> if (10 > 5) == True == True
>
> or 
>
> if (10 > 5) == True == True == True
>
> or even 
>
> if (10 > 5) == True == True == True == True
>
> I hope you see my point now.
>
>
>> because (10 > 5) does evaluate to "True".
>
> I think it is a good time to remind people of some extremely well-thought
> out opposition to the introduction of bools to Python from Laura Creighton:
>
> http://mail.python.org/pipermail/python-list/2002-April/095878.html
>
> She lost the debate, Guido had the final word and Python now has bools.
> Take particular note of her description of Python distinguishing between
> Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc).

Yes and IMO that is a less usefull distinction than the distinction
between True and False. When I write code I think in terms of
conditions. In those conditions this has to be treated this way
otherwise it has to be treated an other way. Conditions give
results that are either True or False, not Something or Nothing.
I don't think of 10 > 5 as Something while 5 < 10 would be
Nothing. So while the paradigma of the language may be the
distinction of Something vs Nothing the programmer will often
enough think in terms of True and False. So IMO it would have
been better if python had made the distinction between True and
False and so made the programmer code the Something/Nothing
disctinction explicitly.

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


Re: Tracing the execution of scripts?

2006-10-27 Thread R. Bernstein
pydb (http://bashdb.sf.net/pydb) has a both the ability to trace lines
as they are executed as well as an --output option to have this sent
to a file rather than stdout. If your program has threads it would be
good to use the --threading option. (The best threading support is if
your program uses the threading module for threads rather than the
lower-level thread module.)

A demo of the debugger including showing line tracing and output to a file is
here:
  http://showmedo.com/videos/video?name=pythonBernsteinPydbIntro&fromSeriesID=28


"Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> writes:

> Alright, I seem to be at a loss for what I am looking for, and I am not
> even really all that sure if it is possible or not.  I found the 'pdb'
> debugger, but I was wondering if there was something that would trace or
> log the order of line execution for a multi-module Python program.  I am
> having a little bit of a problem tracking down a problem that I
> mentioned earlier
> (http://groups.google.com/group/comp.lang.python/msg/9c759fc888b365be),
> and I am hoping that maybe seeing how the statements are executed will
> shed some light on the entire thing for me.
> 
> The debugger isn't working, though, because I have a timer set up to
> fire off every 20ms to check for incoming network traffic from the
> server, and that timer firing off makes stepping through with the
> debugger seemingly impossible to get any useful data.
> 
> Basically, is there something that will log every line of Python code
> executed, in its order of execution, to a text file so that I can see
> what is (or isn't) happening that I am expecting?  I know that the
> server is sending and receiving properly, because I can connect to it
> with a regular telnet client and it works -- but at the same time,
> everything I can think of to check my program's functionality checks out
> just fine (e.g., it reports that it is successfully sending what I am
> typing to the server, and it says that the server is not sending
> anything back to be read from the socket).
> 
> If it makes any difference, I am using wxWidgets' Python bindings for
> the UI code (and the timer), and using Python's socket library for the
> network stuff.
> 
>   -- Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-26, Donn Cave <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Steve Holden <[EMAIL PROTECTED]> wrote:
> ...
>> Maybe so, but that "rule" (and let's not forget that the zen is not 
>> actually a set of prescriptive rules but rather guidelines for the 
>> informed) is immediately preceded by the most important "rule" of all: 
>> "Beautiful is better than ugly". Nobody will shout at you (well, 
>> hopefully, not on this list they won't) for writing
>> 
>>if my_list != []:
>>  ...
>> 
>> in your code, but if they have to incorporate it into their own they 
>> will almost certainly reduce it to
>> 
>>if my_list:
>>  
>> 
>> It's just idiomatic in Python, the same way that "'Sup?" is idiomatic in 
>> English (or what passes for it nowadays ;-) but grates on those who 
>> aren't used to hearing it.
>
> It is idiomatic, but not _just_ idiomatic.  The former requires
> a list object (or a tricky __eq__()), the latter works with a variety
> of objects, exhibiting a useful polymorphism.

The latter will treat None and False the same as [], () and {},
which in most of my code is not what I want. In most cases
I find testing for an empty sequence (however you do it)
useless, because the loop over the sequence does whatever
I want if it is empty. In cases where I do want to test
for it I usually write:

  if len(my_list) > 0:

That provides the polymorphism that is usefull to me and
doesn't treat None the same as an empty sequence.

> As for similarities between computer programming languages
> and natural languages, I think that breaks down pretty fast.
>
> Part of the problem is something that pinches Python pretty
> hard right here, a lack of words that conveniently express
> important concepts in the language.  A few posts back, Carl
> Banks made a distinction between "equaling" and "being", and
> if I understood that right, it expresses a fundamental notion
> about the meaning of Python's "if", "while" etc. statements.
> Unfortunately, though, English conflates existence and identity
> in this word ("be"), so it's not going to serve our purposes
> very well, and when it comes to words like "if" -- well, we
> just have to use what we have.
>
> If there were better words to use with the notion of
> "something-ness", I think we would see booleans as a silly
> thing of little use to Python programmers.

I think you are incorrect. Decisions have to be made and
they are made based on conditions. Conditions are expressed
in terms of True and False not in terms of Nothing or Something.

That is how IMO people think. You can't change that just
because python is implemented with the Nothing vs Something
distinction in mind.

> If you can see
> "if" and "while" as constructs that respond to something-ness,
> you will appreciate idiomatic Python better, because that
> arguably is just what it's about.

And how do I express that a number has to be greater than
100 into a Nothing vs Something dichotomy? Declare all
greater numbers as Something and the rest as Nothing?

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


Re: Embedding Matplotlib images into wxPython

2006-10-27 Thread khromushin

I wrote a matplotlib Boa constructor plug-in. It is very easy to add it into
a wxframe, sizers etc in Boa constructor. 
If you are interested in the plugin, pls. send e-mail to [EMAIL PROTECTED] 

Igor Khromushin



[EMAIL PROTECTED] wrote:
> 
> I am trying to embed images into a wxPython app (created using Boa
> Constructor), but have not been able to do so. I know how to embed
> plots, but images seem to be a problem. I've tried using code analogous
> to the example given at the Matplotlib website to no avail. If anybody
> has been successful at this could you please post some sample code?
> That would be greatly appreciated. Thanks!
> 
> Randy
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 



-- 
View this message in context: 
http://www.nabble.com/Embedding-Matplotlib-images-into-wxPython-tf265283.html#a7027545
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: question about True values

2006-10-27 Thread Fredrik Lundh
Antoon Pardon wrote:

> The latter will treat None and False the same as [], () and {},
> which in most of my code is not what I want.

since you never publish any code, what you do in your code is not very
interesting to anyone.

 



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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-26, Steve Holden <[EMAIL PROTECTED]> wrote:
> John Coleman wrote:

>> As far as using non-booleans as conditions - I just think that if you
>> want a certain block of code to be executed only if, for example, a
>> list is non-empty, why not *say* so? I think "if my_list != []:" just
>> reads better than "if my_list:". I would think that my preferences
>> there mesh with "Explicit is better than implicit" but apparently not.
>> 
> Maybe so, but that "rule" (and let's not forget that the zen is not 
> actually a set of prescriptive rules but rather guidelines for the 
> informed) is immediately preceded by the most important "rule" of all: 
> "Beautiful is better than ugly". Nobody will shout at you (well, 
> hopefully, not on this list they won't) for writing
>
>if my_list != []:
>  ...

That depends on what you consider as shouting. My impression is that
if people come here with a problem and post a sample of code to
illustrate. That if that code would contain something like the above
about half of the responses will be about the code not following
python idiom without further providing anything helpfull with the actual
problem. Now you may not consider that as shouting but I guess it
can be just as intimidating.

>> 
> It probably will, but I wouldn't get too hung up on what's definitely a 
> small point. Enjoy Python the way it is, and the way you are. You and 
> Python will definitely come to an accommodation (and you will love the 
> combination of discipline and freedom that it brings to programming 
> style). Welcome to the language!

I'll second that. Python has it warts, but so has any language.
Chances are John will find the warts of python are minor
issues compared with other languages.

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


Re: conditional computation

2006-10-27 Thread robert
Bruno Desthuilliers wrote:
> robert a écrit :
> (snip)
>> class MemoCache(dict): # cache expensive Objects during a session 
>> (memory only)
>>def memo(self, k, f):
>>try: return self[k]
>>except KeyError:#<- was error 
>>return self.setdefault(k, f())
>> cache=MemoCache()
>> ...
>>
>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )
>>
> 
> And how do you get back the cached value without rewriting both 
> complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ?

the complex-key-expr is written only once in the code - execution inevitable.

expensive-calc-expr is  written only once in code and expensive execution (I 
have mostly matrix math) is only done at "f()" time.


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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-27, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>
>> The latter will treat None and False the same as [], () and {},
>> which in most of my code is not what I want.
>
> since you never publish any code,

This is not True. You shouldn't confuse your lack of recollection
with reality.

> what you do in your code is not very interesting to anyone.

I doubt I'm the only one who has code that treats None and False
differently from [], () and {}

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


Re: Slightly OT: Is pyhelp.cgi documentation search broken?

2006-10-27 Thread Joel Hedlund
> It works now again.  

You are now officially my hero.

> Note that you can also download the module and use it locally.

Cool. I'll do that!

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


struct.pack bug?

2006-10-27 Thread Jansson Christer
Hi all,

I have discovered that in my Python 2.4.1 installation (on Solaris 8), 
struct.pack handles things in a way that seems inconsistent to me.

I haven't found any comprehensible documentation over known issues with 
Python 2.4.1 so I try this...

Here's the thing:

 >>> from struct import pack
 >>> pack('B', -1)
Traceback (most recent call last):
   File "", line 1, in ?
struct.error: ubyte format requires 0<=number<=255
 >>> pack('H', -1)
Traceback (most recent call last):
   File "", line 1, in ?
struct.error: short format requires 0<=number<=USHRT_MAX
 >>> pack('L', -1)
'\xff\xff\xff\xff'
 >>>

Shouldn't pack('L', -1) raise an exception like the others, rather than 
behaving like pack('l', -1)?
Is this fixed in later versions?

(I don't have access to later versions and have failed to install any.
Python 2.5 compiles nicely but "make install" fails without leaving any 
clues about how it failed and no installation troubleshooting guides to 
be found at python.org. Python 2.4.4 doesn't even compile since it 
apparently requires a newer libstdc++ than the one on our system... see 
why I'm asking the newsgroup?)

-- 
--

Christer Jansson
WiseOne AB
+46 708 21 42 84
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Fredrik Lundh
Antoon Pardon wrote:

>> since you never publish any code,
>
> This is not True. You shouldn't confuse your lack of recollection
> with reality.

pointers, please.

 



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


Re: Slurping All Content of a File into a Variable

2006-10-27 Thread marc . wyburn
myfile_content is an object and you have only opened the file.  Python
doesn't yet know whether you want to read it, copy it etc.

to read it try

text = myfile_content.readlines()
print text

this should be in most tutorials


Wijaya Edward wrote:
> Hi,
>
> How can we slurp content of a single file
> into one variable?
>
> I tried this:
>
> >>> myfile_content = open('somefile.txt')
> >>> print myfile_content,
> 
> >>>
>
> But it doesn't print the content of the file.
>
> Regards,
> -- Edward WIJAYA
> SINGAPORE
>
>
>  Institute For Infocomm Research - Disclaimer -
> This email is confidential and may be privileged.  If you are not the 
> intended recipient, please delete it and notify us immediately. Please do not 
> copy or use it for any purpose, or disclose its contents to any other person. 
> Thank you.
> 

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


Re: struct.pack bug?

2006-10-27 Thread Fredrik Lundh
"Jansson Christer" wrote:

> I have discovered that in my Python 2.4.1 installation (on Solaris 8),
> struct.pack handles things in a way that seems inconsistent to me.
>
> I haven't found any comprehensible documentation over known issues with
> Python 2.4.1 so I try this...
>
> Here's the thing:
>
> >>> from struct import pack
> >>> pack('B', -1)
> Traceback (most recent call last):
>   File "", line 1, in ?
> struct.error: ubyte format requires 0<=number<=255
> >>> pack('H', -1)
> Traceback (most recent call last):
>   File "", line 1, in ?
> struct.error: short format requires 0<=number<=USHRT_MAX
> >>> pack('L', -1)
> '\xff\xff\xff\xff'
> >>>
>
> Shouldn't pack('L', -1) raise an exception like the others, rather than
> behaving like pack('l', -1)?

probably; the reason for the old behaviour is probably to simplify for code that
uses Python int's to represent 32-bit values.  (mixing longs and ints used to 
be a
lot more difficult than it is today).

> Is this fixed in later versions?

the "struct" module was rewritten in Python 2.5; the new module issues a
warning, and then appears to *clamp* the value to the allowed range, in-
stead of grabbing the low bits:

>>> import struct

>>> struct.pack("B", -1)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Lib\struct.py", line 63, in pack
return o.pack(*args)
struct.error: ubyte format requires 0 <= number <= 255

>>> struct.pack("H", -1)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Lib\struct.py", line 63, in pack
return o.pack(*args)
struct.error: short format requires 0 <= number <= USHRT_MAX

>>> struct.pack("I", -1)
__main__:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295
'\x00\x00\x00\x00'

>>> struct.pack("L", -1)
__main__:1: DeprecationWarning: 'L' format requires 0 <= number <= 4294967295
'\x00\x00\x00\x00'

 



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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-27, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>
>>> since you never publish any code,
>>
>> This is not True. You shouldn't confuse your lack of recollection
>> with reality.
>
> pointers, please.

Sorry, the answer is no. I don't care whether you can locate my code
or not or wish to believe me or not.

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


virtual function appears in two bases

2006-10-27 Thread joe Li
I saw the following code, but I don't understand the rule for virtual function that appears in two basesCould anyone explain it for me, thanks.class Base1:    def amethod(self):    print "Base1"
class Base2(Base1): passclass Base3:    def amethod(self):    print "Base3"class Derived(Base2, Base3): passaninstance = Derived()aninstance.amethod()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: question about True values

2006-10-27 Thread Steve Holden
Antoon Pardon wrote:
> On 2006-10-27, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> 
>>Antoon Pardon wrote:
>>
>>
since you never publish any code,
>>>
>>>This is not True. You shouldn't confuse your lack of recollection
>>>with reality.
>>
>>pointers, please.
> 
> 
> Sorry, the answer is no. I don't care whether you can locate my code
> or not or wish to believe me or not.
> 
Google finds 2 hits for "Anton Pardoon open source". You are ceratinly 
keeping it well hidden.

Few people have more right to call you on this than the effbot, well 
known for his prolific output.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: struct.pack bug?

2006-10-27 Thread Jansson Christer
Fredrik Lundh wrote:
> "Jansson Christer" wrote:
> 
> 
>>I have discovered that in my Python 2.4.1 installation (on Solaris 8),
>>struct.pack handles things in a way that seems inconsistent to me.
>>
>>I haven't found any comprehensible documentation over known issues with
>>Python 2.4.1 so I try this...
>>
>>Here's the thing:
>>
>>
>from struct import pack
>pack('B', -1)
>>
>>Traceback (most recent call last):
>>  File "", line 1, in ?
>>struct.error: ubyte format requires 0<=number<=255
>>
>pack('H', -1)
>>
>>Traceback (most recent call last):
>>  File "", line 1, in ?
>>struct.error: short format requires 0<=number<=USHRT_MAX
>>
>pack('L', -1)
>>
>>'\xff\xff\xff\xff'
>>
>>Shouldn't pack('L', -1) raise an exception like the others, rather than
>>behaving like pack('l', -1)?
> 
> 
> probably; the reason for the old behaviour is probably to simplify for code 
> that
> uses Python int's to represent 32-bit values.  (mixing longs and ints used to 
> be a
> lot more difficult than it is today).
> 
> 
>>Is this fixed in later versions?
> 
> 
> the "struct" module was rewritten in Python 2.5; the new module issues a
> warning, and then appears to *clamp* the value to the allowed range, in-
> stead of grabbing the low bits:
> 
> 
import struct
> 
> 
struct.pack("B", -1)
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\Lib\struct.py", line 63, in pack
> return o.pack(*args)
> struct.error: ubyte format requires 0 <= number <= 255
> 
> 
struct.pack("H", -1)
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\Lib\struct.py", line 63, in pack
> return o.pack(*args)
> struct.error: short format requires 0 <= number <= USHRT_MAX
> 
> 
struct.pack("I", -1)
> 
> __main__:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295
> '\x00\x00\x00\x00'
> 
> 
struct.pack("L", -1)
> 
> __main__:1: DeprecationWarning: 'L' format requires 0 <= number <= 4294967295
> '\x00\x00\x00\x00'
> 
>  
> 
> 
> 

Ok this implies that somebody is actually thinking about how to handle 
this, so I guess I won't file a bug report and simply solve my problems 
without relying on those exceptions...

Thank you!
-- 
--

Christer Jansson
WiseOne AB
+46 708 21 42 84
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Steve Holden
Antoon Pardon wrote:
> On 2006-10-27, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> 
>>Antoon Pardon wrote:
>>
>>
since you never publish any code,
>>>
>>>This is not True. You shouldn't confuse your lack of recollection
>>>with reality.
>>
>>pointers, please.
> 
> 
> Sorry, the answer is no. I don't care whether you can locate my code
> or not or wish to believe me or not.
> 
... though I might have got more hits by spelling your name correctly :)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: conditional computation

2006-10-27 Thread Bruno Desthuilliers
robert wrote:
> Bruno Desthuilliers wrote:
>> robert a écrit :
>> (snip)
>>> class MemoCache(dict): # cache expensive Objects during a session
>>> (memory only)
>>>def memo(self, k, f):
>>>try: return self[k]
>>>except KeyError:#<- was error   
>>> return self.setdefault(k, f())
>>> cache=MemoCache()
>>> ...
>>>
>>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )
>>>
>>
>> And how do you get back the cached value without rewriting both
>> complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ?
> 
> the complex-key-expr is written only once in the code

How do you get something back from the cache then ?

> expensive-calc-expr is  written only once in code 

Same problem here...  I fail to understand how you intend to use this
"cache".



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tracing the execution of scripts?

2006-10-27 Thread Michael B. Trausch
Jean-Paul Calderone wrote:
> 
> In order of importance:
> 
> 1) Write unit tests for your code.  Keep writing unit tests until you have
> some that _don't pass_.  Then fix your code so that they do.  When you do
> further development, write the tests first, then implement the code that
> makes them pass.
> 

Perhaps I could use some pointers on that.  I have read the bits and
pieces that I have found regarding unit testing in the past, and I have
wrote "unit tests" for things that I have done, but mostly for pieces of
reusable code that interact with other programs.

And I still have to wrap my mind around the idea of test first, develop
later.  It's fully possible that this works for many, but my (admittedly
few) attempts at that methodology have failed me.  I have a problem
writing something without reference to look at while writing it -- so if
I am writing something, say, to test my AnsiTextCtrl, I would need to
look at the AnsiTextCtrl to see what methods and such I should be testing.

That having been said, I don't have the slightest clue how a unit test
would be written for something that is purely user oriented, anyway.  I
was under the impression that unit tests were automated little tests
that required no user intervention to perform, right?

Actually, thinking about the idea of unit tests, I have found a few
resources online that generically talk about unit tests.  Even the books
that I have read on programming talk about unit tests.  However, all the
generic-ness with which the subject is approached makes my head spin.
(It does that a lot when I am trying to learn something new, by the way.)

>
> 2) Don't use threads.  At least have a way to not use threads while you're
> debugging.  Debugging with threads is very difficult. (Actually I'm not
> sure
> if you're using threads.  If you're not, feel free to ignore this point.)
> 

Fortunately, I am not.  At least, I don't think I am, unless wxWidgets
uses them internally or something.  Threading would make my head explode
at this point.  I really am used to just pulling off simple, sysadmin
type things using massive subsets of languages to just "get things done."

>
> 3) Don't poll for network events every 20ms.  If you have a sensible event
> loop you'll find debugging and testing much easier.
> 

I don't know what you mean.  I believe wxWidgets handles the looping.
And, as least, as far as I could tell with the documentation, the wx
networking API is not exposed to Python.  The "event loop" that you are
describing is, I am assuming, the MainLoop which gets started for wx.App
derived objects?

>
> 4) Use an existing library instead of developing a new one.
>

I had looked for one, at least for the AnsiTextCtrl that I was using.  I
never did find anything, so I assumed that it didn't exist.

>
> 5) (Only included so I don't look like a _complete_ jerk.  If you get this
> far and you haven't fixed the problem yet, consider this a booby prize.)
> http://divmod.org/trac/browser/trunk/Epsilon/epsilon/spewer.py
> 

I looked at this, and it made my head spin.  I think it is just a touch
too early for me to be looking at things that I don't quite understand.
 :-)  I will take another look at it when I have been amongst the living
a little bit longer.

Thank you for the pointers here.  At the very least, I have new ideas to
google around with (such as looking into "event loops").

As far as programming goes, I have done minor things with it, and web
applications (in PHP).  I have never done GUI programming, or low-level
network programming, or anything like that before, and I tried doing
this project in C++ at first... and then said it wasn't worth it to me.
 So, I'm not very well versed in many of the concepts -- I am literally
used to just writing tiny things (I can do very simple C programs, and
have been known to use PHP for help automating things) to make my life
easier, so this is the first real project that I have tried to work on.

The goal, of course, is to become a better programmer.  But, I digress. :-)

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


change keybindings for pygtk treeview

2006-10-27 Thread Fabian Braennstroem
Hi,

I am just testing pygtk/glade out and wonder, if I am able
to change the keybindings. E.g. the treeview searches by
default for the entries beginning with the typed keystroke;
moving to the next row works as usual with the Down key. Now
I would like to change the key bindings to e.g. 'j' to move
to the next row (just like in vim) and to use a 'Ctrl' key
combination to search for a certain word beginning with the
typed key stroke.
Is it anyhow possible with pygtk? Would be nice, if somebody
can point my to a small example.

Greetings!
 Fabian

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


How set the source IP adress

2006-10-27 Thread Maksim Kasimov
Hi,

how to set source ip-address when do __socket.connect((host, port))
on a machine that have a several ip-adresses?

many thanks for advice.

__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
__socket.connect((host, port))


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


Re: Tracing the execution of scripts?

2006-10-27 Thread Michael B. Trausch
Ben Finney wrote:
> Jean-Paul Calderone <[EMAIL PROTECTED]> writes:
> 
>> 1) Write unit tests for your code.  Keep writing unit tests until
>> you have some that _don't pass_.  Then fix your code so that they
>> do.  When you do further development, write the tests first, then
>> implement the code that makes them pass.
> 
> Hear hear.
> 
> Be advised, though, that attempting to apply unit tests to code that
> wasn't designed with testing in mind may very quickly reveal a poor
> design. [0] If you can't easily test pieces of the code independently,
> you probably haven't written those pieces to be loosely coupled and
> well-defined.
>

I will whole-heartedly admit that my code is probably poorly designed.
*shrug*  Though, I *do* try to write everything in such a way as to be
able to easily re-use it later.  When I wrote little things just to help
me sysadmin, I learned that was really key to making my life easier.

Besides, I am lazy... reuse certainly serves my needs there!  :-)

> 
> The moral? Writing unit tests *along with* the functional code will
> result in a design that is loosely coupled, and probably
> better-defined. Also, hopefully, easy to test :-)
> 

I think I have more to learn on the concept of unit-testing.  I have
never seen a group push the idea so hard.  I have read about unit
testing before, and even written tests (in other languages) to test
modules of library code that I put together once, but that was about it.
 I need to, I think, get more "into" the concept, though.  It isn't
something that I am able to just whip out and go "Hey, a widget unit
test!  And it works!" probably because of my own lack of practice.

> 
> [0] I have no idea whether this is the case for the OP. It's a very
> common symptom that arises from people who are first advised to
> introduce tests to their code, though.
> 

It is very likely that it is the case.  I am, by all means, what I could
consider to be a novice programmer when it comes to anything outside of
my little world of PHP.  I can write web applications in PHP until the
cows come home with little to no problem, and I can play with SQL the
same way.  But, I seem to have problems when I step out of that little
box, and so, that tells me that I need to work harder at it.  :-)

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


Re: my first software

2006-10-27 Thread Bjoern Schliessmann
Fredrik Lundh wrote:

> cygwin?

I thought so too, but cygwin would use #!/cygdrive/c/..., IIRC.

> exemaker?  some kind of web server? 

Okay, didn't know that :)

Regards,


Björn

-- 
BOFH excuse #22:

monitor resolution too high

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


Re: Using classes in python

2006-10-27 Thread Colin J. Williams
trevor lock wrote:
> Hello,
> 
> I've just started using python and have observed the following :
> 
> class foo:
> a=[]
> def __init__(self, val):
> self.a.append ( val )
> def getA(self):
> print self.a
> return self.a
> 
> z = foo(5)
> y = foo(4)
> z.getA()
>  >> [5, 4]
> 
> I was expecting that everytime I created an instance of the class that a 
> unique dictionary was also created, however it seems that only one 
> dictionary is created.
> 
> How can I create a new dictionary for each instance?
You do already, as the little script below illustrates:

# checkInstance.py

class A(object):
   def __new__(cls, n):
 return object.__new__(cls)
   def __init__(self, n):
 self.a= n


a1= A(21)
a2= A(22)
print a1.a, a2.a, a1.__dict__ is a2.__dict__

Colin W.
> 
> Thanks,
> Trevor.
> 
> 
> All-new Yahoo! Mail 
> -
>  
> Fire up a more powerful email and get things done faster.
> 

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


PyQt-x11-gpl-3.16 compile error

2006-10-27 Thread baur79
[EMAIL PROTECTED] PyQt-x11-gpl-3.16]# python configure.py -q
/usr/lib/qt-3.3/
This is the GPL version of PyQt 3.16 (licensed under the GNU General
Public
License) for Python 2.4.2 on linux2.

Type 'L' to view the license.
Type 'yes' to accept the terms of the license.
Type 'no' to decline the terms of the license.

Do you accept the terms of the license? yes
qextscintillaglobal.h could not be found in /usr/lib/qt-3.3/include and
so the
qtext module will not be built. If QScintilla is installed then use the
-n
argument to explicitly specify the correct directory.
Checking to see if the qtcanvas module should be built...
Checking to see if the qtnetwork module should be built...
Checking to see if the qttable module should be built...
Checking to see if the qtxml module should be built...
Checking to see if the qtgl module should be built...
Checking to see if the qtui module should be built...
Checking to see if the qtsql module should be built...
Checking to see if the QAssistantClient class is available...
Creating features file...
Error: Unable to build mkfeatures utility.


please help to fix the problem

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


Re: Tracing the execution of scripts?

2006-10-27 Thread Michael B. Trausch
Stephan Kuhagen wrote:
> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote:
> 
>> Basically, is there something that will log every line of Python code
>> executed, in its order of execution, to a text file so that I can see
>> what is (or isn't) happening that I am expecting?
> 
> Python itself can do this for you. A __VERY__ simple approach:
> 
[snip]
> 
> Insert this in you program and you get a trace of every line of Python-Code
> executed in the file trace.txt. You must read the documentation of the
> module inspect and of sys.settrace() to understand, what happens and what
> it means. Additionally, if it should work with threads, you must take care
> that every thread gets its own output file. But as a first step to get a
> trace of execution, this should do it.
> 

I will need to keep this around to look at a little later.  It looks
like it would be something particularly useful when line-tracing by
itself fails.  I am constantly finding myself amazed at Python's
capabilities.

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


ANN: the pyfaq wiki has moved

2006-10-27 Thread Fredrik Lundh
Back in April, I posted a copy of the Python FAQ over at infogami.com,
to collect comments and new FAQ entries for python.org.

Since infogami.com development has ceased, and the server's been hit
by spam lately, I've decided to move the material over to a hopefully
more reliable site:

http://effbot.org/pyfaq/

If you have some time to spare, why not drop by, pick some random
article, and let us know how it can be improved:

http://effbot.org/random/pyfaq

Or even better, if you have a FAQ entry or some other idea to share,
post it here:

http://effbot.org/pyfaq/suggest

 



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


Re: my first software

2006-10-27 Thread Steve Holden
Bjoern Schliessmann wrote:
> Fredrik Lundh wrote:
> 
> 
>>cygwin?
> 
> 
> I thought so too, but cygwin would use #!/cygdrive/c/..., IIRC.
> 
Cygwin is actually pretty liberal about paths, and will often take a 
Winwos-style path (unlike the snotty cmd.exe program that insists on 
treating forard slashes ONLY as option indicators.
> 
>>exemaker?  some kind of web server? 
> 
> 
> Okay, didn't know that :)
> 
> Regards,
> 
> 
> Björn
> 

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: question about True values

2006-10-27 Thread Steven D'Aprano
On Fri, 27 Oct 2006 09:16:57 +, Antoon Pardon wrote:

>> I think it is a good time to remind people of some extremely well-thought
>> out opposition to the introduction of bools to Python from Laura Creighton:
>>
>> http://mail.python.org/pipermail/python-list/2002-April/095878.html
>>
>> She lost the debate, Guido had the final word and Python now has bools.
>> Take particular note of her description of Python distinguishing between
>> Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc).
> 
> Yes and IMO that is a less usefull distinction than the distinction
> between True and False. When I write code I think in terms of
> conditions. In those conditions this has to be treated this way
> otherwise it has to be treated an other way. Conditions give
> results that are either True or False, not Something or Nothing.

And if you read the thread that Laura Creighton's post is part of, you
will see that she acknowledges that most people think strongly in terms
of binary true/false yes/no states, and that this is often the wrong thing
to do. There are lots of human thought patterns that are unhealthy, and
binary is often one of them.

The world is continuous, and our brains think in binary. No wonder people
have such trouble with concepts like evolution:

- there is a continual chain of individuals such that every offspring of
an reptile is a reptile, and every parent of a mammal is a mammal, and
yet mammals are directly descended from reptiles.

By I digress. This is too easy to get off topic...


> I don't think of 10 > 5 as Something while 5 < 10 would be
> Nothing. 

Not at all, you got your operators the wrong way around. Five certainly is
less than 10 in every counting system I've ever come across. I think you
meant 5 > 10 is Nothing.

Certainly purely mathematical relations like GT and LT lend themselves
very well to true two-valued algebra. The thing to remember is that
Python's truth model is not the same as pure Boolean algebra. For
starters, it certainly is not two-valued! It is infinitely-valued. It's
just that many of those values are equivalent *in a Boolean context*.

In Pascal, writing "x := 2; if x then..." would be an error, because x is
not a Boolean. But it is certainly useful to be able to write the
equivalent in Python. The designer of Pascal choose strict Boolean
algebra; the designer of Python choose a more flexible, less strict model.

If you are going to argue for strict Booleans, like in Pascal, then
mathematical relations like GT and LT will be your poster-child. 

But if you are going to argue for Python's less strict truth model, then
you'll talk about lots of examples like this:

if somelist:
# work with the list
else:
# nothing to work with



> So while the paradigma of the language may be the
> distinction of Something vs Nothing the programmer will often
> enough think in terms of True and False. 

If you read Laura's post, you will see that she is arguing strongly that
thinking about True and False is often -- usually! -- a mistake. I
acknowledge that there are cases where it is either necessary or desirable
to think in terms of True/False, but that is less common than you might
think.


> So IMO it would have
> been better if python had made the distinction between True and
> False and so made the programmer code the Something/Nothing
> disctinction explicitly.

I don't understand what you are saying here, unless it is that you
believe that Python should have strict Pascal-style Booleans.


-- 
Steven.

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


Re: PyDev + Eclipse (Was: Re: What's the best IDE?)

2006-10-27 Thread Michael B. Trausch
olive wrote:
> Michael B. Trausch wrote:
> 
>> Yep.  Still does it.
> 
> I'm running PyDev 1.2.4 without completion problem so far.
> 
> Are you up to date ?
> 
> Maybe you should install the latest from scratch.
> 

Yep, I am up to date.  As I said, I am totally confused.

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


Re: How to Split Chinese Character with backslash representation?

2006-10-27 Thread Paul McGuire
"Wijaya Edward" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Hi all,
>
> I was trying to split a string that
> represent chinese characters below:
>
>
 str = '\xc5\xeb\xc7\xd5\xbc'
 print str2,
> ???
 fields2 = split(r'\\',str)
 print fields2,
> ['\xc5\xeb\xc7\xd5\xbc']
>
> But why the split function here doesn't seem
> to do the job for obtaining the desired result:
>
> ['\xc5','\xeb','\xc7','\xd5','\xbc']
>

There are no backslash characters in the string str, so split finds nothing 
to split on.  I know it looks like there are, but the backslashes shown are 
part of the \x escape sequence for defining characters when you can't or 
don't want to use plain ASCII characters (such as in your example in which 
the characters are all in the range 0x80 to 0xff).  Look at this example:

>>> s = "\x40"
>>> print s
@

I defined s using the escaped \x notation, but s does not contain any 
backslashes, it contains the '@' character, whose ordinal character value is 
64, or 40hex.

Also, str is not the best name for a string variable, since this masks the 
built-in str type.

-- Paul 


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


Re: Slurping All Content of a File into a Variable

2006-10-27 Thread Paul McGuire
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> myfile_content is an object and you have only opened the file.  Python
> doesn't yet know whether you want to read it, copy it etc.
>
> to read it try
>
> text = myfile_content.readlines()
> print text
>
> this should be in most tutorials
>

readlines() will give you the file content as a list of newline-terminated 
strings.  If you just want the whole file in one big string do:

text = myfile_content.read()

And, yes, you should wade through some of the tutorials, this is basic 
material.

-- Paul 


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


Re: NumPy 1.0 release

2006-10-27 Thread sturlamolden

Travis E. Oliphant wrote:

> We are very pleased to announce the release of NumPy 1.0 available for
> download at http://www.numpy.org

Congratulations to you and the other NumPy developers for completing
this major undertaking. I would also like to express my sincere
gratitude for making this making this software available to all of us.
Thank you.

Sturla Molden

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


Re: Insert Content of a File into a Variable

2006-10-27 Thread Paul McGuire
"Wijaya Edward" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Hi,
>
> How can we slurp all content of a single file
> into one variable?
>

Please don't double-post your questions.  Now you have two threads running 
with people answering the same question.

-- Paul


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


Re: PyDev + Eclipse (Was: Re: What's the best IDE?)

2006-10-27 Thread Éric Daigneault
olive wrote:

> > Michael B. Trausch wrote:
> > 
>   
>> >> Yep.  Still does it.
>> 
> > 
> > I'm running PyDev 1.2.4 without completion problem so far.
> > 
> > Are you up to date ?
> > 
> > Maybe you should install the latest from scratch.
> > 
>   
>
>Yep, I am up to date.  As I said, I am totally confused.
>
>   -- Mike

I run the latest pydev on both windows and linux...  The setup is excatcly the 
same (on the eclipse, path setup and all)  

My windows setup is much better at auto-complete that the linux setup...  In 
linux, other than with self, I seldom get auto complete on other classes.  In 
windows it sometimes can figure out to what class belong the instance and 
propose appropriate choices...

Caus of my present workload I gave up trying to make it work...  

E :D.


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


[Fwd: Using cElementTree and elementtree.ElementInclude]

2006-10-27 Thread Mark


 Original Message 
Subject: Using cElementTree and elementtree.ElementInclude
Date: Mon, 23 Oct 2006 09:40:24 -0500
From: Mark E. Smith <[EMAIL PROTECTED]>
Organization: AEDC
To: python-list@python.org

> cElementTree cannot hold ElementTree instances.
>
> can you post a small but self-contained example showing how you got this
> error?

> 



#from elementtree.ElementTree import ElementTree, dump # This works
from cElementTree import ElementTree, dump # This does not
from elementtree import ElementInclude

etree = ElementTree(file='xml_in.xml').getroot()
dump(etree)

ElementInclude.include(etree)
dump(etree)

for child in etree.find('./included_root').findall('./*'):
# Copy the child down to the root
etree.append(child)
# Remove the root/included_root
etree.remove(etree.find('./included_root'))
dump(etree)



http://www.w3.org/2001/XInclude";>
 
 









Thanks for the help.
Mark

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


To Kill a Process that is Accepting Connection on Socket

2006-10-27 Thread mumebuhi
I removed my previous post about this topic because I apparently have
pasted the wrong code. Sorry for the confusion and thanks for being
patient.

I am having problem to kill the following script completely. The script
basically does the following. The main thread creates a new thread,
which does a completely useless thing, and then starts excepting for a
connection via socket.

# start
import pickle
import signal
import simplejson
import socket
import sys
import threading
import time

counter = 0

class WorkerThread(threading.Thread):
def run(self):
global counter
while True:
counter += 1
time.sleep(10)

worker_thread = WorkerThread()
worker_thread.start()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 2727))
server.listen(2)

def cleanup(signal, frame):
print "die now"
worker_thread.join(1)
server.shutdown(socket.SHUT_RDWR)
sys.exit(0)
signal.signal(signal.SIGINT, cleanup)

while True:
channel, details = server.accept()
stats = { 'key': "value" }
s = simplejson.dumps(stats)
channel.send(s)
channel.close()
# end

The way I can think of right now is to kill the script using Ctrl+C.
Hence, the signal handler in the code. However, the interpreter
complains:
$ python ex_server.py
die now
Traceback (most recent call last):
  File "ex_server.py", line 33, in ?
channel, details = server.accept()
  File "/usr/lib/python2.4/socket.py", line 169, in accept
sock, addr = self._sock.accept()
  File "ex_server.py", line 28, in cleanup
server.shutdown(socket.SHUT_RDWR)
  File "", line 1, in shutdown
socket.error: (128, 'Transport endpoint is not connected')

Does anybody know a better way to do this?

Thank you.

Buhi

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


Re: question about True values

2006-10-27 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Thursday 26 October 2006 02:56, John Salerno wrote:
>  >>> s = 'hello'
>  >>> s == True
> False
>  >>> if s:
> print 'hi'
>
this isn't only a python behavior.
the  "if" test is valid for all non-zero variables. only None, 0 and False 
make the condition to jump over.

F


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


Re: Printing Hidden Character in Python

2006-10-27 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Thursday 26 October 2006 16:43, Wijaya Edward wrote:
> How can we print out the hidden character like
> "\n", "\r" etc in Python?

If it's meant to evidentiate then you should scan each byte an print it out
i.e.
o = open('yourfile'.'rb')

>>> o = open('paths.con','rb')
>>> for c in o.read():
...  if c == '\n':
...   print '\\n'
...  if c == '\r':
...   print '\\r'
...  print c,
...
unfortunately it will be a space between each letter. Maybe using 
sys.stderr.write (c) will avoid that.

F


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


Configfile

2006-10-27 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


HI,

I've a small doubt regarding the way to save a configuration file on the file 
manipulated by ConfigParser.
As far as I could understand this:

cp = ConfigParser.ConfigParser
cp.set(section,option)

will it do the set on the file or do I have to issue a "cp.write(fp)" in order 
to get it done?
My tests didn't resulted positively.

F


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


Re: question about True values

2006-10-27 Thread Steven D'Aprano
On Fri, 27 Oct 2006 12:54:35 +0100, Steve Holden wrote:

> Antoon Pardon wrote:
>> On 2006-10-27, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> 
>>>Antoon Pardon wrote:
>>>
>>>
>since you never publish any code,

This is not True. You shouldn't confuse your lack of recollection
with reality.
>>>
>>>pointers, please.
>> 
>> 
>> Sorry, the answer is no. I don't care whether you can locate my code
>> or not or wish to believe me or not.
>> 
> Google finds 2 hits for "Anton Pardoon open source". You are ceratinly 
> keeping it well hidden.
> 
> Few people have more right to call you on this than the effbot, well 
> known for his prolific output.


This may come as a shock to some of us in the Open Source arena, but the
care-factor of code is not necessarily tied to the number of distinct
pieces of code released to the public by the code's author. Many people,
for example, care a lot about the software running in nuclear reactors,
regardless of whether or not the code's author is a prolific Open Source
developer.

Of course Fredrik has a proven track record, and the quality of his code
is out there for any interested person to see. That means that the wise
person, even if he disagrees with Fredrik, should take what he has to say
seriously. If Fredrik is dismissive of Antoon's use of "if len(list) != 0"
instead of "if list", we should take that opinion very seriously.

But for all we know, Antoon's code might be responsible for keeping
nuclear reactors running, planes in the air, missiles hitting their
targets, or some other really critical application. His lack of visible
code doesn't *necessarily* mean we should dismiss what he has to say -- it
merely means that his track record is unproven to us.

And even if he does nothing but write trivial scripts for his own use,
that fact alone doesn't make his opinion wrong or foolish.

But in this specific instance, I don't see any advantage to explicitly
testing the length of a list. Antoon might think that is sufficiently
polymorphic, but it isn't. He cares whether the object has zero _length_,
but for true polymorphism, he should be caring about whether the object is
_empty_. Not all empty objects have zero length, or even a length at all.
(E.g. binary trees.) That's why Python classes can use a __nonzero__
method, falling back on __len__ only if __nonzero__ is not defined.


-- 
Steven.

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


Re: print dos format file into unix format

2006-10-27 Thread Magnus Lycka
Tim Roberts wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> Suppose I have a dos format text file. The following python code will
>> print ^M at the end. I'm wondering how to print it in unix format.
>>
>> fh = open(options.filename)
>> for line in fh.readlines()
>>  print line,
> 
> Are you running this on Unix or on DOS?
> 
> On Unix, you can do:
> 
> for line in open(options.filename).readlines():
> print line.rstrip()
> 
> Perhaps quicker is:
> 
> sys.stdout.write( open(options.filename).read().replace('\r\n','\n') )

There are more differences between text files than that.
I don't know any unix systems that uses CP 437 etc. I'd
convert the text to unicode through .decode('cp437') etc,
and then print that. If things aren't set up so than
unicode object print correctly, use
.decode('cp437').encode('utf8') etc to get it to an
appropriate encoding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricting import file lookup for pyd, dll, ...

2006-10-27 Thread Magnus Lycka
Bernard Lebel wrote:
> Hi,
> 
> That's because I'm using Python through another application, via the
> pywin32 extensions. When that other application starts, it performs
> several thousands of file requests (we're talking 4,500, roughly) in
> the Python installation, locations where there are Python files, and
> in some other locations that don't make sense. This adds considerable
> time to the startup time of the application, we're talking between 2
> and 9 seconds.

Sounds like a broken (networked?) file system. The only time I've
had that kind of problems with python startup is when I've had really
slow anti-virus programs that scanned all the files I opened. But then
it wasn't file requests that mattered, but actually opening them...
It still wasn't anywhere near 9 seconds though...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: conditional computation

2006-10-27 Thread robert
Bruno Desthuilliers wrote:
> robert wrote:
>> Bruno Desthuilliers wrote:
>>> robert a écrit :
>>> (snip)
 class MemoCache(dict): # cache expensive Objects during a session
 (memory only)
def memo(self, k, f):
try: return self[k]
except KeyError:#<- was error   
 return self.setdefault(k, f())
 cache=MemoCache()
 ...

 o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )

>>> And how do you get back the cached value without rewriting both
>>> complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ?
>> the complex-key-expr is written only once in the code
> 
> How do you get something back from the cache then ?
> 
>> expensive-calc-expr is  written only once in code 
> 
> Same problem here...  I fail to understand how you intend to use this
> "cache".

the first time, "self.setdefault(k, f())" executes the lambda ("f()"), stores 
it to the cache dict and the value is returned.

then on cache hit the stored value is just returned from the cache dict "try: 
return self[k]" and the lambda is not executed again.

note: the lambda expression expensive-calc-expr is just compiled but not 
executed as long as it is not called ( "f()" )

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


Re: Assertion failure on hotshot.stats.load()

2006-10-27 Thread Yang
I created a simple test case showing the zope.interface problem. Just
pass the following file to profile.py (i.e. the 'profile' module in
your Python standard library, run as a standalone app). The culprit
*seems* to be Twisted. Any ideas? Thanks in advance.

#!/usr/bin/env python

"""
error i get:

Traceback (most recent call last):
  File "/home/yang/local/bin/profile.py", line 611, in ?
run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
  File "/home/yang/local/bin/profile.py", line 72, in run
prof = prof.run(statement)
  File "/home/yang/local/bin/profile.py", line 448, in run
return self.runctx(cmd, dict, dict)
  File "/home/yang/local/bin/profile.py", line 454, in runctx
exec cmd in globals, locals
  File "", line 1, in ?
  File "/home/yang/proj/assorted/sandbox/trunk/src/py/profile.py", line 6, in ?
class Cnl( object ):
  File "/opt/zope/lib/python/zope/interface/advice.py", line 132, in advise
return callback(newClass)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
485, in _implements_advice
classImplements(cls, *interfaces)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
462, in classImplements
spec.declared += tuple(_normalizeargs(interfaces))
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
1373, in _normalizeargs
_normalizeargs(v, output)
  File "/opt/zope/lib/python/zope/interface/declarations.py", line
1372, in _normalizeargs
for v in sequence:
TypeError: Error when calling the metaclass bases
iteration over non-sequence

"""

from zope.interface import *
from twisted.internet import interfaces
class Cnl( object ):
implements( interfaces.IPushProducer )

On 10/27/06, Yang fer7msb02-at-sneakemail.com |python|
<...> wrote:
> I fell back onto the old profile module, but got the following error
> when trying to use zope.interface. I am now without any way to profile
> my application.
>
> Traceback (most recent call last):
>   File "/home/yang/local/bin/profile.py", line 611, in ?
> run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
>   File "/home/yang/local/bin/profile.py", line 72, in run
> prof = prof.run(statement)
>   File "/home/yang/local/bin/profile.py", line 448, in run
> return self.runctx(cmd, dict, dict)
>   File "/home/yang/local/bin/profile.py", line 454, in runctx
> exec cmd in globals, locals
>   File "", line 1, in ?
>   File 
> "/.automount/nms.lcs.mit.edu/export/home/yang/proj/cartel/trunk/icedb/src/frontend/icedb-central.py",
> line 5, in ?
> from icedb import *
>   File "/home/yang/local/lib/python2.4/site-packages/icedb/__init__.py",
> line 4, in ?
> import cafnet
>   File "/home/yang/local/lib/python2.4/site-packages/cafnet/__init__.py",
> line 269, in ?
> class Cnl( object ):
>   File "/opt/zope/lib/python/zope/interface/advice.py", line 132, in advise
> return callback(newClass)
>   File "/opt/zope/lib/python/zope/interface/declarations.py", line
> 485, in _implements_advice
> classImplements(cls, *interfaces)
>   File "/opt/zope/lib/python/zope/interface/declarations.py", line
> 462, in classImplements
> spec.declared += tuple(_normalizeargs(interfaces))
>   File "/opt/zope/lib/python/zope/interface/declarations.py", line
> 1373, in _normalizeargs
> _normalizeargs(v, output)
>   File "/opt/zope/lib/python/zope/interface/declarations.py", line
> 1372, in _normalizeargs
> for v in sequence:
> TypeError: Error when calling the metaclass bases
> iteration over non-sequence
>
> On 10/27/06, Yang fer7msb02-at-sneakemail.com |python|
> <...> wrote:
> > Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks
> > several packages I depend on. I'm using Python 2.4.3.
> >
> > I'm getting an AssertionError on "assert not self._stack" when calling
> > hotshot.stats.load() on my app's hotshot profile. The app consistently
> > causes hotshot to generate such a problematic profile, but I have no
> > idea what's causing it. Anybody know what's wrong?
> >
> > Here's the profile:
> >
> > http://www.filefactory.com/file/76fdbd/
> >
> > Potentially relevant bugs:
> >
> > http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470
> > http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470
> >
> > Thanks in advance for any help.
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Test

2006-10-27 Thread Lad
Test

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


Re: Search & Replace

2006-10-27 Thread DataSmash
Really appreciate all the all the different answers and learning tips!

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


Re: Assertion failure on hotshot.stats.load()

2006-10-27 Thread skip

Yang> Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks
Yang> several packages I depend on. I'm using Python 2.4.3.

Not a direct answer to your question, but the cProfile module runs just fine
under 2.4.

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


Re: Tracing the execution of scripts?

2006-10-27 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Friday 27 October 2006 17:31, R. Bernstein wrote:
> pydb (http://bashdb.sf.net/pydb) has a both the ability to trace lines

I faced several time that pydb stuck without sign of errors. In the other hand 
Pdb doesn't appear that problem.
Mostly pydb freeze on long loops.
It might be some problem on my setup, I'll check it up...

F

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


Re: ANN: wxPython 2.7.1.3

2006-10-27 Thread Johann C. Rocholl
Hi Robin,

You may want to use a spell checker for announcements and for the
wxpython.org website. For example, the first paragraph of your
announcement contains the words "plust" and "pacakges", and the word
"pacakge" can also be found on the following pages:

www.wxpython.org/download.php
www.wxpython.org/wxPython.spec
www.wxpython.org/CHANGES.html

Oh, it's fun to be a speling fanatic! :-)

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


Re: subprocess cwd keyword.

2006-10-27 Thread Ivan Vinogradov
On 27-Oct-06, at 2:25 AM, Leo Kislov wrote:

>
> Ivan Vinogradov wrote:
>> ...
>>
>> call("core/main") works but uses .. of core for input/output.
>>
>> call("core/main",cwd="core") and call("main",cwd="core") both  
>> result in
> [snip exception]
>
> Usually current directory is not in the PATH on UNIX. Try
> call("./main",cwd="core")
>
>   -- Leo

Thank you both Leo and Steven.
The solution was indeed calling "main" as "./main" once cwd was changed.

--
Cheers, Ivan.


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


Re: Sentinel values for special cases

2006-10-27 Thread Aahz
In article <[EMAIL PROTECTED]>,
Ben Finney  <[EMAIL PROTECTED]> wrote:
>
>Fourth, if you have decided that a magic sentinel value is called for
>but None is already taken for some other purpose, don't use a
>string. Use a unique do-nothing object, defined at the module level so
>callers can easily get at it, like 'Dmitry Vasiliev' showed
>[reproduced below].
>
>GLOBAL = object()
>
>def insert_ids(ids=GLOBAL):
>if ids is GLOBAL:
>ids = get_global_ids()

The one disadvantage of this approach is that it complicates pickling
if/when you store the stentinel in an instance.  There are ways of
working around that, but none are pleasant.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: Printing Hidden Character in Python

2006-10-27 Thread Brian Mills

Fulvio wrote:
> ***
> Your mail has been scanned by InterScan MSS.
> ***
>
>
> On Thursday 26 October 2006 16:43, Wijaya Edward wrote:
> > How can we print out the hidden character like
> > "\n", "\r" etc in Python?
>
> If it's meant to evidentiate then you should scan each byte an print it out
> i.e.
> o = open('yourfile'.'rb')
>
> >>> o = open('paths.con','rb')
> >>> for c in o.read():
> ...  if c == '\n':
> ...   print '\\n'
> ...  if c == '\r':
> ...   print '\\r'
> ...  print c,
> ...
> unfortunately it will be a space between each letter. Maybe using
> sys.stderr.write (c) will avoid that.
>
> F

Or sys.stdout.write(c).  If efficiency is a major issue, you may also
want to look into the re module's regular expression substitution model
to get a new, converted string before printing it.

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


Re: PyQt-x11-gpl-3.16 compile error

2006-10-27 Thread David Boddie
[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] PyQt-x11-gpl-3.16]# python configure.py -q
> /usr/lib/qt-3.3/
> This is the GPL version of PyQt 3.16 (licensed under the GNU General
> Public
> License) for Python 2.4.2 on linux2.

[...]

> Creating features file...
> Error: Unable to build mkfeatures utility.

Can you run the configure.py script again with the -w option as well as
the others you specified, then post the output here?

David

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


Re: How the event list be sent to EventManager?

2006-10-27 Thread steve
Can an argument to reference an object's attribute??

Fredrik Lundh wrote:
> steve wrote:
>
> > The example code from: http://sjbrown.ezide.com/games/example1.py.html
> > ...
> > def Notify( self, event ):
> > if not isinstance(event, TickEvent): Debug( "
> > Message: " + event.name )
> > for listener in self.listeners.keys():
> > #If the weakref has died, remove it and
> > continue
> > #through the list
> > if listener is None:
> > del self.listeners[ listener ]
> > continue
> > listener.Notify( event )
> >
> > I can not figure out how 'event' can has reference to 'event.name'?
>
> because the developer expects you to pass in an object that has a name
> attribute ?  (one of the Event types defined at the top of that module,
> most likely).
>
> > Anyhow the 'event' has not defined!
>
> it's an argument to the method.
>
> > The 'event' dynamically get its own type through
> > isinstance(event,TickEvent):...?
>
> no, that line simply checks if it's a specific Event type, and enables
> debug logging for all other event types.
> 
> 

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


Re: Configfile

2006-10-27 Thread Diez B. Roggisch
Fulvio schrieb:
> ***
> Your mail has been scanned by InterScan MSS.
> ***
> 
> 
> HI,
> 
> I've a small doubt regarding the way to save a configuration file on the file 
> manipulated by ConfigParser.
> As far as I could understand this:
> 
> cp = ConfigParser.ConfigParser

You are missing a () here

> cp.set(section,option)
> 
> will it do the set on the file or do I have to issue a "cp.write(fp)" in 
> order 
> to get it done?
> My tests didn't resulted positively.

What does that mean? Did your head explode, has a giant mammoth stomped 
your PC into oblivion, or has by any chance an exception occured that 
you don't show us?

I guess you've been told to read this here, but just in case it wasn't, 
or you didn't bother to read it:

http://catb.org/esr/faqs/smart-questions.html

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


Re: virtual function appears in two bases

2006-10-27 Thread Fredrik Lundh
joe Li wrote:

> I saw the following code, but I don't understand the rule for virtual 
> function that appears in two bases
> Could anyone explain it for me, thanks.

http://docs.python.org/tut/node11.html#SECTION001151



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


Re: Tracing the execution of scripts?

2006-10-27 Thread Larry Bates
I just thought I would put my 2 cents in on this issue.  Others
have suggested that unit tests are an excellent way of debugging
your code and I agree.  I also find that writing code from the
outset using a logging class (there is one in the standard
library) that allows you to create log files of information as
you run your application is a good idea.  Using increasingly
detailed logs (I use a debug mode of 1,2,3,4 for more detail)
that dump where you are and intermediate variable values works
EXTREMELY well for me.  I leave this code in the application
so that I can have customers (or myself) run the application
in debug mode should I have a hard to find problem.  This is
especially true for long running or lights-out batch apps
that have no UI making debugging even more difficult.  I find
that the overhead of testing if I'm in debug mode and logging
results is almost non-existent to the overall execution speed
of my scripts, but then I don't have very many really speed
sensitive scripts so your mileage might vary.

Hope the information helps.

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


Re: Configfile

2006-10-27 Thread Larry Bates
Fulvio wrote:
> ***
> Your mail has been scanned by InterScan MSS.
> ***
> 
> 
> HI,
> 
> I've a small doubt regarding the way to save a configuration file on the file 
> manipulated by ConfigParser.
> As far as I could understand this:
> 
> cp = ConfigParser.ConfigParser
> cp.set(section,option)
> 
> will it do the set on the file or do I have to issue a "cp.write(fp)" in 
> order 
> to get it done?
> My tests didn't resulted positively.
> 
> F
> 
> 
Yes you have to get a file pointer (fp) and do the write as you noted.

Also to get instance of ConfigParser you need:

cp = ConfigParser.ConfigParser()  (note the trailing parenthesis)

If you want to read existing .INI file before doing this you need a
cp.read('filename.ini') somewhere in your code.

-Larry


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


Re: Python 2.5 ; Effbot console ; thank ; pb release.

2006-10-27 Thread Magnus Lycka
Méta-MCI wrote:
> Hi!  (***sorry for my approximative english***)

That's ok. Quite amusing to read that you were repaired.

> A few months ago, I needed a console, under Windows.
> After several research, I selected the console of EffBot.
> 
> Thank you very much, Fredrik Lundh, for this small tool,
> quite practical and which repaired me well.
> 
> Then, Python 2.5 arrived.

That doesn't mean it's clever to use 2.5 right now...
There's plenty of code which isn't adapted to 2.5 yet.

Personally, I use 2.4 at work (although sometimes I
still need to be 2.2 compatible) and at home I have
both 2.4 and 2.5 installed. Most of the time I work
with 2.4 since I use packages which don't support 2.5
yet (or at least the last time I checked).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-27 Thread Magnus Lycka
David Boddie wrote:
> You're forgetting that Qt isn't just a widget toolkit.

I suspect that the non-GUI parts are (just like in Wx) C++ stuff
which is more or less equivalent with things that are either Python
builtins or parts of Python's standard library. Besides, getting
those proprietary dependencies even further down into the code than
the GUI is not a plus in my book.

Last time I looked, Qt code wasn't even pure C++ but needed some
preprocessing like embedded SQL. Yet another programming language
in other words. I suppose I can ignore that from Python, but it
still smells...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyDev + Eclipse (Was: Re: What's the best IDE?)

2006-10-27 Thread Fabio Zadrozny
On 10/26/06, Michael B. Trausch  wrote:
Kenneth McDonald wrote:>> With the most recent edition of PyDev, I find Eclipse works quite well
> for me.>Since you mentioned it, I have a question that searching around andpoking around has not solved for me, yet.Do you have auto-completion working with your setup?  It does not seem
to work at all for me.  I have read through the configuration help, andthere are no firewalls on my system at all, and everything else workssave for auto-completion, which I have had to disable.  If left enabled,
even with low timeouts, I have to kill Eclipse and start it again.  :-/
Do you have some firewall on? There was a report
(http://sourceforge.net/tracker/index.php?func=detail&aid=1509582&group_id=85796&atid=577329
)
in which the problem was actually a misconfiguration when creating
local-loops (accessing 127.0.0.1) in linux. If this is not your
problem, please create a bug-report -- check
http://pydev.sf.net/faq.html#ref_0 for bug-writing guidelines.

Cheers,

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

Re: Insert characters into string based on re ?

2006-10-27 Thread guido . thelen

You can test it here: http://www.sqlinform.com

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


Re: conditional computation

2006-10-27 Thread Bruno Desthuilliers
robert wrote:
> Bruno Desthuilliers wrote:
>> robert wrote:
>>> Bruno Desthuilliers wrote:
 robert a écrit :
 (snip)
> class MemoCache(dict): # cache expensive Objects during a session
> (memory only)
>def memo(self, k, f):
>try: return self[k]
>except KeyError:#<- was error  
> return self.setdefault(k, f())
> cache=MemoCache()
> ...
>
> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )
>
 And how do you get back the cached value without rewriting both
 complex-key-expr *and* expensive-calc-expr ? Or did I missed the
 point ?
>>> the complex-key-expr is written only once in the code
>>
>> How do you get something back from the cache then ?
>>
>>> expensive-calc-expr is  written only once in code 
>>
>> Same problem here...  I fail to understand how you intend to use this
>> "cache".
> 
> the first time, "self.setdefault(k, f())" executes the lambda ("f()"),
(snip)
Robert, that's not the point. I do have enough Python knowledge to
understand this (totally trivial) code !-)

What I don't understand is how this code is supposed to save you from
having to actually write both complex-key-expr and
expensive-calc-expression more than once. You need them both each time
you access the cache - whether the result of expensive-calc-expression
has already been cached or not.

Now this seems so obvious that I guess I failed to understand some point
in your original spec (emphasis is mine):
"""
I want to use a computation cache scheme like


o = CACHECOMPUTE  complex-key-expr  expensive-calc-expr

frequently and elegantly *without writing complex-key-expr or
expensive-calc-expr twice*.
"""


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Accessing ClarifyCRM with Python

2006-10-27 Thread Jason
I need to embed the ability to create a Clarify Case in a python
program I have written.  Unfortunately my familiarity with Clarify is
very limited at this point.

Is there a module out there that makes this process semi-painless?  I
couldn't find one googling around...  Has anyone implemented something
like this?  Care to give a few pointers?

I do know that another part of the business has a perl script that can
generate a Clarify case. I'm chasing down that example as well, but I
don't have it in hand at this point.  So I know that this is
possible... I just don't know how much work it will be.

Any pointers would be greatly appreciated.

--Jason

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


Telnetlib to twisted

2006-10-27 Thread Matthew Warren
Hallo,

>>> import telnetlib
>>> l=telnetlib.Telnet('dbprod')
>>> l.interact()
telnet (dbprod)

Login:


Could anyone show how the above would be written using the twisted
framework? All I'm after is a more 'intelligent' interactive telnet
session (handles 'vi' etc..) rather than the full capabilities of the
twisted framework.


Thanks,

Matt.


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Telnetlib to twisted

2006-10-27 Thread Bjoern Schliessmann
Matthew Warren wrote:

> Could anyone show how the above would be written using the twisted
> framework? All I'm after is a more 'intelligent' interactive
> telnet session (handles 'vi' etc..) rather than the full
> capabilities of the twisted framework.

Not done this until now, but have a look at twisted.conch.telnet.
 
> This email is confidential and may be privileged. If you are not
> the intended recipient please notify the sender immediately and
> delete the email from your computer.

Am I the inteded recipient? I'm not listed in the headers.

Regards,


Björn

-- 
BOFH excuse #439:

Hot Java has gone cold

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


Re: How the event list be sent to EventManager?

2006-10-27 Thread Fredrik Lundh
steve wrote:

> Can an argument to reference an object's attribute??

sorry, cannot parse that sentence.

the arguments to a method are objects, and objects have attributes.  why 
do you find this surprising?



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


Re: Tracing the execution of scripts?

2006-10-27 Thread fumanchu
Stephan Kuhagen wrote:
> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote:
>
> > Basically, is there something that will log every line of Python code
> > executed, in its order of execution, to a text file so that I can see
> > what is (or isn't) happening that I am expecting?
>
> Python itself can do this for you. A __VERY__ simple approach:
> ...
> Additionally, if it should work with threads, you must take care
> that every thread gets its own output file.

Or be differentiated *somehow*. My pyconquer module tabs each thread's
activity into swimlanes, so you can even see when each thread starts,
obtains/releases the GIL, and stops. See the longer example here:
http://projects.amor.org/misc/wiki/PyConquer


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]

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


importing class

2006-10-27 Thread gmarkowsky
Hi all,

I'm trying to import a class from a module. The class looks like this:
class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()

self.button = Button(frame, text=text_1, command= self.comm_1)
self.button.pack(side=LEFT)

self.hi_there = Button(frame, text=text_2, command=self.comm_2)
self.hi_there.pack(side=LEFT)

def comm_1(self):
command1()
root.quit()

def comm_2(self):
command2()
root.quit()

It's supposed to just make a Tkinter window with two choices. The
problem is that when I import it from a module, I get the following
error:

NameError: global name 'Frame' is not defined

But when I copy and paste it into the file, it works. Can anyone tell
me what's wrong?

Greg

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


Re: Handling emails

2006-10-27 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Friday 27 October 2006 06:48, Ben Finney wrote:
> There is always the option to not send messages to this list using
> that mail server

Once again sorry for that. I'll take action to switch to another mailserver.
Thank for the advice

F


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


Re: importing class

2006-10-27 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, gmarkowsky
wrote:

> Hi all,
> 
> I'm trying to import a class from a module. The class looks like this:
> class App:
> 
> def __init__(self, master):
> 
> frame = Frame(master)
> frame.pack()
> 
> self.button = Button(frame, text=text_1, command= self.comm_1)
> self.button.pack(side=LEFT)
> 
> self.hi_there = Button(frame, text=text_2, command=self.comm_2)
> self.hi_there.pack(side=LEFT)
> 
> def comm_1(self):
> command1()
> root.quit()
> 
> def comm_2(self):
> command2()
> root.quit()
> 
> It's supposed to just make a Tkinter window with two choices. The
> problem is that when I import it from a module, I get the following
> error:
> 
> NameError: global name 'Frame' is not defined
> 
> But when I copy and paste it into the file, it works. Can anyone tell
> me what's wrong?

Yes, the global name `Frame` is not defined.  `Frame` is a name in the
`Tkinter` module and you have to import it to reference it.  Add the
following import statement to your file:

from Tkinter import Frame, Button

You use `Button` too and this also lives in the `Tkinter` module.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Telnetlib to twisted

2006-10-27 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote:

>> This email is confidential and may be privileged. If you are not
>> the intended recipient please notify the sender immediately and
>> delete the email from your computer.
> 
> Am I the inteded recipient? I'm not listed in the headers.

This is irrelevant because the whole paragraph is about emails and not
about newsgroup postings.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Antoon Pardon <[EMAIL PROTECTED]> wrote:
...
> I think you are incorrect.

Thanks!  I rest my case!

> And how do I express that a number has to be greater than
> 100 into a Nothing vs Something dichotomy? Declare all
> greater numbers as Something and the rest as Nothing?

Well, would you declare numbers less than 100 False?

Think about it in more philosophical terms.  What is Truth?
The Internet Encyclopedia of Philosophy may be some help
with this - http://www.iep.utm.edu/t/truth.htm

Then when you get tired of that, suppose that "if" and
"while" are asking for "yes" and "no", instead of "true"
and "false", and ask yourself if we have the philosophical
problems with "yes" that we do with "true".

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How set the source IP adress

2006-10-27 Thread Irmen de Jong
Maksim Kasimov wrote:
> Hi,
> 
> how to set source ip-address when do __socket.connect((host, port))
> on a machine that have a several ip-adresses?
> 
> many thanks for advice.
> 
> __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> __socket.connect((host, port))
> 
> 

sock.connect ( ('11.22.33.44', ) )

i.e. just put the ip address as string parameter into the connect address tuple
(where you wrote: host)

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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-27, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> But in this specific instance, I don't see any advantage to explicitly
> testing the length of a list. Antoon might think that is sufficiently
> polymorphic, but it isn't. He cares whether the object has zero _length_,
> but for true polymorphism, he should be caring about whether the object is
> _empty_. Not all empty objects have zero length, or even a length at all.
> (E.g. binary trees.) That's why Python classes can use a __nonzero__
> method, falling back on __len__ only if __nonzero__ is not defined.

Nobody can force you to write a container class that also provides a
__len__ method. But if you don't provide one then IMO it is your class
that deviates from standard practice. Mathematically, sets and
directories have no length either, yet the len function does provide
an answer if you give it a set or directory as an argument. So
it seems that python has generalised the len function to provide
the number of elements in the container. 

I have written a Tree class(*). It can be used as a drop in replacement
anywhere where a directory is used, as long as there is a full order
relationship in the key domain. That tree class provides a __len__
method that will anser with the number of items in the tree just
as a directory would and I see nothing wrong with that.

Of course I can't account for all possible ways someone wishes to
write a class, but I don't see what is wrong with counting on
the fact that an empty container has a length of zero.

I can write a container class where the truth value of an object
is independent of whether or not the object is empty and then
the "if obj:" idiom will fail to provide true polymorphism too.

(*) http://www.pardon-sleeuwaegen.be/antoon/avltree.html

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


Using xtopdf, a PDF creation toolkit - Creating PDF Output from Plain Text, DBF, CSV, TDV, and XLS Data

2006-10-27 Thread vasudevram

Hi,

Though I posted about this article earlier, reposting it with a more
appropriate title, to make it easier for searches.

"Using xtopdf, a PDF creation toolkit"
URL: http://www.packtpub.com/article/Using_xtopdf

This is an article by me, written for Packt Publishing, about how to
use my xtopdf toolkit to create PDF from text, DBF, TDV, CSV and XLS
data.

xtopdf is available at http://www.dancingbison.com/products.html .

Enjoy,
and feel free to give your feedback on wanted features, bugs, etc. in
xtopdf - its appreciated.
Vasudev Ram
~~
Software consulting and training
Dancing Bison Enterprises
http://www.dancingbison.com
"Now creating PDFs from Python is even easier" - Steve Holden
http://del.icio.us/steve.holden/pdf 
~~

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


Re: ANN: the pyfaq wiki has moved

2006-10-27 Thread John Salerno
Fredrik Lundh wrote:

> If you have some time to spare, why not drop by, pick some random
> article, and let us know how it can be improved:
> 
> http://effbot.org/random/pyfaq

How do we log in to make changes?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-27, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Fri, 27 Oct 2006 09:16:57 +, Antoon Pardon wrote:
>
>>> I think it is a good time to remind people of some extremely well-thought
>>> out opposition to the introduction of bools to Python from Laura Creighton:
>>>
>>> http://mail.python.org/pipermail/python-list/2002-April/095878.html
>>>
>>> She lost the debate, Guido had the final word and Python now has bools.
>>> Take particular note of her description of Python distinguishing between
>>> Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc).
>> 
>> Yes and IMO that is a less usefull distinction than the distinction
>> between True and False. When I write code I think in terms of
>> conditions. In those conditions this has to be treated this way
>> otherwise it has to be treated an other way. Conditions give
>> results that are either True or False, not Something or Nothing.
>
> And if you read the thread that Laura Creighton's post is part of, you
> will see that she acknowledges that most people think strongly in terms
> of binary true/false yes/no states, and that this is often the wrong thing
> to do. There are lots of human thought patterns that are unhealthy, and
> binary is often one of them.

The Nothing/Something dichotomy is just as binary as the True/False
dichotomy. And in the case of deciding whether you will take the
"then" branch or "else" branch I see nothing unhealthy in checking
whether the condition was true or not.

> The world is continuous, and our brains think in binary. No wonder people
> have such trouble with concepts like evolution:

The world may be continuous, programming structures are discrete.
You take the "then" branch or not. In the latter case you can
again decide to take the elif branch or not. There is nothing
continuous in that.

> - there is a continual chain of individuals such that every offspring of
> an reptile is a reptile, and every parent of a mammal is a mammal, and
> yet mammals are directly descended from reptiles.
>
> By I digress. This is too easy to get off topic...
>
>
>> I don't think of 10 > 5 as Something while 5 < 10 would be
>> Nothing. 
>
> Not at all, you got your operators the wrong way around. Five certainly is
> less than 10 in every counting system I've ever come across. I think you
> meant 5 > 10 is Nothing.

Yes that was a type, I meant I don't think of 5 > 10 as Nothing.

> Certainly purely mathematical relations like GT and LT lend themselves
> very well to true two-valued algebra. The thing to remember is that
> Python's truth model is not the same as pure Boolean algebra. For
> starters, it certainly is not two-valued! It is infinitely-valued. It's
> just that many of those values are equivalent *in a Boolean context*.

That it is infinitely-valued is a red herring. It is partitioned in
two, so all these infinite values are mapped into two possibilities
because at the end you have to decide a simple yes/no question.
Will I repeat the loop or not. Will I take the "then" branch or
not.

> In Pascal, writing "x := 2; if x then..." would be an error, because x is
> not a Boolean. But it is certainly useful to be able to write the
> equivalent in Python. The designer of Pascal choose strict Boolean
> algebra; the designer of Python choose a more flexible, less strict model.
>
> If you are going to argue for strict Booleans, like in Pascal, then
> mathematical relations like GT and LT will be your poster-child. 
>
> But if you are going to argue for Python's less strict truth model, then
> you'll talk about lots of examples like this:
>
> if somelist:
> # work with the list
> else:
> # nothing to work with

In most case I just do:

  for el in somelist:

which works for empty lists just as good as non-empty ones. So
why should an empty list be treated differently from an non-empty
one if it is used in a boolean context?

>> So while the paradigma of the language may be the
>> distinction of Something vs Nothing the programmer will often
>> enough think in terms of True and False. 
>
> If you read Laura's post, you will see that she is arguing strongly that
> thinking about True and False is often -- usually! -- a mistake.

Yes she argues that? So? I think she is wrong and her argument
lacking.

> I
> acknowledge that there are cases where it is either necessary or desirable
> to think in terms of True/False, but that is less common than you might
> think.

Control structures in programming languages do nothing else but decide
things in terms of True/False. You may dress things up but in the
end a statement like:

  if obj:

Will evaluate/map into a two valued domain, where one value will lead you
into the "then" branch and the other value will not. And IMO the more
clearer the relationship between the written code and the final result
the better.

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


Re: How set the source IP adress

2006-10-27 Thread Grant Edwards
On 2006-10-27, Irmen de Jong <[EMAIL PROTECTED]> wrote:

>> how to set source ip-address when do __socket.connect((host, port))
>> on a machine that have a several ip-adresses?
>> 
>> __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>> __socket.connect((host, port))
>
> sock.connect ( ('11.22.33.44', ) )
>
> i.e. just put the ip address as string parameter into the
> connect address tuple (where you wrote: host)

Um, no. That controls the _destination_ IP address, not the
source.  If you want to control the source IP addresss you can
bind it to a local interface's IP address before doing the
connect() call.

sock.bind(('10.0.0.99',-1))  # -1: don't care about source port number
sock.connect((host,port))

That will make sure that 10.0.0.99 is used as the source IP
address.  Of course you have to have an interface with that
address.

-- 
Grant Edwards   grante Yow!  I'm a nuclear
  at   submarine under the
   visi.compolar ice cap and I need
   a Kleenex!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-27 Thread Carl Banks
Steven D'Aprano wrote:
> But in this specific instance, I don't see any advantage to explicitly
> testing the length of a list. Antoon might think that is sufficiently
> polymorphic, but it isn't. He cares whether the object has zero _length_,
> but for true polymorphism, he should be caring about whether the object is
> _empty_. Not all empty objects have zero length, or even a length at all.
> (E.g. binary trees.)

Conversely, not all objects that have length consider zero-length to be
false.  Whether you test with "if a:" or "if len(a)>0", some objects
are going to be denied.

Thing is, objects that don't have length have almost no overlapping
uses with lists (i.e., you'd hardly ever write a function that could
take an int or a list, unless you type check the argument or use only
object protocol stuff like id and getattr, or pass it to another
function that does the same).  Iterators do have overlapping uses with
lists, but the "if a:" doesn't work for them, so it's moot.  OTOH,
objects that have length but don't consider zero-length to be false
(numpy arrays) do have overlapping uses with lists.

So, as a practical matter, I'd be inclined to side with Antoon on this
issue, even if it only increases polymorphism for certain people.

"if a:" almost never increases polymorphism because almost no
lengthless objects would work in that function anyways.  Even if you
don't use numpy arrays, there's little practical benefit of "if a:"
except to save typing.  If you do use numpy, it limits polymorphism.

"if len(a)>0" does increase polymorphism because it allows for objects
that have length but don't equate empty to false.

P.S. binary trees do have length: it's the number of nodes, just as the
number of keys is the length of a dict.  I can't think of any objects
that use indexing but don't have a length, except for
poorly-implemented proxy objects.  It's possible to define such types,
but would that be a Pythonic use of indexing?



Carl Banks

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


Re: How set the source IP adress

2006-10-27 Thread Grant Edwards
On 2006-10-27, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2006-10-27, Irmen de Jong <[EMAIL PROTECTED]> wrote:
>
>>> how to set source ip-address when do __socket.connect((host, port))
>>> on a machine that have a several ip-adresses?
>>> 
>>> __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> __socket.connect((host, port))
>>
>> sock.connect ( ('11.22.33.44', ) )
>>
>> i.e. just put the ip address as string parameter into the
>> connect address tuple (where you wrote: host)
>
> Um, no. That controls the _destination_ IP address, not the
> source.  If you want to control the source IP addresss you can
> bind it to a local interface's IP address before doing the
> connect() call.
>
> sock.bind(('10.0.0.99',-1))  # -1: don't care about source port number
> sock.connect((host,port))

Doh!  That should have been 0 not -1.

-- 
Grant Edwards   grante Yow!  Do I hear th'
  at   SPINNING of various
   visi.comWHIRRING, ROUND, and WARM
   WHIRLOMATICS?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Beautiful women, aged clones, and Ultimate Fighting Championship

2006-10-27 Thread baseballsoccer123
Friend,

I'm always looking for good and intelligent individuals like you to
visit my website, www.ChezBrandon.com , and it has pictures of
beautiful women, information about aged clones, and a link to Ultimate
Fighting Championship, a very good show.

My name is Brandon, and I'm in my 20s, am a college student, and as lie
detectors, both conventional and unconventional would show, I've never
been sexually penetrated. Moreover, I could be shown pictures of X, Y,
and Z, and it would show that I'm only sexually attracted to women.

The Murders of Our Leaders were Stopped.

I can take lie detector and psychological tests. I tell the truth. A
mini-psychological test: 8 times 2 = 16, the world is round, not flat,
and the year is 2006. Feel free to call me, cellphone number is
503.740.0272, and utilize a GK-1 voice analyzer truth detecting device
too:

>From Congressmen Bill Frist to John Kerry to Dennis Hastert to Hillary
Clinton to John Warner to Ron Wyden to Gordon Smith to John McCain to
Joseph Lieberman to Nancy Pelosi to Diane Feinstein to Ted Kennedy to
anyone else who happened to be in the Congressional chambers during
either a joint session of Congress or a State of the Union address from
Masons to Skull and Bones members to Secret Service agents to pages to
visitors to other good individuals, they all would have been murdered,
all of their accomplishments stripped away, their earned wealth
stripped away, their homes stripped away, their family and friends
stripped away. Moreover, someone else would have been sleeping with
their spouses.

Elements of an organization, not of course the Masons or Skull and
Bones -- I was able, thank God, to thwart the conquest of the USA and
the world, and was able to thwart the murder of United States and world
leaders, via a psychic vision of Senator John Warner and other
Congressmen being choked to death by gas, which was confirmed
auditorially from both ears, such as "He saved Congress," who they were
going to kill "all of them,""how did he know that?" and "he's psychic"
-- murdered my biological Aunt Gloria Atkinson, whom I loved very much,
as she did of me, and there is a tribute to her on my website. Please,
friend, be sure to barricade your bedroom door at night. I'm not afraid
of aged clones or the attempted chopping off of my appendages (elements
of an organization talked about chopping off my right middle finger and
right ear, and 10 out of 10 of my toes, like my right middle finger
have unique steeple designs).

I'm not afraid of anything. I'll defend myself to the best of my
ability, and I commit my life to saving the lives of men, women, and
children and strengthening good organizations. Sincerely, Brandon

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


Re: Telnetlib to twisted

2006-10-27 Thread Jean-Paul Calderone
On Fri, 27 Oct 2006 16:40:44 +0100, Matthew Warren <[EMAIL PROTECTED]> wrote:
>Hallo,
>
 import telnetlib
 l=telnetlib.Telnet('dbprod')
 l.interact()
>telnet (dbprod)
>
>Login:
>
>
>Could anyone show how the above would be written using the twisted
>framework? All I'm after is a more 'intelligent' interactive telnet
>session (handles 'vi' etc..) rather than the full capabilities of the
>twisted framework.
>

Basically you want to hook up a telnet connection to stdio.  You can find
a couple examples of using stdio in a Twisted application here:

http://twistedmatrix.com/projects/core/documentation/examples/stdiodemo.py
http://twistedmatrix.com/projects/core/documentation/examples/stdin.py

Then you need a telnet connection to send the bytes you read from stdin to
and from which to receive bytes to write to stdout.

I don't think there are any good examples of using telnet as a client, but
it's pretty straightforward.  Something like this, for example, will make
a telnet connection and then write all the non-telnet negotiation data to
stdout:

  from twisted.internet.protocol import ClientCreator, reactor
  from twisted.conch.telnet import Telnet
  
  class PrintingTelnet(Telnet):
  def applicationDataReceived(self, bytes):
  print bytes

  def main():
  cc = ClientCreator(reactor, PrintingTelnet)
  d = cc.connectTCP(host, port)
  def connected(proto):
  print 'Connected'
  reactor.run()

  if __name__ == '__main__':
  main()

The part where a lot of people get stuck is hooking up the stdio protocol
to the network protocol.  For this, you just need to make sure each
instance has a reference to the other.  You can then call methods on the
stdio protocol from the telnet protocol when bytes are received, and vice
versa.

You may need to add in a layer to handle terminal control sequences, since
those pass through telnet and will get through to your application.  On the
other hand, if all you do is write them to stdout, your actual terminal
should handle them.  You'll only need an extra layer if you want to do extra
interpretation.

Hope this helps,

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


Re: question about True values

2006-10-27 Thread Antoon Pardon
On 2006-10-27, Donn Cave <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Antoon Pardon <[EMAIL PROTECTED]> wrote:
> ...
>> I think you are incorrect.
>
> Thanks!  I rest my case!
>
>> And how do I express that a number has to be greater than
>> 100 into a Nothing vs Something dichotomy? Declare all
>> greater numbers as Something and the rest as Nothing?
>
> Well, would you declare numbers less than 100 False?

No but the condition: x > 100, will map all numbers to
either True or False. Can you provide a condition that will
provide a mapping to Nothing and Something? Without
artificially mapping False to Nothing and True to Something?

> Think about it in more philosophical terms.  What is Truth?
> The Internet Encyclopedia of Philosophy may be some help
> with this - http://www.iep.utm.edu/t/truth.htm

I don't care about such philosophical issues. I also
doubt that you could provide better answers if you
would subsituted Somthingness for truth is that text.

> Then when you get tired of that, suppose that "if" and
> "while" are asking for "yes" and "no", instead of "true"
> and "false", and ask yourself if we have the philosophical
> problems with "yes" that we do with "true".

Of course we have. Deciding whether a statment/condition is true
or not is equivallent to deciding whether or not we should answer
yes or no to a related question.

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


Re: Tracing the execution of scripts?

2006-10-27 Thread R. Bernstein
Fulvio <[EMAIL PROTECTED]> writes:
> ***
> Your mail has been scanned by InterScan MSS.
> ***
Delighted to know that.

> 
> On Friday 27 October 2006 17:31, R. Bernstein wrote:
> > pydb (http://bashdb.sf.net/pydb) has a both the ability to trace lines
> 
> I faced several time that pydb stuck without sign of errors. In the other 
> hand 
> Pdb doesn't appear that problem.
> Mostly pydb freeze on long loops.

In version 1.19 (released today), I extended signal handling so that
you can send the program a signal and it will print a stack trace of
where it is and continue. But even before this release, you could
arrange to enter the debugger by sending it a signal. It's possible
something like this might be used help track down the problem in
either pydb or another Python program that seems to be not
responding. On the other hand, use at your own risk - I don't
guarentee this will work for you.

And.. before you ask for more details, I'll repeat what someone else
posted in response to another of your questions:

  I guess you've been told to read this here, but just in case it
  wasn't, or you didn't bother to read it:

  http://catb.org/esr/faqs/smart-questions.html

> It might be some problem on my setup, I'll check it up...

Given your other posts, that's quite possible. If it's not, submit a
bug report. (Posting to c.l.r isn't the same as submitting a bug
report). Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More Noob Questions

2006-10-27 Thread Omar
thank you all for your replies

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


  1   2   >