Re: Renaming files in ftplib

2006-01-09 Thread [EMAIL PROTECTED]
Do for instance:
Step 1. Move the file to another directory from the remote computer -
see http://docs.python.org/lib/ftp-objects.html
Step 2. Rename the file here. See
http://docs.python.org/lib/os-file-dir.html, function rename
Step 3. Move  the file to the desired directory, use the same function

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Anders Hammarquist
In article <[EMAIL PROTECTED]>,
Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>Request for more information
>
>My request for readers of comp.lang.python is to search your own code
>to see if map's None fill-in feature was ever used in real-world code
>(not toy examples).

I had a quick look through our (Strakt's) codebase and found one example.

The code is used to process user-designed macros, where the user wants
to append data to strings stored in the system. Note that all data is
stored as lists of whatever the relevant data type is.

While I didn't write this bit of code (so I can't say what, if any,
alternatives were considered), it does seem to me the most straight-
forward way to do it. Being able to say what the fill-in value should
be would make the code even simpler.

oldAttrVal is the original stored data, and attValue is what the macro
wants to append.

--->8---
newAttrVal = []
for x, y in map(None, oldAttrVal, attrValue):
newAttrVal.append(u''.join((x or '', y or '')))
--->8---

/Anders

-- 
 -- Of course I'm crazy, but that doesn't mean I'm wrong.
Anders Hammarquist  | [EMAIL PROTECTED]
Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50
G|teborg, Sweden.   RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: config errors on Freebsd and python 2.3

2006-01-09 Thread [EMAIL PROTECTED]

Safeer Tabassum wrote:
> why you are not installing it from ports?
>

The port distribution doesn't build to support Tkinter. That's why I
started building python from source. And since I'm building from source
I can be more up-to-date then the ports distribution, and include pil,
pmw, etc in the build.

Curtis

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


Re: itertools.izip brokeness

2006-01-09 Thread Antoon Pardon
Op 2006-01-05, Bengt Richter schreef <[EMAIL PROTECTED]>:
> On 5 Jan 2006 15:48:26 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>>On 2006-01-04, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>><[EMAIL PROTECTED]> wrote:
 But here is my real question...
 Why isn't something like this in itertools, or why shouldn't
 it go into itertools?
>>>
>>>
>>>   4) If a need does arise, it can be met by __builtins__.map() or by
>>>  writing:  chain(iterable, repeat(None)).
>>>
>>> Yes, if youre a python guru.  I don't even understand the
>>> code presented in this thread that uses chain/repeat,
>>
>>And it wouldn't work in this case. chain(iterable, repeat(None))
>>changes your iterable into an iterator that first gives you
>>all elements in the iterator and when these are exhausted
>>will continue giving the repeat parameter. e.g.
>>
>>  chain([3,5,8],repeat("Bye")
>>
>>Will produce  3, 5 and 8 followed by an endless stream
>>of "Bye".
>>
>>But if you do this with all iterables, and you have to
>>because you don't know which one is the smaller, all
>>iterators will be infinite and izip will never stop.
>
> But you can fix that (only test is what you see ;-) :

Maybe, but not with this version.

> >>> from itertools import repeat, chain, izip
> >>> it = iter(lambda z=izip(chain([3,5,8],repeat("Bye")), 
> >>> chain([11,22],repeat("Bye"))):z.next(), ("Bye","Bye"))
> >>> for t in it: print t
>  ...
>  (3, 11)
>  (5, 22)
>  (8, 'Bye')
>
> (Feel free to generalize ;-)

The problem with this version is that it will stop if for some reason
each iterable contains a 'Bye' at the same place. Now this may seem
far fetched at first. But consider that if data is collected from
experiments certain values may be missing. This can be indicated
by a special "Missing Data" value in an iterable. But this "Missing
Data" value would also be the prime canidate for a fill parameter
when an iterable is exhausted.

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


email.Utils.parseaddr() gives arcane result

2006-01-09 Thread Mark Sapiro
email.Utils.parseaddr('Real Name ((comment)) <[EMAIL PROTECTED]>')

returns

('comment <[EMAIL PROTECTED]>', 'Real')

Granted the string above is invalid as RFC 2822 does not allow
parentheses within comments, but most mail agents seem to at least take
the contents of the angle brackets as the address.

rfc822.parseaddr() returns the same result in this case.

If these functions aren't going to return their respective failure
indication in this case, I think they should at least return
'[EMAIL PROTECTED]' as the second item of the returned tuple.

--
(for email use this address please - you can figure it out)

Mark Sapiro msapiro -at- value netAny clod can have the facts;
San Francisco Bay Area, Californiahaving opinions is an art. -
  C. McCabe, The Fearless Spectator

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


Re: Renaming files in ftplib

2006-01-09 Thread [EMAIL PROTECTED]
how to get files: http://docs.python.org/lib/ftp-objects.html, see
function retrlines for a textfile
how to rename files: mhttp://docs.python.org/lib/os-file-dir.htmlv,
function rename

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


Re: PyQt Access Violations

2006-01-09 Thread gregarican
Phil Thompson wrote:

> What version of Qt?
>
> Phil

It's version 2.3.0 non-commerical for Windows. My OS is Windows 2000
Professional SP4. Using this same version of Qt for a Ruby-based
implementation of a similar app I didn't experience the access
violation crashes when invoking the setCentralWidget() method. It's
sporadic, as the crashes sometimes take 2-3 widget opens/closes to
happen. Other times it takes more. Trying to debug the crashes the
script never makes it past this method. Here's an excerpt from the Dr.
Watson error log:

function: QGList::findRef
39d2dd42 807c240800   cmp byte ptr [esp+0x8],0x0
ss:00c09513=00
39d2dd47 7407 jz  QString::fromUtf8+0x8a
(39d36850)
FAULT ->39d2dd49 8b4108   mov eax,[ecx+0x8]
ds:00cd9f51=48001500
39d2dd4c 33d2 xor edx,edx
39d2dd4e eb06 jmp QString::fromUtf8+0x90
(39d36856)
39d2dd50 8b4110   mov eax,[ecx+0x10]
ds:00cd9f51=48001500
39d2dd53 8b5114   mov edx,[ecx+0x14]
ds:00cd9f51=48001500
39d2dd56 56   pushesi
39d2dd57 85c0 testeax,eax
39d2dd59 740e jz  QString::fromLatin1+0xb
(39d36869)
39d2dd5b 8b30 mov esi,[eax]
ds:007ad4d8=00858340
39d2dd5d 3b742408 cmp esi,[esp+0x8]
ss:00c09513=
39d2dd61 7406 jz  QString::fromLatin1+0xb
(39d36869)
39d2dd63 8b4008   mov eax,[eax+0x8]
ds:012873be=

*> Stack Back Trace <*

FramePtr ReturnAd Param#1  Param#2  Param#3  Param#4  Function Name
0012F664 1E057D56 089FE908 00857948 0001 088FAAD0 !QGList::findRef
0012F6C8 0001   007A5234 00779288 !PyCFunction_Call

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


string to datetime parser?

2006-01-09 Thread beza1e1
Is there a library which can parse strings and output a datetime
object? It should be as magical as possible and allow things like:
12:30
tomorrow
10.10.2005
02-28-00
28/03/95
1995-03-28
1996.Feb.29 (Thu) 16:45:23.7

Is there anything like that out there? My Google can't find anything
useful ...

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


Re: MVC programming with python (newbie) - please help

2006-01-09 Thread has
bwaha wrote:
> The author refers to mvctree.py in wxPython as an example of MVC design.
> However I'm still too green so I find that particular example too complex
> and I'm not understanding the separation the author is recommending.

MVC is all about separation of concerns.

The Model is responsible for managing the program's data (both private
and client data). The View/Controller is responsible for providing the
outside world with the means to interact with the program's client
data.

The Model provides an internal interface (API) to enable other parts of
the program to interact with it. The View/Controller provides an
external interface (GUI/CLI/web form/high-level IPC/etc.) to enable
everything outwith the program to communicate with it.

The Model is responsible for maintaining the integrity of the program's
data, because if that gets corrupted then it's game over for everyone.
The View/Controller is responsible for maintaining the integrity of the
UI, making sure all text views are displaying up-to-date values,
disabling menu items that don't apply to the current focus, etc.

The Model contains no View/Controller code; no GUI widget classes, no
code for laying out dialog boxes or receiving user input. The
View/Controller contains no Model code; no code for validating URLs or
performing SQL queries, and no original state either: any data held by
widgets is for display purposes only, and merely a reflection of the
true data stored in the Model.


Now, here's the test of a true MVC design: the program should in
essence be fully functional even without a View/Controller attached.
OK, the outside world will have trouble interacting with it in that
form, but as long as one knows the appropriate Model API incantations,
the program will hold and manipulate data as normal.

Why is this possible? Well, the simple answer is that it's all thanks
to the low coupling between the Model and View/Controller layers.
However, this isn't the full story. What's key to the whole MVC pattern
is the _direction_ in which those connection goes: ALL instructions
flow _from_ the View/Controller _to_ the Model. The Model NEVER tells
the View/Controller what to do.

Why? Because in MVC, while the View/Controller is permitted to know a
little about the Model (specifically, the Model's API), but the Model
is not allowed to know anything whatsoever about the View/Controller.

Why? Because MVC is about creating a clear separation of concerns.

Why? To help prevent program complexity spiralling out of control and
burying you, the developer, under it. The bigger the program, the
greater the number of components in that program. And the more
connections exist between those components, the harder it is for
developers to maintain/extend/replace individual components, or even
just follow how the whole system works. Ask yourself this: when looking
at a diagram of the program's structure, would you rather see a tree or
a cat's cradle? The MVC pattern avoids the latter by disallowing
circular connections: B can connect to A, but A cannot connect to B. In
this case, A is the Model and B is the View/Controller.

BTW, if you're sharp, you'll notice a problem with the 'one-way'
restriction just described: how can the Model inform the
View/Controller of changes in the Model's user data when the Model
isn't even allowed to know that the View/Controller, never mind send
messages to it? But don't worry: there is a solution to this, and it's
rather neat even if it does seem a bit roundabout at first. We'll get
back to that in a moment.


In practical terms, then, a View/Controller object may, via the Model's
API, 1. tell the Model to do things (execute commands), and 2. tell the
Model to give it things (return data). The View/Controller layer
*pushes instructions* to the Model layer and *pulls information* from
the Model layer.

And that's where your first MyCoolListControl example goes wrong,
because the API for that class requires that information be *pushed*
into it, so you're back to having a two-way coupling between layers,
violating the MVC rules and dumping you right back into the cat's
cradle architecture that you were [presumably] trying to avoid in the
first place.

Instead, the MyCoolListControl class should go with the flow, pulling
the data it needs from the layer below, when it needs it. In the case
of a list widget, that generally means asking how many values there are
and then asking for each of those items in turn, because that's about
the simplest and loosest way to do it and therefore keeps what coupling
there is to a minimum. And if the widget wants, say, to present those
values to the user in nice alphabetical order then that's its
perogative; and its responsibility, of course.


Now, one last conundrum, as I hinted at earlier: how do you keep the
UI's display synchronised with the Model's state in an MVC-based
system?

Here's the problem: many View objects are stateful, e.g. a checkbox may
be ticked or unticked, a text field ma

Re: PIL implementation

2006-01-09 Thread arkestra
The error message is --> "Syntax error" and it highlights the last
"else" statement.

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


Do you have real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
I am evaluating a request for an alternate version of itertools.izip()
that has a None fill-in feature like the built-in map function:

>>> map(None, 'abc', '12345')   # demonstrate map's None fill-in feature
[('a', '1'), ('b', '2'), ('c', '3'), (None, '4'), (None, '5')]

The movitation is to provide a means for looping over all data elements
when the input lengths are unequal.  The question of the day is whether
that is both a common need and a good approach to real-world problems.
The answer to the question can likely be found in results from other
programming languages or from real-world Python code that has used
map's None fill-in feature.

I scanned the docs for Haskell, SML, and Perl and found that the norm
for map() and zip() is to truncate to the shortest input or raise an
exception for unequal input lengths.  I scanned the standard library
and found no instances where map's fill-in feature was used.  Likewise,
I found no examples in all of the code I've ever written.

The history of Python's current zip() function serves as another
indicator that the proposal is weak.  PEP 201 contemplated and rejected
the idea as one that likely had unintended consequences.  In the years
since zip() was introduced in Py2.0, SourceForge has shown no requests
for a fill-in version of zip().

My request for readers of comp.lang.python is to search your own code
to see if map's None fill-in feature was ever used in real-world code
(not toy examples).  I'm curious about the context, how it was used,
and what alternatives were rejected (i.e. did the fill-in feature
improve the code).

Also, I'm curious as to whether someone has seen a zip fill-in feature
employed to good effect in some other programming language, perhaps
LISP or somesuch?

Maybe a few real-word code examples and experiences from other
languages will shed light on the question of whether lock-step
iteration has meaning beyond the length of the shortest matching
elements.  If ordinal position were considered as a record key, then
the proposal equates to a database-style outer join operation (where
data elements with unmatched keys are included) and order is
significant.  Does an outer-join have anything to do with lock-step
iteration?  Is this a fundamental looping construct or just a
theoretical wish-list item?  IOW, does Python really need
itertools.izip_longest() or would that just become a distracting piece
of cruft?


Raymond Hettinger


P.S.  FWIW, the OP's use case involved printing files in multiple
columns:

for f, g in itertools.izip_longest(file1, file2, fillin_value=''):
print '%-20s\t|\t%-20s' % (f.rstrip(), g.rstrip())

The alternative was straight-forward but not as terse:

while 1:
f = file1.readline()
g = file2.readline()
if not f and not g:
break
print '%-20s\t|\t%-20s' % (f.rstrip(), g.rstrip())

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


Re: Newline at EOF Removal

2006-01-09 Thread Dylan Wilson
Do you mean somthing like this?

>>> f = open("file.txt")
>>> w = open('outfile.txt', 'w')
>>> for line in f.split('\n'):
...w.write(line)
...
>>> w.close()
>>> '\n' in open('/home/wandleg/outfile.txt').read()
False

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[Alex Martelli]
> I had (years ago, version was 1.5.2) one real-world case of map(max,
> seq1, seq2).  The sequences represented alternate scores for various
> features, using None to mean "the score for this feature cannot be
> computed by the algorithm used to produce this sequence", and it was
> common to have one sequence longer (using a later-developed algorithm
> that computed more features).  This use may have been an abuse of my
> observation that max(None, N) and max(N, None) were always N on the
> platform I was using at the time.

Analysis


That particular dataset has three unique aspects allowing the map(max,
s1, s2, s3) approach to work at all.

1) Fortuitious alignment in various meanings of None:
   - the input sequence using it to mean "feature cannot be computed"
   - the auto-fillin of None meaning "feature used in later
 algorithms, but not earlier ones"
   - the implementation quirk where max(None, n) == max(n, None) == n

