Re: How to check the exists of a name?

2009-10-17 Thread David
Il Sat, 17 Oct 2009 23:43:36 -0700 (PDT), StarWing ha scritto:

> I got a idea, use a try...except statement. there are another way to
> do it ?
> 
> (I just curious now, because I solve my problem in another way :-)

locals().has_key(myname) 
globals().has_key(myname)

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


Re: How to check the exists of a name?

2009-10-17 Thread StarWing
On 10月18日, 下午2时37分, Chris Rebert  wrote:
> On Sat, Oct 17, 2009 at 11:30 PM, StarWing  wrote:
> > Sometimes I want to make a simple flags. and i need to check there is
> > a name in current scope or not (that is, we can visit this name, no
> > matter where is it). and how to do that in python?
>
> You should avoid needing to do that in the first place. Common
> alternatives include using a dict instead of variables, depending on
> your circumstances.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Okay... Thank you... But if I want to do that, what shall I do?

I got a idea, use a try...except statement. there are another way to
do it ?

(I just curious now, because I solve my problem in another way :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check the exists of a name?

2009-10-17 Thread David
Il Sat, 17 Oct 2009 23:30:02 -0700 (PDT), StarWing ha scritto:

> Sometimes I want to make a simple flags. and i need to check there is
> a name in current scope or not (that is, we can visit this name, no
> matter where is it). and how to do that in python?

Just use it in a try..except block.

try:
print myname
except NameError:
print "myname does not exists"


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


Re: The rap against "while True:" loops

2009-10-17 Thread Paul Rubin
Steven D'Aprano  writes:
> For the record, the four lines Paul implies are "confusing" are:
> 
> try:
> d[key] += value
> except KeyError:
> d[key] = value

Consider what happens if the computation of "key" or "value" itself
raises KeyError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check the exists of a name?

2009-10-17 Thread Chris Rebert
On Sat, Oct 17, 2009 at 11:30 PM, StarWing  wrote:
> Sometimes I want to make a simple flags. and i need to check there is
> a name in current scope or not (that is, we can visit this name, no
> matter where is it). and how to do that in python?

You should avoid needing to do that in the first place. Common
alternatives include using a dict instead of variables, depending on
your circumstances.

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


How to check the exists of a name?

2009-10-17 Thread StarWing
Sometimes I want to make a simple flags. and i need to check there is
a name in current scope or not (that is, we can visit this name, no
matter where is it). and how to do that in python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weekdays in range

2009-10-17 Thread Ben Finney
Jive Dadson  writes:

> Can someone think of an easy way to calculate the number of weekdays
> between two calendar dates (in Python)?

That depends on what you mean by “weekdays”.

>>> import datetime
>>> begin_date = datetime.date(2009, 10, 9)
>>> end_date = datetime.date(2009, 10, 22)
>>> import calendar
>>> print calendar.month(2009, 10)
October 2009
Mo Tu We Th Fr Sa Su
  1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
>>> end_date - begin_date
datetime.timedelta(13)

If you're expecting to exclude Saturday and Sunday (i.e. if you expect
the above result to be 9 days instead of 13), you can use other
functions of the ‘calendar’ module; try starting with:

>>> friday_weekday = 4
>>> len([
... date for date in (
... begin_date + datetime.timedelta(days)
... for days in range((end_date - begin_date).days))
... if calendar.weekday(date.year, date.month, date.day) <= 
friday_weekday])
9

-- 
 \   “Selfish, adj. Devoid of consideration for the selfishness of |
  `\  others.” —Ambrose Bierce, _The Devil's Dictionary_, 1906 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help to convert c++ fonction in python

2009-10-17 Thread Toff
On 18 oct, 02:13, geremy condra  wrote:
> On Sat, Oct 17, 2009 at 7:57 PM, David Robinow  wrote:
> > On Sat, Oct 17, 2009 at 7:48 PM, geremy condra  wrote:
> >> For the love of baby kittens, please, please, please tell me that
> >> you do not believe this securely encrypts your data.
> >  Yeah, I think it's pretty good.
> > Can you do better?
>
> Trivially. Use AES, 3DES, any standard cryptosystem- there are
> literally dozens of excellent, well-studied implementations in
> both C++ and Python, and hardware implementations on many
> processors.
>
> The cipher listed will fall in a single round of chosen plaintext
> attacks or chosen ciphertext attacks, and with a keylength of
> 40 bytes against a message length of 768 will give me roughly
> 19 windows on a single encryption. Frequency analysis is
> therefore going to be extremely profitable, not to mention
> trivially easy.
>
> Geremy Condra



Thanks a lot Tim !



@Geremy :
this is not a methode to encrypt data
it is more a methode to encode /decode strings

for exemple to store passwords that need  to be used by others
programs
yes it 's insecure
but there is no secure way to store password that 's need to be
retrieve


PS : sorry for my english
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list to tuple and vice versa

2009-10-17 Thread StarWing
On 10月18日, 下午1时32分, Ben Finney  wrote:
> StarWing  writes:
> > On 10月18日, 下午12时19分, Ben Finney  wrote:
> > > Jabba Laci  writes:
> > > > Right, it was my bad. After removal the tuple() function works
> > > > perfectly.
>
> > > Note that, though it is callable, ‘tuple’ is not a function but a
> > > type:
>
> > A type is always callable.
>
> Yes (modulo perversions like explicitly making a non-callable type).
> This matches what I said above.
>
> > call a type will call its __init__ special method (or and __new__
> > special method together).
>
> No http://docs.python.org/reference/datamodel.html#object.__new__>
> http://docs.python.org/reference/datamodel.html#object.__init__>.
>
> --
>  \      “Anyone who believes exponential growth can go on forever in a |
>   `\        finite world is either a madman or an economist.” —Kenneth |
> _o__)                                                         Boulding |
> Ben Finney

Sorry for my ambiguity. I exactly mean that, but thanks for the
docs :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: restriction on sum: intentional bug?

2009-10-17 Thread Dieter Maurer
Christian Heimes  writes on Fri, 16 Oct 2009 17:58:29 +0200:
> Alan G Isaac schrieb:
> > I expected this to be fixed in Python 3:
> > 
>  sum(['ab','cd'],'')
> > Traceback (most recent call last):
> >File "", line 1, in 
> > TypeError: sum() can't sum strings [use ''.join(seq) instead]
> > 
> > Of course it is not a good way to join strings,
> > but it should work, should it not?  Naturally,
> 
> It's not a bug. sum() doesn't work on strings deliberately. ''.join()
> *is* the right and good way to concatenate strings.

Apparently, "sum" special cases 'str' in order to teach people to use "join".
It would have been as much work and much more friendly, to just use "join"
internally to implement "sum" when this is possible.

Dieter

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


Re: a gap of do....while?

2009-10-17 Thread StarWing
On 10月18日, 下午1时36分, Chris Rebert  wrote:
> On Sat, Oct 17, 2009 at 10:34 PM, Chris Rebert  wrote:
> > On Sat, Oct 17, 2009 at 10:22 PM, StarWing  wrote:
> 
> >> but in python, we only can:
> >> cond = 1
> >> while cond:
> >>    cond = 0
> >>    .
> >>    if : cond = 1
>
> >> has any polite way to handle this?
>
> > It's essentially the same:
>
> > while True:
> >    ...
> >    if not cond: break
>
> Substituting in the appropriate conditional expression for cond of
> course (your use of cond for the flag caught me off guard).
>
> Cheers,
> Chris

Thank you, this is nice than mine :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list to tuple and vice versa

2009-10-17 Thread Ben Finney
StarWing  writes:

> On 10月18日, 下午12时19分, Ben Finney  wrote:
> > Jabba Laci  writes:
> > > Right, it was my bad. After removal the tuple() function works
> > > perfectly.
> >
> > Note that, though it is callable, ‘tuple’ is not a function but a
> > type:
>
> A type is always callable.

Yes (modulo perversions like explicitly making a non-callable type).
This matches what I said above.

> call a type will call its __init__ special method (or and __new__
> special method together).

No http://docs.python.org/reference/datamodel.html#object.__new__>
http://docs.python.org/reference/datamodel.html#object.__init__>.

-- 
 \  “Anyone who believes exponential growth can go on forever in a |
  `\finite world is either a madman or an economist.” —Kenneth |
_o__) Boulding |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a gap of do....while?

2009-10-17 Thread Chris Rebert
On Sat, Oct 17, 2009 at 10:34 PM, Chris Rebert  wrote:
> On Sat, Oct 17, 2009 at 10:22 PM, StarWing  wrote:

>> but in python, we only can:
>> cond = 1
>> while cond:
>>    cond = 0
>>    .
>>    if : cond = 1
>>
>> has any polite way to handle this?
>
> It's essentially the same:
>
> while True:
>    ...
>    if not cond: break

Substituting in the appropriate conditional expression for cond of
course (your use of cond for the flag caught me off guard).

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


Re: a gap of do....while?

2009-10-17 Thread Chris Rebert
On Sat, Oct 17, 2009 at 10:22 PM, StarWing  wrote:
> okay, I think somethings dowhile is useful, but why python didn't
> have it?

For simplicity of syntax and less duplication among the basic
syntactic constructs.

> in lisp, we can (while (progn ))
> and in all other language we have do...while.
> but in python, we only can:
> cond = 1
> while cond:
>    cond = 0
>    .
>    if : cond = 1
>
> has any polite way to handle this?

It's essentially the same:

while True:
...
if not cond: break

This is considered idiomatic; and FWIW, I see do-while as having no
significant advantage over this.

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


Re: a gap of do....while?

2009-10-17 Thread Stephen Hansen
On Sat, Oct 17, 2009 at 10:22 PM, StarWing  wrote:

> okay, I think somethings dowhile is useful, but why python didn't
> have it?
>
> in lisp, we can (while (progn ))
> and in all other language we have do...while.
> but in python, we only can:
> cond = 1
> while cond:
>cond = 0
>.
>if : cond = 1
>
> has any polite way to handle this?
>

Although recently there's been a big thread about some people thinking its
bad, the idiomatic way to do it in Python is:

while True:
...
if :
break

Basically, the answer to "why doesn't Python have a do...while" statement
is-- there's no universally satisfactory way to spell it with Python's
indent-based syntax. Every once in awhile someone proposes a particular way
to do it, but no one has ever really been able to come up with a syntax
everyone likes.

See PEP315 (http://www.python.org/dev/peps/pep-0315/) for the deferred
proposal to add such a construct and links to extensive discussions about
it.

HTH,

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


Re: python along or bash combined with python (for manipulating files)

2009-10-17 Thread Aahz
In article <38890afc-c542-478a-bbe7-9a63dc6c9...@j9g2000vbp.googlegroups.com>,
TerryP   wrote:
>
>Very sophisticated scripts are possible using bash and ksh, there is
>even a form of ksh that has tk capabilities! (tksh). The Python and
>Bourne-derived languages are however fundamentally different
>creatures, and use very different data models. You should **not**
>write Python (or Perl) scripts as if they were shell scripts -- doing
>so is very bad practice. When you want a shell script, write a shell
>script. When you write a Python script, write a Python script. It
>really is that simple.

Oh, well, I guess I follow bad practice a lot.  Shame on me.

(That is, I disagree that it's bad practice to use Python as if it were
a straight scripting language, os.system() and all.  I prefer using
Python because it makes it easy to upgrade scripts as needed.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


a gap of do....while?

2009-10-17 Thread StarWing
okay, I think somethings dowhile is useful, but why python didn't
have it?

in lisp, we can (while (progn ))
and in all other language we have do...while.
but in python, we only can:
cond = 1
while cond:
cond = 0
.
if : cond = 1

has any polite way to handle this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib connection fails with multiple nics

2009-10-17 Thread Sean DiZazzo
On Oct 16, 4:51 pm, Sean DiZazzo  wrote:
> Hi all,
>
> I'm trying to connect to an ftp site from a windows machine with two
> nics going to two different networks, but I keep getting the below
> exception:
>
> Traceback (most recent call last):
>   File "ftp.pyo", line 70, in connect
>   File "ftp.pyo", line 17, in __init__
>   File "ftplib.pyo", line 131, in connect
>   File "socket.pyo", line 498, in create_connection
> gaierror: [Errno 10093] getaddrinfo failed
>
> I think it is because of the two nics, because the code runs fine on
> other machines.  Any ideas on how to fix this?
>
> TIA.
>
> ~Sean

What does socket.getaddrinfo() rely on??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-17 Thread Steven D'Aprano
On Sat, 17 Oct 2009 15:22:59 -0700, Paul Rubin wrote:

> Terry Reedy  writes:
>> >d[key] += value
>> 
>> Yes, the motivation was to reduce 4 lines to 1 line for a common use
>> case, and not because of any sense of 'inappropriateness'.
> 
> Reducing 4 confusing lines to 1 clear one is almost always appropriate.

This is true, but there is nothing confusing about "Asking for 
forgiveness is better than asking for permission".

For the record, the four lines Paul implies are "confusing" are:

try:
d[key] += value
except KeyError:
d[key] = value

Paul, if that confuses you, perhaps you should consider a change of 
career. *wink*

On the other hand:

d = collections.defaultdict(int)
d[key] += value

is confusing, at least to me. I would expect the argument to defaultdict 
to be the value used as a default, not a callable. In other words, I 
would expect the above to try adding the type `int` to the integer 
`value` and fail, and wonder why it wasn't written as:

d = collections.defaultdict(0)
d[key] += value

Having thought about it, I can see why defaultdict is done that way, 
instead of this:

class MyDefaultDict(dict):
def __init__(self, default=None):
self._default = default
def __getitem__(self, key):
if key in self:
return self[key]
else:
return self._default

And here's why this doesn't work too well:

>>> d = MyDefaultDict([])
>>> d['a'] = [1,2]
>>> d['b'] = [3,4,5]
>>> d
{'a': [1, 2], 'b': [3, 4, 5]}
>>> d['c'] += [6,7]
>>> d
{'a': [1, 2], 'c': [6, 7], 'b': [3, 4, 5]}

So far so good. But wait:

>>> d['d'] += [8]
>>> d
{'a': [1, 2], 'c': [6, 7, 8], 'b': [3, 4, 5], 'd': [6, 7, 8]}

Oops. So even though it's initially surprising and even confusing, the 
API for collections.defaultdict functionally more useful.



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


Re: list to tuple and vice versa

2009-10-17 Thread StarWing
On 10月18日, 下午12时19分, Ben Finney  wrote:
> Jabba Laci  writes:
> > Right, it was my bad. After removal the tuple() function works
> > perfectly.
>
> Note that, though it is callable, ‘tuple’ is not a function but a type:
>
>     >>> tuple
>     
>     >>> len
>     
>
> You can use the built-in ‘type’ type to get the type of any object:
>
>     >>> foo = 12
>     >>> type(foo)
>     
>     >>> bar = 1, 2, 3
>     >>> type(bar)
>     
>     >>> type(tuple)
>     
>     >>> type(len)
>     
>     >>> type(type)
>     
>
> --
>  \      “Pinky, are you pondering what I'm pondering?” “Uh, I think so |
>   `\  Brain, but this time, you wear the tutu.” —_Pinky and The Brain_ |
> _o__)                                                                  |
> Ben Finney

A type is always callable. call a type will call its __init__ special
method (or and __new__ special method together).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slicing return iter?

2009-10-17 Thread StarWing
On 10月18日, 上午9时09分, Raymond Hettinger  wrote:
> [StarWing]
>
> > > > sometimes I want to iterate a part of a sequence. but don't want to
> > > > copy it. i.e.
>  . . .
> > I had checked it for serval times. maybe it's my inattention :-(. but
> > what i could find the nearest thing is itertools.islice. but it can't
> > process negative index -- that's supported by slice. so I need
> > something, bind object with slice, and return a iter. I can find
> > anything like it...:-(
>
> If it really is a sequence (with len and getitem), you can write your
> own indexing iterator:
>
>   def myslice(seq, start, stop, step):
>'Allow forward or backwards iteration over a subslice'
>for i in range(start, stop, step):
>yield seq[i]
>
> Raymond

Thank you. but it can't support negative index :-(
Terry Reedy is right. since a range (or xrange or slice etc.) don't
have a length, so it can't support a negative index. so the best way
to do it is that binding a range with a object. and return a iter.

I think, why standard library didn't have anything like that, that
will be very useful. maybe we should have a builtin functoin
itertools.bslice (stands for bind slice)...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: restriction on sum: intentional bug?

2009-10-17 Thread Steven D'Aprano
On Sat, 17 Oct 2009 07:27:44 -0700, Aahz wrote:

>>(For the record, summing lists is O(N**2), and unlike strings, there's
>>no optimization in CPython to avoid the slow behaviour.)
> 
> Are you sure?

Not 100% -- I haven't read the CPython source code.

But I have done timing tests for repeated concatenation of strings, and 
demonstrated to my own satisfaction that CPython can avoid O(N**2) 
behaviour under certain circumstances (but not all). I've repeated those 
same tests using lists instead of strings, and seen O(N**2) behaviour 
under all circumstances.

This was under Python 2.5 or 2.6, not 3.1. The situation may have changed.



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


Re: SimpleXMLRPCServer clobbering sys.stderr? (2.5.2)

2009-10-17 Thread Gabriel Genellina
En Sat, 17 Oct 2009 23:54:23 -0300, Joseph Turian   
escribió:



I was having a mysterious problem with SimpleXMLRPCServer. (I am using
Python 2.5.2)


I'd start updating Python to the latest 2.5 release: 2.5.4


The request handlers were sometimes failing without any error message
to the log output.

What I discovered was perplexing.
I had some 'print' statements in the handers that, assuming the
request would be handled, would print just fine. When I switched to
'print >> sys.stderr', the request handlers would just fail
completely, and not make the sys.stderr output that I desired.


Perhaps you need to flush the file also? sys.stderr.flush()


It seems that SimpleXMLRPCServer is clobbering stderr in some bizarre
and silent-error-causing way.
I can't really find any documentation of explanation of this
phenomenon.

Could someone please illuminate it for me?


XMLRPCServer doesn't reassign or alter sys.stderr, just uses it in the  
log_message method. I'd look in some other place...


--
Gabriel Genellina

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


Re: list to tuple and vice versa

2009-10-17 Thread Ben Finney
Jabba Laci  writes:

> Right, it was my bad. After removal the tuple() function works
> perfectly.

Note that, though it is callable, ‘tuple’ is not a function but a type:

>>> tuple

>>> len


You can use the built-in ‘type’ type to get the type of any object:

>>> foo = 12
>>> type(foo)

>>> bar = 1, 2, 3
>>> type(bar)

>>> type(tuple)

>>> type(len)

>>> type(type)


-- 
 \  “Pinky, are you pondering what I'm pondering?” “Uh, I think so |
  `\  Brain, but this time, you wear the tutu.” —_Pinky and The Brain_ |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list to tuple and vice versa

2009-10-17 Thread Jabba Laci
>> The error message is: "TypeError: 'tuple' object is not callable".
>
> You created a variable named "tuple" somewhere, which is shadowing the
> built-in type. Rename that variable to something else.

Right, it was my bad. After removal the tuple() function works perfectly.

Thanks,

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


Re: list to tuple and vice versa

2009-10-17 Thread Ben Finney
Jabba Laci  writes:

> Hi,
>
> I have some difficulties with list -> tuple conversion:
>
> t = ('a', 'b')
> li = list(t)   # tuple -> list, works
> print li   # ['a', 'b']
>
> tu = tuple(li)   # list -> tuple, error
> print tu   # what I'd expect: ('a', 'b')

Works fine for me:

Python 2.5.4 (r254:67916, Sep 26 2009, 11:00:02) 
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t = ('a', 'b')
>>> li = list(t)
>>> print li
['a', 'b']
>>> 
>>> tu = tuple(li)
>>> print tu
('a', 'b')

> The error message is: "TypeError: 'tuple' object is not callable".

Nothing in your example code is calling a tuple object. This makes me
suspect that what you showed us is not what you actually tried.

You might want to try the above session yourself and paste the resulting
session *literally* (rather than re-typing) as I did above, so we can
see what you're seeing.

-- 
 \   “If you ever fall off the Sears Tower, just go real limp, |
  `\ because maybe you'll look like a dummy and people will try to |
_o__)catch you because, hey, free dummy.” —Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list to tuple and vice versa

2009-10-17 Thread Chris Rebert
On Sat, Oct 17, 2009 at 8:24 PM, Jabba Laci  wrote:
> Hi,
>
> I have some difficulties with list -> tuple conversion:
>
> t = ('a', 'b')
> li = list(t)   # tuple -> list, works
> print li   # ['a', 'b']
>
> tu = tuple(li)   # list -> tuple, error
> print tu   # what I'd expect: ('a', 'b')
>
> The error message is: "TypeError: 'tuple' object is not callable".

You created a variable named "tuple" somewhere, which is shadowing the
built-in type. Rename that variable to something else.

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


list to tuple and vice versa

2009-10-17 Thread Jabba Laci
Hi,

I have some difficulties with list -> tuple conversion:

t = ('a', 'b')
li = list(t)   # tuple -> list, works
print li   # ['a', 'b']

tu = tuple(li)   # list -> tuple, error
print tu   # what I'd expect: ('a', 'b')

The error message is: "TypeError: 'tuple' object is not callable".

Thanks,

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Alan G Isaac

On 10/16/2009 8:16 PM, Terry Reedy wrote:

The fact that two or three people who agree on something agree on the
thing that they agree on confirms nothing.
 
On 10/17/2009 7:03 PM, Terry Reedy wrote:

If you disagree with this, I think *you* are being silly.



Well, ...


Alan G Isaac wrote:

Of course the numbers do not matter.
The *reasons* matter.


But you cut that...

It is a good idea not to quote too selectively if you
want to look like you are actually engaging the argument.
Anything else looks very self-serving.



On 10/17/2009 7:03 PM, Terry Reedy wrote:

Nothing I have said bears on whether I would have voted for or against
the current behavior.


While that certainly provides you with convenient shelter,
it does not move the discussion forward.

Cheers,
Alan Isaac

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


Re: Installation question 2.5.4

2009-10-17 Thread ryles
On Sat, Oct 17, 2009 at 9:55 PM, JimR  wrote:
> Thanks.  As it turned out, I needed /usr/local/python instead of /usr/local
> as the prefix. After setting that, all worked as it should.
-- 
http://mail.python.org/mailman/listinfo/python-list


SimpleXMLRPCServer clobbering sys.stderr? (2.5.2)

2009-10-17 Thread Joseph Turian
I was having a mysterious problem with SimpleXMLRPCServer. (I am using
Python 2.5.2)
The request handlers were sometimes failing without any error message
to the log output.

What I discovered was perplexing.
I had some 'print' statements in the handers that, assuming the
request would be handled, would print just fine. When I switched to
'print >> sys.stderr', the request handlers would just fail
completely, and not make the sys.stderr output that I desired.

It seems that SimpleXMLRPCServer is clobbering stderr in some bizarre
and silent-error-causing way.
I can't really find any documentation of explanation of this
phenomenon.

Could someone please illuminate it for me?

Best,
   Joseph
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple files

2009-10-17 Thread Benjamin Kaplan
On Sat, Oct 17, 2009 at 9:58 PM, Someone Something  wrote:
> I was trying to write a program with just one class and it was working fine.
> Then, I seperated that class into two different files and made the objects
> and called the methods in a third (client.py IO.py main.py). Now, when I use
> the command:
>
> python client.py IO.py main.py
>
> Nothing prints. I think its only interpreting client.py (the objects are
> declared in main.py)
>
> How can I fix this?

Python is a scripting language that compiles files as needed. You
don't need to declare every module you're using Run only the script
you need.

python main.py

When the script is run, the current directory is automatically added
to the python path, the list of directories python looks through for
modules (stored in sys.path). When python sees "import client", it
looks through that path for client.py and then compiles it if it's not
already been compiled.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Multiple files

2009-10-17 Thread Someone Something
I was trying to write a program with just one class and it was working fine.
Then, I seperated that class into two different files and made the objects
and called the methods in a third (client.py IO.py main.py). Now, when I use
the command:

python client.py IO.py main.py

Nothing prints. I think its only interpreting client.py (the objects are
declared in main.py)

How can I fix this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

Diez B. Roggisch schrieb:

Arian Kuschki schrieb:
Whoa, that was quick! Thanks for all the answers, I'll try to 
recapitulate



What does this show you in your interactive interpreter?


print "\xc3\xb6"

ö

For me, it's o-umlaut, ö. This is because the above bytes are the
sequence for ö in utf-8.

If this shows something else, you need to adjust your terminal settings.


for me it also prints the correct o-umlaut (ö), so that was not the 
problem.



All of the below result in xml that shows all umlauts correctly when 
printed:


xml.decode("cp1252")
xml.decode("cp1252").encode("utf-8")
xml.decode("iso-8859-1")
xml.decode("iso-8859-1").encode("utf-8")

But when I want to parse the xml then, it only works if I
do both decode and encode. If I only decode, I get the following error:
SAXParseException: :1:1: not well-formed (invalid token)

Do I understand right that since the encoding was not specified in the 
xml response, it should have been utf-8 by default? And that if it had 
indeed been utf-8 I would not have had the encoding problem in the 
first place?


Yes. XML without explicit encoding is implicitly UTF-8, and the page is 
borked using cp* or latin* without saying so.


Ok, after reading some other posts in this thread this assumption seems 
not to hold. HTTP-protocol allows for other encodings to be implicitly 
given. Which I think is an atrocity.


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


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

Arian Kuschki schrieb:

Whoa, that was quick! Thanks for all the answers, I'll try to recapitulate


What does this show you in your interactive interpreter?


print "\xc3\xb6"

ö

For me, it's o-umlaut, ö. This is because the above bytes are the
sequence for ö in utf-8.

If this shows something else, you need to adjust your terminal settings.


for me it also prints the correct o-umlaut (ö), so that was not the problem.


All of the below result in xml that shows all umlauts correctly when printed:

xml.decode("cp1252")
xml.decode("cp1252").encode("utf-8")
xml.decode("iso-8859-1")
xml.decode("iso-8859-1").encode("utf-8")

But when I want to parse the xml then, it only works if I
do both decode and encode. If I only decode, I get the following error:
SAXParseException: :1:1: not well-formed (invalid token)

Do I understand right that since the encoding was not specified in the xml 
response, it should have been utf-8 by default? And that if it had indeed been utf-8 I 
would not have had the encoding problem in the first place?


Yes. XML without explicit encoding is implicitly UTF-8, and the page is 
borked using cp* or latin* without saying so.



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


Re: Threading from a class

2009-10-17 Thread MRAB

Someone Something wrote:

anyone?

On Sat, Oct 17, 2009 at 4:26 PM, Someone Something > wrote:


I'm trying to write a IRC client that has to have a method inside
class Client that has to start a new thread that goes to run() which
is in the same class. I'm not really understanding all the threading
tutorials i've found. Can someone help?

p.s. trying to use the threading module, not the thread module.


# Written for Python v2.6

import threading
import time

class Client(object):
def test_thread(self):
print "starting thread"
self.thread = threading.Thread(target=self.run)
self.thread.start()
print "sleeping for 6 seconds"
time.sleep(6)
print "woken up"
self.thread.join()
def run(self):
for i in range(5):
print i
time.sleep(1)

c = Client()
c.test_thread()
--
http://mail.python.org/mailman/listinfo/python-list


Re: print()

2009-10-17 Thread Mark Tolonen


"Terry Reedy"  wrote in message 
news:hbdh51$g0...@ger.gmane.org...

Gabriel Genellina wrote:


Presumably he's using Python 3:


And apparently not IDLE

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
p3> import sys
p3> sys.stdout.write("hello")
hello5

See http://bugs.python.org/issue6345


IDLE

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] 
on win32


>>> import sys
>>> sys.stdout.write('abc')
abc