2) Use of a reduction function like max() which does not care about the
order of inputs (i.e. the output sequence does not indicate which
algorithm produced the best score).

3) Later-developed sequences had to be created with the knowledge of
the features used by all earlier sequences (lest two of the sequences
get extended with different features corresponding to the same ordinal
position).

Getting around the latter limitation suggests using a mapping
(feature->score) rather than tracking scores by ordinal position (with
position corresponding to a particular feature):

bestscore = {}
for d in d1, d2, d3:
for feature, score in d.iteritems():
bestscore[feature] = max(bestscore.get(feature, 0), score)

Such an approach also gets around dependence on the other two unique
aspects of the dataset.  With dict.get() any object can be specified as
a default value (with zero being a better choice for a null input to
max()).  Also, the pattern is not limited to commutative reduction
functions like max(); instead, it would work just as well with a
result.setdefault(feature, []).append(score) style accumulation of all
results or with other combining/analysis functions.

So, while map's None fill-in feature happened to apply to this
dataset's unique features, I wonder if its availability steered you
away from a better data-structure with greater flexibility, less
dependence on quirks, and more generality.

Perhaps the lesson is that outer-join operations are best expressed
with dictionaries rather than sequences with unequal lengths.


> I was relatively new at Python, and
> in retrospect I feel I might have been going for "use all the new toys
> we've just gotten"

That suggests that if itertools.zip_longest() doesn't turn out to be
TheRightTool(tm) for many tasks, then it may have ill-effects beyond
just being cruft -- it may steer folks away from better solutions.  As
you know, it can take a while for Python newcomers to realize the full
power and generality of dictionary based approaches.  I wonder if this
proposed itertool would distract from that realization.


> I don't recall ever relying on map's None-filling feature in other
> real-world cases, and, as I mentioned, even here the reliance was rather
> doubtful.  OTOH, if I had easily been able to specify a different
> filler, I _would_ have been able to use it a couple of times.

Did you run across any cookbook code that would have been improved by
the proposed itertools.zip_longest() function?



Raymond

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


Re: Copying files between different linux machines

2006-01-09 Thread malv
Sorry, the above link should read:
http://shfs.sourceforge.net

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread rurpy

"Raymond Hettinger" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Proposal
> 
> I am gathering data to evaluate a request for an alternate version of
> itertools.izip() with a None fill-in feature like that for the built-in
> map() function:
>
> >>> map(None, 'abc', '12345')   # demonstrate map's None fill-in feature
> [('a', '1'), ('b', '2'), ('c', '3'), (None, '4'), (None, '5')]
>
> The motivation is to provide a means for looping over all data elements
> when the input lengths are unequal.  The question of the day is whether
> that is both a common need and a good approach to real-world problems.
> The answer can likely be found in results from other programming
> languages and from surveying real-world Python code.
>
> Other languages
> ---
> I scanned the docs for Haskell, SML, and Perl6's yen operator and found
> that the norm for map() and zip() is to truncate to the shortest input
> or raise an exception for unequal input lengths.  Ruby takes the
> opposite approach and fills-in nil values -- the reasoning behind the
> design choice is somewhat inscrutable:
>   http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-dev/18651

>From what I can make out (with help of internet
language translation sites) the relevent part
(section [2]) of this presents three options for
handling unequal length arguments:
1. zip to longest (Perl6 does it this way)
2. zip to shortest (Python does it this way)
3. use zip method and choose depending on
  whether argument list is shorter or longer
  than object's list.
It then solicits opinions on the best way.
It does not state or justify any particular choice.

If "perl6"=="perl6 yen operator" then there
is a contradiction with your earlier statement.

> Real-world code
> ---
> I scanned the standard library, my own code, and a few third-party
> tools.  I
> found no instances where map's fill-in feature was used.
>
> History of zip()
> 
> PEP 201 (lock-step iteration) documents that a fill-in feature was
> contemplated and rejected for the zip() built-in introduced in Py2.0.
> In the years before and after, SourceForge logs show no requests for a
> fill-in feature.

My perception is that many people view the process
of advocating for a library addition as
1. Very time consuming due to the large amount of
   work involved in presenting and defending a proposal.
2. Having a very small chance of acceptance.
I do not know whether this is really the case or even if my
perception is correct, but if it is, it could account for the
lack of feature requests.

> Request for more information
> 
> My request for readers of comp.lang.python is to search your own code
> to see if map's None fill-in feature was ever used in real-world code
> (not toy examples).  I'm curious about the context, how it was used,
> and what alternatives were rejected (i.e. did the fill-in feature
> improve the code).  Likewise, I'm curious as to whether anyone has seen
> a zip-style fill-in feature employed to good effect in some other
> programming language.

How well correlated in the use of map()-with-fill with the
(need for) the use of zip/izip-with-fill?

> Parallel to SQL?
> 
> If an iterator element's ordinal position were considered as a record
> key, then the proposal equates to a database-style full outer join
> operation (one which includes unmatched keys in the result) where record
> order is significant.  Does an outer-join have anything to do with
> lock-step iteration?  Is this a fundamental looping construct or just a
> theoretical wish-list item?  Does Python need itertools.izip_longest()
> or would it just become a distracting piece of cruft?
>
> Raymond Hettinger
>
> FWIW, the OP's use case involved printing files in multiple
> columns:
>
> for f, g in itertools.izip_longest(file1, file2, fillin_value=''):
> print '%-20s\t|\t%-20s' % (f.rstrip(), g.rstrip())
>
> The alternative was straightforward but less terse:
>
> while 1:
> f = file1.readline()
> g = file2.readline()
> if not f and not g:
> break
> print '%-20s\t|\t%-20s' % (f.rstrip(), g.rstrip())

Actuall my use case did not have quite so much
perlish line noise :-)
Compared to
for f, g in izip2 (file1, file2, fill=''):
print '%s\t%s' % (f, g)
the above looks like a relatively minor loss
of conciseness, but consider the uses of the
current izip, for example

for i1, i2 in itertools.izip (iterable_1, iterable_2):
  print '%-20s\t|\t%-20s' % (i1.rstrip(), i2.rstrip())

can be replaced by:
while 1:
i1 = iterable_1.next()
i2 = iterable_2.next()
print '%-20s\t|\t%-20s' % (i1.rstrip(), i2.rstrip())

yet that was not justification for rejecting izip()'s
inclusion in itertools.

The other use case I had was a simple file diff.
All I cared about was if the files were the same or
not, and if not, what were the first differin

Re: Optional typecheck

2006-01-09 Thread Gregory Petrosyan
Btw, why not in 2.x?

Thanks for link, nice module. But I prefer built-in solution, that I
can use in any piece of python code. So, I'll wait for version of
Python that supports it.

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


Re: config errors on Freebsd and python 2.3

2006-01-09 Thread [EMAIL PROTECTED]

Safeer Tabassum wrote:
> why you are not installing it from ports?
>

The port distribution doesn't build to support Tkinter. That's why I
started building python from source. And since I'm building from source
I can be more up-to-date then the ports distribution, and include pil,
pmw, etc in the build.

Curtis

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


Re: PIL implementation

2006-01-09 Thread arkestra
The error message is --> "Syntax error" and it highlights the last
"else" statement.

thanks for the reply.

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


Re: MVC programming with python (newbie) - please help

2006-01-09 Thread has
bwaha wrote:
> The author refers to mvctree.py in wxPython as an example of MVC design.
> However I'm still too green so I find that particular example too complex
> and I'm not understanding the separation the author is recommending.

MVC is all about separation of concerns.

The Model is responsible for managing the program's data (both private
and client data). The View/Controller is responsible for providing the
outside world with the means to interact with the program's client
data.

The Model provides an internal interface (API) to enable other parts of
the program to interact with it. The View/Controller provides an
external interface (GUI/CLI/web form/high-level IPC/etc.) to enable
everything outwith the program to communicate with it.

The Model is responsible for maintaining the integrity of the program's
data, because if that gets corrupted then it's game over for everyone.
The View/Controller is responsible for maintaining the integrity of the
UI, making sure all text views are displaying up-to-date values,
disabling menu items that don't apply to the current focus, etc.

The Model contains no View/Controller code; no GUI widget classes, no
code for laying out dialog boxes or receiving user input. The
View/Controller contains no Model code; no code for validating URLs or
performing SQL queries, and no original state either: any data held by
widgets is for display purposes only, and merely a reflection of the
true data stored in the Model.


Now, here's the test of a true MVC design: the program should in
essence be fully functional even without a View/Controller attached.
OK, the outside world will have trouble interacting with it in that
form, but as long as one knows the appropriate Model API incantations,
the program will hold and manipulate data as normal.

Why is this possible? Well, the simple answer is that it's all thanks
to the low coupling between the Model and View/Controller layers.
However, this isn't the full story. What's key to the whole MVC pattern
is the _direction_ in which those connection goes: ALL instructions
flow _from_ the View/Controller _to_ the Model. The Model NEVER tells
the View/Controller what to do.