reported, for better or worse, in http://bugs.python.org/issue7163

Since interactive users do not usually use sys.stdout.write (versus 
print), the mixed output is not usually a problem.


tjr


Apparently, Pythonwin has the same "problem":

PythonWin 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for 
further copyright information.

import sys
sys.stdout.write('hello')

hello

print(sys.stdout.write('hello'))

helloNone

-Mark 



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


Re: slicing return iter?

2009-10-17 Thread Raymond Hettinger
[StarWing]
> > > sometimes I want to iterate a part of a sequence. but don't want to
> > > copy it. i.e.
 . . .
> I had checked it for serval times. maybe it's my inattention :-(. but
> what i could find the nearest thing is itertools.islice. but it can't
> process negative index -- that's supported by slice. so I need
> something, bind object with slice, and return a iter. I can find
> anything like it...:-(

If it really is a sequence (with len and getitem), you can write your
own indexing iterator:

  def myslice(seq, start, stop, step):
   'Allow forward or backwards iteration over a subslice'
   for i in range(start, stop, step):
   yield seq[i]

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


Re: Threading from a class

2009-10-17 Thread Someone Something
anyone?

On Sat, Oct 17, 2009 at 4:26 PM, Someone Something wrote:

> I'm trying to write a IRC client that has to have a method inside class
> Client that has to start a new thread that goes to run() which is in the
> same class. I'm not really understanding all the threading tutorials i've
> found. Can someone help?
>
> p.s. trying to use the threading module, not the thread module.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


help to convert c++ fonction in python

2009-10-17 Thread geremy condra
On Sat, Oct 17, 2009 at 7:57 PM, David Robinow  wrote:
> On Sat, Oct 17, 2009 at 7:48 PM, geremy condra  wrote:
>> For the love of baby kittens, please, please, please tell me that
>> you do not believe this securely encrypts your data.
>  Yeah, I think it's pretty good.
> Can you do better?
>

Trivially. Use AES, 3DES, any standard cryptosystem- there are
literally dozens of excellent, well-studied implementations in
both C++ and Python, and hardware implementations on many
processors.

The cipher listed will fall in a single round of chosen plaintext
attacks or chosen ciphertext attacks, and with a keylength of
40 bytes against a message length of 768 will give me roughly
19 windows on a single encryption. Frequency analysis is
therefore going to be extremely profitable, not to mention
trivially easy.

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


Re: help to convert c++ fonction in python

2009-10-17 Thread geremy condra
On Sat, Oct 17, 2009 at 6:15 PM, Tim Roberts  wrote:
> Toff  wrote:
>>
>>I'm trying to convert  2 c++ functions  in python
>>
>>they come from wpkg client
>>https://wpkg.svn.sourceforge.net/svnroot/wpkg/wpkg-client/Sources/Components/XmlSettings.cpp
>>
>>they are
>>CString CXmlSettings::Crypt(CString str)
>>CString CXmlSettings::Decrypt(CString str)
>>
>>CAn someone help me?
>>i d'ont know much about c++
>
> I should have tested before I posted.  These work.  There is one
> significant difference between my code and the C++ original: my code will
> not explode if the string to be encrypted is longer than 768 characters.
> Theirs will.
>
>
> key = (
>    0x50, 0xF7, 0x82, 0x69, 0xEA, 0x2D, 0xDD, 0x2D, 0x6A, 0xB4,
>    0x33, 0x8F, 0xD5, 0xC7, 0x90, 0x9C, 0x22, 0x95, 0x61, 0xE5,
>    0x65, 0xF6, 0xB0, 0x4B, 0x94, 0x47, 0xB0, 0xBD, 0x73, 0x58,
>    0x56, 0x87, 0x79, 0x7B, 0xE6, 0xB0, 0xD2, 0x20, 0x28, 0xE1
> )
>
> import base64
> import itertools
>
> def Crypt( s ):
>    return base64.b64encode(
>        ''.join(
>            chr(ord(x)^y) for x,y in itertools.izip(s,itertools.cycle(key))
>        )
>    )
>
> def Decrypt( s ):
>    s1 = base64.b64decode( s )
>    return ''.join(
>        chr(ord(x)^y) for x,y in itertools.izip(s,itertools.cycle(key))
>    )
>
> s = 'Hello, there'
> print s
> t = Crypt(s)
> print t
> u = Decrypt(t)
> print s
> --
> Tim Roberts, t...@probo.com
> Providenza & Boekelheide, Inc.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

For the love of baby kittens, please, please, please tell me that
you do not believe this securely encrypts your data.

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread MRAB

Carl Banks wrote:

On Oct 17, 2:22 pm, Alan G Isaac  wrote:

On 10/17/2009 7:06 AM, Carl Banks wrote:


I'm basically saying here is, by shutting out strings from sum,
you don't really lose much in terms of duck typing, because duck
typing wouldn't have been that helpful anyway.

That boils down to an argument for type checking
whenever you cannot imagine my use case.  I hope
you do not write your own code that way...


No, it doesn't.  It's an argument that the type check, IN THIS CASE,
doesn't cost you much since duck typing isn't that useful here, IN
THIS CASE, to begin with.  Nothing more.

Extrapolating this argument to be a general defense of type checking
is something you did.



Here is a use case you might have ruled out with
that approach.  A PyX `path` defines `__add__`
so that paths can be combined as subpaths of a
single path. This is  **VERY USEFUL**.
Now if I have a list of paths, it is useful to
to combine them: sum(pathlst,path()).


That's a fair counterargument.  It definitely seems a lot more likely
that some code could be written that works for a list of strings or a
list of path components, meaning that it'd be desirable to have a
single operation which works on both, for which sum() seems like it'd
be a convenient candidate.  Consider my argument weakened somewhat.


Here's a suggestion: add a new special method '__sum__' for summing
sequences.

If 'sum' isn't given an initial value then the first value in the
sequence is used as the initial value. The (remainder of) the sequence
is passed to initial_value.__sum__ to perform the summation. If __sum__
isn't defined then the __add__ method is used repeatedly as at present.

The 'str' and 'unicode' classes (although I'd expected it would be the
'bytes' and 'str' classes in Python 3) would define __sum__ as an
efficient summation. Other classes like 'list' could do likewise.

No more special cases!
--
http://mail.python.org/mailman/listinfo/python-list


Re: restriction on sum: intentional bug?

2009-10-17 Thread Terry Reedy

Alan G Isaac wrote:

On 10/16/2009 8:16 PM, Terry Reedy wrote:

The fact that two or three people who agree on something agree on the
thing that they agree on confirms nothing.


If you disagree with this, I think *you* are being silly.

>> One could just as well argue

that summing anything but numbers is semantically incoherent, not
correct.  Certainly, my dictionary points in that direction.


Ditto.


Come on now, that is just a silly argument.


And I think this is a silly response ;-).


And dictionaries are obviously irrelevant;


Not when talking about the semantics of English words.


The only serious reason that has been offered
for the current behavior is that people who do
not know better will sum strings instead of
joining them, which is more efficient.  That is
a pretty weak argument for breaking expectations
and so refusing to do duck typing that an error
is raise. Especially in a language like Python.
(As Tim and Peter make clear.)


The absence of other responses is not the same as the absence of other 
possible responses. Some people have better things to do than rehash all 
the details of a past discussion.


Nothing I have said bears on whether I would have voted for or against 
the current behavior. I have only addressed your to-me silly claim to 
have 'confirmed' the correctness of one position.


Terry Jan Reedy

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


Re: executing a function/method from a variable

2009-10-17 Thread Terry Reedy

Yves wrote:
What is the best way to execute a function which name is stored in a 
variable ?


One standard way is a dict mapping names to function objects.

>>> numfuncs = {'int':int, 'float':float}
>>> f='int'
>>> numfuncs[f]('33')
33

Since attributes gets mapped to a dict, this is similar to previous answer.

tjr

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


Re: print()

2009-10-17 Thread Terry Reedy

Gabriel Genellina wrote:


Presumably he's using Python 3:


And apparently not IDLE

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
p3> import sys
p3> sys.stdout.write("hello")
hello5

See http://bugs.python.org/issue6345


IDLE

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32


>>> import sys
>>> sys.stdout.write('abc')
abc

reported, for better or worse, in http://bugs.python.org/issue7163

Since interactive users do not usually use sys.stdout.write (versus 
print), the mixed output is not usually a problem.


tjr

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Aahz
In article ,
Mark Dickinson   wrote:
>On Oct 17, 9:49=A0pm, a...@pythoncraft.com (Aahz) wrote:
>>
>> Ahhh, I vaguely remember there being some discussion of this when sum()
>> was introduced -- I think that using InPlaceAdd would have caused bad
>> behavior when the initial list was referred to by multiple names.
>
>Thanks for the pointer: I've now found the thread.  It looks like
>Alex Martelli made this exact change 6 years ago, and then had to
>revert it because it changed behaviour:
>
>http://mail.python.org/pipermail/python-dev/2003-October/039511.html
>
>I've just checked in an extra test to test_builtin.py to make sure
>this bright idea isn't repeated. :)

Thanks!  I hope you added a comment to the code, too.  ;-)

And wow, sometimes my memory amazes me...
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "dictionary with attribute-style access"?

2009-10-17 Thread Aahz
In article ,
Terry Reedy   wrote:
>Aahz wrote:
>> In article ,
>> Andreas Balogh   wrote:
>>>
>>> My question to the Python specialists: which one is the most correct?
>>> Are there restrictions with regards to pickling or copy()?
>>> Which one should I choose?
>> 
>> What's your goal?  I'd probably do the dirt simple myself:
>> 
>> class AttrDict(dict):
>> def __getattr__(self, attr):
>> if attr in self:
>> return self[attr]
>> else:
>> raise AttributeError
>
>Why the double lookup? Harking to another thread on using exceptions,
>
>try:
> return self[attr]
>except KeyError:
> raise AttributeError(attr)

For this purpose, it's almost entirely a stylistic difference; I happen
to prefer using the test, but the other way is fine, too.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: id( ) function question

2009-10-17 Thread Aahz
In article ,
Laszlo Nagy   wrote:
>
>All right, I see your point now. So can we say, that the id function can 
>be used to tell if two mutable objects are different as long as they are 
>both alive during the comparison?

Yes
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "dictionary with attribute-style access"?

2009-10-17 Thread Terry Reedy

Aahz wrote:

In article ,
Andreas Balogh   wrote:

My question to the Python specialists: which one is the most correct?
Are there restrictions with regards to pickling or copy()?
Which one should I choose?


What's your goal?  I'd probably do the dirt simple myself:

class AttrDict(dict):
def __getattr__(self, attr):
if attr in self:
return self[attr]
else:
raise AttributeError


Why the double lookup? Harking to another thread on using exceptions,

try:
return self[attr]
except KeyError:
raise AttributeError(attr)


def __setattr__(self, attr, value):
self[attr] = value

d = AttrDict()
d.foo = 'bar'
print d.foo


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


Re: The rap against "while True:" loops

2009-10-17 Thread Paul Rubin
Terry Reedy  writes:
> >d[key] += value
> 
> Yes, the motivation was to reduce 4 lines to 1 line for a common use
> case, and not because of any sense of 'inappropriateness'.

Reducing 4 confusing lines to 1 clear one is almost always appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-17 Thread Terry Reedy

Steven D'Aprano wrote:

On Fri, 16 Oct 2009 18:30:50 +0100, Tim Rowe wrote:


Also, using exceptions this way is a structured form of GOTO -- it's
easy to abuse and turn it into spaghetti code. Actually, not that easy
to abuse, because you can't jump back into the try block. It's more
like a multi-level break outside of a loop than a general GOTO.

I don't think it's *only* the performance thing, it's also clarity. The
understood meaning of throwing an exception is to say "something
happened that shouldn't have". If one uses it when something has
happened that *should* have, because it happens to have the right
behaviour (even if the overhead doesn't matter), then one is
misrepresenting the program logic.


No, you have a fundamental misunderstanding. They're called exceptions, 
not errors, because they represent exceptional cases. Often errors are 
exceptional cases, but they're not the only sort of exceptional case.


Python uses exceptions for flow control: e.g. for-loops swallow 
StopIteration or IndexError to indicate the end of the loop. In the 
context of a for-loop, StopIteration or IndexError doesn't represent an 
error. It doesn't represent an unexpected case. It represents an 
expected, but exceptional (special) case: we expect that most sequences 
are finite, and it is normal to eventually reach the end of the sequence, 
after which the loop must change behaviour.


Similarly, it's hardly an *error* for [1, 2, 3].index(5) to fail -- who 
is to say that the list is supposed to have 5 in it? ValueError (a 
slightly misleading name in this situation) is used to indicate an 
exceptional, but not unexpected, occurrence.


Likewise, KeyboardInterrupt is used to allow the user to halt processing; 
SystemExit is used to shut down the Python virtual machine; and warnings 
are implemented using exceptions. There may be others among the built-ins 
and standard library, but even if there aren't, there is plenty of 
precedence for us to do the same.


Nicely put. Programmers are exceptional people, but not erroneous, in 
spite of nerd stereotypes ;-).


tjr


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


Re: help to convert c++ fonction in python

2009-10-17 Thread Tim Roberts
Toff  wrote:
>
>I'm trying to convert  2 c++ functions  in python
>
>they come from wpkg client
>https://wpkg.svn.sourceforge.net/svnroot/wpkg/wpkg-client/Sources/Components/XmlSettings.cpp
>
>they are
>CString CXmlSettings::Crypt(CString str)
>CString CXmlSettings::Decrypt(CString str)
>
>CAn someone help me?
>i d'ont know much about c++

I should have tested before I posted.  These work.  There is one
significant difference between my code and the C++ original: my code will
not explode if the string to be encrypted is longer than 768 characters.
Theirs will.


key = (
0x50, 0xF7, 0x82, 0x69, 0xEA, 0x2D, 0xDD, 0x2D, 0x6A, 0xB4,
0x33, 0x8F, 0xD5, 0xC7, 0x90, 0x9C, 0x22, 0x95, 0x61, 0xE5,
0x65, 0xF6, 0xB0, 0x4B, 0x94, 0x47, 0xB0, 0xBD, 0x73, 0x58,
0x56, 0x87, 0x79, 0x7B, 0xE6, 0xB0, 0xD2, 0x20, 0x28, 0xE1
)

import base64
import itertools

def Crypt( s ):
return base64.b64encode( 
''.join(
chr(ord(x)^y) for x,y in itertools.izip(s,itertools.cycle(key))
)
)

def Decrypt( s ):
s1 = base64.b64decode( s )
return ''.join(
chr(ord(x)^y) for x,y in itertools.izip(s,itertools.cycle(key))
)

s = 'Hello, there'
print s
t = Crypt(s)
print t
u = Decrypt(t)
print s
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-17 Thread Terry Reedy

Paul Rubin wrote:

a...@pythoncraft.com (Aahz) writes:

Standard Python idiom:

try:
d[key] += value
except KeyError:
d[key] = value

Maybe you need to re-think "appropriate".


But more recent style prefers:

   d = collections.defaultdict(int)
   ...
   d[key] += value


Yes, the motivation was to reduce 4 lines to 1 line for a common use 
case, and not because of any sense of 'inappropriateness'.


tjr

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


Re: help to convert c++ fonction in python

2009-10-17 Thread Tim Roberts
Toff  wrote:
>
>I'm trying to convert  2 c++ functions  in python
>
>they come from wpkg client
>https://wpkg.svn.sourceforge.net/svnroot/wpkg/wpkg-client/Sources/Components/XmlSettings.cpp
>
>they are
>CString CXmlSettings::Crypt(CString str)
>CString CXmlSettings::Decrypt(CString str)
>
>CAn someone help me?
>i d'ont know much about c++

It's possible this solution is a bit too clever.


import base64
import itertools

key = (
0x50, 0xF7, 0x82, 0x69, 0xEA, 0x2D, 0xDD, 0x2D, 0x6A, 0xB4,
0x33, 0x8F, 0xD5, 0xC7, 0x90, 0x9C, 0x22, 0x95, 0x61, 0xE5,
0x65, 0xF6, 0xB0, 0x4B, 0x94, 0x47, 0xB0, 0xBD, 0x73, 0x58,
0x56, 0x87, 0x79, 0x7B, 0xE6, 0xB0, 0xD2, 0x20, 0x28, 0xE1
)

def Crypt( s ):
return base64.encode(
''.join(
chr(ord(x)^y) for x,y in itertools.izip(s,itertools.cycle(key))
)
)

def Decrypt( s )
s1 = base64.decode( s )
return ''.join(
chr(ord(x)^y) for x,y in itertools.izip(s1,itertools.cycle(key))
)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: restriction on sum: intentional bug?

2009-10-17 Thread Mark Dickinson
On Oct 17, 9:49 pm, a...@pythoncraft.com (Aahz) wrote:
> Ahhh, I vaguely remember there being some discussion of this when sum()
> was introduced -- I think that using InPlaceAdd would have caused bad
> behavior when the initial list was referred to by multiple names.

Thanks for the pointer: I've now found the thread.  It looks like
Alex Martelli made this exact change 6 years ago, and then had to
revert it because it changed behaviour:

http://mail.python.org/pipermail/python-dev/2003-October/039511.html

I've just checked in an extra test to test_builtin.py to make sure
this bright idea isn't repeated. :)

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


Re: slicing return iter?

2009-10-17 Thread Terry Reedy
StarWing wrote:

> I had checked it for serval times. maybe it's my inattention :-(. but
> what i could find the nearest thing is itertools.islice. but it can't
> process negative index 

A negative index -n is an abbreviation for len(sequence) - n.
Since iterables in general do not have a length, islice(iterable) cannot
handle the abbreviation. If you pass a sequence to islice, just
un-abbreviate negative indexes.

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Carl Banks
On Oct 17, 2:22 pm, Alan G Isaac  wrote:
> On 10/17/2009 7:06 AM, Carl Banks wrote:
>
> > I'm basically saying here is, by shutting out strings from sum,
> > you don't really lose much in terms of duck typing, because duck
> > typing wouldn't have been that helpful anyway.
>
> That boils down to an argument for type checking
> whenever you cannot imagine my use case.  I hope
> you do not write your own code that way...

No, it doesn't.  It's an argument that the type check, IN THIS CASE,
doesn't cost you much since duck typing isn't that useful here, IN
THIS CASE, to begin with.  Nothing more.

Extrapolating this argument to be a general defense of type checking
is something you did.


> Here is a use case you might have ruled out with
> that approach.  A PyX `path` defines `__add__`
> so that paths can be combined as subpaths of a
> single path. This is  **VERY USEFUL**.
> Now if I have a list of paths, it is useful to
> to combine them: sum(pathlst,path()).

That's a fair counterargument.  It definitely seems a lot more likely
that some code could be written that works for a list of strings or a
list of path components, meaning that it'd be desirable to have a
single operation which works on both, for which sum() seems like it'd
be a convenient candidate.  Consider my argument weakened somewhat.


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


Re: umlauts

2009-10-17 Thread Neil Hodgson
   The server is sniffing the User-Agent header to decide whether to
send UTF-8 or ISO-8859-1. Try this code:

import urllib2
r = urllib2.Request("http://www.google.de/ig/api?weather=Muenchen";,
None, {"User-Agent":"Mozilla/5.0"})
f = urllib2.urlopen(r)
i = f.info()
print(i)
xml = f.read()
f.close()
print(xml)

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Alan G Isaac

On 10/17/2009 7:06 AM, Carl Banks wrote:

I'm basically saying here is, by shutting out strings from sum,
you don't really lose much in terms of duck typing, because duck
typing wouldn't have been that helpful anyway.


That boils down to an argument for type checking
whenever you cannot imagine my use case.  I hope
you do not write your own code that way...

Here is a use case you might have ruled out with
that approach.  A PyX `path` defines `__add__`
so that paths can be combined as subpaths of a
single path. This is  **VERY USEFUL**.
Now if I have a list of paths, it is useful to
to combine them: sum(pathlst,path()).

Alan Isaac

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


Re: The rap against "while True:" loops

2009-10-17 Thread Paul Rubin
a...@pythoncraft.com (Aahz) writes:
> >   d = collections.defaultdict(int)
> >   ...
> >   d[key] += value
> 
> That was a trivial example; non-trivial examples not addressed by
> defaultdict are left as an exercise for the reader.

Even in the "nontrivial" examples, I think avoiding the exception is
stylistically preferable:

d[key] = value + d.get(key, 0)

It might be worth handling the exception in an inner loop where you
want to avoid the cost of looking up key in the dictionary twice, but
even that requires profiling to be sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: restriction on sum: intentional bug?

2009-10-17 Thread Mark Dickinson
On Oct 17, 9:49 pm, a...@pythoncraft.com (Aahz) wrote:
> Ahhh, I vaguely remember there being some discussion of this when sum()
> was introduced -- I think that using InPlaceAdd would have caused bad
> behavior when the initial list was referred to by multiple names.

Ah yes.  Good point.  With my one-line modification, I get:

Python 2.7a0 (trunk:75468M, Oct 17 2009, 21:57:02)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> acc = []
>>> sum(([i] for i in range(10)), acc)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> acc
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

There should probably be a test for this somewhere, to make
sure that no-one else is tempted to make this change.

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


Re: print()

2009-10-17 Thread Dave Angel

Lie Ryan wrote:

mattia wrote:
Another question (always py3). How can I print only the first number 
after the comma of a division?

e.g. print(8/3) --> 2.667
I just want 2.6 (or 2.66)


Are you sure you don't want that to be 2.7 or 2.67? Then you can use:
n = int(n * 10**2) / 10**2
else if 2.7 pr 2.67 is what you wanted, you could use:
n = round(n, 2)


Bad idea to use round() to make numbers format properly.  No guarantees 
that the print logic will then print the number rounded the way you 
want.  It could just as easily do 2.69  when you finally go 
to print it.


Best to use format(), the way it was intended.  Round to decimal while 
converting to decimal.  Otherwise surprises await in dark corners.


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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Aahz
In article <7e905311-c561-4b93-9414-f873e6fee...@j19g2000yqk.googlegroups.com>,
Mark Dickinson   wrote:
>
>For some reason that I don't really understand, the CPython source does
>the equivalent of concat2 instead of concat3.  See the builtin_sum
>function in
>
>http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=3Dmarkup
>
>and scroll past the special cases for ints and floats.  After a
>one- line source change, replacing the PyNumber_Add call with
>PyNumber_InPlaceAdd,

Ahhh, I vaguely remember there being some discussion of this when sum()
was introduced -- I think that using InPlaceAdd would have caused bad
behavior when the initial list was referred to by multiple names.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Arian Kuschki
Hm yes, that is true. In Firefox on the other hand, the response header is
"Content-Type text/xml; charset=UTF-8"

On Sat 17, 13:16 -0700, Mark Tolonen wrote:

> 
> "Diez B. Roggisch"  wrote in message
> news:7jub5rf37div...@mid.uni-berlin.de...
> [snip]
> >This is wierd. I looked at the site in FireFox - and it was
> >displayed correctly, including umlauts. Bringing up the
> >info-dialog claims the page is UTF-8, the XML itself says so as
> >well (implicit, through the missing declaration of an encoding) -
> >but it clearly is *not* utf-8.
> >
> >One would expect google to be better at this...
> >
> >Diez
> 
> According to the XML 1.0 specification:
> 
> "Although an XML processor is required to read only entities in the
> UTF-8 and UTF-16 encodings, it is recognized that other encodings
> are used around the world, and it may be desired for XML processors
> to read entities that use them. In the absence of external character
> encoding information (such as MIME headers), parsed entities which
> are stored in an encoding other than UTF-8 or UTF-16 must begin with
> a text declaration..."
> 
> So UTF-8 and UTF-16 are the defaults supported without an xml
> declaration in the absence of external encoding information.  But we
> have external character encoding information:
> 
> >>>f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
> >>>f.headers.dict['content-type']
> 'text/xml; charset=ISO-8859-1'
> 
> So the page seems correct.
> 
> -Mark
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: restriction on sum: intentional bug?

2009-10-17 Thread Mark Dickinson
On Oct 17, 3:27 pm, a...@pythoncraft.com (Aahz) wrote:
> In article <0062f568$0$26941$c3e8...@news.astraweb.com>,
> Steven D'Aprano   wrote:
> > (For the record, summing lists is O(N**2), and unlike strings, there's no
> > optimization in CPython to avoid the slow behaviour.)
>
> Are you sure?

The O(N**2) claim surprised me too, but it certainly looks that
way.  Here's a script to produce some timings:

def concat1(list_of_lists):
return sum(list_of_lists, [])

def concat2(list_of_lists):
acc = []
for l in list_of_lists:
acc = acc + l
return acc

def concat3(list_of_lists):
acc = []
for l in list_of_lists:
acc += l
return acc

def concat4(list_of_lists):
acc = []
for l in list_of_lists:
acc.extend(l)
return acc

test_list = [[i] for i in xrange(10)]

from timeit import Timer

for fn in ["concat1", "concat2", "concat3", "concat4"]:
t = Timer(fn + "(test_list)", "from __main__ import test_list, " +
fn)
print fn, t.timeit(number=3)/3.0


On my machine (OS X 10.5/Core 2 Duo), under Python 2.7 svn I get:

newton:trunk dickinsm$ ./python.exe ~/time_list_sum.py
concat1 48.1459733645
concat2 48.4200883706
concat3 0.0146766503652
concat4 0.0184679826101


For some reason that I don't really understand, the CPython source
does
the equivalent of concat2 instead of concat3.  See the builtin_sum
function in

http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup

and scroll past the special cases for ints and floats.  After a one-
line
source change, replacing the PyNumber_Add call with
PyNumber_InPlaceAdd,
I get the following results:

newton:trunk dickinsm$ ./python.exe ~/time_list_sum.py
concat1 0.0106019973755
concat2 48.0212899844
concat3 0.0138022899628
concat4 0.0179653167725

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


Re: The rap against "while True:" loops

2009-10-17 Thread Aahz
In article <7xmy3peq3s@ruckus.brouhaha.com>,
Paul Rubin   wrote:
>a...@pythoncraft.com (Aahz) writes:
>>
>> Standard Python idiom:
>> 
>> try:
>> d[key] += value
>> except KeyError:
>> d[key] = value
>> 
>> Maybe you need to re-think "appropriate".
>
>But more recent style prefers:
>
>   d = collections.defaultdict(int)
>   ...
>   d[key] += value

That was a trivial example; non-trivial examples not addressed by
defaultdict are left as an exercise for the reader.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Neo
Hi,

Victor Subervi schrieb:
> Let me clarify. This prints out "all sorts of crap", which means an
> image string, the image as a string, to the screen:
>  
> print 'Content-type: image/jpeg'
> print 'Content-Encoding: base64'
> print
> print pic().encode('base64')
> print ''
>  
> The following once upon a time printed images, but now it doesn't. Why
> would that be? I would refresh the screen, and it would print. I'd
> change a line and it wouldn't. I'd change it back to what it was and it
> would no longer the image to the screen. Why is that? The same happens
> with or without the base64 stuff. Commenting out a line seemed to make a
> difference!
>  
> print 'Content-type: text/plain'
> #print 'Content-type: image/jpeg'
> print
> print pic()
> print ''
> 
> The above prints out a broken image of correct dimensions.

Only with a broken client (I assume Internetexplorer here?)
Any you don't know what it does in guessing and caching (Try
shift-reload when you test things)