Why? Because in MVC, while the View/Controller is permitted to know a
little about the Model (specifically, the Model's API), but the Model
is not allowed to know anything whatsoever about the View/Controller.

Why? Because MVC is about creating a clear separation of concerns.

Why? To help prevent program complexity spiralling out of control and
burying you, the developer, under it. The bigger the program, the
greater the number of components in that program. And the more
connections exist between those components, the harder it is for
developers to maintain/extend/replace individual components, or even
just follow how the whole system works. Ask yourself this: when looking
at a diagram of the program's structure, would you rather see a tree or
a cat's cradle? The MVC pattern avoids the latter by disallowing
circular connections: B can connect to A, but A cannot connect to B. In
this case, A is the Model and B is the View/Controller.

BTW, if you're sharp, you'll notice a problem with the 'one-way'
restriction just described: how can the Model inform the
View/Controller of changes in the Model's user data when the Model
isn't even allowed to know that the View/Controller, never mind send
messages to it? But don't worry: there is a solution to this, and it's
rather neat even if it does seem a bit roundabout at first. We'll get
back to that in a moment.


In practical terms, then, a View/Controller object may, via the Model's
API, 1. tell the Model to do things (execute commands), and 2. tell the
Model to give it things (return data). The View/Controller layer
*pushes instructions* to the Model layer and *pulls information* from
the Model layer.

And that's where your first MyCoolListControl example goes wrong,
because the API for that class requires that information be *pushed*
into it, so you're back to having a two-way coupling between layers,
violating the MVC rules and dumping you right back into the cat's
cradle architecture that you were [presumably] trying to avoid in the
first place.

Instead, the MyCoolListControl class should go with the flow, pulling
the data it needs from the layer below, when it needs it. In the case
of a list widget, that generally means asking how many values there are
and then asking for each of those items in turn, because that's about
the simplest and loosest way to do it and therefore keeps what coupling
there is to a minimum. And if the widget wants, say, to present those
values to the user in nice alphabetical order then that's its
perogative; and its responsibility, of course.


Now, one last conundrum, as I hinted at earlier: how do you keep the
UI's display synchronised with the Model's state in an MVC-based
system?

Here's the problem: many View objects are stateful, e.g. a checkbox may
be ticked or unticked, a text field ma

Re: config errors on Freebsd and python 2.3

2006-01-09 Thread [EMAIL PROTECTED]
Safeer Tabassum wrote:
> why you are not installing it from ports?
>

The port distribution doesn't build to support Tkinter. That's why I
started building python from source. And since I'm building from source
I can be more up-to-date then the ports distribution, and include pil,
pmw, etc in the build.

Curtis

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


Re: Apology Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread Patrick Maupin
Mike Meyer wrote:
> This is where we disagree. I think their understanding of references
> is dead on. What's broken is their understanding of what variables are
> and what assignments mean. Once you fix that, the rest falls into
> place.
>
> (Steven D'Aprano wrote:)
> > The fact that call by object is unfamiliar is precisely its advantage.
> > Instead of people jumping to conclusions about what it means, like they do
> > with "reference", they will stop and think and if need be look for further
> > information about Python's object model. At the very least, they won't say
> > "Everything in Python is a reference, so this should work, but it
> > doesn't".
>
> What you're advocating is intentionally misleading people to deal with
> a symptom. I'd rather give them enough truth to deal with the disease.

I agree completely.  I have personally "converted" around a half-dozen
or so coworkers to Python over the course of the last three or four
years.  The conversion takes place in stages.  Usually, I have written
a small script for them which they later want to enhance, so they come
to me for a tutorial session.

My initial 5-10 minute tutorial starts off with an explanation of
name-binding, including something like "a=[1,2,3]; b=a; a[1]=4; print
b; b=42; print a, b".  Note that this also demonstrates the dynamic
nature of Python typing -- 'b' is not restricted to being bound to a
list merely because the first time it was bound was to a list.

Once they have that down, I describe "immutable" vs. "mutable".  I
start off by explaining that of course integers are immutable because
you cannot change 1 into 5.  I then explain (with examples) that,
additionally, in the language, strings are immutable (which does NOT
mean you cannot usefully manipulate them, just that, for example, in "x
= 'abc'; x = x + 'd'" the manipulation "x + 'd'" results in a
completely new string. (The attempted example x[1] = "d" also gets them
used to the exception reporting mechanism.)

I actually spend more time (of this 10 minutes!)  on "immutable" vs.
"mutable" (including ancillary lessons) than I spend on anything else.
After showing that strings are immutable, I then explain that tuples
are a sort of immutable list.  This usually elicits the question of why
such a thing is needed, which is a great segue into a minute or so
spent on dictionaries and their keys. (Dictionaries can occupy
additional time if the student recognizes that they are a good fit for
a pressing need.)

Only about the last 30 seconds or so is spent on function calling.  I
explain that all parameters are passed by reference, but that
OBVIOUSLY, if the called function wants to alter the caller's object,
the referenced object must be mutable, because, JUST AS WITH C
POINTERS, the pointer to the object is passed by making a copy of it on
the stack, so there is no way that the callee can directly alter the
caller's own pointer to the object.

After this lesson, I send them back to look at their script with
information about the online docs and a standing offer to help them
over any rough spots.  NOT ONE PERSON has ever been confused about the
parameter passing.

I have only given these tutorials to accomplished programmers, so my
opinion about teaching newbies is not as well-formed, but for a
C/C++/assembler programmer, the REAL question about parameters is "What
is pushed onto the stack?"  They are capable of a high level of
abstraction, so all they really want to know "Is a COPY of the object
passed on the stack, or is a POINTER to the object passed on the
stack?"

With such an accomplished student, if the teacher described Python's
parameter passing as anything but "call by reference",  it would lead
to confusion, and, ultimately, disrespect for the teacher.

Regards,
Pat

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Duncan Booth
Raymond Hettinger wrote:

> My request for readers of comp.lang.python is to search your own code
> to see if map's None fill-in feature was ever used in real-world code
> (not toy examples).  I'm curious about the context, how it was used,
> and what alternatives were rejected (i.e. did the fill-in feature
> improve the code).  Likewise, I'm curious as to whether anyone has seen
> a zip-style fill-in feature employed to good effect in some other
> programming language.

One example of padding out iterators (although I didn't use map's fill-in 
to implement it) is turning a single column of items into a multi-column 
table with the items laid out across the rows first. The last row may have 
to be padded with some empty cells.

Here's some code I wrote to do that. Never mind for the moment that the use 
of zip isn't actually defined here, it could use izip, but notice that the 
input iterator has to be converted to a list first so that I can add a 
suitable number of empty strings to the end. If there was an option to izip 
to pad the last element with a value of choice (such as a blank string) the 
code could work with iterators throughout:

def renderGroups(self, group_size=2, allow_add=True):
"""Iterates over the items rendering one item for each group.
Each group contains an iterator for group_size elements.
The last group may be padded out with empty strings.
"""
elements = list(self.renderIterator(allow_add)) + ['']*(group_size-
1)
eliter = iter(elements)
return zip(*[eliter]*group_size)

If there was a padding option to izip this could could have been something 
like:

def renderGroups(self, group_size=2, allow_add=True):
"""Iterates over the items rendering one item for each group.
Each group contains an iterator for group_size elements.
The last group may be padded out with empty strings.
"""
iter = self.renderIterator(allow_add)
return itertools.izip(*[iter]*group_size, pad='')

The code is then used to build a table using tal like this:


  
4X Slot element
  

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


Re: Apology Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread Patrick Maupin
Mike Meyer wrote:
> This is where we disagree. I think their understanding of references
> is dead on. What's broken is their understanding of what variables are
> and what assignments mean. Once you fix that, the rest falls into
> place.
>
> (Steven D'Aprano wrote:)
> > The fact that call by object is unfamiliar is precisely its advantage.
> > Instead of people jumping to conclusions about what it means, like they do
> > with "reference", they will stop and think and if need be look for further
> > information about Python's object model. At the very least, they won't say
> > "Everything in Python is a reference, so this should work, but it
> > doesn't".
>
> What you're advocating is intentionally misleading people to deal with
> a symptom. I'd rather give them enough truth to deal with the disease.

I agree completely.  I have personally "converted" around a half-dozen
or so coworkers to Python over the course of the last three or four
years.  The conversion takes place in stages.  Usually, I have written
a small script for them which they later want to enhance, so they come
to me for a tutorial session.

My initial 5-10 minute tutorial starts off with an explanation of
name-binding, including something like "a=[1,2,3]; b=a; a[1]=4; print
b; b=42; print a, b".  Note that this also demonstrates the dynamic
nature of Python typing -- 'b' is not restricted to being bound to a
list merely because the first time it was bound was to a list.

Once they have that down, I describe "immutable" vs. "mutable".  I
start off by explaining that of course integers are immutable because
you cannot change 1 into 5.  I then explain (with examples) that,
additionally, in the language, strings are immutable (which does NOT
mean you cannot usefully manipulate them, just that, for example, in "x
= 'abc'; x = x + 'd'" the manipulation "x + 'd'" results in a
completely new string. (The attempted example x[1] = "d" also gets them
used to the exception reporting mechanism.)

I actually spend more time (of this 10 minutes!)  on "immutable" vs.
"mutable" (including ancillary lessons) than I spend on anything else.
After showing that strings are immutable, I then explain that tuples
are a sort of immutable list.  This usually elicits the question of why
such a thing is needed, which is a great segue into a minute or so
spent on dictionaries and their keys. (Dictionaries can occupy
additional time if the student recognizes that they are a good fit for
a pressing need.)

Only about the last 30 seconds or so is spent on function calling.  I
explain that all parameters are passed by reference, but that
OBVIOUSLY, if the called function wants to alter the caller's object,
the referenced object must be mutable, because, JUST AS WITH C
POINTERS, the pointer to the object is passed by making a copy of it on
the stack, so there is no way that the callee can directly alter the
caller's own pointer to the object.

After this lesson, I send them back to look at their script with
information about the online docs and a standing offer to help them
over any rough spots.  NOT ONE PERSON has ever been confused about the
parameter passing.

I have only given these tutorials to accomplished programmers, so my
opinion about teaching newbies is not as well-formed, but for a
C/C++/assembler programmer, the REAL question about parameters is "What
is pushed onto the stack?"  They are capable of a high level of
abstraction, so all they really want to know "Is a COPY of the object
passed on the stack, or is a POINTER to the object passed on the
stack?"

With such an accomplished student, if the teacher described Python's
parameter passing as anything but "call by reference",  it would lead
to confusion, and, ultimately, disrespect for the teacher.

Regards,
Pat

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


Re: pdb.py - why is this debugger different from all other debuggers?

2006-01-09 Thread ilya
> - There is no way (I know of) to start a python script
>  from the command line with the debugger active;
>  I always have to modify the source to insert a
 > pdb.set_trace().

With python 2.4 you can do
python -m pdb.py yourscript arg1 arg2 

Ilya

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


Re: Why it doesn't work?

2006-01-09 Thread Martin P. Hellwig
Lad wrote:
> I have a list
> L={}
> Now I can assign the value
> L['a']=1
> and I have
> L={'a': 1}
> 
> but I would like to have a dictionary like this
> L={'a': {'b':2}}
> 
> so I would expect I can do
> L['a']['b']=2
> 
> but it does not work. Why?
> 
> Thank you for reply
> Rg,
> L.
> 

Hi,

Perhaps what you try to do is something different than what I did here 
but it works for me:

 >>> D={'a':{'b':''}}
 >>> D['a']['b']=2
 >>> D
{'a': {'b': 2}}

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


Re: PyQt Access Violations

2006-01-09 Thread gregarican
Phil Thompson wrote:

> What version of Qt?
>
> Phil

It's version 2.3.0 non-commerical for Windows. My OS is Windows 2000
Professional SP4. Using this same version of Qt for a Ruby-based
implementation of a similar app I didn't experience the access
violation crashes when invoking the setCentralWidget() method. It's
sporadic, as the crashes sometimes take 2-3 widget opens/closes to
happen. Other times it takes more. Trying to debug the crashes the
script never makes it past this method. Here's an excerpt from the Dr.
Watson error log:

function: QGList::findRef
39d2dd42 807c240800   cmp byte ptr [esp+0x8],0x0
ss:00c09513=00
39d2dd47 7407 jz  QString::fromUtf8+0x8a
(39d36850)
FAULT ->39d2dd49 8b4108   mov eax,[ecx+0x8]
ds:00cd9f51=48001500
39d2dd4c 33d2 xor edx,edx
39d2dd4e eb06 jmp QString::fromUtf8+0x90
(39d36856)
39d2dd50 8b4110   mov eax,[ecx+0x10]
ds:00cd9f51=48001500
39d2dd53 8b5114   mov edx,[ecx+0x14]
ds:00cd9f51=48001500
39d2dd56 56   pushesi
39d2dd57 85c0 testeax,eax
39d2dd59 740e jz  QString::fromLatin1+0xb
(39d36869)
39d2dd5b 8b30 mov esi,[eax]
ds:007ad4d8=00858340
39d2dd5d 3b742408 cmp esi,[esp+0x8]
ss:00c09513=
39d2dd61 7406 jz  QString::fromLatin1+0xb
(39d36869)
39d2dd63 8b4008   mov eax,[eax+0x8]
ds:012873be=

*> Stack Back Trace <*

FramePtr ReturnAd Param#1  Param#2  Param#3  Param#4  Function Name
0012F664 1E057D56 089FE908 00857948 0001 088FAAD0 !QGList::findRef
0012F6C8 0001   007A5234 00779288 !PyCFunction_Call

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


Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-09 Thread Paul Rubin
"Raymond Hettinger" <[EMAIL PROTECTED]> writes:
> I am evaluating a request for an alternate version of itertools.izip()
> that has a None fill-in feature like the built-in map function:
> 
> >>> map(None, 'abc', '12345')   # demonstrate map's None fill-in feature

I think finding different ways to write it was an entertaining
exercise but it's too limited in usefulness to become a standard
feature.

I do think some idiom ought to develop to allow checking whether an
iterator is empty, without consuming an item.  Here's an idea:
introduce something like

   iterator = check_empty(iterator)

where check_empty would work roughly like (untested):
   
   def check_empty(iterator):
  iclass = iterator.__class__
  class buffered(iclass):
 def __init__(self):
n = iter((self.next(),))  # might raise StopIteration
self.__save = chain(n, self)
 def next(self):
return self.__save.next()
 # all other operations are inherited from iclass

  return buffered(iterator)

The idea is you get back a new iterator which yields the same stream
and supports the same operations as the old one, if the old one is
non-empty.  Otherwise it raises StopIteration.

There are some obvious problems with the above:

 1) the new iterator should support all of the old one's attributes,
not just inherit its operations
 2) In the case where the old iterator is already buffered, the
constructor should just peek at the lookahead instead of making
a new object.  That means that checking an iterator multiple times
won't burn more and more memory.

Maybe there is some way of doing the above with metaclasses but I've
never been able to wrap my head around those.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sockets on Windows and Mac

2006-01-09 Thread rodmc
Hi Peter,

I am currently importing the socket library when I write the programs,
I have had no problems with it on my PC at work, but the Mac at home
steadfastly refuses to work. As for existing libraries, I am new to
Python so am kean to avoid re-inventing the wheel :-)

Cheers,

rod

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


Why it doesn't work?

2006-01-09 Thread Lad
I have a list
L={}
Now I can assign the value
L['a']=1
and I have
L={'a': 1}

but I would like to have a dictionary like this
L={'a': {'b':2}}

so I would expect I can do
L['a']['b']=2

but it does not work. Why?

Thank you for reply
Rg,
L.

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


Re: string to datetime parser?

2006-01-09 Thread Fuzzyman
On 7 Jan 2006 21:00:34 -0800, "beza1e1"
<[EMAIL PROTECTED]> wrote:

>Is there a library which can parse strings and output a datetime
>object? It should be as magical as possible and allow things like:
>12:30
>tomorrow
>10.10.2005
>02-28-00
>28/03/95
>1995-03-28
>1996.Feb.29 (Thu) 16:45:23.7
>
>Is there anything like that out there? My Google can't find anything
>useful ...

There is a module called DateUtil which will do *most* of what you
want. (Possibly all).

I can't recall the URL, but google should turn it up for you.

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
-- 
http://mail.python.org/mailman/listinfo/python-list


cant get py2exe exe file to work

2006-01-09 Thread Blaze Bresko
heres my log file:

Traceback (most recent call last):
  File "Pong.pyw", line 264, in ?
  File "Pong.pyw", line 258, in main
  File "Pong.pyw", line 166, in __init__
  File "livewires\games.pyc", line 575, in __init__
  File "livewires\games.pyc", line 581, in init_text
RuntimeError: default font not found
Exception exceptions.AttributeError: "Text instance has no attribute
'_gone'" in > ignored

im using py2exe V 0.6, python V 2.4, and the newest pygame and
livewires and distutils...ill put my setup.py file up if needed.

What on earth is wrong?

Blaze

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


Determination of disk types

2006-01-09 Thread Mondal
Hello,

Is there a way to determine which drive letter is a FDD, a local disk,
a CD-ROM/COMBO Drive, or a mapped network drive?

I wrote a script to identify all the drive letters on my Windows XP
system. Now I want to determine their type, too.

Thanks for your help, in advance.

Regards
Mondal

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


Re: Help wanted with md2 hash algorithm

2006-01-09 Thread wjb131

Paul Rubin wrote:
> [EMAIL PROTECTED] writes:
> > below you find my simple python version of MD2 algorithm
> > as described in RFC1319  (http://rfc1319.x42.com/MD2).
> > It produces correct results for strings shorter than 16 Bytes and wrong
> > results for longer strings.
>
> Why do you want to use MD2?  It's very slow and it's also been
> deprecated for security reasons.  Use SHA1 (built into Python library)
> or SHA256/384/512 (implementations are circulating) instead.

I want to understand it, and -- therefor ;-) -- I want to implement it
in pure Pyhton.

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


Re: Multiway Branching

2006-01-09 Thread bearophileHUGS
A dict can be useful:

byte1, byte2 = 32, 1

conv1 = {(32, 32):0, (36,32):"natural", (32,1):5, (66,32):0.167}
print conv1[byte1, byte2]

If you use Psyco maybe something like this can be faster:

conv2 = dict((k1*256+k2,v) for (k1,k2),v in conv1.items())
print conv2[(byte1<<8) + byte2]

conv1/conv2 has to be defined just one time.

Bye,
bearophile

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


Re: Newline at EOF Removal

2006-01-09 Thread Alex N
Thank you guys for all your help. Was able to nail it down.
uh I dunno where i saw the 'wt' at. somewhere online though.
I have to do it in 2 stages though and run through a coula files but it
works.
import re
f = open("oldfile.txt")
w = open("newfile.txt", "w")
for line in f:
if line.strip():

w.write(line)


f.close()
w.close()

g = open("newfile.txt")
x = open("mynewfile.txt", "w")

x.write(g.read().rstrip('\n'))

x.close()

Got around the I/O errors luckily
thanks guys

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


Re: Multiway Branching

2006-01-09 Thread Justin Azoff
[EMAIL PROTECTED] wrote:
> I need to look at two-byte pairs coming from a machine, and interpret the
> meaning based on the relative values of the two bytes. In C I'd use a switch
> statement. Python doesn't have such a branching statement. I have 21
> comparisons to make, and that many if/elif/else statements is clunky and
> inefficient. Since these data are coming from an OMR scanner at 9600 bps (or
> faster if I can reset it programmatically to 38K over the serial cable), I
> want a fast algorithm.
>
>   The data are of the form:
>
>   if byte1 == 32 and byte2 == 32:
>   row_value = 0
>   elif byte1 == 36 and byte2 == 32:
>   row_value = "natural"
>...
>   elif byte1 == 32 and byte2 == 1:
>   row_value = 5
>   elif byte1 == 66 and byte2 == 32:
>   row_value = 0.167
>
>   There are two rows where the marked response equates to a string and 28
> rows where the marked response equates to an integer (1-9) or float of
> defined values.
>
>   Suggestions appreciated.
>
> Rich
>
> --
> Richard B. Shepard, Ph.D.   |   Author of "Quantifying 
> Environmental
> Applied Ecosystem Services, Inc. (TM)   |  Impact Assessments Using Fuzzy 
> Logic"
>  Voice: 503-667-4517 Fax: 503-667-8863

Use a dictionary:

byte_values = {
   (32,32)  : 0,
   (36,32)  : 'natural',
   (32,1 )  : 5,
}

row_value = byte_values[byte1,byte2]

-- 
- Justin

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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-09 Thread rurpy

"Anton Vredegoor" <[EMAIL PROTECTED]> wrote:
...
> I already sent some reply via google, got a server error, resent, got a
> confirmation that my message was posted, but it doesn't show up and also
> there's no way to retrieve my message except fishing in the cache?
>
> Yesterday I had a post not showing up (in another group) but today it
> was there. This makes me feel insecure enough about whether or not my
> replies come through via google to start using another provider. It's
> not like I'm on a secret google no fly list no? (slightly paranoic)
...

Nearly every message I've posted to c.l.p. in the last week
or so from Google has been badly delayed (12-24 hours
or more) or has disappeared.

Google seems to be quite badly broken.
Or mayby there really is a c.l.p. no fly list.  I noticed this
started happening right after GvR was hired. :-)

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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-09 Thread Anton Vredegoor
Alex Martelli wrote:

> Anton Vredegoor <[EMAIL PROTECTED]> wrote:
>
> > However I still maintain that I was never able to meet these fine
> > people you speak about and which you seem to know because the cost
> > involved (a few hundred euro to visit pycon for example) was too high
> > compared to my food budget.
>
> Europython is cheap to attend, and has been held twice in Charleroi,
> Belgium, for example -- if you're in the Netherlands, you could have
> bycicled there, crashed with somebody (I've seen lots of impecunious
> people offered hospitality that way), and not spent more on food than
> you would by staying in the Netherlands.  You'll have to invent some
> better excuse, to explain why you chose not to attend it.

I looked it up: 160 euro (early registration). My food budget is about
16 euro a week now, maybe even less if I want to keep feeding myself a
bit longer, maybe in 2003 my reserves were a bit higher than now, but I
had not yet learned then to be without a regular income, so I was very
scared to become pennyless at that time.

I am perfectly used to sleeping at other peoples' places, for example I
was at many go (baduk) tournaments and if the prices and atmosphere
would be anything comparable to that I guarantee you that I would have
been present.

IIRC I got an offer from Laura Creighton at the time to borrow me the
money, so one could say it was a choice, although by that time the
price had gone up to 270 euro.

But frankly indeed, I just don't even like to participate to events
that claim to be open for all but don't even acknowledge that the
barriers are extremely high compared to some participants budgets. Your
hype about it being cheap has a very chilling effect on my enthousiasm,
it's the same way with pypy congresses, which I also would have liked
to attend (and this thing even seems to be sponsored by public EU
money). Probably I am still a *rich* person, on a global scale, because
I live in a place with free internet (from a public library).

You *do* realize that even posting to usenet is impossible (or at least
very hard) for a lot of people, including me for at least 6 months. I
had to find someone to invite me to gmail and also a way to access my
previous internet account, which I lost access to when they cut my
phone line, to recieve the mail that finally enabled me to post via
google. Nowadays it's probably possible to open a hotmail account and
get invited to gmail from there, so one can post to usenet.

Theoretically I have now yet another option to post (except via
google), but IMO it remains true that one needs at least one link to
corruption to be able to post to usenet.

Anton

'hey, and my laptop doesn't even have a cdrom, needs almost continous
electricity, it's keyboard is broken (but it works fine with external
keyboard), and it networks via a pcmcia card with a *cable* '

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