You should work from a static page and a static image and look what
is transferred by the server (wireshark or tcpflow are of great help,
but nc | hexdump -C | more is probably more easy if you work out the
HTTP protocol (see rfc2616)

You script needs to do the same as a server would do serving a static
resource. Just look how it works and rebuild it.

You will quickly find out, that there is obviously no reason to have
  at the end of a binary resource an Image is.
Also correct mime type is important unless you deal with broken clients.

There are a lot more HTTP-Headers you want to understand and use but the
simple usage above, provided pic() indeed returns the binary data of the
image unaltered, should work (w/o the html crap at the end).
You would not use print since it adds a linefeed at the end which is not
part of the data. sys.stdout.write() should work better (and can be used
incremental to avoid returning the whole image data from memory)

> Of course I try and figure out how things work once they get working.
> Sometimes, however, there is __no__ logic to it __at__all__. Sorry.
> After years of struggling with python I've come to realize that even
> though I may not be a good programmer, it isn't me. It may not be python
> itself. It may be the crappy hardware the server farms use. It may be
> the way they tweak their python interpreter. But it isn't just me.

Sorry to tell you that but its just you. There is no magic in that.
Ok, there is one thing: what makes you sure the data in the database
is really unaltered image data? I mean, you are using mysql...
for a first thing I'd write the output into a file and try to open it
in a graphic viewer.

> It would be nice if I could get this code printing images to the screen
> as it was before I had to put out another unnecessary fire when code

Images are not "printed to screen" the whole idea is just wrong.

> that previously uploaded the images in the first place inexplicably no
> longer worked. Then, lo and behold, when I came back to this code that I
> hadn't touched and was working fine earlier this week, it no longer
> works. Lovely. My "plug-and-play" program has devoured two weeks of my
> time and I'm still up the creek without a paddle. Sure would appreciate
> any help you can give.

I see "plug and play" and read cargo-cult. You need to read a bit about
the basics on the matter or you will constantly run uphill - and even if
it seems to work it has no value if you don't know _why_.

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


Threading from a class

2009-10-17 Thread Someone Something
I'm trying to write a IRC client that has to have a method inside class
Client that has to start a new thread that goes to run() which is in the
same class. I'm not really understanding all the threading tutorials i've
found. Can someone help?

p.s. trying to use the threading module, not the thread module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Mark Tolonen


"Diez B. Roggisch"  wrote in message 
news:7jub5rf37div...@mid.uni-berlin.de...

[snip]
This is wierd. I looked at the site in FireFox - and it was displayed 
correctly, including umlauts. Bringing up the info-dialog claims the page 
is UTF-8, the XML itself says so as well (implicit, through the missing 
declaration of an encoding) - but it clearly is *not* utf-8.


One would expect google to be better at this...

Diez


According to the XML 1.0 specification:

"Although an XML processor is required to read only entities in the UTF-8 
and UTF-16 encodings, it is recognized that other encodings are used around 
the world, and it may be desired for XML processors to read entities that 
use them. In the absence of external character encoding information (such as 
MIME headers), parsed entities which are stored in an encoding other than 
UTF-8 or UTF-16 must begin with a text declaration..."


So UTF-8 and UTF-16 are the defaults supported without an xml declaration in 
the absence of external encoding information.  But we have external 
character encoding information:



f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
f.headers.dict['content-type']

'text/xml; charset=ISO-8859-1'

So the page seems correct.

-Mark


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


Re: The rap against "while True:" loops

2009-10-17 Thread Paul Rubin
a...@pythoncraft.com (Aahz) writes:
> Standard Python idiom:
> 
> try:
> d[key] += value
> except KeyError:
> d[key] = value
> 
> Maybe you need to re-think "appropriate".

But more recent style prefers:

   d = collections.defaultdict(int)
   ...
   d[key] += value
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread I V
On Sat, 17 Oct 2009 21:24:59 +0330, Arian Kuschki wrote:
> I just checked and I see the following in the headers: Content-Type
> text/xml; charset=UTF-8
> 
> Where does it say ISO-8859-1?

In the headers returned via urllib (and via wget). But checking in 
Firefox, it does indeed specify UTF-8 in the content type. Using wget, 
but specifying the same User-Agent header that Firefox uses, I get the 
same UTF-8 Content-Type that I see in Firefox. How bizarre.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Arian Kuschki
I just checked and I see the following in the headers:
Content-Type text/xml; charset=UTF-8

Where does it say ISO-8859-1?

On Sat 17, 20:57 +0200, I V wrote:

> On Sat, 17 Oct 2009 18:54:10 +0200, Diez B. Roggisch wrote:
> 
> > This is wierd. I looked at the site in FireFox - and it was displayed
> > correctly, including umlauts. Bringing up the info-dialog claims the
> > page is UTF-8, the XML itself says so as well (implicit, through the
> > missing declaration of an encoding) - but it clearly is *not* utf-8.
> 
> The headers correctly identify it as ISO-8859-1, which overrides the 
> implicit specification of UTF-8. I'm not sure why Firefox is reporting it 
> as UTF-8 (it does that for me, too); I can see the umlauts, so it's 
> clearly processing it as ISO-8859-1.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: umlauts

2009-10-17 Thread Arian Kuschki
Whoa, that was quick! Thanks for all the answers, I'll try to recapitulate

>What does this show you in your interactive interpreter?
>
 print "\xc3\xb6"
>ö
>
>For me, it's o-umlaut, ö. This is because the above bytes are the
>sequence for ö in utf-8.
>
>If this shows something else, you need to adjust your terminal settings.

for me it also prints the correct o-umlaut (ö), so that was not the problem.


All of the below result in xml that shows all umlauts correctly when printed:

xml.decode("cp1252")
xml.decode("cp1252").encode("utf-8")
xml.decode("iso-8859-1")
xml.decode("iso-8859-1").encode("utf-8")

But when I want to parse the xml then, it only works if I
do both decode and encode. If I only decode, I get the following error:
SAXParseException: :1:1: not well-formed (invalid token)

Do I understand right that since the encoding was not specified in the xml 
response, it should have been utf-8 by default? And that if it had indeed been 
utf-8 I 
would not have had the encoding problem in the first place?

Anyway, thanks everybody, this has helped me a lot.

Arian


On Sat 17, 20:17 +0200, Diez B. Roggisch wrote:

> StarWing schrieb:
> >On 10月18日, 上午12时50分, "Diez B. Roggisch"  wrote:
> >>StarWing schrieb:
> >>
> >>
> >>
> >>>On 10月17日, 下午9时54分, Arian Kuschki 
> >>>wrote:
> Hi all
> this has been bugging me for a long time and I do not seem to be able to
> understand what to do. I always have problems when dealing input text that
> contains umlauts. Consider the following:
> In [1]: import urllib
> In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
> In [3]: xml = f.read()
> In [4]: f.close()
> In [5]: print xml
> --> print(xml)
>  tab_id="0" mobile_row="0" mobile_zipped="1" row="0" 
> section="0"> y data="Munich, BY"/> data=""/> data="2009-10-17"/> data="SI"/> data="Meistens
> bew kt"/> umidity data="Feuchtigkeit: 87 %"/> data="/ig/images/weather/mostly_cloudy.gif"/> ent_conditions> data="1"/> data="/ig/images/weather/chance_of_rain.gif"/> data="So."/> data="/ig/images/weather/chance_of_sno
> w.gif"/> data="Mo."/> data="Di."/> /> data="Klar"/>
> As you can see the umlauts in the XML are not displayed properly. When I 
> want
> to process this text (for example with xml.sax), I get error messages 
> because
> the parses can't read this.
> I've tried to read up on this and there is a lot of information on the 
> web, but
> nothing seems to work for me. For example setting the coding to UTF like 
> this:
> # -*- coding: utf-8 -*- or using the decode() string method.
> I always have this kind of problem when input contains umlauts, not just 
> in
> this case. My locale (on Ubuntu) is en_GB.UTF-8.
> Cheers
> Arian
> >>>try this?
> >>># vim: set fencoding=utf-8:
> >>>import urllib
> >>>import xml.sax as sax, xml.sax.handler as handler
> >>>f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
> >>>xml = f.read()
> >>>xml = xml.decode("cp1252")
> >>>f.close()
> >>>class my_handler(handler.ContentHandler):
> >>>def startElement(self, name, attrs):
> >>>print "begin:", name, attrs
> >>>def endElement(self, name):
> >>>print "end:", name
> >>>sax.parseString(xml, my_handler())
> >>This is wrong. XML is a *byte*-based format, which explicitly states
> >>encodings. So decoding a byte-string to a unicode-object and then
> >>passing it to a parser is not working in the very moment you have data that
> >>
> >>  - is outside your default-system-encoding (ususally ascii)
> >>  - the system-encoding and the declared decoding differ
> >>
> >>Besides, I don't see where the whole SAX-stuff is supposed to do
> >>anything the direct print  and the decode() don't do - smells like
> >>cargo-cult to me.
> >>
> >>Diez
> >
> >yes, XML is a *byte*-based format, and so as utf-8 and code-page
> >(cp936, cp1252, etc.). so usually XML will sign its coding at head.
> >but this didn't work now.
> >
> >in Python2.6, sys.getdefaultcoding() return 'ascii', and I can't use
> >sys.setdefaultcoding(), and f.read() return a str. so it must be a
> >undecoded, byte-base format (i.e. raw XML data). so use the right code-
> >page to decode it is safe.(notice the webpage is google.de).
> >
> >in Python3.1, read() returns a bytes object. so we *must* decode it,
> >nor we can't pass it into a parser.
> 
> You didn't get my point. A XML-parser only *takes* a byte-string.
> Decoding is it's business. So your above last sentence is wrong.
> 
> Because regardless of the python-version, if you feed the parser a
> unicode-object, python will first encode that to a byte-string,
> possibly giving a UnicodeError (maybe this automated conversion has
> gone in Py3K, but then you get a type-error instead).
> 
> So to make the above work (if one wants to parse the xml), the
> proper thing to do would be
> 
>   xm

Re: umlauts

2009-10-17 Thread I V
On Sat, 17 Oct 2009 18:54:10 +0200, Diez B. Roggisch wrote:

> This is wierd. I looked at the site in FireFox - and it was displayed
> correctly, including umlauts. Bringing up the info-dialog claims the
> page is UTF-8, the XML itself says so as well (implicit, through the
> missing declaration of an encoding) - but it clearly is *not* utf-8.

The headers correctly identify it as ISO-8859-1, which overrides the 
implicit specification of UTF-8. I'm not sure why Firefox is reporting it 
as UTF-8 (it does that for me, too); I can see the umlauts, so it's 
clearly processing it as ISO-8859-1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

StarWing schrieb:

On 10月18日, 上午12时50分, "Diez B. Roggisch"  wrote:

StarWing schrieb:




On 10月17日, 下午9时54分, Arian Kuschki 
wrote:

Hi all
this has been bugging me for a long time and I do not seem to be able to
understand what to do. I always have problems when dealing input text that
contains umlauts. Consider the following:
In [1]: import urllib
In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
In [3]: xml = f.read()
In [4]: f.close()
In [5]: print xml
--> print(xml)

As you can see the umlauts in the XML are not displayed properly. When I want
to process this text (for example with xml.sax), I get error messages because
the parses can't read this.
I've tried to read up on this and there is a lot of information on the web, but
nothing seems to work for me. For example setting the coding to UTF like this:
# -*- coding: utf-8 -*- or using the decode() string method.
I always have this kind of problem when input contains umlauts, not just in
this case. My locale (on Ubuntu) is en_GB.UTF-8.
Cheers
Arian

try this?
# vim: set fencoding=utf-8:
import urllib
import xml.sax as sax, xml.sax.handler as handler
f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
xml = f.read()
xml = xml.decode("cp1252")
f.close()
class my_handler(handler.ContentHandler):
def startElement(self, name, attrs):
print "begin:", name, attrs
def endElement(self, name):
print "end:", name
sax.parseString(xml, my_handler())

This is wrong. XML is a *byte*-based format, which explicitly states
encodings. So decoding a byte-string to a unicode-object and then
passing it to a parser is not working in the very moment you have data that

  - is outside your default-system-encoding (ususally ascii)
  - the system-encoding and the declared decoding differ

Besides, I don't see where the whole SAX-stuff is supposed to do
anything the direct print  and the decode() don't do - smells like
cargo-cult to me.

Diez


yes, XML is a *byte*-based format, and so as utf-8 and code-page
(cp936, cp1252, etc.). so usually XML will sign its coding at head.
but this didn't work now.

in Python2.6, sys.getdefaultcoding() return 'ascii', and I can't use
sys.setdefaultcoding(), and f.read() return a str. so it must be a
undecoded, byte-base format (i.e. raw XML data). so use the right code-
page to decode it is safe.(notice the webpage is google.de).

in Python3.1, read() returns a bytes object. so we *must* decode it,
nor we can't pass it into a parser.


You didn't get my point. A XML-parser only *takes* a byte-string. 
Decoding is it's business. So your above last sentence is wrong.


Because regardless of the python-version, if you feed the parser a 
unicode-object, python will first encode that to a byte-string, possibly 
giving a UnicodeError (maybe this automated conversion has gone in Py3K, 
but then you get a type-error instead).


So to make the above work (if one wants to parse the xml), the proper 
thing to do would be


  xml = xml.decode("cp1252").encode("utf-8")

and then feed that. Of course the really good thing would be to fix the 
webpage, but that's beyond our capabilities I fear...


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


Re: slicing return iter?

2009-10-17 Thread Arnaud Delobelle
On Oct 17, 6:05 pm, StarWing  wrote:
> On 10月17日, 下午11时56分, Arnaud Delobelle  wrote:
> > thanks for attention :-)
>
> > Check the itertools module.
>
> > HTH
>
> > --
> > Arnaud
>
> I had checked it for serval times. maybe it's my inattention :-(. but
> what i could find the nearest thing is itertools.islice. but it can't
> process negative index -- that's supported by slice. so I need
> something, bind object with slice, and return a iter. I can find
> anything like it...:-(

Sorry, I read your post too quickly.  I don't think there's anything
in the standard library.  Your solution is fine!

--
Arnaud

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


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Lie Ryan

Carsten Haese wrote:

Victor Subervi wrote:

[snip...]

print 'Content-type: image/jpeg'
print 'Content-Encoding: base64'
print
print pic().encode('base64')
print ''

[snip...]


Why are you printing "" at the end of a page that is
supposed to be a base64-encoded JPEG file?


I'm testing my "psychic" mode today.


Your old script produces the line drawing image in 
http://allpointsmarinevi.com/stxresort/cart/getpic1.py; a JPEG image to 
be exact.


Now, you want to embed this image into a webpage.

You thought: "well I could simply put the code I used previously to the 
code that produced the HTML"


Let's say, you used something like this to produce the image:

###
# in file getpic.py
# for simplicity, the image is pre-generated
def foo():
img = open('myimg.jpg')
print 'some header information'
print img.read()
###



While your HTML-producing code is something like this:


# note that I avoided putting an exact working code
# so you don't start copy and pasting without
# digesting and understanding what you're doing

import getpic
print 'html header'
getpic.foo()
print 'html header end'


You thought... this should work, I just called a code that previously works.

Well, if my psychic prediction capability doesn't have bugs in it, and 
the weather is fine today, and the moon is full, and the 42nd road is 
not jammed today; then, as Carsten Haese remarked before, you have no 
idea why getpic.py works but calling a function it doesn't.


First off; HTML doesn't have a way to "embed" image information[1]. What 
it can do, and what you should do is to "link" the image (unless you 
want to invite neverending troubles including poor browser support and a 
standard that practically nobody uses).


First and foremost though, please understand how HTML works; 
particularly  tag.

This is how you "link" image inside a webpage:


Since you don't actually use a static image but a script-generated 
image; as long as the server is configured to handle python script, you 
can use this as well:



[1] actually, there is a standard for image embedding; but browser 
support is flaky, at best. Especially for IE. Hint: src="data:image/png;base64,BASE64ENCODEDIMAGESTRING" />



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


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Carsten Haese
Victor Subervi wrote:
> in line...
> 
> On Sat, Oct 17, 2009 at 11:33 AM, Carsten Haese  > wrote:
> Why would turning a comment into a statement NOT make a difference?!?
> 
>  
> You misunderstood. Leaving in the __commented__ line __commented__ and
> __not__uncommented__ made a difference. Why?

Alright, so let me rephrase the question: Why would turning a statement
into a comment not make a difference?

Answer: The only way commenting out a line of code makes no difference
is if the line of code was superfluous to begin with. The fact that
commenting it out *does* make a difference therefore means that the line
of code is not superfluous.

> What the heck is a "broken image of correct dimensions"? 
> 
>  
> http://allpointsmarinevi.com/stxresort/cart/getpic1.py

That doesn't look like a broken image to me. When I try that URL, I get
a 750x900 pixel JPEG image that appears to be a line-drawing of sorts.
Of course I have no idea whether that's the expected result because for
some reason you decided to keep that a secret.

> You can prove whether it's your server farm or you by running the same
> code on a different server.
> 
>  
> Which one?

Which one what? Which code? Try all versions you have, until you find
one that works. When you do, run that on your server farm to see if it
still works.

> Again, you have to help us help you. I have listed the three things you
> need to post together, and you haven't done that. You're giving us bits
> and pieces, but nothing that's sufficiently cohesive to do any
> meaningful troubleshooting on.
> 
>  
> Forgive me. I must have misunderstood. I have deleted the old message.
> Would you be so kind as to re-post those three things you need me to
> provide you?

Here's what I said earlier:
"""
The only way we have a fighting chance to help you in figuring out
what's going in is if you post the *exact* code you're running (and by
that I mean the actual code that you know your server is executing, and
not just some code that somewhat resembles the code that the server
might be executing), a detailed description of the result you're
expecting, and a detailed description of the result you're getting instead.
"""

So, the three things I'm asking for:
* Show us EXACTLY the code you're running.
* Tell us the result you're expecting.
* Tell us the result you're getting instead.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: slicing return iter?

2009-10-17 Thread StarWing
On 10月17日, 下午11时56分, Arnaud Delobelle  wrote:
> On Oct 17, 3:40 pm, StarWing  wrote:
>
>
>
> > hello everyone, I'm new here :-)
>
> > sometimes I want to iterate a part of a sequence. but don't want to
> > copy it. i.e.
>
> > a = list(...)
> > # now a is a list, and a[:] is another list, and so a[m:n]
> > # now we do something with the 0~len(a)-3 elements of a
> > for val in a[:-2]:
> > #do something
>
> > but, this will cause a copy on a, has some convenience way to get a
> > iter to iterate on a part of list?
>
> > i made this:
> > class iterslice:
> > def __init__(self, list):
> > self.list = list
>
> > def __len__(self):
> > return len(self.list)
>
> > def __getitem__(self, slice):
> > import itertools
> > listlen = len(self.list)
> > range = (((slice.start + listlen) % listlen) if slice.start
> > else 0,
> > ((slice.stop + listlen) % listlen) if slice.stop else
> > listlen,
> > slice.step)
> > return itertools.islice(self.list, *range)
>
> > a = [1,2,3,4]
> > for i in iterslice(a)[:-1:2]:
> > print i
>
> > my question is:
> >   - are there any *Standard* way to do this? (a buit-in function? a
> > module?)
> >   - are there any better implements?
>
> > thanks for attention :-)
>
> Check the itertools module.
>
> HTH
>
> --
> Arnaud

I had checked it for serval times. maybe it's my inattention :-(. but
what i could find the nearest thing is itertools.islice. but it can't
process negative index -- that's supported by slice. so I need
something, bind object with slice, and return a iter. I can find
anything like it...:-(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread StarWing
On 10月18日, 上午12时50分, "Diez B. Roggisch"  wrote:
> StarWing schrieb:
>
>
>
> > On 10月17日, 下午9时54分, Arian Kuschki 
> > wrote:
> >> Hi all
>
> >> this has been bugging me for a long time and I do not seem to be able to
> >> understand what to do. I always have problems when dealing input text that
> >> contains umlauts. Consider the following:
>
> >> In [1]: import urllib
>
> >> In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
>
> >> In [3]: xml = f.read()
>
> >> In [4]: f.close()
>
> >> In [5]: print xml
> >> --> print(xml)
> >>  >> tab_id="0" mobile_row="0" mobile_zipped="1" row="0" 
> >> section="0">
> >> y data="Munich, BY"/> >> data=""/> >> data="2009-10-17"/> >> data="SI"/> >> data="Meistens
> >> bew kt"/> >> umidity data="Feuchtigkeit: 87 %"/> >> data="/ig/images/weather/mostly_cloudy.gif"/> >> ent_conditions> >> data="1"/> >> data="/ig/images/weather/chance_of_rain.gif"/> >> data="So."/> >> data="/ig/images/weather/chance_of_sno
> >> w.gif"/> >> data="Mo."/> >> data="Di."/> >> /> >> data="Klar"/>
>
> >> As you can see the umlauts in the XML are not displayed properly. When I 
> >> want
> >> to process this text (for example with xml.sax), I get error messages 
> >> because
> >> the parses can't read this.
>
> >> I've tried to read up on this and there is a lot of information on the 
> >> web, but
> >> nothing seems to work for me. For example setting the coding to UTF like 
> >> this:
> >> # -*- coding: utf-8 -*- or using the decode() string method.
>
> >> I always have this kind of problem when input contains umlauts, not just in
> >> this case. My locale (on Ubuntu) is en_GB.UTF-8.
>
> >> Cheers
> >> Arian
>
> > try this?
>
> > # vim: set fencoding=utf-8:
> > import urllib
> > import xml.sax as sax, xml.sax.handler as handler
>
> > f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
> > xml = f.read()
> > xml = xml.decode("cp1252")
> > f.close()
>
> > class my_handler(handler.ContentHandler):
> >     def startElement(self, name, attrs):
> >         print "begin:", name, attrs
>
> >     def endElement(self, name):
> >         print "end:", name
>
> > sax.parseString(xml, my_handler())
>
> This is wrong. XML is a *byte*-based format, which explicitly states
> encodings. So decoding a byte-string to a unicode-object and then
> passing it to a parser is not working in the very moment you have data that
>
>   - is outside your default-system-encoding (ususally ascii)
>   - the system-encoding and the declared decoding differ
>
> Besides, I don't see where the whole SAX-stuff is supposed to do
> anything the direct print  and the decode() don't do - smells like
> cargo-cult to me.
>
> Diez

yes, XML is a *byte*-based format, and so as utf-8 and code-page
(cp936, cp1252, etc.). so usually XML will sign its coding at head.
but this didn't work now.

in Python2.6, sys.getdefaultcoding() return 'ascii', and I can't use
sys.setdefaultcoding(), and f.read() return a str. so it must be a
undecoded, byte-base format (i.e. raw XML data). so use the right code-
page to decode it is safe.(notice the webpage is google.de).

in Python3.1, read() returns a bytes object. so we *must* decode it,
nor we can't pass it into a parser.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread StarWing
On 10月18日, 上午12时14分, MRAB  wrote:
> Arian Kuschki wrote:
> > Hi all
>
> > this has been bugging me for a long time and I do not seem to be able to
> > understand what to do. I always have problems when dealing input text that
> > contains umlauts. Consider the following:
>
> > In [1]: import urllib
>
> > In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
>
> > In [3]: xml = f.read()
>
> > In [4]: f.close()
>
> > In [5]: print xml
> > --> print(xml)
> >  > tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"
> >>  > y data="Munich, BY"/> > data=""/> > data="2009-10-17"/> > data="SI"/> > data="Meistens
> > bew kt"/> > umidity data="Feuchtigkeit: 87 %"/> > data="/ig/images/weather/mostly_cloudy.gif"/> > ent_conditions> > data="1"/> > data="/ig/images/weather/chance_of_rain.gif"/> > data="So."/> > data="/ig/images/weather/chance_of_sno
> > w.gif"/> > data="Mo."/> > data="Di."/> > /> > data="Klar"/>
>
> > As you can see the umlauts in the XML are not displayed properly. When I 
> > want
> > to process this text (for example with xml.sax), I get error messages 
> > because
> > the parses can't read this.
>
> > I've tried to read up on this and there is a lot of information on the web, 
> > but
> > nothing seems to work for me. For example setting the coding to UTF like 
> > this:
> > # -*- coding: utf-8 -*- or using the decode() string method.
>
> > I always have this kind of problem when input contains umlauts, not just in
> > this case. My locale (on Ubuntu) is en_GB.UTF-8.
>
> The string you received from the website is a bytestring and you're just
> printing it to your console, which is configured for UTF-8. However, the
> bytestring isn't valid UTF-8, so the console is replacing the invalid
> parts with the funny characters.
>
> You should decode the bytestring to Unicode and then re-encode it to
> UTF-8. I don't know what encoding the website is actually using; here
> I'm assuming ISO-8859-1:
>
> print xml.decode("iso-8859-1").encode("utf-8")

in 2.6, str.decode return unicode, so you can directly print it.
in 3.1, str.encode return bytes, so you can also directly print it.

so, just decode("cp1252"), it's enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

MRAB schrieb:

Arian Kuschki wrote:

Hi all

this has been bugging me for a long time and I do not seem to be able 
to understand what to do. I always have problems when dealing input 
text that contains umlauts. Consider the following:


In [1]: import urllib

In [2]: f = 
urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)


In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)
tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"

y data="Munich, BY"/>data=""/>data="2009-10-17"/>data="SI"/>data="Meistens bew�kt"/>umidity data="Feuchtigkeit: 87�%"/>data="/ig/images/weather/mostly_cloudy.gif"/>data="Wind: W mit Windgeschwindigkeiten von 13 km/h"/>ent_conditions>data="1"/>data="/ig/images/weather/chance_of_rain.gif"/>data="So."/>data="/ig/images/weather/chance_of_sno
w.gif"/>data="Mo."/>data="Di."/>/>data="Klar"/>


As you can see the umlauts in the XML are not displayed properly. When 
I want to process this text (for example with xml.sax), I get error 
messages because the parses can't read this.


I've tried to read up on this and there is a lot of information on the 
web, but nothing seems to work for me. For example setting the coding 
to UTF like this: # -*- coding: utf-8 -*- or using the decode() string 
method.


I always have this kind of problem when input contains umlauts, not 
just in this case. My locale (on Ubuntu) is en_GB.UTF-8.



The string you received from the website is a bytestring and you're just
printing it to your console, which is configured for UTF-8. However, the
bytestring isn't valid UTF-8, so the console is replacing the invalid
parts with the funny characters.


This is wierd. I looked at the site in FireFox - and it was displayed 
correctly, including umlauts. Bringing up the info-dialog claims the 
page is UTF-8, the XML itself says so as well (implicit, through the 
missing declaration of an encoding) - but it clearly is *not* utf-8.


One would expect google to be better at this...

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


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

MRAB schrieb:

Arian Kuschki wrote:

Hi all

this has been bugging me for a long time and I do not seem to be able 
to understand what to do. I always have problems when dealing input 
text that contains umlauts. Consider the following:


In [1]: import urllib

In [2]: f = 
urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)


In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)
tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"

y data="Munich, BY"/>data=""/>data="2009-10-17"/>data="SI"/>data="Meistens bew�kt"/>umidity data="Feuchtigkeit: 87�%"/>data="/ig/images/weather/mostly_cloudy.gif"/>data="Wind: W mit Windgeschwindigkeiten von 13 km/h"/>ent_conditions>data="1"/>data="/ig/images/weather/chance_of_rain.gif"/>data="So."/>data="/ig/images/weather/chance_of_sno
w.gif"/>data="Mo."/>data="Di."/>/>data="Klar"/>


As you can see the umlauts in the XML are not displayed properly. When 
I want to process this text (for example with xml.sax), I get error 
messages because the parses can't read this.


I've tried to read up on this and there is a lot of information on the 
web, but nothing seems to work for me. For example setting the coding 
to UTF like this: # -*- coding: utf-8 -*- or using the decode() string 
method.


I always have this kind of problem when input contains umlauts, not 
just in this case. My locale (on Ubuntu) is en_GB.UTF-8.



The string you received from the website is a bytestring and you're just
printing it to your console, which is configured for UTF-8. However, the
bytestring isn't valid UTF-8, so the console is replacing the invalid
parts with the funny characters.