Re: Help wanted with md2 hash algorithm

2006-01-09 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I want to understand it, and -- therefor ;-) -- I want to implement it
> in pure Pyhton.

OK.  It should be pretty easy to implement.  You should find the
official rfc at ietf.org.  I remember there was some minor erratum in
the original version that may or may not have been corrected, but it
shouldn't cause any serious confusion.  I implemented it in Javascript
a long time ago and as I remember, all the test vectors passed.
-- 
http://mail.python.org/mailman/listinfo/python-list


livewires to py2exe problem :(

2006-01-09 Thread Blaze Bresko
hey,

I am using python 2.4 and py2exe v 0.6. I have made a program using
pygame/livewires. I have the newest version of both but i dont know
what version they are (im on a different computer right now). When I
use py2exe to make the exe file, it works and there are no errors in
the whole thing. When I run the exe, it doesn't like the last line in
the program:

main()

this is the only real line in my game, everything else is either a
function or a class. This line calls the fuction main:

def main():

then in there it sets up all of my classes and everything else. The
program works fine as a .pyw file but I can't get the exe to work. I
have also had problems with the images and music. I have tried to add
them to the distutils but havent been able to so i just put them in the
dist folder. Is this ok or is this my problem?

If you want, I will give you the .exe.log and my distutils script.

Blaze

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


Re: Apology Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread Patrick Maupin
Mike Meyer wrote:
> This is where we disagree. I think their understanding of references
> is dead on. What's broken is their understanding of what variables are
> and what assignments mean. Once you fix that, the rest falls into
> place.
>
> (Steven D'Aprano wrote:)
> > The fact that call by object is unfamiliar is precisely its advantage.
> > Instead of people jumping to conclusions about what it means, like they do
> > with "reference", they will stop and think and if need be look for further
> > information about Python's object model. At the very least, they won't say
> > "Everything in Python is a reference, so this should work, but it
> > doesn't".
>
> What you're advocating is intentionally misleading people to deal with
> a symptom. I'd rather give them enough truth to deal with the disease.

I agree completely.  I have personally "converted" around a half-dozen
or so coworkers to Python over the course of the last three or four
years.  The conversion takes place in stages.  Usually, I have written
a small script for them which they later want to enhance, so they come
to me for a tutorial session.

My initial 5-10 minute tutorial starts off with an explanation of
name-binding, including something like "a=[1,2,3]; b=a; a[1]=4; print
b; b=42; print a, b".  Note that this also demonstrates the dynamic
nature of Python typing -- 'b' is not restricted to being bound to a
list merely because the first time it was bound was to a list.

Once they have that down, I describe "immutable" vs. "mutable".  I
start off by explaining that of course integers are immutable because
you cannot change 1 into 5.  I then explain (with examples) that,
additionally, in the language, strings are immutable (which does NOT
mean you cannot usefully manipulate them, just that, for example, in "x
= 'abc'; x = x + 'd'" the manipulation "x + 'd'" results in a
completely new string. (The attempted example x[1] = "d" also gets them
used to the exception reporting mechanism.)

I actually spend more time (of this 10 minutes!)  on "immutable" vs.
"mutable" (including ancillary lessons) than I spend on anything else.
After showing that strings are immutable, I then explain that tuples
are a sort of immutable list.  This usually elicits the question of why
such a thing is needed, which is a great segue into a minute or so
spent on dictionaries and their keys. (Dictionaries can occupy
additional time if the student recognizes that they are a good fit for
a pressing need.)

Only about the last 30 seconds or so is spent on function calling.  I
explain that all parameters are passed by reference, but that
OBVIOUSLY, if the called function wants to alter the caller's object,
the referenced object must be mutable, because, JUST AS WITH C
POINTERS, the pointer to the object is passed by making a copy of it on
the stack, so there is no way that the callee can directly alter the
caller's own pointer to the object.

After this lesson, I send them back to look at their script with
information about the online docs and a standing offer to help them
over any rough spots.  NOT ONE PERSON has ever been confused about the
parameter passing.

I have only given these tutorials to accomplished programmers, so my
opinion about teaching newbies is not as well-formed, but for a
C/C++/assembler programmer, the REAL question about parameters is "What
is pushed onto the stack?"  They are capable of a high level of
abstraction, so all they really want to know "Is a COPY of the object
passed on the stack, or is a POINTER to the object passed on the
stack?"

With such an accomplished student, if the teacher described Python's
parameter passing as anything but "call by reference",  it would lead
to confusion, and, ultimately, disrespect for the teacher.

Regards,
Pat

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


CGI errror in (only in) IIS 6.0 server 2003

2006-01-09 Thread [EMAIL PROTECTED]
Hi, I've been using ActivePython 2.3 (cgi) on IIS on win xp, 2000 and
they work fine.
Until I upgrade the system the server 2003. The ASP script engine is ok
but not the CGIs.

I got these errors:

HTTP Error 403.1 - Forbidden: Execute access is denied.



I already have execute access on the directory.



Can anyone help me?


=
kychan

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


Re: PyHtmlGUI Project is looking for developers

2006-01-09 Thread Paul Boddie
John J. Lee wrote:
> "Paul Boddie" <[EMAIL PROTECTED]> writes:
> [...]
> > many would advocate using "AJAX" techniques and dropping support for
> > conventional Web interactions, but I think that such advocacy and the
> > resulting applications threaten the usability of the Web for fairly
> > large groups of people.
>
> That may well be true in practice, but I don't see any intrinsic
> reason for it.  Do you {,care}?

As I've probably said before, it's tempting for some people to demand
JavaScript for their Web applications whilst claiming that JavaScript
implementations are ready for serious use. Yet, aside from some of the
more hyped toolkits managing either to crash my
not-particularly-incapable browser or failing to do anything visible,
there's still a lot to be said for simple, "old school" Web
interactions. Would I prefer a silky drag-and-drop experience on an
Internet banking site, or would I rather be presented with the
pertinent facts for a transaction with some buttons on the page to
either confirm or cancel my actions? The latter approach quite probably
reduces the "what's going on now?" factor amongst large sections of
society familiar (but not intimately so) with computers - ie. more than
95% of users, I'd imagine. In attempting to replicate some dubious user
interface metaphor from their Mac, I imagine that most of the more
vocal "AJAX" advocates forget this.

Paul

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


Pliant language

2006-01-09 Thread bearophileHUGS
This post is about a programming language that I've never used, called
Pliant. Sometimes knowing something about other languages can be useful
for our language, so I think this is not a fully off topic post. Time
ago I have found Python (that now I am using a lot) because I like to
explore less known languages.

It's a bit like a Lisp without most of its parenthesis:
http://en.wikipedia.org/wiki/Pliant
http://fullpliant.org/

An example of Pliant code:
http://fullpliant.org/pliant/util/encoding/zlib.pli


As bitwise operators Pliant uses the following ones instead of the
cryptic symbols (~ | & ^) used by C and Python:
.not. .or. .and. .xor.

For the same purpose maybe Python 3 can use:
NOT OR AND XOR
That are easy to remember.

Pliant uses indentations almost as Python, this is an example (I have
added the ! to keep the indentations):

! function factorial x -> f
!   arg Int x f
!   if x=0
! f := 1
!   else
! f := x * (factorial x-1)


But with a difference (this is from Pliant online documentation):

>Tabs are not allowed in the source code: you have to use spaces instead. The 
>main reason for not allowing them is that not everybody agrees on the number 
>of spaces each tab stands for, so when a program contains several modules 
>provided by different people, the number could be different in various 
>modules. Tabs could be allowed if the number of spaces they stood for were 
>declared at the beginning of the module, but then the various editors would 
>have to be aware of that ... so it is simpler to use only spaces. Furthermore, 
>most editors provide a 'translate tabs to spaces' function.<

Bye,
bearophile

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


CGI errror in (only in) IIS 6.0 server 2003

2006-01-09 Thread [EMAIL PROTECTED]
Hi, I've been using ActivePython 2.3 (cgi) on IIS on win xp, 2000 and
they work fine.
Until I upgrade the system the server 2003. The ASP script engine is ok
but not the CGIs.

I got these errors:

HTTP Error 403.1 - Forbidden: Execute access is denied.



I already have execute access on the directory.



Can anyone help me?


=
kychan

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


py vs pyc

2006-01-09 Thread Sakcee
Hi

I want to know that is .pyc files execute faster than .py files,? since
both are interpreted by python  , is there any speedup in using one or
other.?

e.g.

what is the difference between runing from cmd  "python test.py" and
"python test.pyc"


thanks

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


Re: config errors on Freebsd and python 2.3

2006-01-09 Thread [EMAIL PROTECTED]

Safeer Tabassum wrote:
> why you are not installing it from ports?
> 

Python as installed from ports doesn't support Tkinter.

Curtis

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


Re: is there any lib can split string in this way?

2006-01-09 Thread bonono
This has been asked not long ago. the shlex module as well as csv
module both should be able to handle it. for this simple case
shlex.split() seems to be the easiest.

Leo Jay wrote:
> I want to split a string like this:
> 'abc  def  "this is a test"  ok'
> into:
> ['abc', 'def', 'this is a test', 'ok']
>
> is there any lib meet my need?
> 
> thanks
> 
> --
> Best Regards,
> Leo Jay

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


Re: decorator question

2006-01-09 Thread Duncan Booth
Bengt Richter wrote:

>>is it possible to pass parameters to a decorator function?
>>
> Yes, but then the function must return the same kind of thing
> a bare decorator-function name would have, which is a function
> able to take a single argument of a function and return a function.
>
> So your decorator won't take f as an argument, just the optional
> logfile, and it will return a function that does the wrapping like the
> original decorator. 

This sounds to me like something that should be done using a decorator. 
e.g. (everything from 'def timelogger' onwards is unchanged from the OP's 
code):

def decoratorwithargs(f):
def wrapper(*args,**kw):
def inner(target):
return f(target, *args, **kw)
return inner
return wrapper

@decoratorwithargs
def timelogger(f, logfile=sys.stdout):
 def wrapper(*a,**kw):
 logfile.write("started at %s" % time.ctime())
 t0 = time.time()
 f(*a, **kw)
 t1 = time.time()
 logfile.write("ended at %s" % time.ctime())
 logfile.write("diff = %f %s" % (t1-t0, "sec"))
 return wrapper

@timelogger(file("hierher", "a"))   ### << (1)
def loops(a,b,c):
sum = 0
for i in range(a):
  for j in range(b):
 for k in range(c):
sum += 1

(I think the logfile output could do with some newlines.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sockets on Windows and Mac

2006-01-09 Thread rodmc
I am on 10.3, I keep getting exceptions when it hits lines like

mySocket.bind (SERVER_IP, 2727 )
or
mySocket = socket.socket(socket.AF_NET,socket.SOCK_STREAM)

The code I am using is copied from a tutorial on a website somewhere.

Cheers,

rod

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


Re: Newline at EOF Removal

2006-01-09 Thread Alex N
Actually Im doing a process with PHP, Unicode, Ansi. I am trying to
format these text files to be acceptable to PHP. The first process is
to strip the unicode and convert to ansi. But there are blank lines in
the file and at the end of the file. I was just having trouble with the
lines at the end. PHP blows up if there is a blank or empty line in the
text files. So thats where i was at.
Peter gave me a good clue here
w.write(f.read().rstrip('\n') + '\n')
However the 2nd \n puts that empty line at the end of the file so I
tried it with just
w.write(f.read().rstrip('\n'))
and it works great!

Now I can go on to the next step. Thank you guys for your help

Alex

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


using livewires in py2exe?

2006-01-09 Thread Blaze Bresko
hey,

I am using python 2.4 and py2exe v 0.6. I have made a program using
pygame/livewires. I have the newest version of both but i dont know
what version they are (im on a different computer right now). When I
use py2exe to make the exe file, it works and there are no errors in
the whole thing. When I run the exe, it doesn't like the last line in
the program:

main()

this is the only real line in my game, everything else is either a
function or a class. It also doesn't like 2 other lines and I'll
include the setup.py and my error log if needed.

Does anyone know what the problem is?

Blaze

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


Re: Spelling mistakes!

2006-01-09 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> Terry> But not faster than use a dict server!  Why not just use (e.g.)
> Terry> kdict? 
>
> Maybe because not everybody has it?

Lame excuse. If you don't have something but you do want to use it,
you get it. If everybody just used what they had at one point in time,
and never acquired anything new, the world certainly would look
different.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Apology Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread Patrick Maupin
Mike Meyer wrote:
> This is where we disagree. I think their understanding of references
> is dead on. What's broken is their understanding of what variables are
> and what assignments mean. Once you fix that, the rest falls into
> place.
>
> (Steven D'Aprano wrote:)
> > The fact that call by object is unfamiliar is precisely its advantage.
> > Instead of people jumping to conclusions about what it means, like they do
> > with "reference", they will stop and think and if need be look for further
> > information about Python's object model. At the very least, they won't say
> > "Everything in Python is a reference, so this should work, but it
> > doesn't".
>
> What you're advocating is intentionally misleading people to deal with
> a symptom. I'd rather give them enough truth to deal with the disease.

I agree completely.  I have personally "converted" around a half-dozen
or so coworkers to Python over the course of the last three or four
years.  The conversion takes place in stages.  Usually, I have written
a small script for them which they later want to enhance, so they come
to me for a tutorial session.

My initial 5-10 minute tutorial starts off with an explanation of
name-binding, including something like "a=[1,2,3]; b=a; a[1]=4; print
b; b=42; print a, b".  Note that this also demonstrates the dynamic
nature of Python typing -- 'b' is not restricted to being bound to a
list merely because the first time it was bound was to a list.

Once they have that down, I describe "immutable" vs. "mutable".  I
start off by explaining that of course integers are immutable because
you cannot change 1 into 5.  I then explain (with examples) that,
additionally, in the language, strings are immutable (which does NOT
mean you cannot usefully manipulate them, just that, for example, in "x
= 'abc'; x = x + 'd'" the manipulation "x + 'd'" results in a
completely new string. (The attempted example x[1] = "d" also gets them
used to the exception reporting mechanism.)

I actually spend more time (of this 10 minutes!)  on "immutable" vs.
"mutable" (including ancillary lessons) than I spend on anything else.
After showing that strings are immutable, I then explain that tuples
are a sort of immutable list.  This usually elicits the question of why
such a thing is needed, which is a great segue into a minute or so
spent on dictionaries and their keys. (Dictionaries can occupy
additional time if the student recognizes that they are a good fit for
a pressing need.)

Only about the last 30 seconds or so is spent on function calling.  I
explain that all parameters are passed by reference, but that
OBVIOUSLY, if the called function wants to alter the caller's object,
the referenced object must be mutable, because, JUST AS WITH C
POINTERS, the pointer to the object is passed by making a copy of it on
the stack, so there is no way that the callee can directly alter the
caller's own pointer to the object.

After this lesson, I send them back to look at their script with
information about the online docs and a standing offer to help them
over any rough spots.  NOT ONE PERSON has ever been confused about the
parameter passing.

I have only given these tutorials to accomplished programmers, so my
opinion about teaching newbies is not as well-formed, but for a
C/C++/assembler programmer, the REAL question about parameters is "What
is pushed onto the stack?"  They are capable of a high level of
abstraction, so all they really want to know "Is a COPY of the object
passed on the stack, or is a POINTER to the object passed on the
stack?"

With such an accomplished student, if the teacher described Python's
parameter passing as anything but "call by reference",  it would lead
to confusion, and, ultimately, disrespect for the teacher.

Regards,
Pat

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


Re: Why it doesn't work?

2006-01-09 Thread Tomasz Lisowski
Lad wrote:
> I have a list
> L={}

This IS a dictionary, not a list.

> Now I can assign the value
> L['a']=1
> and I have
> L={'a': 1}
> 
> but I would like to have a dictionary like this
> L={'a': {'b':2}}

You need to initialise L['a'] first, before referencing L['a']['b']

So, you need to call first:
L['a'] = {}

Then you can write:
L['a']['b'] = 2

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


Re: Spelling mistakes!

2006-01-09 Thread Sybren Stuvel
Walter S. Leipold enlightened us with:
> [Gee, I hope their were no spelling misteaks inn that paragraph...]
 
 It should be "where"

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string to datetime parser?

2006-01-09 Thread Sybren Stuvel
beza1e1 enlightened us with:
> Is there a library which can parse strings and output a datetime
> object?

If you're happy with a mx.DateTime object, take a look at its parser.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .py vs .pyc

2006-01-09 Thread Duncan Booth
Sakcee wrote:

> is execution of pyc files faster than py files? since both files are
> interpreted by python , is there any speedup in using one or other?
> 
> what is difference if i type from cmd line,
> python test.py  vs. python test.pyc
> 
There was no need to post your question twice.

Python compiles .py files and (if it can) saves the compiled code in a .pyc 
file. Next time around it can simply load the .pyc file and bypass the 
compilation stage. There is no difference in execution speed, in both cases 
the same compiled code will be executed.

The main script (the one named on the command line) works slightly 
differently from imported modules in that a .pyc file is not automatically 
generated or used, so the compilation happens every time.
Unless you have a very large script the difference in load time is not 
likely to be noticeable (and if you have a very large script then you 
should split it into modules).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread rurpy

"Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
...snip...
> afaik, the Python Language Reference never defines the word "reference".
>
> It carefully defines words like "object" and "value", though, and terms like
> "call by object" or "call by object reference" are perfectly understandable
> if you use the words as they are defined in the language reference.

The Language Reference's definition of "value" is a non-definition.
About "value" it says that it is one of the three things an object
has.  It then says some values can change and talks about
mutable and immutable.  But we don't know what *it* is that
is mutable or immutable (other that it's called a "value" and it
is something an object "has").

Further down the page it says that container objects may have
references that are part of it's value.  Part?  Which part?  Part
of what?  Is an attribute part of a value?

I started a list of python doc problems a while ago.  Right
near the top is "object value defintion is useless".

As I've said before, the Language Reference is badly
broken and needs a major rewrite.  I don't think it should
be recommended to anyone as a source of authorative
information (except possibly for syntax since it in mostly
a Syntax Reference right now.)

[I posted another version of this yesterday from Google
but it has not appeared so...]

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


Re: py vs pyc

2006-01-09 Thread Tomasz Lisowski
Sakcee wrote:
> Hi
> 
> I want to know that is .pyc files execute faster than .py files,? since
> both are interpreted by python  , is there any speedup in using one or
> other.?
> 
> e.g.
> 
> what is the difference between runing from cmd  "python test.py" and
> "python test.pyc"
> 
> 
> thanks
> 
When running "python test.py" the interpreter will first precompile the 
test.py source file, and then execute it. When running "python 
test.pyc", the interpreter will go straight to the execution of the script.

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


Re: Multiway Branching

2006-01-09 Thread Justin Azoff
[EMAIL PROTECTED] wrote:
> I need to look at two-byte pairs coming from a machine, and interpret the
> meaning based on the relative values of the two bytes. In C I'd use a switch
> statement. Python doesn't have such a branching statement. I have 21
> comparisons to make, and that many if/elif/else statements is clunky and
> inefficient. Since these data are coming from an OMR scanner at 9600 bps (or
> faster if I can reset it programmatically to 38K over the serial cable), I
> want a fast algorithm.
>
>   The data are of the form:
>
>   if byte1 == 32 and byte2 == 32:
>   row_value = 0
>   elif byte1 == 36 and byte2 == 32:
>   row_value = "natural"
>...
>   elif byte1 == 32 and byte2 == 1:
>   row_value = 5
>   elif byte1 == 66 and byte2 == 32:
>   row_value = 0.167
>
>   There are two rows where the marked response equates to a string and 28
> rows where the marked response equates to an integer (1-9) or float of
> defined values.
>
>   Suggestions appreciated.
>
> Rich
>
> --
> Richard B. Shepard, Ph.D.   |   Author of "Quantifying 
> Environmental
> Applied Ecosystem Services, Inc. (TM)   |  Impact Assessments Using Fuzzy 
> Logic"
>  Voice: 503-667-4517 Fax: 503-667-8863

Use a dictionary:

byte_values = {
   (32,32)  : 0,
   (36,32)  : 'natural',
   (32,1 )  : 5,
}

row_value = byte_values[byte1,byte2]

-- 
- Justin

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


Re: PyHtmlGUI Project is looking for developers

2006-01-09 Thread Paul Boddie
John J. Lee wrote:
> "Paul Boddie" <[EMAIL PROTECTED]> writes:
> [...]
> > many would advocate using "AJAX" techniques and dropping support for
> > conventional Web interactions, but I think that such advocacy and the
> > resulting applications threaten the usability of the Web for fairly
> > large groups of people.
>
> That may well be true in practice, but I don't see any intrinsic
> reason for it.  Do you {,care}?

As I've probably said before, it's tempting for some people to demand
JavaScript for their Web applications whilst claiming that JavaScript
implementations are ready for serious use. Yet, aside from some of the
more hyped toolkits managing either to crash my
not-particularly-incapable browser or failing to do anything visible,
there's still a lot to be said for simple, "old school" Web
interactions. Would I prefer a silky drag-and-drop experience on an
Internet banking site, or would I rather be presented with the
pertinent facts for a transaction with some buttons on the page to
either confirm or cancel my actions? The latter approach quite probably
reduces the "what's going on now?" factor amongst large sections of
society familiar (but not intimately so) with computers - ie. more than
95% of users, I'd imagine. In attempting to replicate some dubious user
interface metaphor from their Mac, I imagine that most of the more
vocal "AJAX" advocates forget this.

Paul

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


Re: Sockets on Windows and Mac

2006-01-09 Thread rodmc
Hi Peter,

I am currently importing the socket library when I write the programs,
I have had no problems with it on my PC at work, but the Mac at home
steadfastly refuses to work. As for existing libraries, I am new to
Python so am kean to avoid re-inventing the wheel :-)

Cheers,

rod

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


Re: config errors on Freebsd and python 2.3

2006-01-09 Thread [EMAIL PROTECTED]

Safeer Tabassum wrote:
> why you are not installing it from ports?
> 

Python as installed from ports doesn't support Tkinter.

Curtis

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[Anders Hammarquist]:
> I had a quick look through our (Strakt's) codebase and found one example.

Thanks for the research :-)


> The code is used to process user-designed macros, where the user wants
> to append data to strings stored in the system. Note that all data is
> stored as lists of whatever the relevant data type is.
>
> While I didn't write this bit of code (so I can't say what, if any,
> alternatives were considered), it does seem to me the most straight-
> forward way to do it. Being able to say what the fill-in value should
> be would make the code even simpler.
>
> oldAttrVal is the original stored data, and attValue is what the macro
> wants to append.
>
> newAttrVal = []
> for x, y in map(None, oldAttrVal, attrValue):
> newAttrVal.append(u''.join((x or '', y or '')))

I'm finding this case difficult to analyze and generalize without
knowing the significance of position in the list.  It looks like None
fill-in is used because attrValue may be a longer list whenever the
user is specifying new system strings and it may be shorter when some
of there are no new strings and the system strings aren't being updated
at all.  Either way, it looks like the ordinal position has some
meaning that is shared by both oldAttrVal and newAttrVal, perhaps a
message number or somesuch.  If that is the case, is there some other
table the assigns meanings to the resulting strings according to their
index?  What does the code look like that accesses newAttrVal and how
does it know the significance of various positions in the list?  This
is important because it could shed some light on how an app finds
itself looping over two lists which share a common meaning for each
index position, yet they are unequal in length.



Raymond

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


Re: Why it doesn't work?

2006-01-09 Thread Peter Otten
Lad wrote:

> I have a list

A dictionary.

> L={}
> Now I can assign the value
> L['a']=1
> and I have
> L={'a': 1}
> 
> but I would like to have a dictionary like this
> L={'a': {'b':2}}
> 
> so I would expect I can do
> L['a']['b']=2
> 
> but it does not work. Why?

D["a"]["b"] = 2

translates to

D.__getitem__("a").__setitem__("b", 2)

When D doesn't already contain a key/value pair D = {"a": {}} the
__getitem__() call fails with a KeyError. If you don't know whether D
contains a key "a", use setdefault(key, value) which inserts the value only
if key is currently not in the dictionary. E. g.

>>> D = {}
>>> D.setdefault("a", {})["b"] = 42
>>> D.setdefault("a", {})["c"] = 24
>>> D
{'a': {'c': 24, 'b': 42}}

Peter

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


Get path of a class

2006-01-09 Thread Florian Lindner
Hello,
how can I get the path of a class. I managed to do it with

c.__module__ + "." + c.__name__

but I'm sure there is a better way.

Thanks,

Florian

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


CGI errror in (only in) IIS 6.0 server 2003

2006-01-09 Thread [EMAIL PROTECTED]
Hi, I've been using ActivePython 2.3 (cgi) on IIS on win xp, 2000 and
they work fine.
Until I upgrade the system the server 2003. The ASP script engine is ok
but not the CGIs.

I got these errors:

HTTP Error 403.1 - Forbidden: Execute access is denied.



I already have execute access on the directory.



Can anyone help me?


=
kychan

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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-09 Thread Anton Vredegoor
Alex Martelli wrote:

> Anton Vredegoor <[EMAIL PROTECTED]> wrote:
>
> > However I still maintain that I was never able to meet these fine
> > people you speak about and which you seem to know because the cost
> > involved (a few hundred euro to visit pycon for example) was too high
> > compared to my food budget.
>
> Europython is cheap to attend, and has been held twice in Charleroi,
> Belgium, for example -- if you're in the Netherlands, you could have
> bycicled there, crashed with somebody (I've seen lots of impecunious
> people offered hospitality that way), and not spent more on food than
> you would by staying in the Netherlands.  You'll have to invent some
> better excuse, to explain why you chose not to attend it.

I looked it up: 160 euro (early registration). My food budget is about
16 euro a week now, maybe even less if I want to keep feeding myself a
bit longer, maybe in 2003 my reserves were a bit higher than now, but I
had not yet learned then to be without a regular income, so I was very
scared to become pennyless at that time.

I am perfectly used to sleeping at other peoples' places, for example I
was at many go (baduk) tournaments and if the prices and atmosphere
would be anything comparable to that I guarantee you that I would have
been present.

IIRC I got an offer from Laura Creighton at the time to borrow me the
money, so one could say it was a choice, although by that time the
price had gone up to 270 euro.

But frankly indeed, I just don't even like to participate to events
that claim to be open for all but don't even acknowledge that the
barriers are extremely high compared to some participants budgets. Your
hype about it being cheap has a very chilling effect on my enthousiasm,
it's the same way with pypy congresses, which I also would have liked
to attend (and this thing even seems to be sponsored by public EU
money). Probably I am still a *rich* person, on a global scale, because
I live in a place with free internet (from a public library).

You *do* realize that even posting to usenet is impossible (or at least
very hard) for a lot of people, including me for at least 6 months. I
had to find someone to invite me to gmail and also a way to access my
previous internet account, which I lost access to when they cut my
phone line, to recieve the mail that finally enabled me to post via
google. Nowadays it's probably possible to open a hotmail account and
get invited to gmail from there, so one can post to usenet.

Theoretically I have now yet another option to post (except via
google), but IMO it remains true that one needs at least one link to
corruption to be able to post to usenet.

Anton

'hey, and my laptop doesn't even have a cdrom, needs almost continous
electricity, it's keyboard is broken (but it works fine with external
keyboard), and it networks via a pcmcia card with a *cable* '

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


Re: HELP! on wxPython Error

2006-01-09 Thread Franz Steinhaeusler
On Mon, 2 Jan 2006 21:44:11 +0600, Suranga Sarukkali
<[EMAIL PROTECTED]> wrote:

>Hello, I'm Sam and I've been under som trouble with using wxPython
>that when I try to execute code containing wxPython gui programs
>provided with wxPython geting started sample progams it's giving a
>error but when I type the code to the shell prompt it works fine. Is
>it beacus I'm on windows or will I have to download again? or is it
>else. Please answer my deeply troblesome question replying to me at
>[EMAIL PROTECTED]

Is the wxPython Demo working?
What Getting Started Code are you referring to?
Can you show us the code?
Did you get any tracebacks?
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Determination of disk types

2006-01-09 Thread Tim Golden
[Mondal]

| Is there a way to determine which drive letter is a FDD, a local disk,
| a CD-ROM/COMBO Drive, or a mapped network drive?
| 
| I wrote a script to identify all the drive letters on my Windows XP
| system. Now I want to determine their type, too.

Initial quick reposnse: look at WMI. Something like
the following could get you going:

WMI info from MS:
http://msdn.microsoft.com/library/en-us/dnanchor/html/anch_wmi.asp
Python module: http://timgolden.me.uk/python/wmi.html


import wmi

c = wmi.WMI ()
for disk in c.Win32_LogicalDisk ():
  print disk



You probably want to look at the DriveType and MediaType
attributes, and you may well want to look into other
classes such as Win32_DiskDrive. WMI often involves a
fair bit of poking around to find the info you need.

Fortunately if you can find someone who's answered the
question in some other language, perhaps on the WMI
newsgroups, you can easily translate that into Python.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: decorator question

2006-01-09 Thread Michele Simionato
Schüle Daniel wrote:
> Can someone give me some pointers to the metaprogramming in Python?
> links etc

Check the Python Wiki. For the decorators in particular I wrote a
module that
you may find useful. See

http://www.phyast.pitt.edu/~micheles/python/decorator.zip
http://www.phyast.pitt.edu/~micheles/python/documentation.html

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


Re: Detecting Python Installs from the Windows Registry

2006-01-09 Thread Ziga Seilnacht
Fuzzyman wrote:

> Does anyone know how to use _winreg to get path information (location
> of install) for all versions of Python installed (and also which is the
> most recent) ?

This should probably work:

import _winreg

def get_subkey_names(reg_key):
index = 0
L = []
while True:
try:
name = _winreg.EnumKey(reg_key, index)
except EnvironmentError:
break
index += 1
L.append(name)
return L

def function_in_search_of_a_name():
"""
Return a list with info about installed versions of Python.

Each version in the list is represented as a tuple with 3 items:

0   A long integer giving when the key for this version was last
  modified as 100's of nanoseconds since Jan 1, 1600.
1   A string with major and minor version number e.g '2.4'.
2   A string of the absolute path to the installation directory.
"""
python_path = r'software\python\pythoncore'
L = []
for reg_hive in (_winreg.HKEY_LOCAL_MACHINE,
  _winreg.HKEY_CURRENT_USER):
try:
python_key = _winreg.OpenKey(reg_hive, python_path)
except EnvironmentError:
continue
for version_name in get_subkey_names(python_key):
key = _winreg.OpenKey(python_key, version_name)
modification_date = _winreg.QueryInfoKey(key)[2]
install_path = _winreg.QueryValue(key, 'installpath')
L.append((modification_date, version_name, install_path))
return L

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


.py vs .pyc

2006-01-09 Thread Sakcee
Hi all

is execution of pyc files faster than py files? since both files are
interpreted by python , is there any speedup in using one or other?

what is difference if i type from cmd line,
python test.py  vs. python test.pyc


thanks

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


Re: Spelling mistakes!

2006-01-09 Thread Michele Simionato
[EMAIL PROTECTED] wrote:
>  The OP sort of seemed like he was pining
> for attribute declarations.  __slots__ is the closest thing Python has to
> them.  I don't use them myself (since I've basically avoided new-style
> classes so far).
>
> Skip

No, slots are a memory optimization trick and should NOT be used as
declarations.
You can find a few posts of the Martellibot on the subject. I even
wrote a recipe
to tell people who want static declarations how to implement them
without slots:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158

 Michele Simionato

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


Re: Spelling mistakes!

2006-01-09 Thread Michele Simionato
I like to play devil's advocate here, so I will say that in this case
using automatic testing
will increase your probability of spelling mistakes: I do most of my
spelling mistakes 
in the test cases! <0.5 wink>

Michele Simionato

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Paul Rubin
"Raymond Hettinger" <[EMAIL PROTECTED]> writes:
> The generator version is plain, simple, boring, and uninspirational.
> But it took only seconds to write and did not require a knowledge of
> advanced itertool combinations.  It more easily explained than the
> versions with zip tricks.

I had this cute idea of using dropwhile to detect the end of an iterable:

it = chain(iterable, repeat(''))
while True:
   row = tuple(islice(it, group_size))
   # next line raises StopIteration if row is entirely null-strings
   dropwhile(lambda x: x=='', row).next()
   yield row
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
Duncan Booth wrote:
> One example of padding out iterators (although I didn't use map's fill-in
> to implement it) is turning a single column of items into a multi-column
> table with the items laid out across the rows first. The last row may have
> to be padded with some empty cells.

ANALYSIS


This case relies on the side-effects of zip's implementation details --
the trick of windowing or data grouping with code like:  zip(it(),
it(), it()).  The remaining challenge is handling missing values when
the reshape operation produces a rectangular matrix with more elements
than provided by the iterable input.

The proposed function directly meets the challenge:

it = iter(iterable)
result = izip_longest(*[it]*group_size, pad='')

Alternately, the need can be met with existing tools by pre-padding the
iterator with enough extra values to fill any holes:

it = chain(iterable, repeat('', group_size-1))
result = izip_longest(*[it]*group_size)

Both approaches require a certain meaure of inventiveness, rely on
advacned tricks, and forgo readability to gain the raw speed and
conciseness afforded by a clever use of itertools.  They are also a
challenge to review, test, modify, read, or explain to others.

In contrast, a simple generator is trivially easy to create and read,
albiet less concise and not as speedy:

it = iter(iterable)
while 1:
row = tuple(islice(it, group_size))
if len(row) == group_size:
yield row
else:
yield row + ('',) * (group_size - len(row))
break

The generator version is plain, simple, boring, and uninspirational.
But it took only seconds to write and did not require a knowledge of
advanced itertool combinations.  It more easily explained than the
versions with zip tricks.


Raymond

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


Re: Is 'everything' a refrence or isn't it?

2006-01-09 Thread Antoon Pardon
Op 2006-01-06, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> If we say "Python is call be reference" (or call by value, as many people
> also say) we *know* the consequence will be newbies writing in saying "I
> was told Python is call by reference, so I did this, and it didn't work,
> is that a bug in Python? What is wrong?" It is not a bug in Python, it is
> a bug in their mental model of how Python works, and we put that bug in
> their head. Every time that happens, it is *our* fault, not theirs, for
> using language guaranteed to mislead.

Well then I would think that the language that misleads is not
"reference" but assignment. Because it is not their idea of
call by reference that leads to the misconception, but their
idea of what an assignment does.

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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Duncan Booth
Raymond Hettinger wrote:

> The generator version is plain, simple, boring, and uninspirational.
> But it took only seconds to write and did not require a knowledge of
> advanced itertool combinations.  It more easily explained than the
> versions with zip tricks.
> 
I can't argue with that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spelling mistakes!

2006-01-09 Thread Antoon Pardon
Op 2006-01-06, Terry Hancock schreef <[EMAIL PROTECTED]>:
> On 6 Jan 2006 07:30:41 -0800
> "KraftDiner" <[EMAIL PROTECTED]> wrote:
>> I've spent hours trying to find a bug that was a simple
>> spelling mistake.
>
> You're not the first. ;-)
>
>> in an init method I declare a variable  self.someLongName
>> 
>> later in a different method of the class I use
>> self.sumLongName
>> Now I really meant self.someLongName.
>> In fact I don't want a variable called sumLongName.
>> Frankly how are you ever to know if this type of error is
>> occuring?
>
> Both "unit tests" and "interfaces" are useful for catching
> simple errors like this one.  There is a 'unittest' module
> in the Python standard library, and 'interface' modules are
> available from the Zope 3 project and PyProtocols, both are
> good.

I don't think unit tests are that helpfull in this case.
Unit tests help you in finding out there is a bug, they
don't help that much in tracking down a bug.

I for some reason a person is reading over the difference
between sumLongName and someLongName and doesn't notice
the different spelling in his source a unit test won't
be of much help.

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


Re: building Python 2.4.2 on Mac OS X

2006-01-09 Thread Walter Overby
Not sure if this will meet your needs, but I have had good luck using
the "Fink" package manager, which has 2.4.2 in unstable.  It takes a
while to update the package list and build, but it worked for me
without errors.

Regards,

Walter.

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


testing units in a specific order?

2006-01-09 Thread Antoon Pardon
I  have  used  unit  tests now for a number of project. One thing
that I dislike is it that the order in which the tests  are  done
bears no relationship to the order they appear in the source.

This  makes  using  unit tests somewhat cumbersome. Is there some
way to force the tests being done in a particular order?

-- 
Antoon Pardon


























































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


Re: build curiosities of svn head (on WinXP)

2006-01-09 Thread David Murmann
Paul Moore schrieb:
>> btw, if anyone is interested in the (rather small) build-script for
>> nant, just ask,
> 
> I haven't seen anyone ask, so can I? I'd love to see the build script.

sorry it took me so long, i have been busy the last couple of days,
but here it is:

"PCBuild/nant-sln.build":
---


  

  

  




  

  

  

---

note that bsddb is explicitly excluded because i have not figured
out how to build it without visual studio. the rest of the extensions
are more or less straightforward if you follow the instructions in
"PCBuild/readme.txt". 

> Actually, beyond the script, what tool setup is needed? I have various
> bits of stuff (MS Visual C++ toolkit 2003, platform SDK, Visual Studio
> 8, VS .NET 2003). I found a few oddities, such as problems finding a
> usable msvcrt.lib (should it not have been using msvcr71.lib?) and
> issues generating pythonnt_rc.h.

as you can see in my .build-file i had problems with pythonnt_rc.h too.
AFAICT it should be generated by "make_versioninfo.vcproj" but somehow
it doesn't (i did not investigate further cause the above workaround
works quite well). i had no problems with any libs while building the
core python, but when building c-extensions (especially ssl was tricky
if i remember correctly).

> I sort-of got it working, and I was using a fairly old version of the
> sources (it was just a quick hack, to see if I could work out what I
> needed as a build script) but it would be nice to see the actual
> toolset listed out.

the tools i installed were:
- cygwin (with appropriate tools like svn)

- visual c++ toolkit

- nant

- the platform sdk (you dont need it complete but i dont know exactly what
  parts you need...)

- platform sdk for sp2 (i dont know whether you need this at all)

- MS .NET framework redistributable

that should be it, but i might be forgetting something.
you then need to set some environment variables like PATH, LIB and INCLUDE
to point to the directories in the different packages.


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


Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote:
> The other use case I had was a simple file diff.
> All I cared about was if the files were the same or
> not, and if not, what were the first differing lines.
> This was to compare output from a process that
> was supposed to match some saved reference
> data.  Because of error propagation, lines beyond
> the first difference were meaningless.
 . . .
> This same use case occured again very recently
> when writing unit tests to compare output of a parser
> with known correct output during refactoring.

Analysis


Both of these cases compare two data streams and report the first
mismatch, if any.  Data beyond the first mismatch is discarded.

The example code seeks to avoid managing two separate iterators and the
attendant code for trapping StopIteration and handling end-cases.  The
simplification is accomplished by generating a single fill element so
that the end-of-file condition becomes it own element capable of being
compared or reported back as a difference.  The EOF element serves as a
sentinel and allows a single line of comparison to handle all cases.
This is a normal and common use for sentinels.

The OP's code appends the sentinel using a proposed variant of zip()
which pads unequal iterables with a specified fill element:

for x, y in izip_longest(file1, file2, fill=''):
if x != y:
return 'Mismatch', x, y
return 'Match'

Alternately, the example can be written using existing itertools:

for x, y in izip(chain(file1, ['']), chain(file2, [''])):
if x != y:
return 'Mismatch', x, y
return 'Match'

This is a typical use of chain() and not at all tricky.  The chain()
function was specifically designed for tacking one or more elements
onto the end of another iterable. It is ideal for appending sentinels.


Raymond

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


Perhaps Python can do this better ?

2006-01-09 Thread news
[EMAIL PROTECTED] wrote:

> Using a script:--
> lynx -dump '' > Fl1
> 
> lynx -dump '' > Fln
> 
>   where the URLs are filled in off line, is a great online-telco-cost
> saver for me here in 3rd world S. Africa.
> 
> I want to similarly send a set of pre-written emails via the
> same script.
> 
> Is this possible & how ?
> 
> And if not via lynx, by some other means.
> What I like about the above is that you don't even need to
> load/see lynx, which is just in the background.

[EMAIL PROTECTED] wrote:
] can't you use 'mail' or 'mutt'?
] $ man mail
] $ man mailx
] $ man mutt

Enrique Perez-Terron wrote:
} The oldest Unix email I know of used this syntax to send mail:
} 
}  mail -s "subject" [EMAIL PROTECTED] < mailfile
} 
} but it actually invokes "sendmail" to do the delivery. Configuring
} sendmail is **dificult**.   Postfix is somewhat easier.   Most systems
} come with sendmail already installed.
} 
} The trouble is that the standard sendmail config supposes that your
} computer is a first-class citizen of the Internet, with it's own
} properly registered dns hostname.   Then sendmail would use DNS to
} figure out what computer to relay the mail to for the given recipient
} address.
}   ...etc...BIG explanation.
} 
} Andrew Preater wrote:
} A simple mailer such as ssmtp would do this trick.   It's
} sendmail-compliant so you can use it with mutt et al., all it
} does it send mail through to your smarthost which could be your
} ISPs server or another machine on your network.   It can rewrite
} the From and envelope for you too, but you might as well do that
} in mutt.
} ..
} IIRC pine can do this.   But then you'd be using pine (aaargh!)
} rather than mutt.

Yea well I don't want to install ssmtp or other stuff.
That's how bloat spreads.
"mail" apparently calls 'sendmail' - a monster AFAIK ?
It was enough trouble setting up: dial > ppp.
I don't need another layer of crap.
Perhaps I'll use pine.
But since lynx can do it 'manually' please remind me of the bash
syntax for:

1. 'output char("x") as if in CLI'
2. 'output string("string1") as if in CLI'
3. 'output text of File1 as if in CLI'

Then I can just make some templates to combine with the 
'getHttp-to-file' which lynx does so well already.

Thanks for any input,

== chris Glur.

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


Re: testing units in a specific order?

2006-01-09 Thread Michele Simionato
You could use py.test

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


Re: Calling foreign functions from Python? ctypes?

2006-01-09 Thread Neil Hodgson
Paul Watson:

> I cannot find any way to get to GetVersionInfo in VBScript (cscript).

Set objFSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo objFSO.GetFileVersion("c:\bin\SciLexer.dll")

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


Re: CGI errror in (only in) IIS 6.0 server 2003

2006-01-09 Thread David Wahler
[EMAIL PROTECTED] wrote:
> Hi, I've been using ActivePython 2.3 (cgi) on IIS on win xp, 2000 and
> they work fine.
> Until I upgrade the system the server 2003. The ASP script engine is ok
> but not the CGIs.
>
> I got these errors:
>
> HTTP Error 403.1 - Forbidden: Execute access is denied.
>
> I already have execute access on the directory.
>
> Can anyone help me?

This is an IIS configuration issue, and has nothing to do with Python.
You will probably get much better responses if you post it in a more
appropriate group -- a quick search of Google Groups turns up
microsoft.public.inetserver.iis and
comp.os.ms-windows.nt.admin.networking, to get you started.