This is wierd. I looked at the site in FireFox - and it was displayed 
correctly, including umlauts. Bringing up the info-dialog claims the 
page is UTF-8, the XML itself says so as well (implicit, through the 
missing declaration of an encoding) - but it clearly is *not* utf-8.


One would expect google to be better at this...

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


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

StarWing schrieb:

On 10月17日, 下午9时54分, Arian Kuschki 
wrote:

Hi all

this has been bugging me for a long time and I do not seem to be able to
understand what to do. I always have problems when dealing input text that
contains umlauts. Consider the following:

In [1]: import urllib

In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)

In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)


As you can see the umlauts in the XML are not displayed properly. When I want
to process this text (for example with xml.sax), I get error messages because
the parses can't read this.

I've tried to read up on this and there is a lot of information on the web, but
nothing seems to work for me. For example setting the coding to UTF like this:
# -*- coding: utf-8 -*- or using the decode() string method.

I always have this kind of problem when input contains umlauts, not just in
this case. My locale (on Ubuntu) is en_GB.UTF-8.

Cheers
Arian


try this?

# vim: set fencoding=utf-8:
import urllib
import xml.sax as sax, xml.sax.handler as handler

f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
xml = f.read()
xml = xml.decode("cp1252")
f.close()

class my_handler(handler.ContentHandler):
def startElement(self, name, attrs):
print "begin:", name, attrs

def endElement(self, name):
print "end:", name

sax.parseString(xml, my_handler())


This is wrong. XML is a *byte*-based format, which explicitly states 
encodings. So decoding a byte-string to a unicode-object and then 
passing it to a parser is not working in the very moment you have data that


 - is outside your default-system-encoding (ususally ascii)
 - the system-encoding and the declared decoding differ

Besides, I don't see where the whole SAX-stuff is supposed to do 
anything the direct print  and the decode() don't do - smells like 
cargo-cult to me.


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


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

StarWing schrieb:

On 10月17日, 下午9时54分, Arian Kuschki 
wrote:

Hi all

this has been bugging me for a long time and I do not seem to be able to
understand what to do. I always have problems when dealing input text that
contains umlauts. Consider the following:

In [1]: import urllib

In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)

In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)


As you can see the umlauts in the XML are not displayed properly. When I want
to process this text (for example with xml.sax), I get error messages because
the parses can't read this.

I've tried to read up on this and there is a lot of information on the web, but
nothing seems to work for me. For example setting the coding to UTF like this:
# -*- coding: utf-8 -*- or using the decode() string method.

I always have this kind of problem when input contains umlauts, not just in
this case. My locale (on Ubuntu) is en_GB.UTF-8.

Cheers
Arian


try this?

# vim: set fencoding=utf-8:
import urllib
import xml.sax as sax, xml.sax.handler as handler

f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
xml = f.read()
xml = xml.decode("cp1252")
f.close()

class my_handler(handler.ContentHandler):
def startElement(self, name, attrs):
print "begin:", name, attrs

def endElement(self, name):
print "end:", name

sax.parseString(xml, my_handler())


This is wrong. XML is a *byte*-based format, which explicitly states 
encodings. So decoding a byte-string to a unicode-object and then 
passing it to a parser is not working in the very moment you have data that


 - is outside your default-system-encoding (ususally ascii)
 - the system-encoding and the declared decoding differ

Besides, I don't see where the whole SAX-stuff is supposed to do 
anything the direct print  and the decode() don't do - smells like 
cargo-cult to me.


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


Re: how to write a unicode string to a file ?

2009-10-17 Thread Mark Tolonen


"Mark Tolonen"  wrote in message 
news:hbbo6d$6u...@ger.gmane.org...


"Kee Nethery"  wrote in message 
news:aaab63c6-6e44-4c07-b119-972d4f49e...@kagi.com...


On Oct 16, 2009, at 5:49 PM, Stephen Hansen wrote:

On Fri, Oct 16, 2009 at 5:07 PM, Stef Mientki   
wrote:


snip

The thing is, I'd be VERY surprised (neigh, shocked!) if Excel can't 
open a file that is in UTF8-- it just might need to be TOLD that its 
utf8 when you go and open the file, as UTF8 looks just like ASCII --  
until it contains characters that can't be expressed in ASCII. But I 
don't know what type of file it is you're saving.


We found that UTF-16 was required for Excel. It would not "do the  right 
thing" when presented with UTF-8.


Excel seems to expect a UTF-8-encoded BOM (byte order mark) to correctly 
decide a file is written in UTF-8.  This worked for me:


f=codecs.open('test.csv','wb','utf-8')
f.write(u'\ufeff') # write a BOM
f.write(u'马克,testing,123\r\n')
f.close()

When opened in Excel without the BOM (\ufeff), I got gibberish, but with 
the BOM the Chinese characters were displayed correctly.


Also, it turns out the python 'utf-16' encoder adds a BOM for you, which is 
probably why UTF-16 worked for you and UTF-8 didn't:



u'\u0102'.encode('utf-16-be') # explicit big-endian, no BOM

'\x01\x02'

u'\u0102'.encode('utf-16-le') # explicit little-endian, no BOM

'\x02\x01'

u'\u0102'.encode('utf-16') # machine native-endian, with BOM

'\xff\xfe\x02\x01'

u'\u0102'.encode('utf-8') # no BOM

'\xc4\x82'

u'\ufeff\u0102'.encode('utf-8') # explicit BOM

'\xef\xbb\xbf\xc4\x82'

-Mark



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


help to convert c++ fonction in python

2009-10-17 Thread Toff
hello

I'm trying to convert  2 c++ functions  in python


they come from wpkg client
https://wpkg.svn.sourceforge.net/svnroot/wpkg/wpkg-client/Sources/Components/XmlSettings.cpp

they are
CString CXmlSettings::Crypt(CString str)
CString CXmlSettings::Decrypt(CString str)



CAn someone help me?
i d'ont know much about c++

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


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Victor Subervi
in line...

On Sat, Oct 17, 2009 at 11:33 AM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Let me clarify. This prints out "all sorts of crap", which means an
> > image string, the image as a string, to the screen:
> >
> > print 'Content-type: image/jpeg'
> > print 'Content-Encoding: base64'
> > print
> > print pic().encode('base64')
> > print ''
>
> This has no hope of working, since you're sending data that's not valid
> base64 code and pretend that it's base64-encoded. A browser trying to
> display this result will produce something anywhere between
> unpredictable and garbage.
>

This was recommended to me previously on this list, so I tried it.

>
> > The following once upon a time printed images, but now it doesn't. Why
> > would that be? I would refresh the screen, and it would print. I'd
> > change a line and it wouldn't. I'd change it back to what it was and it
> > would no longer the image to the screen. Why is that? The same happens
> > with or without the base64 stuff. Commenting out a line seemed to make a
> > difference!
>
> Why would turning a comment into a statement NOT make a difference?!?
>

You misunderstood. Leaving in the __commented__ line __commented__ and
__not__uncommented__ made a difference. Why?

>
> >
> > print 'Content-type: text/plain'
> > #print 'Content-type: image/jpeg'
> > print
> > print pic()
> > print ''
>
> This should produce plain text, not an image.
>
> > The above prints out a broken image of correct dimensions.
>
> What the heck is a "broken image of correct dimensions"?


http://allpointsmarinevi.com/stxresort/cart/getpic1.py


> Are you looking
> at the output of the script itself, or are you looking at an html page
> that uses this script as src-attribute for an img-tag? In the latter
> case, if you're also giving the img-tag width and height attributes, it
> shouldn't be surprising that you're getting the correct dimensions, and
> you're getting a broken image because your src is producing plain text
> instead of an image.
>

Before, when it produced plain text it printed the same to screen. Now it
does not.

>
> > Of course I try and figure out how things work once they get working.
> > Sometimes, however, there is __no__ logic to it __at__all__. Sorry.
> > After years of struggling with python I've come to realize that even
> > though I may not be a good programmer, it isn't me. It may not be python
> > itself. It may be the crappy hardware the server farms use. It may be
> > the way they tweak their python interpreter. But it isn't just me.
>
> I suppose it's possible that there is something quirky about the way the
> server has been set up, but so far, the more likely explanation is that
> you don't really know what you're doing.
>

Well, if I did, I wouldn't be asking for your help. I was hoping you could
help me.

>
> You can prove whether it's your server farm or you by running the same
> code on a different server.
>

Which one?

>
> > It would be nice if I could get this code printing images to the screen
> > as it was before I had to put out another unnecessary fire when code
> > that previously uploaded the images in the first place inexplicably no
> > longer worked. Then, lo and behold, when I came back to this code that I
> > hadn't touched and was working fine earlier this week, it no longer
> > works. Lovely. My "plug-and-play" program has devoured two weeks of my
> > time and I'm still up the creek without a paddle. Sure would appreciate
> > any help you can give.
>
> Again, you have to help us help you. I have listed the three things you
> need to post together, and you haven't done that. You're giving us bits
> and pieces, but nothing that's sufficiently cohesive to do any
> meaningful troubleshooting on.
>

Forgive me. I must have misunderstood. I have deleted the old message. Would
you be so kind as to re-post those three things you need me to provide you?
TIA,
V

>
> --
> Carsten Haese
> http://informixdb.sourceforge.net
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe and croatian letters

2009-10-17 Thread Mark Tolonen


"Samir aluko...@work"  wrote in message 
news:ab6475d0-133c-478d-8f08-eafea0733...@j39g2000yqh.googlegroups.com...

I am making a simple program in Croatian. In the beginning I set "# -
*- coding: cp1250 -*-" code and when i run it in Python shell it comes
out fine, but when i compile it with py2exe he doesn't print out
croatian letters but he prints out tottaly other letters. I checked
the CMD and it supports croatian letters. If you want an source code
and setup file send me an e-mail at a.dexter...@gmail.com


Not knowing what were considered Croatian characters, I found 
http://www.geocities.com/click2speak/unicode/chars_hr.html for my testing.


Run 'chcp' from CMD and see what code page you are in.  I was able to output 
correctly by changing the codepage from 437 (my U.S. default), to 1250.  I 
also had to change my console window font from 'Raster Fonts' to 'Lucida 
Console', since the former supported the cp437 character set only.


-Mark




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


Re: umlauts

2009-10-17 Thread StarWing
On 10月17日, 下午9时54分, Arian Kuschki 
wrote:
> Hi all
>
> this has been bugging me for a long time and I do not seem to be able to
> understand what to do. I always have problems when dealing input text that
> contains umlauts. Consider the following:
>
> In [1]: import urllib
>
> In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
>
> In [3]: xml = f.read()
>
> In [4]: f.close()
>
> In [5]: print xml
> --> print(xml)
>  tab_id="0" mobile_row="0" mobile_zipped="1" row="0" 
> section="0">
> y data="Munich, BY"/> data=""/> data="2009-10-17"/> data="SI"/> data="Meistens
> bew kt"/> umidity data="Feuchtigkeit: 87 %"/> data="/ig/images/weather/mostly_cloudy.gif"/> ent_conditions> data="1"/> data="/ig/images/weather/chance_of_rain.gif"/> data="So."/> data="/ig/images/weather/chance_of_sno
> w.gif"/> data="Mo."/> data="Di."/> /> data="Klar"/>
>
> As you can see the umlauts in the XML are not displayed properly. When I want
> to process this text (for example with xml.sax), I get error messages because
> the parses can't read this.
>
> I've tried to read up on this and there is a lot of information on the web, 
> but
> nothing seems to work for me. For example setting the coding to UTF like this:
> # -*- coding: utf-8 -*- or using the decode() string method.
>
> I always have this kind of problem when input contains umlauts, not just in
> this case. My locale (on Ubuntu) is en_GB.UTF-8.
>
> Cheers
> Arian

try this?

# vim: set fencoding=utf-8:
import urllib
import xml.sax as sax, xml.sax.handler as handler

f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)
xml = f.read()
xml = xml.decode("cp1252")
f.close()

class my_handler(handler.ContentHandler):
def startElement(self, name, attrs):
print "begin:", name, attrs

def endElement(self, name):
print "end:", name

sax.parseString(xml, my_handler())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: umlauts

2009-10-17 Thread MRAB

Arian Kuschki wrote:

Hi all

this has been bugging me for a long time and I do not seem to be able to 
understand what to do. I always have problems when dealing input text that 
contains umlauts. Consider the following:


In [1]: import urllib

In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)

In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)
tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" 

y data="Munich, BY"/>data=""/>data="2009-10-17"/>data="SI"/>umidity data="Feuchtigkeit: 87�%"/>data="/ig/images/weather/mostly_cloudy.gif"/>ent_conditions>data="1"/>data="/ig/images/weather/chance_of_rain.gif"/>data="So."/>data="/ig/images/weather/chance_of_sno
w.gif"/>data="Mo."/>data="Di."/>/>data="Klar"/>


As you can see the umlauts in the XML are not displayed properly. When I want 
to process this text (for example with xml.sax), I get error messages because 
the parses can't read this.


I've tried to read up on this and there is a lot of information on the web, but 
nothing seems to work for me. For example setting the coding to UTF like this: 
# -*- coding: utf-8 -*- or using the decode() string method.


I always have this kind of problem when input contains umlauts, not just in 
this case. My locale (on Ubuntu) is en_GB.UTF-8.



The string you received from the website is a bytestring and you're just
printing it to your console, which is configured for UTF-8. However, the
bytestring isn't valid UTF-8, so the console is replacing the invalid
parts with the funny characters.

You should decode the bytestring to Unicode and then re-encode it to
UTF-8. I don't know what encoding the website is actually using; here
I'm assuming ISO-8859-1:

print xml.decode("iso-8859-1").encode("utf-8")
--
http://mail.python.org/mailman/listinfo/python-list


Re: slicing return iter?