Hope this helps,

-- David

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


Re: Newbie with some doubts.

2006-01-09 Thread Bruno Desthuilliers
Edgar A. Rodriguez a écrit :
> Hi everybody,
> 
> Im newbie to Python (I found it three weeks ago) , in fact Im newbie to
> programming. I'm being reading and training with the language, but I
> still wondering about what Classes are used to. 

A class is the definition of a type of object, and let you add your own 
object types to the language.

In fact, as soon as you're programming in Python, you are using classes 
and objects, even if you're not aware of it. *Everything* in Python is 
an object (ie: an 'instance' of a class). The string "foo" is an 
instance of class string, the number 42 is an instance of class int, 
etc. Even functions are objects (instances of class function, yes), so 
you can access (and modify) the properties of a function:

def fun():
   "a dummy function"
   return "foo"

fun.___doc__
=>"a dummy function"
fun.__class__
=> 


> Could you please give
> me some examples??

Let's go with the good ole (and very dumb) example of a shapes drawing 
program.

# The procedural (ie: no classes) version:

def draw_line(from, to):
   # code here

def draw_square(origin, width):
   # code here

def draw_circle(center, radius):
   # code here


shapes = [
   {'type': 'square',
'origin' : (10,10),
'width' : 20},
   {'type': 'circle',
'center': (40, 40),
'radius': 10},
   {'type', 'line',
'origin' : (42,42)
'end' : (48,84)}
]

def draw_shape(shapes):
   for s in shapes:
 if s['type'] == 'line':
   draw_line(s['origin'], s['end'])
 elif s['type'] == 'square':
   draw_square(s['origin'], s['width'])
 elif s['type'] == 'circle':
   draw_circle(s['center'], s['radius'])
 else:
   raise TypeError, "item %s is not a valid shape" % s



# the ObjectOriented version :

class Line(object):
   def __init__(self, origin, end):
 self.origin = origin
 self.end = end

   def draw(self):
 # code here

class Circle(object):
   def __init__(self, center, radius):
 self.center = center
 self.radius = radius

   def draw(self):
 # code here

class Square(object):
   def __init__(self, origin, width):
 self.origin = origin
 self.width = width

   def draw(self):
 # code here


shapes = [
   Square((10,10), 20),
   Circle((40, 40),10),
   Line((42,42), (48,84)),
]

def draw_shapes(shapes):
   for s in shapes:
 s.draw()



Now try to add to both versions a new type of shape, 'rect', with 
origin, width and height. In the first case, you'll need to modify the 
draw_shapes() function. In the second case, since each shape type know 
how to draw itself (this is called 'encapsulation'), you'll only have to 
define the Rect class.

The example being a small and dumb example, the advantage may not be 
that obvious, but think of what this would mean for a full-featured 
shape drawing program. And there is of course *much* more than this in 
OOP...

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


URL 'special character' replacements

2006-01-09 Thread Claude Henchoz
Hi guys

I have a huge list of URLs. These URLs all have ASCII codes for special
characters, like "%20" for a space or "%21" for an exclamation mark.

I've already googled quite some time, but I have not been able to find
any elegant way on how to replace these with their 'real' counterparts
(" " and "!").

Of course, I could just replace(), but that seems to be a lot of work.

Thanks for any help.

Cheers, Claude

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


py2exe and Amara

2006-01-09 Thread Doru-Catalin Togea
Hi!

I am using Amara 1.1.6 in a project. I made an executable with py2exe but 
when I try to run it I am referred to the log file, which states:

Traceback (most recent call last):
   File "makeTestSpec.py", line 281, in ?
   File "makeTestSpec.py", line 114, in __init__
   File "makeTestSpec.py", line 125, in loadTests
   File "amara\__init__.pyc", line 50, in parse
NameError: global name 'IsXml' is not defined

The lines reffered to are:

281: mainWindow = MakeTestSpec(root)
114: self.loadTests()
125: doc = amara.parse(fileName)

I import amara like this: 'import amara'. These three files have been 
zipped into the library.zip file: bindery.pyc, binderytools.pic, 
binderyxpath.pyc, which are the amara files.

Any suggestions as to how to make this executable work?

Everything else seems to work fine; if I disable the XML stuff from my 
script, all the rest seems to work, even Pmw loads up correctly.

Thanks,
Catalin


-- 

  == 
 << We are what we repeatedly do.  >>
 <<  Excellence, therefore, is not an act  >>
 << but a habit.   >>
  == 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: URL 'special character' replacements

2006-01-09 Thread Duncan Booth
Claude Henchoz wrote:

> I have a huge list of URLs. These URLs all have ASCII codes for special
> characters, like "%20" for a space or "%21" for an exclamation mark.
> 
> I've already googled quite some time, but I have not been able to find
> any elegant way on how to replace these with their 'real' counterparts
> (" " and "!").
> 
> Of course, I could just replace(), but that seems to be a lot of work.
> 

urllib.unquote() or urllib.unquote_plus() as appropriate:

unquote( string) 

Replace "%xx" escapes by their single-character equivalent. 
Example: unquote('/%7Econnolly/') yields '/~connolly/'. 


unquote_plus( string) 

Like unquote(), but also replaces plus signs by spaces, as required for 
unquoting HTML form values. 

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


Re: URL 'special character' replacements

2006-01-09 Thread Fredrik Lundh
Claude Henchoz wrote:

> I have a huge list of URLs. These URLs all have ASCII codes for special
> characters, like "%20" for a space or "%21" for an exclamation mark.
>
> I've already googled quite some time, but I have not been able to find
> any elegant way on how to replace these with their 'real' counterparts
> (" " and "!").
>
> Of course, I could just replace(), but that seems to be a lot of work.

>>> import urllib
>>> urllib.unquote("http://docs.python.org/lib/module-urllib.html%20%21";)
'http://docs.python.org/lib/module-urllib.html !'

 



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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-09 Thread Anton Vredegoor
Alex Martelli wrote:

> I just don't understand, always assuming you're in the Netherlands, how
> attending Europython in Belgium (as opposed to Pycon in the US) could
> have cost hundreds of euros.  Conference registration is free to
> speakers, bicycling NL->BE not costly (many were driving from NL, so
> bumming a ride was far from impossible either), many attendants arranged
> to "crash" for free thanks to the hospitality of others, food costs in
> Belgium aren't much different from those in NL.

Ah, I see. You're approaching this from a 'speaker' scenario. You
already have a lot of contacts, know where you can sleep, where to eat
and so on.
 
> I'm not saying a few hundred euros is 'cheap' -- it obviously isn't, if
> your income is low to nonexistent; rather, I'm wondering where that
> "hundreds" amount comes from.  You originally mentioned only pycon
> (where the need to fly to the US, for people living in Europe, can
> obviously account for "hundreds of euros" already); Europython is
> specifically held in Europe to be cheaper and more convenient to attend
> for Europeans, and I've always met many people there who fell in the
> "income low to nonexistent" bracket for one reason or another.

Now going back to my claim that elitism is bad, I think you are the
perfect proof of my point. You live in luxurious (with respect to
community, education and financial aspects of being a computer scientist
or programmer) conditions and can just not understand why some people
have problems entering that same environment and privileged conditions
as yourself. This attitude is very common and needs only some kind
Blair-alike kind of selfhypnosis in order to effectively not being aware
of lying.

What is shunned is any form selfanalysis, because it would immediately
reveal that you yourself are violently keeping all these people out of
opportunities (the backstabbing), in your case for example by requesting
certain degrees, without realizing that what you are selecting for is
not what you think it is. It is selection for socialization and
belonging to some kind of social group, not any mental ability really,
not even the likeliness of being able to grasp Haskell which you somehow
seem to link to having a mathematical education. 

Seriously, this is just a fraction of a unit above craniometry and you
would be wiser if you dropped this attitude.

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


Re: CGI errror in (only in) IIS 6.0 server 2003

2006-01-09 Thread Fredrik Lundh
David Wahler wrote:

>> I got these errors:
>>
>> HTTP Error 403.1 - Forbidden: Execute access is denied.
>>
>> I already have execute access on the directory.
>>
>> Can anyone help me?
>
> This is an IIS configuration issue, and has nothing to do with Python.
> You will probably get much better responses if you post it in a more
> appropriate group -- a quick search of Google Groups turns up
> microsoft.public.inetserver.iis and
> comp.os.ms-windows.nt.admin.networking, to get you started.

checking the IIS documentation may help:

http://support.microsoft.com/default.aspx?scid=kb;en-us;318380

(scroll down a bit for the section that explains common causes for
the 403.1 message)

the IIS faq page may also be helpful:

http://www.iisfaq.com

e.g.

http://www.iisfaq.com/Default.aspx?tabid=2814
HTTP 403.1 Forbidden: Execute Access Forbidden

 



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


Re: 2D canvas for GTK

2006-01-09 Thread Sandro Dentella
Il 2006-01-09, John Bauman <[EMAIL PROTECTED]> ha scritto:
>
> "Sandro Dentella" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>>I need a (decent) canvas for PyGTK. I used tkinter.canvas with real 
>>pleasure
>> in the past but now I need to use the canvas in a Gtk application. Does
>> anybody know of one with similar capabilities? It must work on Windows 
>> too.
>> It must be able to produce postscript output.
>
> I think that PyCairo might be what you're looking for, at least if you're 
> using gtk 2.8.

No, that's definitely a lower level tool. I need someting that has
rectangles, lines, possibility to move object around, easy bindings, tags
for objects, grouping. All that is already in tkinter.canvas but I need to
use it from a GTK application.

Any other ideas?

sandro
*:-)

-- 
Sandro Dentella  *:-)
http://www.tksql.orgTkSQL Home page - My GPL work
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: URL 'special character' replacements

2006-01-09 Thread Tim N. van der Leeuw
My outline for a solution would be:

- Use StringIO or cStringIO for reading the original URLs character for
character, and to build the result URLs character for character

- When you read a '%' then read the next 2 character (should be
digits!!!) and create a new string with them
- The numbers like '20' etc. are hexadecimal values, meaning integers
with base 16.
  Get the actual int-value like this:
  code_int = int(code_str, 16)
- Convert to character as: code_chr = chr(code_int)
- Write this character to the output cStringIO buffer
- When the whole URL is done, do getvalue() to get the string of the
new URL and close the cStringIO buffer.

Is that sufficiently comprehensible? Or still too convoluted for you?

(PS: I researched doing it the manual way, 'the hard way'. However,
there are plenty of libraries in Python for all sorts of internet
stuff. Perhaps urllib or urllib2 already has the functionality that you
need -- didn't look it up)

cheers,

--Tim

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


Re: testing units in a specific order?

2006-01-09 Thread Michele Simionato
Carl Friedrich Bolz wrote:
> If you like it so much (and I am being optimistic here :-) that you want
> to switch tests that use the stdlib unittest module over to py.test you
> can use a script called utestconvert.py which converts the unittest
> syntax over to py.test syntax. It can be found in the tool directory of
> the py-lib.

This looks new. Can you comment on how utestconvert.py work and how
reliable is it?
Thanks,  


Michele Simionato

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


Re: URL 'special character' replacements

2006-01-09 Thread Claude Henchoz
Thanks guys, I like the urllib solution. Stupid me, looked at urllib
reference, but thought that "quote" and "unquote" deal with
_&_n_b_s_p_;_ style entities.

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


  1   2   3   >