2009-10-17 Thread Arnaud Delobelle
On Oct 17, 3:40 pm, StarWing  wrote:
> hello everyone, I'm new here :-)
>
> sometimes I want to iterate a part of a sequence. but don't want to
> copy it. i.e.
>
> a = list(...)
> # now a is a list, and a[:] is another list, and so a[m:n]
> # now we do something with the 0~len(a)-3 elements of a
> for val in a[:-2]:
>     #do something
>
> but, this will cause a copy on a, has some convenience way to get a
> iter to iterate on a part of list?
>
> i made this:
> class iterslice:
>     def __init__(self, list):
>         self.list = list
>
>     def __len__(self):
>         return len(self.list)
>
>     def __getitem__(self, slice):
>         import itertools
>         listlen = len(self.list)
>         range = (((slice.start + listlen) % listlen) if slice.start
> else 0,
>                 ((slice.stop + listlen) % listlen) if slice.stop else
> listlen,
>                 slice.step)
>         return itertools.islice(self.list, *range)
>
> a = [1,2,3,4]
> for i in iterslice(a)[:-1:2]:
>     print i
>
> my question is:
>   - are there any *Standard* way to do this? (a buit-in function? a
> module?)
>   - are there any better implements?
>
> thanks for attention :-)

Check the itertools module.

HTH

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


Re: umlauts

2009-10-17 Thread Diez B. Roggisch

Arian Kuschki schrieb:

Hi all

this has been bugging me for a long time and I do not seem to be able to 
understand what to do. I always have problems when dealing input text that 
contains umlauts. Consider the following:


In [1]: import urllib

In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)

In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)
tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" 

y data="Munich, BY"/>data=""/>data="2009-10-17"/>data="SI"/>umidity data="Feuchtigkeit: 87�%"/>data="/ig/images/weather/mostly_cloudy.gif"/>ent_conditions>data="1"/>data="/ig/images/weather/chance_of_rain.gif"/>data="So."/>data="/ig/images/weather/chance_of_sno
w.gif"/>data="Mo."/>data="Di."/>/>data="Klar"/>


As you can see the umlauts in the XML are not displayed properly. When I want 
to process this text (for example with xml.sax), I get error messages because 
the parses can't read this.


I've tried to read up on this and there is a lot of information on the web, but 
nothing seems to work for me. For example setting the coding to UTF like this: 
# -*- coding: utf-8 -*- or using the decode() string method.


The encoding of the python-source-file has nothing to do with this. It's 
only relevant for unicode-literals (in python 2.x, that's u"...")




I always have this kind of problem when input contains umlauts, not just in 
this case. My locale (on Ubuntu) is en_GB.UTF-8.


If we assume the data on the website is correct (it appears to be when I 
open it in FF), then your problem is most probably your display/terminal.


What does this show you in your interactive interpreter?

>>> print "\xc3\xb6"
ö

For me, it's o-umlaut, ö. This is because the above bytes are the 
sequence for ö in utf-8.


If this shows something else, you need to adjust your terminal settings.

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


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Carsten Haese
Victor Subervi wrote:
> Let me clarify. This prints out "all sorts of crap", which means an
> image string, the image as a string, to the screen:
>  
> print 'Content-type: image/jpeg'
> print 'Content-Encoding: base64'
> print
> print pic().encode('base64')
> print ''

This has no hope of working, since you're sending data that's not valid
base64 code and pretend that it's base64-encoded. A browser trying to
display this result will produce something anywhere between
unpredictable and garbage.

> The following once upon a time printed images, but now it doesn't. Why
> would that be? I would refresh the screen, and it would print. I'd
> change a line and it wouldn't. I'd change it back to what it was and it
> would no longer the image to the screen. Why is that? The same happens
> with or without the base64 stuff. Commenting out a line seemed to make a
> difference!

Why would turning a comment into a statement NOT make a difference?!?

>  
> print 'Content-type: text/plain'
> #print 'Content-type: image/jpeg'
> print
> print pic()
> print ''

This should produce plain text, not an image.

> The above prints out a broken image of correct dimensions.

What the heck is a "broken image of correct dimensions"? Are you looking
at the output of the script itself, or are you looking at an html page
that uses this script as src-attribute for an img-tag? In the latter
case, if you're also giving the img-tag width and height attributes, it
shouldn't be surprising that you're getting the correct dimensions, and
you're getting a broken image because your src is producing plain text
instead of an image.

> Of course I try and figure out how things work once they get working.
> Sometimes, however, there is __no__ logic to it __at__all__. Sorry.
> After years of struggling with python I've come to realize that even
> though I may not be a good programmer, it isn't me. It may not be python
> itself. It may be the crappy hardware the server farms use. It may be
> the way they tweak their python interpreter. But it isn't just me.

I suppose it's possible that there is something quirky about the way the
server has been set up, but so far, the more likely explanation is that
you don't really know what you're doing.

You can prove whether it's your server farm or you by running the same
code on a different server.

> It would be nice if I could get this code printing images to the screen
> as it was before I had to put out another unnecessary fire when code
> that previously uploaded the images in the first place inexplicably no
> longer worked. Then, lo and behold, when I came back to this code that I
> hadn't touched and was working fine earlier this week, it no longer
> works. Lovely. My "plug-and-play" program has devoured two weeks of my
> time and I'm still up the creek without a paddle. Sure would appreciate
> any help you can give.

Again, you have to help us help you. I have listed the three things you
need to post together, and you haven't done that. You're giving us bits
and pieces, but nothing that's sufficiently cohesive to do any
meaningful troubleshooting on.

--
Carsten Haese
http://informixdb.sourceforge.net

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


umlauts

2009-10-17 Thread Arian Kuschki
Hi all

this has been bugging me for a long time and I do not seem to be able to 
understand what to do. I always have problems when dealing input text that 
contains umlauts. Consider the following:

In [1]: import urllib

In [2]: f = urllib.urlopen("http://www.google.de/ig/api?weather=Muenchen";)

In [3]: xml = f.read()

In [4]: f.close()

In [5]: print xml
--> print(xml)


As you can see the umlauts in the XML are not displayed properly. When I want 
to process this text (for example with xml.sax), I get error messages because 
the parses can't read this.

I've tried to read up on this and there is a lot of information on the web, but 
nothing seems to work for me. For example setting the coding to UTF like this: 
# -*- coding: utf-8 -*- or using the decode() string method.

I always have this kind of problem when input contains umlauts, not just in 
this case. My locale (on Ubuntu) is en_GB.UTF-8.

Cheers
Arian



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


Re: print()

2009-10-17 Thread Lie Ryan

mattia wrote:
Another question (always py3). How can I print only the first number 
after the comma of a division?

e.g. print(8/3) --> 2.667
I just want 2.6 (or 2.66)


Are you sure you don't want that to be 2.7 or 2.67? Then you can use:
n = int(n * 10**2) / 10**2
else if 2.7 pr 2.67 is what you wanted, you could use:
n = round(n, 2)
--
http://mail.python.org/mailman/listinfo/python-list


Re: More & More Fun w/ Pics & MySQL

2009-10-17 Thread Victor Subervi
Let me clarify. This prints out "all sorts of crap", which means an image
string, the image as a string, to the screen:

print 'Content-type: image/jpeg'
print 'Content-Encoding: base64'
print
print pic().encode('base64')
print ''

The following once upon a time printed images, but now it doesn't. Why would
that be? I would refresh the screen, and it would print. I'd change a line
and it wouldn't. I'd change it back to what it was and it would no longer
the image to the screen. Why is that? The same happens with or without the
base64 stuff. Commenting out a line seemed to make a difference!

print 'Content-type: text/plain'
#print 'Content-type: image/jpeg'
print
print pic()
print ''

The above prints out a broken image of correct dimensions.

Of course I try and figure out how things work once they get working.
Sometimes, however, there is __no__ logic to it __at__all__. Sorry. After
years of struggling with python I've come to realize that even though I may
not be a good programmer, it isn't me. It may not be python itself. It may
be the crappy hardware the server farms use. It may be the way they tweak
their python interpreter. But it isn't just me.

It would be nice if I could get this code printing images to the screen as
it was before I had to put out another unnecessary fire when code that
previously uploaded the images in the first place inexplicably no longer
worked. Then, lo and behold, when I came back to this code that I hadn't
touched and was working fine earlier this week, it no longer works. Lovely.
My "plug-and-play" program has devoured two weeks of my time and I'm still
up the creek without a paddle. Sure would appreciate any help you can give.
V

On Fri, Oct 16, 2009 at 8:54 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > I'm sorry. These scripts worked fine before and should have been
> > plug-and-play. I have wasted 2 frustrating weeks trying to figure out
> > why they don't work only to discover things that make no sense at all
> > that do the trick. I thought programming was straight-forward and
> > "logical"...boy, am I disappointed. Sorry for the jade.
>
> Clearly, you're not jaded enough. When my code does things that I don't
> understand, I try to understand what's going on. Your approach seems to
> be to randomly mutate your code until it works. There is nothing
> inherently wrong with that as long as you then try to understand *why*
> it works once you get it work. You seem to have omitted this step. Since
> you never understood why your code worked, consequently now you don't
> understand why your code has stopped working.
>
> > What I mean is that the code supplied merely posts a broken image, with
> > the correct dimensions, interestingly enough. It makes no difference at
> > all if one adds the line "print ''" or not. I also believe
> > (and hope) my initial post is pretty clear.
>
> Actually, your original post was not clear at all. Your original post
> said "This will print all sorts of crap to the screen." This is not
> useful at all. The only reason why I responded at all was because I
> noticed the  line in your code that clearly didn't have
> any business being there. The fact that you even considered the
> possibility that that line could help shows just how little you know
> about what's going on in your code.
>
> By the way, you now have changed your story from "random crap" to "a
> broken image". Which one is it?
>
> The only way we have a fighting chance to help you in figuring out
> what's going in is if you post the *exact* code you're running (and by
> that I mean the actual code that you know your server is executing, and
> not just some code that somewhat resembles the code that the server
> might be executing), a detailed description of the result you're
> expecting, and a detailed description of the result you're getting instead.
>
> --
> Carsten Haese
> http://informixdb.sourceforge.net
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


slicing return iter?

2009-10-17 Thread StarWing
hello everyone, I'm new here :-)

sometimes I want to iterate a part of a sequence. but don't want to
copy it. i.e.

a = list(...)
# now a is a list, and a[:] is another list, and so a[m:n]
# now we do something with the 0~len(a)-3 elements of a
for val in a[:-2]:
#do something

but, this will cause a copy on a, has some convenience way to get a
iter to iterate on a part of list?

i made this:
class iterslice:
def __init__(self, list):
self.list = list

def __len__(self):
return len(self.list)

def __getitem__(self, slice):
import itertools
listlen = len(self.list)
range = (((slice.start + listlen) % listlen) if slice.start
else 0,
((slice.stop + listlen) % listlen) if slice.stop else
listlen,
slice.step)
return itertools.islice(self.list, *range)


a = [1,2,3,4]
for i in iterslice(a)[:-1:2]:
print i


my question is:
  - are there any *Standard* way to do this? (a buit-in function? a
module?)
  - are there any better implements?

thanks for attention :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print()

2009-10-17 Thread Dave Angel

mattia wrote:

Il Fri, 16 Oct 2009 22:40:34 -0700, Dennis Lee Bieber ha scritto:

  

On Fri, 16 Oct 2009 23:39:38 -0400, Dave Angel 
declaimed the following in gmane.comp.python.general:




You're presumably testing this in the interpreter, which prints extra
stuff.  In particular, it prints the result value of any expressions
entered at the interpreter prompt.  So if you type

sys.stdout.write("hello")

then after the write() method is done, the return value of the method
(5) will get printed by the interpreter.

  
	I was about to respond that way myself, but before doing so I 


wanted
  

to produce an example in the interpreter window... But no effect?

C:\Documents and Settings\Dennis Lee Bieber>python ActivePython 2.5.2.2
(ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27
2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.


import sys
sys.stdout.write("hello")
  

hello>>>


PythonWin 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin'
for further copyright information.


import sys
sys.stdout.write("This is a test")
  

This is a test


print sys.stdout.write("Hello")
  

HelloNone

  

No count shows up... neither PythonWin or Windows command line/


shell

Indeed I'm using py3. But now everythong is fine. Everything I just 
wanted to know was just to run this simple script (I've also sent the msg 
'putchar(8)' to the newsgroup):


import time
import sys

val = ("|", "/", "-", "\\", "|", "/", "-", "\\")
for i in range(100+1):
print("=", end="")
# print("| ", end="")
print(val[i%len(val)], " ", sep="", end="")
print(i, "%", sep="", end="")
sys.stdout.flush()
time.sleep(0.1)
if i > 9:
print("\x08"*5, " "*5, "\x08"*5, sep="", end="")

else:
print("\x08"*4, " "*4, "\x08"*4, sep="", end="")
print(" 100%\nDownload complete!")  

  
Seems to me you're spending too much energy defeating the things that 
print() is automatically doing for you.  The whole point of write() is 
that it doesn't do anything but ship your string to the file/device.  So 
if you want control, do your own formatting.


Consider:

import time, sys, itertools

val = ("|", "/", "-", "\\", "|", "/", "-", "\\")
sys.stdout.write(" ")
pattern = "\x08"*8 + "   {0}{1:02d}%"
for percentage, string in enumerate(itertools.cycle(val)):
   if percentage>99 : break
   paddednum = pattern.format(string, percentage)
   sys.stdout.write(paddednum)
   sys.stdout.flush()
   time.sleep(0.1)
print("\x08\x08\x08\x08 100%\nDownload complete!")


Note the use of cycle() which effectively repeats a list indefinitely.  
And enumerate, which makes an index for you automatically when you're 
iterating through a list.  And  str.format() that builds our string, 
including using 0 padding so the percentages are always two digits.



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


Re: The rap against "while True:" loops

2009-10-17 Thread Aahz
In article ,
Tim Rowe   wrote:
>
>The point is that an exception causes a change in program flow, so of
>course they're used for flow control. It's what they do. The question
>is in what cases it's appropriate to use them.

Standard Python idiom:

try:
d[key] += value
except KeyError:
d[key] = value

Maybe you need to re-think "appropriate".
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --re...@lion.austin.ibm.com
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >