Re: SSH utility

2009-07-07 Thread romeoamp

Please look at on :


http://www.lag.net/paramiko/ http://www.lag.net/paramiko/ 


Sample Code: Find Attachment


Thanks,
S.V.RAJKUMAR,
XOU Solutions India Private Limited
No. 37, PM Towers,
Greams Road,
Thousand Lights,
Chennai - 6 .
Mobile No : +91 - 9940632275. 





half.italian wrote:
> 
> On Aug 11, 5:17 am, edwin.mad...@verizonwireless.com wrote:
>> for similar tasks, I use pexpecthttp://pypi.python.org/pypi/pexpect.
>>
>> spawning bash process and simulate an interactive session. Here sending
>> ls command, retrieving results and exiting. In the spawned process ssh or
>> any other command, is just another command.
>>
>> actual session--
>> $ python
>> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
>> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
>> Type "help", "copyright", "credits" or "license" for more information.>>>
>> import pexpect
>> >>> c = pexpect.spawn('/bin/bash')
>> >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ '])
>> 2
>> >>> c.before, c.after
>>
>> ('\x1b[?1034hmada...@njwarhqd0it696a:~\r\n', '$ ')>>> c.sendline('ls')
>> 3
>> >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ '])
>> 2
>> >>> c.before, c.after
>>
>> ('ls\r\x.txt  xx.txt  xy.txt  y.txt\r\nmada...@njwarhqd0it696a:~\r\n', '$
>> ')>>> c.sendline('exit')
>> 5
>> >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ '])
>> 1
>> >>> c.before, c.after
>>
>> ('exit\r\nexit\r\n', )>>> exit()
>>
>> mada...@njwarhqd0it696a:~
>> $
>> ---
>>
>> hope that helps.
>>
>> regards.
>> Edwin
>>
>> -Original Message-
>> From: python-list-bounces+edwin.madari=verizonwireless@python.org
>>
>> [mailto:python-list-bounces+edwin.madari=verizonwireless@python.org]
>> On Behalf Of James Brady
>> Sent: Monday, August 11, 2008 12:26 AM
>> To: python-l...@python.org
>> Subject: SSH utility
>>
>> Hi all,
>> I'm looking for a python library that lets me execute shell commands
>> on remote machines.
>>
>> I've tried a few SSH utilities so far: paramiko, PySSH and pssh;
>> unfortunately all been unreliable, and repeated questions on their
>> respective mailing lists haven't been answered...
>>
>> It seems like the sort of commodity task that there should be a pretty
>> robust library for. Are there any suggestions for alternative
>> libraries or approaches?
>>
>> Thanks!
>> James
>> --http://mail.python.org/mailman/listinfo/python-list
>>
>> The information contained in this message and any attachment may be
>> proprietary, confidential, and privileged or subject to the work
>> product doctrine and thus protected from disclosure.  If the reader
>> of this message is not the intended recipient, or an employee or
>> agent responsible for delivering this message to the intended
>> recipient, you are hereby notified that any dissemination,
>> distribution or copying of this communication is strictly prohibited.
>> If you have received this communication in error, please notify me
>> immediately by replying to this message and deleting it and all
>> copies and backups thereof.  Thank you.
> 
> I second pexpect and the nice little module that comes with it
> ssh_session.py.
> 
> Been using it for ages now!
> 
> ~Sean
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
http://www.nabble.com/file/p24385961/sshclient.py sshclient.py 
-- 
View this message in context: 
http://www.nabble.com/SSH-utility-tp18920030p24385961.html
Sent from the Python - python-list mailing list archive at Nabble.com.
-- 
http://mail.python.org/mailman/listinfo/python-list


count

2009-07-07 Thread Dhananjay
Dear all,

I have file as follows,however, tab seperated (not shown in following file):

 6   3   4.309726
 7   65 93.377388
 8   47 50.111952
 9   270   253.045923
 10 184182.684670
 11 76 121.853455
 12 85 136.283470
 13 114145.910662
 14 45  80.703013
 15 44  47.154646
 16 41  66.461339
 17 16  33.819488
 18 127 136.105455
 19 70  88.798681
 20 29  61.297823


I wanted to sort column 2 in assending order  and I read whole file in array
"data" and did the following:

data.sort(key = lambda fields:(fields[2]))

I have sorted column 2, however I want to count the numbers in the column 2.
i.e. I want to know, for example, how many repeates of say '3' (first row,
2nd column in above data) are there in column 2.

I could write seperate programme to get the result.s.

However, is there any way to count the numbers there itself while sorting in
column 2 ?


Thanking you in advance,


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


Re: tough-to-explain Python

2009-07-07 Thread Steven D'Aprano
On Tue, 07 Jul 2009 20:04:46 +, kj wrote:

> I'm having a hard time coming up with a reasonable way to explain
> certain things to programming novices.

[...]


> Or consider this one:
> 
 ham = [1, 2, 3, 4]
 spam = (ham,)
 spam
> ([1, 2, 3, 4],)
 spam[0] is ham
> True
 spam[0] += [5]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
 ham += [5]
 spam
> ([1, 2, 3, 4, 5, 5],)
 
 
> What do you say to that?


That one surely is very straight forward. Just like the exception says, 
tuples don't support item assignment, so spam[0] += [5] is not allowed.

But just because you have put a list inside a tuple doesn't mean the list 
stops being a list -- you can still append to the list, which is what 
ham += [5] does. So spam is unchanged: it is still the one-item tuple 
containing a list. It is just that the list has now been modified.

This is only troublesome (in my opinion) if you imagine that tuples are 
somehow magical "frozen-lists", where the contents can't be modified once 
created. That's not the case -- the tuple itself can't be modified, but 
the objects inside it remain ordinary objects, and the mutable ones can 
be modified.

The thing to remember is that the tuple spam doesn't know anything about 
the *name* ham -- it knows the object referred to by the name ham. You 
can modify the name, and nothing happens to the tuple:

>>> spam
([1, 2, 3, 4, 5],)
>>> ham = [5]
>>> spam
([1, 2, 3, 4, 5],)

Or if you prefer:

>>> ham = spam[0]  # label the list inside spam as 'ham'
>>> ham += [6]  # modify the list labelled as 'ham'
>>> spam
([1, 2, 3, 4, 5, 6],)
>>> pork = ham  # create a new label, 'pork', and bind it to the same list
>>> del ham  # throw away the label 'ham'
>>> pork += [7]  # modify the list labelled as 'pork'
>>> spam
([1, 2, 3, 4, 5, 6, 7],)


It's all about the objects, not the names.



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


Re: Python and webcam capture delay?

2009-07-07 Thread Tim Roberts
Nobody  wrote:
>
>The webcam is bound to do some encoding; most of them use USB "full speed"
>(12Mbit/sec), which isn't enough for raw 640x480x24...@30fps data.

That's not true.  Most of the web cams made in the last 5 years or so run
at high speed, 480 Mbps.  Full speed only gets you 1 fps at 640x480
uncompressed, so it's really only useful for the most primitive video
conference cams.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check file is locked?

2009-07-07 Thread Rajat
On Jul 8, 4:57 am, Lawrence D'Oliveiro  wrote:
> In message , Christian
>
> Heimes wrote:
> > By the way most operating systems don't lock a file when it's opened for
> > reading or writing or even executed.
>
> The general conclusion seems to be that mandatory locking is more trouble
> than it's worth.

My OS is a windows XP sp3. All I'm trying to achieve is to close an
application ( which could be a notepad, a wordpad or some other text
editor) that have opened my file. Once the file is closed I can easily
delete that file.

I guess, if file is opened by one of that application, the file must
be locked and so is the reason I cannot delete the file.

Please suggest if this is fine.

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


Re: DBI module deprecated at Python 2.5--what to use in its place?

2009-07-07 Thread John Machin
On Jul 8, 3:05 am, dana  wrote:
> I have a variety of Python 2.4 scripts that utilitize the DBI and ODBC
> modules together. Although I don't have Python 2.5, I've been informed
> the DBI module has been deprecated at 2.5.
>
> A few questions:
>
> 1) Although deprecated, will it work at all in 2.5? Does the fact that
> it is deprecrated mean it has been removed entirely, or does Python
> 2.5 simply issuing a warning?

Deprecated certainly doesn't mean removed.

>
> 2) What do I use in place of DBI for my Python 2.4. scripts that
> import modules DBI and ODBC together. I don't use DBI directly. It was
> simply a dependency for the ODBC module as best I knew.

For a start, none of (DBI, ODBC, dbi, odbc) are standard Python-
supplied modules. Perhaps you are referring to the odbc (and dbi) from
the pywin32 package? Where did you get them from? If you can't
remember, try this:

|Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> import odbc
| >>> odbc.__file__
| 'C:\\python24\\lib\\site-packages\\win32\\odbc.pyd'
| >>>

If this is what you're talking about, you should be asking on the
pywin32 dicussion list (http://mail.python.org/mailman/listinfo/python-
win32).

General advice: if you are thinking of upgrading your Python version,
go straight to 2.6. odbc is AFAIK stuck at version 1.0 of the Python
DB API; consider switching to pyodbc (http://code.google.com/p/
pyodbc/)

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


Re: tough-to-explain Python

2009-07-07 Thread Simon Forman
On Jul 7, 4:04 pm, kj  wrote:
> I'm having a hard time coming up with a reasonable way to explain
> certain things to programming novices.
>
> Consider the following interaction sequence:
>
> >>> def eggs(some_int, some_list, some_tuple):
>
> ... some_int += 2
> ... some_list += [2]
> ... some_tuple += (2,)
> ...
>
> >>> x = 42
> >>> y = (42,)
> >>> z = [42]
> >>> eggs(x, y, z)
> >>> x
> 42
> >>> y
> (42,)
> >>> z
> [42, 2]

You have transposed some_list and some some_tuple. I.e. you should be
calling eggs(x, z, y).

> How do I explain to rank beginners (no programming experience at
> all) why x and y remain unchanged above, but not z?

You don't. Rank beginners don't have enough background knowledge to
grok that code.

Why would you even tell the poor bastards about "+=" before they were
comfortable with (python's style of) function calls, immutable
integers, mutable lists and immutable tuples?

Let them use "x = x + y" until they have enough knowledge to
understand "augmented" assignment.

Syntax matters (I mean general order of things, not linguistic
syntax.)  Making an omelette requires putting eggs in a pan and
cracking them, but not in that order.

> Or consider this one:
>
> >>> ham = [1, 2, 3, 4]
> >>> spam = (ham,)
> >>> spam
> ([1, 2, 3, 4],)
> >>> spam[0] is ham
> True
> >>> spam[0] += [5]
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
> >>> ham += [5]
> >>> spam
>
> ([1, 2, 3, 4, 5, 5],)
>
>
>
> What do you say to that?

I say, "Don't use augmented assignment with indexed tuples."

Seriously, python's augmented assignment is almost magical. I think
you're just making trouble for yourself and your students if you
introduce it too early.

I get python pretty well (if I say so myself) but I wouldn't know how
to explain:

In [1]: def foo(a_list):
   ...: a_list = a_list + [5]
   ...:
   ...:

In [2]: n = []

In [3]: foo(n)

In [4]: n
Out[4]: []

In [5]: def bar(a_list):
   ...: a_list += [5]
   ...:
   ...:

In [6]: bar(n)

In [7]: n
Out[7]: [5]


It's "Just The Way It Is". Freakin' magic, man.

> I can come up with much mumbling about pointers and stacks and
> heaps and much hand-waving about the underlying this-and-that, but
> nothing that sounds even remotely illuminating.
>
> Your suggestions would be much appreciated!

Frankly, I'm of the impression that it's a mistake not to start
teaching programming with /the bit/ and work your way up from there.
I'm not kidding. I wrote a (draft) article about this: "Computer
Curriculum" http://docs.google.com/View?id=dgwr777r_31g4572gp4

I really think the only good way to teach computers and programming is
to start with a bit, and build up from there. "Ontology recapitulates
phylogeny"

I realize that doesn't help you teach python, but I wanted to put it
out there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use Python to interface with Web pages?

2009-07-07 Thread Ralf Schoenian

Peter wrote:

Any help would be appreciated :-)

I want to write an auction sniping tool in Python. I know Python, but
I know absolutely nothing about web pages, javascript etc i.e. I want
the program to automatically log me into my eBay account, access the
appropriate item, locate how many mins/seconds until the bid time ends
and then automatically place a bid at the last possible moment.

I can see the web-page source - it looks to be javascript (to my
untutored eye :-)).

But how do I enter data and "simulated" mouse presses on a web-page
that I have accessed via a Python program?

So where can I start to learn how to do this? Any books available? web
resources that show examples or offer tutorials?

I have (in the past) written some python to scoop data off web-sites
but I have never written anything that interactively interacts with
the web-page contents and don't know where to even start on this one.

Thanks for any help/pointers

Peter


Hi,

a good starting point possibly is 
http://wwwsearch.sourceforge.net/mechanize/


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


How to use Python to interface with Web pages?

2009-07-07 Thread Peter
Any help would be appreciated :-)

I want to write an auction sniping tool in Python. I know Python, but
I know absolutely nothing about web pages, javascript etc i.e. I want
the program to automatically log me into my eBay account, access the
appropriate item, locate how many mins/seconds until the bid time ends
and then automatically place a bid at the last possible moment.

I can see the web-page source - it looks to be javascript (to my
untutored eye :-)).

But how do I enter data and "simulated" mouse presses on a web-page
that I have accessed via a Python program?

So where can I start to learn how to do this? Any books available? web
resources that show examples or offer tutorials?

I have (in the past) written some python to scoop data off web-sites
but I have never written anything that interactively interacts with
the web-page contents and don't know where to even start on this one.

Thanks for any help/pointers

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


Re: tough-to-explain Python

2009-07-07 Thread Gabriel Genellina

En Tue, 07 Jul 2009 17:04:46 -0300, kj  escribió:


I'm having a hard time coming up with a reasonable way to explain
certain things to programming novices.


ham = [1, 2, 3, 4]
spam = (ham,)
spam

([1, 2, 3, 4],)

spam[0] is ham

True

spam[0] += [5]

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

ham += [5]
spam

([1, 2, 3, 4, 5, 5],)




What do you say to that?

I can come up with much mumbling about pointers and stacks and
heaps and much hand-waving about the underlying this-and-that, but
nothing that sounds even remotely illuminating.


This article is based on an old thread in this list that is very
enlightening:

How To Think Like A Pythonista
http://python.net/crew/mwh/hacks/objectthink.html

and I'll quote just a paragraph from Alex Martelli:

«There is [...] a huge difference
between changing an object, and changing (mutating) some
OTHER object to which the first refers.

In Bologna over 100 years ago we had a statue of a local hero
depicted pointing forwards with his finger -- presumably to
the future, but given where exactly it was placed, the locals
soon identified it as "the statue that points to Hotel
Belfiore".  Then one day some enterprising developer bought
the hotel's building and restructured it -- in particular,
where the hotel used to be was now a restaurant, Da Carlo.

So, "the statue that points to Hotel Belfiore" had suddenly
become "the statue that points to Da Carlo"...!  Amazing
isn't it?  Considering that marble isn't very fluid and the
statue had not been moved or disturbed in any way...?

This is a real anecdote, by the way (except that I'm not
sure of the names of the hotel and restaurant involved --
I could be wrong on those), but I think it can still help
here.  The dictionary, or statue, has not changed at all,
even though the objects it refers/points to may have been
mutated beyond recognition, and the name people know it
by (the dictionary's string-representation) may therefore
change.  That name or representation was and is referring
to a non-intrinsic, non-persistent, "happenstance"
characteristic of the statue, or dictionary...»

--
Gabriel Genellina

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


Re: tough-to-explain Python

2009-07-07 Thread python
Ben,

> I have got very good results from teaching using the analogy of "paper tags 
> tied to physical objects" to describe Python's references to values.

Great analogy!! And an excellent analogy for newcomers to Python. (this
would have saved me some personal pain in my early days).

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


Re: tough-to-explain Python

2009-07-07 Thread Steven D'Aprano
On Tue, 07 Jul 2009 21:18:53 +, kj wrote:

> I had not realized how *profoundly* different the meaning of the "=" in
> Python's
> 
>   spam = ham
> 
> is from the "=" in its
> 
>   spam[3] = ham[3]
> 
> So much for "explicit is better than implicit"...

I'm sorry, I don't get it. Can you explain please? I don't see why it's 
so "profoundly" different. Apart from spam[3] = x not being permitted if 
spam is an immutable type.

I suppose though they are *fundamentally* different, in that spam=ham is 
dealt with by the compiler while spam[3]=ham is handled by the object 
spam using the __setitem__ method. Is that the difference you're talking 
about?


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


Re: IP Address Function

2009-07-07 Thread Gabriel Genellina
En Tue, 07 Jul 2009 22:45:24 -0300, Fred Atkinson   
escribió:



Is there a Python function I can use to get the user's IP
address so I can display it on his browser?


There is a long distance between "Python" and "browser" - you'll have to  
tell us what is in between the two.
By example, do you have a server and the user connects to it? is it  
running Python? how do you run the Python application?
And why do you want to do that on the server side? Isn't easier to do that  
on the client side? What about proxies? NAT?


If using CGI, look at the REMOTE_ADDR environment variable.

--
Gabriel Genellina

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


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Gabriel Genellina
En Tue, 07 Jul 2009 09:51:10 -0300, Jean-Michel Pichavant  
 escribió:
I've never used sense in that way before, nor I've seen used by others  
until now. However Kj is right, and my dictionary seems wrong  
(wordreference.com). I've searched through others dictionaries and find  
out this is actually applicable to functions. My bad.


Using a common word with its common meaning is important too in order to  
understand the code. It's hard enough for students to grasp the algorithm  
itself, why make it artificially harder by using strange variable names.


Some years ago I had to endure using an in-house framework with names like  
bring_XXX and fix_XXX instead of the usual names get_XXX and set_XXX (that  
was C++, emulating properties; I'm not sure of the actual verbs used,  
perhaps "obtain" and "establish", but certainly not get/set/put). Add some  
undecipherable comments in spanglish, profuse usage of macros that alter  
the lexical appearance of the language, and even reading code was a  
torture.


--
Gabriel Genellina

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


Re: tough-to-explain Python

2009-07-07 Thread John Yeung
On Jul 7, 8:06 pm, Ben Finney  wrote:
> I have got very good results from teaching using
> the analogy of “paper tags tied to physical objects”
> to describe Python's references to values.

Ah, I like that!  I think it's better than what I used in my post
(which I composed and submitted before yours showed up in my reader).

I am not formally a teacher, but I do try to help "nonprogrammers"
learn Python from time to time, and this will be a good one to
remember.

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


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Paul Rubin
pdpi  writes:
> while abs(func(guess) - target) > epsilon:
> guess = (lo + hi) / 2.
> if sense * func(guess) > sense * target:
> hi = guess
> elif sense * func(guess) < sense * target:
> lo = guess
> elif lo == hi:
> return None
> return guess

That is completely confusing.  I get the, er, impression that "sense"
is supposed to change during the loop, and it takes much head
scratching to tell whether what you have there is right or not.  Also,
it calls func 3 times on each loop, which could be extremely slow.
You don't know what func does, so eliminating 2/3 of the calls to it
is not a micro-optimization--it could be a major time saving.

Yet another version:

def _binary_search(x0, x1, func, target, epsilon):
y0,y1 = func(x0), func(x1)
while abs(y1 - target) > epsilon:
if x0 == x1 or cmp(y0,target) == cmp(y1,target):
return None
xn = (x0 + x1) / 2.
yn = func(xn)
if cmp(yn,target) == cmp(y0,target):
   x0,y0 = xn,yn
else:
   x1,y1 = xn,yn
return x1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IP Address Function

2009-07-07 Thread Chris Rebert
On Tue, Jul 7, 2009 at 6:45 PM, Fred Atkinson wrote:
>        Is there a Python function I can use to get the user's IP
> address so I can display it on his browser?

from socket import gethostname, gethostbyname
ip = gethostbyname(gethostname())

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


Re: IP Address Function

2009-07-07 Thread Tim Harig
On 2009-07-08, Fred Atkinson  wrote:
>   Is there a Python function I can use to get the user's IP
> address so I can display it on his browser?  

If you are using CGI you can get it from the REMOTE_ADDR environmental
variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tough-to-explain Python

2009-07-07 Thread John Yeung
On Jul 7, 5:11 pm, kj  wrote:
> I don't plan to present these examples to them.
> But beginners have a way of bumping into such
> conundrums all on their own [...].  I doubt that
> an answer of the form "don't worry your pretty
> little head over this now; wait until your second
> course" will do the trick.

I agree that beginners are bound to come across difficult issues on
their own, and when they do, you have to at least try to explain,
rather than dismiss them.  I believe that the beginners which are most
curious, and thus most likely to run into things you didn't plan for
them, are also most likely to be ready and able to receive your
explanation.

That said, I think it's worth planning a fairly controlled flow of
information.  For example, you can go a LONG way without touching
tuples or the augmented assignment operators.

For your function example, I suppose the key ideas to understand are
binding and containers (which may or may not be mutable).  The
oversimplified version I think I would attempt to explain is that, as
far as the "outside world" is concerned, a function cannot rebind the
arguments passed to it.  However, the contents of a mutable container
may be altered without rebinding.  That is, you can hold a bucket,
pass that bucket to a function, and the function can put stuff in the
bucket or take stuff out without you ever letting go of the bucket.
When the function returns, you are still holding the bucket.

Nested containers, especially with "outside" bindings to inner
containers, may be tougher to visualize with real-world objects.
Hopefully by then the students can grasp a more abstract (pointerlike)
notion of binding!  Good luck!

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


IP Address Function

2009-07-07 Thread Fred Atkinson
Is there a Python function I can use to get the user's IP
address so I can display it on his browser?  

Regards, 




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


Re: Write matrix to text file

2009-07-07 Thread Gabriel Genellina
En Tue, 07 Jul 2009 14:46:47 -0300, Hanna Michelsen   
escribió:


I'm working with both python and matlab at the moment and I was  
wondering if
there is an efficient way to take a 2-D array (of 1s and 0s) in python  
and

write it to a text file such that matlab will be able to create a sparse
matrix from it later.


Your yesterday post appeared on this list successfully.
Posting the very same text again isn't going to help - those that are  
reading it now are likely the same that read it before.
If nobody replied, assume that something is wrong with the question  
itself. Not the grammar, looks clear to me. Maybe the meaning: you say "a  
2-D array" but you don't say what that means (a list? an array.array  
object? a Numpy array?).


Consider *who* might be able to answer: someone that knows both Python and  
matlab, and knows how to use a sparse matrix, and knows how to read data  
from files, and knows how to generate such files from Python. The last  
part is the easy part, because people here is supposed to know how to do  
things in Python; but not how matlab works. So, please help people help  
you: tell us what file format would be fine for matlab to read, and people  
here surely will suggest the best way to write that in Python.


Reading http://www.mikeash.com/getting_answers.html may help too.

--
Gabriel Genellina

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


Re: tough-to-explain Python

2009-07-07 Thread Ben Finney
kj  writes:

> In  Chris Rebert 
>  writes:
> 
> >You might find the following helpful (partially):
> >http://effbot.org/zone/call-by-object.htm
> 
> Extremely helpful.  Thanks!  (I learned more from it than someone
> who will teach the stuff would care to admit...)

I have got very good results from teaching using the analogy of “paper
tags tied to physical objects” to describe Python's references to
values.

The analogy allows illustration of many otherwise confusing facts:

  * an assignment is the act of putting a tag onto an object

  * a tag leads to exactly one object, and it can be re-tied to a
different object

  * an object can have arbitrarily many tags on it

  * containers (e.g. lists, dicts, sets, etc.) don't contain objects,
they contain tags leading to objects

  * passing arguments to a function always makes new tags leading to the
objects passed in, and throws those new tags away once the function
returns

  * etc.

The analogy can then be contrasted to how Python *doesn't* do it: named
boxes with one value per box. You can point out that many other
languages do use this model, so they should be aware of it, but Python
doesn't use it.

> I had not realized how *profoundly* different the meaning of the
> "=" in Python's
> 
>   spam = ham

Access the object referenced by ‘ham’, and assigns the reference ‘spam’
to that object.

> is from the "=" in its
> 
>   spam[3] = ham[3]

Access the object referenced by ‘ham[3]’, and assigns the reference
‘spam[3]’ to that object.

No, they're exactly the same. The only thing that's different is the
references you use; the assignment operates *exactly* the same in both
cases.

-- 
 \ “We are no more free to believe whatever we want about God than |
  `\ we are free to adopt unjustified beliefs about science or |
_o__)  history […].” —Sam Harris, _The End of Faith_, 2004 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check file is locked?

2009-07-07 Thread Lawrence D'Oliveiro
In message , Christian 
Heimes wrote:

> By the way most operating systems don't lock a file when it's opened for
> reading or writing or even executed.

The general conclusion seems to be that mandatory locking is more trouble 
than it's worth.

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


Re: tough-to-explain Python

2009-07-07 Thread Bret Fledderjohn
I really enjoyed your boxes analogy, from a guy with a trucking background,
it makes a lot of sense!
-Bret


> ... The more I delve into OOP the more I liken an 'object' to a box. A box
> with a shipping manifest.
>
> There are big boxes,
> little boxes,
> squat boxes and so on.
>
> A box can contain corn flakes,
> bullets, raisins, rice, burlap, silk, motorcycle(s), soap and more.
>
> The manifest describes contents.
> The manifest is there but the description(s) change with content (type).
> The descriptions always use one or more of the basics like: color, count,
> dimension and so forth.
>
> Just like an OOP object.
>
> A box can contain things of all sorts, including references to the contents
> of other box(es). A box can even be a virtual of another (the global
> concept).  The return statement, in this context, means hauling the contents
> of the box (and/or its manifest) back to (wherever) and disposing of the
> current box (a local).
>
> Just like an OOP object.
>
>
> It is easier to visualize a box and it's use than a non described blob.
> Abstracts are never precise -  hence the evolution of the word.
>
>
> The one thing a teacher will always fail is the same as anyone else who
> tries to adequately describe a pretty sunset to a person born totally blind.
> No point(s) of reference.
>
>
>
> Time for me to sign off.  To all those that helped me when I needed it -
>
> I thank you very much.
>
> Food for thought: your watch (clock) does not tell time.
> The watch (clock) only mimics one movement of the earth.
> ie... 3 dimensions are still static, the 4th is movement.
>
>
> Steve


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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Stef Mientki

J Kenneth King wrote:

Stef Mientki  writes:

  

So, the question is, can the same thing be done for Python apps?



I love Python and all, but it'd be apt to ask, what's the point?

The iPhone is running on what? A 400Mhz ARM processor? Resources on the
device are already limited; running your program on top of an embedded
Python interpreter would only be adding pressure to the constraints;
even if it was an optimized interpreter.
  
  

I don't know iPhone,
but I've done some experiments with 400 MHz arm, running Windows Mobile,
and found PocketPyGUI running very very well on these devices.

cheers,
Stef Mientki



Sure, but it's pretty relative in the sense that it might be fast enough
if I'm sitting around but too slow if I want to enter some information
in the app before the next train comes.

As a programmer, I don't really see the benefit of using an embedded
interpreter on the iPhone.  Objective-C isn't the greatest language, but
it's easy to learn and well supported.  It also compiles into some
pretty speedy executables.

If you can sacrifice a little run-time speed for your users in exchange
for ease of development on your part, all the more to you.

My original point was that I don't see the benefit in that decision.


  

ok 20 years ago I might have agreed with you,
but now a days,
speed of development is a much more important decision maker than speed 
of execution ;-)


cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Embedded Python : Why does thread lock here?

2009-07-07 Thread Gabriel Genellina
En Tue, 07 Jul 2009 15:01:17 -0300, roschler   
escribió:



I have the Python Intepreter embedded in a Delphi (Object Pascal)
program.  In the Python script shown below, I have a module that
creates a thread object and starts it.


Do you *execute* the module or do you *import* it?
Isn't a good idea to spawn a thread by side effect of importing a module.


The thread's run() call calls
a function called deleteOutputVariables() declared at the module
level.  In my code's first incarnation the thread's run() call would
deadlock when trying to call the deleteOutputVariables() function
declared at Module level.  I would never see the statement
"(deleteOutputVariables) Top of Call" printed to the screen.  I now
know that I must periodically call join() with a very fast time-out to
keep Python threads happy, and that solved the problem.


What does the Delphi code? Isn't a join with a long timeout enough?


However I am
curious as to why it deadlocked at the deleteOutputVariables() call?
Is it because deleteOutputVariables() is declared at the module level
or because that function deletes module level variables?  If so why?


I don't know, but you can make some experiments - move te  
deleteOutputVariables as a method, or don't delete module level variables  
at all, and see what happens. I'd say both factors are irrelevant.



# FUNCTION: Delete the variables given in the list.
def deleteOutputVariables(theModule, theOutputVariablesListOfNames):
try:
print "(deleteOutputVariables) Top of call."
for theOutputVariableName in theOutputVariablesListOfNames:
if theModule.__dict__.has_key(theOutputVariableName):
print "(Python::deleteOutputVariables) Deleting the
Output Variable named " + theOutputVariableName
del theModule.__dict__[theOutputVariableName]
except:
print "(deleteOutputVariables) Exception occurred."


As a rule, avoid using __special__ names. There is almost never need of  
using them (__init__ is a notable exception) unless you want to change  
Python behaviour.

In this case:

for theOutputVariableName in theOutputVariablesListOfNames:
  if hasattr(theModule, theOutputVariableName):
delattr(theModule, theOutputVariableName)

(a name like theOutputVariablesListOfNames is too long for my taste, but  
that's a matter of style...)



theNewThread = None
theNewThread = threadRun("TestThread")


That first line is useless...

--
Gabriel Genellina

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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread J Kenneth King
Stef Mientki  writes:

>>> So, the question is, can the same thing be done for Python apps?
>>> 
>>
>> I love Python and all, but it'd be apt to ask, what's the point?
>>
>> The iPhone is running on what? A 400Mhz ARM processor? Resources on the
>> device are already limited; running your program on top of an embedded
>> Python interpreter would only be adding pressure to the constraints;
>> even if it was an optimized interpreter.
>>   
> I don't know iPhone,
> but I've done some experiments with 400 MHz arm, running Windows Mobile,
> and found PocketPyGUI running very very well on these devices.
>
> cheers,
> Stef Mientki

Sure, but it's pretty relative in the sense that it might be fast enough
if I'm sitting around but too slow if I want to enter some information
in the app before the next train comes.

As a programmer, I don't really see the benefit of using an embedded
interpreter on the iPhone.  Objective-C isn't the greatest language, but
it's easy to learn and well supported.  It also compiles into some
pretty speedy executables.

If you can sacrifice a little run-time speed for your users in exchange
for ease of development on your part, all the more to you.

My original point was that I don't see the benefit in that decision.


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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Stef Mientki



So, the question is, can the same thing be done for Python apps?



I love Python and all, but it'd be apt to ask, what's the point?

The iPhone is running on what? A 400Mhz ARM processor? Resources on the
device are already limited; running your program on top of an embedded
Python interpreter would only be adding pressure to the constraints;
even if it was an optimized interpreter.
  

I don't know iPhone,
but I've done some experiments with 400 MHz arm, running Windows Mobile,
and found PocketPyGUI running very very well on these devices.

cheers,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


RE: A Bug By Any Other Name ...

2009-07-07 Thread Phil Runciman

-Original Message-
From: Dennis Lee Bieber [mailto:wlfr...@ix.netcom.com] 
Sent: Tuesday, 7 July 2009 4:45 p.m.
To: python-list@python.org
Subject: Re: A Bug By Any Other Name ...

On Mon, 6 Jul 2009 19:48:39 -0700, Daniel Fetchinson
 declaimed the following in
gmane.comp.python.general:

> Yes, there are plenty of languages other than Java and C, but the
> influence of C is admittedly huge in Python. Why do you think loops
> are called "for", conditionals "if" or "while", functions return via
> "return", loops terminate via "break" and keep going via "continue"
> and why is comparison written as "==", etc, etc? All of these are
> coming from C (or an even earlier language) and my point is that users

for, if, and return were common keywords in FORTRAN.

Not to mention BASIC

Both of which predate C

-- 
__

Guido was probably influenced by the ALGOL language stream, which used "for" 
and "if". ALGOL 60 was a joint American and European effort and was significant 
in the late 50s and 60's.

Guido's fellow countryman, Edsgar Dijkstra, took this publication language (the 
ALGOL60 version) and produced a compiler for it. (It was not the first, but was 
very early on). Then B. Randell and L.J. Russell visited him, learnt from his 
experiences and returned to the UK to produce the KDF9 Whetstone ALGOL60 
Compiler. Their book "ALGOL 60 Implementation" was a very early and influential 
book in the field and occupies a significant place in the history of computing. 
Computer language designers, including Nicholas Wirth (Pascal, Modula, Oberon), 
have been influenced by ALGOL.

Sadly, "C" and its ilk, come from a totally different stream of language 
development beginning with the likes of "CPL", "BCPL", "B" and developing into 
"C" and "C++". This stream was originally focussed on language portability and 
performance. This stream was much closer to the assembler language end of the 
language spectrum, whereas the other stream was heavily biased towards 
publication and later teaching. 

I could say more but will restrain myself.

My 2c 

Phil

FWIW "++" reeks of assembler language notation.

The KDF9 Whetstone ALGOL60 Compiler was the one I used at Whetstone for 
1-Dimensional Transient Heat-Flow calculations and Steam-Table generation. Our 
course on it was 2.5 days long. We had wonderful training by English Electric, 
Kidsgrove staff. I hate to think how long the same course would be now, a 
month? 

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


Re: tough-to-explain Python

2009-07-07 Thread norseman

Bearophile wrote:

kj, as Piet van Oostrum as said, that's the difference between mutable
an immutable. It comes from the procedural nature of Python, and
probably an explanation of such topic can't be avoided if you want to
learn/teach Python.

...(snip)


See you later,
bearophile


==Perhaps because it is the way I learned or the 
way I "naturally" approach programming, or maybe the way one influences 
the other, but at any rate I think "newbies" to programming should first 
learn a few basic concepts (if/then, for, while, do and other loops and 
other control constructs) and then be forced to deal with the computer 
on it's own terms. Assembly. Once the student learns what the computer 
already knows, that the whole thing is just bits and the combination of 
them determines it's responses, it then becomes easier to present 
'idealistic' concepts and their implementations.  With the knowledge and 
'mental picture' of the computer's nature the rest of the ideas for 
programming have a tendency to drift in the direction of reality and the 
underlying needs to fulfill the 'better' and/or 'easier' languages. 
Having both the knowledge of the 'full capabilities' of a computer and 
the experience of a formalized language the student can, or should, 
learn/compare the trade offs of each.  By understanding the computer (I 
at least) grasp the basics of a new language quite quickly. No, I don't 
become a guru overnight, if at all, but I do have the advantage in 
deciding if a given language is appropriate for a given job with very 
little research.


The more I delve into OOP the more I liken an 'object' to a box. A box 
with a shipping manifest.


There are big boxes,
little boxes,
squat boxes and so on.

A box can contain corn flakes,
bullets, raisins, rice, burlap, silk, motorcycle(s), soap and more.

The manifest describes contents.
The manifest is there but the description(s) change with content (type).
The descriptions always use one or more of the basics like: color, 
count, dimension and so forth.


Just like an OOP object.

A box can contain things of all sorts, including references to the 
contents of other box(es). A box can even be a virtual of another (the 
global concept).  The return statement, in this context, means hauling 
the contents of the box (and/or its manifest) back to (wherever) and 
disposing of the current box (a local).


Just like an OOP object.


It is easier to visualize a box and it's use than a non described blob.
Abstracts are never precise -  hence the evolution of the word.


The one thing a teacher will always fail is the same as anyone else who 
tries to adequately describe a pretty sunset to a person born totally 
blind. No point(s) of reference.




Time for me to sign off.  To all those that helped me when I needed it -

I thank you very much.

Food for thought: your watch (clock) does not tell time.
The watch (clock) only mimics one movement of the earth.
ie... 3 dimensions are still static, the 4th is movement.


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


Re: Python Error from Apress book

2009-07-07 Thread Gabriel Genellina

En Tue, 07 Jul 2009 09:55:13 -0300, Dave Angel  escribió:

Gabriel Genellina wrote:
En Mon, 06 Jul 2009 19:56:40 -0300, matt0177   
escribió:



When I try to run the command as outlined in
the book "simple_markup2.py < test_input.txt > test_output.html i get  
the

following error every time.

IOError: [Errno 9] Bad file descriptor


That's a Windows problem. When you execute the script as itself (either  
as you do in the command line, or by double-clicking on it), it doesn't  
have valid standard handles.

You have to invoke Python explicitely:

python simple_markup2.py < test_input.txt > test_output.html

(you may need to specify the full path to python.exe, or add the  
directory where Python is installed to your system PATH).


I use stdout this way all the time, with no problem (python 2.6, Windows  
XP).  But as you point out, stdin redirection doesn't seem to work using  
the file associations.  I do get a different error though. When I look  
at sys.stdin, it shows an open file, with handle of zero, as expected.   
But when I do a raw_input(), it gets:

 EOFError: EOF when reading a line


I think the error depends on the specific OS version/service pack. But at  
least on XP this appears to fix it:


http://support.microsoft.com/kb/321788/en-us

--
Gabriel Genellina

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


Re: Python and webcam capture delay?

2009-07-07 Thread Nobody
On Tue, 07 Jul 2009 09:01:39 +0300, jack catcher (nick) wrote:

> Thanks for the comments. Unfortunately, such specifications aren't easy 
> to find, even in reviews. Fortunately several newer webcams seem at 
> least to use usb2.

Supporting USB-2 doesn't mean that the camera necessarily uses high-speed
(480Mbit/sec).

AFAIK, the only real difference between "USB-1 conformant" and "USB-2
conformant" is that the latter actually passed a test of its ability to
say "no, I can't do high-speed", while the former didn't. The check for
high-speed capability was designed such that it shouldn't cause problems
for USB-1 devices, but individual USB-1 devices weren't actually tested
for this.

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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread python
> If you do write the interpreter, let me know. I would certainly experiment 
> with it.

+2 over here!

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


Re: finding most common elements between thousands of multiple arrays.

2009-07-07 Thread Andrew Henshaw

"mclovin"  wrote in message 
news:c5332c9b-2348-4194-bfa0-d70c77107...@x3g2000yqa.googlegroups.com...
> Currently I need to find the most common elements in thousands of
> arrays within one large array (arround 2 million instances with ~70k
> unique elements)
>
> so I set up a dictionary to handle the counting so when I am
> iterating  I up the count on the corrosponding dictionary element. I
> then iterate through the dictionary and find the 25 most common
> elements.
>
> the elements are initially held in a array within an array. so I am am
> just trying to find the most common elements between all the arrays
> contained in one large array.
> my current code looks something like this:
> d = {}
> for arr in my_array:
> -for i in arr:
> #elements are numpy integers and thus are not accepted as dictionary
> keys
> ---d[int(i)]=d.get(int(i),0)+1
>
> then I filter things down. but with my algorithm that only takes about
> 1 sec so I dont need to show it here since that isnt the problem.
>
>
> But there has to be something better. I have to do this many many
> times and it seems silly to iterate through 2 million things just to
> get 25. The element IDs are integers and are currently being held in
> numpy arrays in a larger array. this ID is what makes up the key to
> the dictionary.
>
> It currently takes about 5 seconds to accomplish this with my current
> algorithm.
>
> So does anyone know the best solution or algorithm? I think the trick
> lies in matrix intersections but I do not know.

Would the following work for you, or am I missing something?  For a 5Kx5K 
array, this takes about a tenth of a second on my machine.  This code 
doesn't deal with the sub-array issue.

#
import numpy
import time

LOWER = 0
UPPER = 1024
SIZE = 5000
NUM_BEST = 4

# sample data
data = numpy.random.randint(LOWER, UPPER, (SIZE,SIZE)).astype(int)

time.clock()
count = numpy.bincount(data.flat)
best = sorted(zip(count, range(len(count[-NUM_BEST:]
print 'time=', time.clock()
print best



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


Re: tough-to-explain Python

2009-07-07 Thread Bearophile
kj, as Piet van Oostrum as said, that's the difference between mutable
an immutable. It comes from the procedural nature of Python, and
probably an explanation of such topic can't be avoided if you want to
learn/teach Python.

Lot of people think that a language where everything is immutable is
simpler for newbies to understand (even if they have to learn what
higher-order functions are). That's why some people think Scheme or
other languages (even Clojure, I guess) are better for novices (Scheme
has mutability, but you can avoid showing it to newbies).

Some people say that languages that mostly encourage the use of
immutable data structures (like F#, Clojure, Scala and many other less
modern ones) help avoid bugs, maybe for novices too.

On the other hand, it's hard or impossible to actually remove
complexity from a system, and you usually just move it elsewhere. So
other things will become harder to do for those novices. I have no
idea if for the average novice it's simpler to learn to use a
immutables-based language instead of a mutables-based one (it can also
be possible that some novices prefer the first group, and other
novices prefer the second group).

>From what I have seen lot of students seem able to learn Python, so
it's not a bad choice.

Python isn't perfect, and in *many* situations it is pragmatic, for
example to increase its performance. Generally for a novice programmer
running speed is not important, but it's important to have a really
coherent and clean language. I've personally seen that for such people
even Python looks very "dirty" (even if it's one of the less dirty
ones).

For example a novice wants to see 124 / 38 to return the 62/19
fraction and not 3 or 3.263157894736842 :-)

People may be able to invent a clean and orthogonal language that's
easy to use and has very few compromises, fit for newbies. But this
language may be very slow, not much useful in practice (who knows?
Maybe there's a practical niche even for such very high level
language), and it doesn't teach how to use lower level languages like
C :-)

Today I think there are no languages really fit for teaching. Python
is one of the few fit ones, but it's getting more and more complex as
time passes because it's getting used in more and more complex real
world situations (a language fit for newbies must not have abstract
base classes, decorators, etc). D language is too much complex for a
newbie. Java is not too much bad, but it's requires to write too much
code, it's too much fussy (semicolons at the end of lines? Newbies say
that the computer is an idiot when it refuses code just because
there's a missing useless semicolon!), and it misses some necessary
things (first class functions! Damn). A nice language like Boo running
on the Mono VM seems another option :-)

In the past Pascal was good enough, but I think it's not good enough
anymore. The problem is that teaching is a niche activity (even if a
very important one). PLT Scheme is one of the few environments (beside
Squeak, Python itself, and little more) that look refined and
implemented well enough for such purpose.

See you later,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread J Kenneth King
Dr Mephesto  writes:

> Sure, I am learning Objective C already, but the syntax is really
> unfriendly after python.
>
> I think it really depends on the type of app you want to write.
> Anything held back by network delays or that sits around waiting for
> user input are perfectly acceptable target apps. If you need speed for
> something really intensive, falling back to C is still much nicer than
> coding in Objective C. I agree that having a certain basic
> understanding of objective C is a must, but having the option to use a
> coder-friendly language like Ruby or Python can cut development time
> dramatically.
>
> If Ruby can do it (and it generally slower than python), why can
> Python also get a legal iPhone interpreter?

It can if you want to write the interpreter.

I just don't see the point.

I can understand wanting a higher level language than assembler or maybe
even C, but that's precisely what Objective-C is.

Unfortunately, while the hardware for these mobile platforms is getting
better these days, it's still not where it needs to be to run programs
written in interpreted languages, IMO.  Users typically only interact
with an app for around two minutes at a time.  Your app needs to be as
fast as it can be.  It's one of the few areas of software development
today where optimizations can be justified (the other are games and
scientific computing).

Trust me, if there were an SMS app for the iPhone that loaded faster
than the one that ships with it, guaranteed it would sell like hot-cakes
(if Apple would let it in the store of course).

If you do write the interpreter, let me know.  I would certainly
experiment with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DBI module deprecated at Python 2.5--what to use in its place?

2009-07-07 Thread Kevin Dwyer
Hello,

I think this is discussed PEP 249 - see the "major changes" section.

http://www.python.org/dev/peps/pep-0249/

Kev

On Tue, 07 Jul 2009 10:05:07 -0700, dana wrote:

> I have a variety of Python 2.4 scripts that utilitize the DBI and ODBC
> modules together. Although I don't have Python 2.5, I've been informed
> the DBI module has been deprecated at 2.5. A few questions:
> 
> 1) Although deprecated, will it work at all in 2.5? Does the fact that
> it is deprecrated mean it has been removed entirely, or does Python 2.5
> simply issuing a warning?
> 
> 2) What do I use in place of DBI for my Python 2.4. scripts that import
> modules DBI and ODBC together. I don't use DBI directly. It was simply a
> dependency for the ODBC module as best I knew.
> 
> Thanks.
> 
> Dana


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


Re: tough-to-explain Python

2009-07-07 Thread kj
In  Chris Rebert 
 writes:

>You might find the following helpful (partially):
>http://effbot.org/zone/call-by-object.htm


Extremely helpful.  Thanks!  (I learned more from it than someone
who will teach the stuff would care to admit...)

I had not realized how *profoundly* different the meaning of the
"=" in Python's

  spam = ham

is from the "=" in its

  spam[3] = ham[3]

So much for "explicit is better than implicit"...


And it confirmed Paul Graham's often-made assertion that all of
programming language design is still catching up to Lisp...

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


Re: tough-to-explain Python

2009-07-07 Thread kj
In  Piet van Oostrum  writes:

>> kj  (k) wrote:

>>k> I'm having a hard time coming up with a reasonable way to explain
>>k> certain things to programming novices.

>>k> Consider the following interaction sequence:

>> def eggs(some_int, some_list, some_tuple):
>>k> ... some_int += 2
>>k> ... some_list += [2]
>>k> ... some_tuple += (2,)
>>k> ...
>> x = 42
>> y = (42,) 
>> z = [42] 
>> eggs(x, y, z)
>> x
>>k> 42
>> y
>>k> (42,)
>> z
>>k> [42, 2] 
>> 

>>k> How do I explain to rank beginners (no programming experience at
>>k> all) why x and y remain unchanged above, but not z?

>You shouldn't. That's not for beginners.

No, of course not.  And I don't plan to present these examples to
them.  But beginners have a way of bumping into such conundrums
all on their own, and, as a former beginner myself, I can tell you
that they find them, at best, extremely frustrating, and at worst,
extremely discouraging.  I doubt that an answer of the form "don't
worry your pretty little head over this now; wait until your second
course" will do the trick.

Thanks for your comments!

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


Re: Opening a SQLite database in readonly mode

2009-07-07 Thread Joshua Kugler
Roger Binns wrote:
> Joshua Kugler wrote:
>> BTW, APSW is written by the same author as pysqlite.
> Not even remotely true :-)

Sorry about that...since pysqlite and APSW are both discusses on the
pysqlite list, I had made an incorrect assumption. Oops.

j

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


Re: tough-to-explain Python

2009-07-07 Thread Piet van Oostrum
> kj  (k) wrote:

>k> I'm having a hard time coming up with a reasonable way to explain
>k> certain things to programming novices.

>k> Consider the following interaction sequence:

> def eggs(some_int, some_list, some_tuple):
>k> ... some_int += 2
>k> ... some_list += [2]
>k> ... some_tuple += (2,)
>k> ...
> x = 42
> y = (42,) 
> z = [42] 
> eggs(x, y, z)
> x
>k> 42
> y
>k> (42,)
> z
>k> [42, 2] 
> 

>k> How do I explain to rank beginners (no programming experience at
>k> all) why x and y remain unchanged above, but not z?

You shouldn't. That's not for beginners. Leave it waiing until you get
to the advanced level.

>k> Or consider this one:

> ham = [1, 2, 3, 4]
> spam = (ham,)
> spam
>k> ([1, 2, 3, 4],)
> spam[0] is ham
>k> True
> spam[0] += [5]
>k> Traceback (most recent call last):
>k>   File "", line 1, in 
>k> TypeError: 'tuple' object does not support item assignment
> ham += [5]
> spam
>k> ([1, 2, 3, 4, 5, 5],)
> 

>k> What do you say to that?

Mutable and immutable. But use different examples. Like

ham = [1, 2, 3, 4]
spam = (1, 2, 3, 4)

spam[0] += 1 will give the same error message. You can't change the
components of a tuple.

Your example above is similar. The spam[0] += [5] appends the 5 to the
list in spam[0] (so it appends to ham), and then tries to assign the
result of it to spam[0], which is not allowed. That the item it tries to
assign is the same as the item that was already there doesn't matter.

So dont't forget += is a real assignment, even when it is an in-place
modification.  Your example just proves that. The language ref manual
says:

With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments.

But I think that your example isn't for beginners either.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem reading file with umlauts

2009-07-07 Thread MRAB

Claus Hausberger wrote:

Thanks a lot. Now I am one step further but I get another strange error:

Traceback (most recent call last):
  File "./read.py", line 12, in 
of.write(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 
0: ordinal not in range(128)

according to google ufeff has something to do with byte order.

I use an Linux system, maybe this helps to find the error.


'text' contains Unicode, but you're writing it to a file that's not
opened for Unicode. Either open the output file for Unicode:

of = codecs.open("umlaut-out.txt", "w", encoding="latin1")

or encode the text before writing:

text = text.encode("latin1")

(I'm assuming you want the output file to be in Latin1.)




Claus Hausberger wrote:


I have a text file with is encoding in Latin1 (ISO-8859-1). I can't
change that as I do not create those files myself. I have to read
those files and convert the umlauts like ö to stuff like &oumol; as
the text files should become html files.

umlaut-in.txt:

This file is contains data in the unicode
character set and is encoded with utf-8.
Viele Röhre. Macht spaß!  Tsüsch!


umlaut-in.txt hexdump:

00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
20: 65 20 75 6E 69 63 6F 64  65 0D 0A 63 68 61 72 61 e unicode..chara
30: 63 74 65 72 20 73 65 74  20 61 6E 64 20 69 73 20 cter set and is
40: 65 6E 63 6F 64 65 64 20  77 69 74 68 20 75 74 66 encoded with utf
50: 2D 38 2E 0D 0A 56 69 65  6C 65 20 52 C3 B6 68 72 -8...Viele R..hr
60: 65 2E 20 4D 61 63 68 74  20 73 70 61 C3 9F 21 20 e. Macht spa..!
70: 20 54 73 C3 BC 73 63 68  21 0D 0A 00 00 00 00 00  Ts..sch!...


umlaut.py:

# -*- coding: utf-8 -*-
import codecs
text=codecs.open("umlaut-in.txt",encoding="utf-8").read()
text=text.replace(u"ö",u"oe")
text=text.replace(u"ß",u"ss")
text=text.replace(u"ü",u"ue")
of=open("umlaut-out.txt","w")
of.write(text)
of.close()


umlaut-out.txt:

This file is contains data in the unicode
character set and is encoded with utf-8.
Viele Roehre. Macht spass!  Tsuesch!


umlaut-out.txt hexdump:

00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
20: 65 20 75 6E 69 63 6F 64  65 0D 0D 0A 63 68 61 72 e unicode...char
30: 61 63 74 65 72 20 73 65  74 20 61 6E 64 20 69 73 acter set and is
40: 20 65 6E 63 6F 64 65 64  20 77 69 74 68 20 75 74  encoded with ut
50: 66 2D 38 2E 0D 0D 0A 56  69 65 6C 65 20 52 6F 65 f-8Viele Roe
60: 68 72 65 2E 20 4D 61 63  68 74 20 73 70 61 73 73 hre. Macht spass
70: 21 20 20 54 73 75 65 73  63 68 21 0D 0D 0A 00 00 !  Tsuesch!.





--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html




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


Re: ISO library ref in printed form

2009-07-07 Thread Piet van Oostrum
> kj  (kj) wrote:

>kj> Does anyone know where I can buy the Python library reference in
>kj> printed form?  (I'd rather not print the whole 1200+-page tome
>kj> myself.)  I'm interested in both/either 2.6 and 3.0.

Maybe you can have a copy printed at lulu.com. It would even be nicer if
the PSF would offer them at lulu. They could even make some money from
it if enough copies would be sold..
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO library ref in printed form

2009-07-07 Thread Diez B. Roggisch

kj schrieb:

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


In article , kj   wrote:

Does anyone know where I can buy the Python library reference in
printed form?  (I'd rather not print the whole 1200+-page tome
myself.)  I'm interested in both/either 2.6 and 3.0.



There used to be one for Python 2.1, but I can't tell whether it's ever
been updated because the website isn't responding:



http://wiki.python.org/moin/ReferenceBooks


Hmmm.  That's a shame.  How is one supposed to keep it under one's
pillow???



That's what netbooks were created for...

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


Re: tough-to-explain Python

2009-07-07 Thread Chris Rebert
On Tue, Jul 7, 2009 at 1:04 PM, kj wrote:
>
>
> I'm having a hard time coming up with a reasonable way to explain
> certain things to programming novices.
>
> Consider the following interaction sequence:
>
 def eggs(some_int, some_list, some_tuple):
> ...     some_int += 2
> ...     some_list += [2]
> ...     some_tuple += (2,)
> ...
 x = 42
 y = (42,)
 z = [42]
 eggs(x, y, z)
 x
> 42
 y
> (42,)
 z
> [42, 2]

>
> How do I explain to rank beginners (no programming experience at
> all) why x and y remain unchanged above, but not z?
>
> Or consider this one:
>
 ham = [1, 2, 3, 4]
 spam = (ham,)
 spam
> ([1, 2, 3, 4],)
 spam[0] is ham
> True
 spam[0] += [5]
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
 ham += [5]
 spam
> ([1, 2, 3, 4, 5, 5],)

>
> What do you say to that?
>
> I can come up with much mumbling about pointers and stacks and
> heaps and much hand-waving about the underlying this-and-that, but
> nothing that sounds even remotely illuminating.
>
> Your suggestions would be much appreciated!

You might find the following helpful (partially):
http://effbot.org/zone/call-by-object.htm

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


Re: Check file is locked?

2009-07-07 Thread Christian Heimes
dudeja.ra...@gmail.com wrote:
> How to check if a particular file is locked by some application? (i.e. the
> file is opened by some application)?

It depends on your operating system. By the way most operating systems
don't lock a file when it's opened for reading or writing or even executed.

Christian

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


Re: library search path when compiling python

2009-07-07 Thread Christian Heimes
nn wrote:
> I am trying to compile python with ssl support but the libraries are
> not in /usr/lib but in /opt/freeware/lib. How do I add that folder to
> the default library search path?
> 
> It looks like configure --libdir=DIR might do the job but I don't want
> to replace the default lib search path, just add an additional folder
> to it.

You didn't mention your OS. On Linux you can set the environment
variable LD_RUN_PATH prior to compiling Python. The env var sets the
rpath for the linker. See man ld(1) for details.

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


tough-to-explain Python

2009-07-07 Thread kj


I'm having a hard time coming up with a reasonable way to explain
certain things to programming novices.

Consider the following interaction sequence:

>>> def eggs(some_int, some_list, some_tuple):
... some_int += 2
... some_list += [2]
... some_tuple += (2,)
...
>>> x = 42
>>> y = (42,) 
>>> z = [42] 
>>> eggs(x, y, z)
>>> x
42
>>> y
(42,)
>>> z
[42, 2] 
>>> 

How do I explain to rank beginners (no programming experience at
all) why x and y remain unchanged above, but not z?

Or consider this one:

>>> ham = [1, 2, 3, 4]
>>> spam = (ham,)
>>> spam
([1, 2, 3, 4],)
>>> spam[0] is ham
True
>>> spam[0] += [5]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> ham += [5]
>>> spam
([1, 2, 3, 4, 5, 5],)
>>> 

What do you say to that?

I can come up with much mumbling about pointers and stacks and
heaps and much hand-waving about the underlying this-and-that, but
nothing that sounds even remotely illuminating.

Your suggestions would be much appreciated!

TIA!

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


library search path when compiling python

2009-07-07 Thread nn
I am trying to compile python with ssl support but the libraries are
not in /usr/lib but in /opt/freeware/lib. How do I add that folder to
the default library search path?

It looks like configure --libdir=DIR might do the job but I don't want
to replace the default lib search path, just add an additional folder
to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO library ref in printed form

2009-07-07 Thread kj
In  Scott David Daniels 
 writes:

>Also consider grabbing Gruet's "Python Quick Reference" page.

Not quite what I had in mind, but handy all the same.  Thanks.

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


Re: ISO library ref in printed form

2009-07-07 Thread kj
In  a...@pythoncraft.com (Aahz) writes:

>In article , kj   wrote:
>>
>>Does anyone know where I can buy the Python library reference in
>>printed form?  (I'd rather not print the whole 1200+-page tome
>>myself.)  I'm interested in both/either 2.6 and 3.0.

>There used to be one for Python 2.1, but I can't tell whether it's ever
>been updated because the website isn't responding:

>http://wiki.python.org/moin/ReferenceBooks

Hmmm.  That's a shame.  How is one supposed to keep it under one's
pillow???

kj

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


Check file is locked?

2009-07-07 Thread dudeja . rajat
How to check if a particular file is locked by some application? (i.e. the
file is opened by some application)?

-- 
Regrads,
Rajat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Error from Apress book

2009-07-07 Thread Dave Angel

Matthew Edmondson wrote:

Thanks a ton for the help. At first adding the path didn't work, but after
restarting my computer, ran like a champ :)

Hopefully I can get decent with this language one day!

  
All you needed was to restart the DOS-box (Command Prompt), after you 
did the control-panel thing.  Those changes don't affect currently 
running processes.


.
By the way, those "standalone executables" could very well be python 
scripts.  Except for input redirection, all my single-file scripts work 
fine stored there.  And if you add  .py and .pyw to the PATHEXT 
environment variable, you can run them without extension, so they're 
pretty much interchangeable with .exe files.


So I have a script called digest.py, and I run it from a directory I 
want to analyze, by just typing

   digest  .


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


Re: Clarity vs. code reuse/generality

2009-07-07 Thread pdpi
On Jul 7, 8:04 pm, Dave Angel  wrote:
> And of course your clarified function will fail if the func is
> monotonically decreasing.

yeah, I eventually realized that and corrected it... And the assert()/
cmp() confusion too. I blame lack of sleep.

The whole sign/sense thing left a really bad taste in my mouth,
though, and the swapping lo and hi suggestion of yours seems like the
neatest solution presented.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Dave Angel

pdpi wrote:

On Jul 7, 2:16 am, Steven D'Aprano  wrote:
  

On Mon, 06 Jul 2009 16:43:43 +0100, Tim Rowe wrote:


2009/7/4 kj :
  

Precisely.  As I've stated elsewhere, this is an internal helper
function, to be called only a few times under very well-specified
conditions.  The assert statements checks that these conditions are as
intended.  I.e. they are checks against the module writer's programming
errors.


Good for you. I'm convinced that you have used the assertion
appropriately, and the fact that so many here are unable to see that
looks to me like a good case for teaching the right use of assertions.
For what it's worth, I read assertions at the beginning of a procedure
as part of the specification of the procedure, and I use them there in
order to document the procedure. An assertion in that position is for me
a statement to the user of the procedure "it's your responsibility to
make sure that you never call this procedure in such a way as to violate
these conditions". They're part of a contract, as somebody (maybe you)
pointed out.
  
As somebody who works in the safety-critical domain, it's refreshing to

see somebody teaching students to think about the circumstances in which
a procedure can legitimately be called. The hostility you've received to
that idea is saddening, and indicative of why there's so much buggy
software out there.
  

LOL.

Maybe the reason for "so much buggy software" is that people
inappropriately use assert, thus changing the behaviour of code depending
on whether it is run with the -O flag or not.

I don't know what "hostility" you're seeing. The only hostility I'm
seeing is from the OP, which is bizarre considering that he asked for
advice and we gave it. What I see is a bunch of people concerned that the
OP is teaching novices a bad habit, namely, using assert for error
checking. He claims -- angrily and over and over again -- that in his
code, the assertions should never fail. Great. Good for him for knowing
when to use assert. (...)



But he doesn't.

He asserts:
assert lo < hi
but then compares:
sense =mp(func(hi), func(lo))

sense can't ever be anything other than 1. I actually find it amusing
that this threat got to 50 posts of raving discussion about assertions
without anyone spotting that.

  
That's because the assert and the comparison are unrelated to each 
other.  If the function is monotonically decreasing, then by definition 
lo= func(hi), which would yield a 
sense of 0 or -1.


Trivial example of monotonically decreasing:
   def func(inp):
return 53.0 - inp


Personally, I think the code is an unreadable mess, but that's mostly
because of all the micro optimizations, not the generality of it.
Here's my unoptimized, but still equally generic, version:

def _binary_search(lo, hi, func, target, epsilon):
sense =mp(func(hi), func(lo))
if sense =0:
return None
guess =lo + hi) / 2.
while abs(func(guess) - target) > epsilon:
guess =lo + hi) / 2.
if func(guess) > target:
hi =uess
elif func(guess) < target:
lo =uess
elif lo =hi:
return None
return guess

  
And of course your clarified function will fail if the func is 
monotonically decreasing.


I still think that rather than using sense in the loop, one should 
simply swap lo and hi, and continue.

This is a newbie course, right? A while True loop might be faster, but
it's all sorts of wrong for teaching newbies. Likewise, calculating a
midpoint as mid =hi + lo) * .5 is an aberration in a beginner
environment. You want your students asking why you're calculating an
average, not asking why you're multiplying by 0.5. In the same vein, I
have no words for your target_plus/target_minus cleverness.

The right way to go about it, IMO, is to give them my version, let
them digest it, make all the necessary changes to it to turn it into
your (faster) version. Present benchmarks for both, then let the
readability/performance trade-off sink in. What you achieve with this
exercise is that, instead of making your students think "I have to
read that crud!?", they'll respect that ugly code is often the result
of eking out every last drop of performance from a program as you
possibly can.

  

(untested)

def _binary_search(lo, hi, func, target, epsilon):
   """ lo, hi  are floats representing the desired range of input values to 
func()
   func() is a function that takes a float argument, and returns a float 
result
   target is the desired result value of func()
   epsilon is the allowable error compared to target.  If set too small, 
this function will fail by returning None
   precondition:  func is monotonic over the range of floating point inputs from lo to hi 
"""
   return a float value between lo and hi (inclusive) which yields 
approximately target
   if func(lo) > func(hi):
   lo, hi = hi, lo
   if not (func(lo) <= target <= func(hi)):
   return N

Re: Problem reading file with umlauts

2009-07-07 Thread Claus Hausberger
Thanks a lot. Now I am one step further but I get another strange error:

Traceback (most recent call last):
  File "./read.py", line 12, in 
of.write(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 
0: ordinal not in range(128)

according to google ufeff has something to do with byte order.

I use an Linux system, maybe this helps to find the error.

Claus

> Claus Hausberger wrote:
> 
> > I have a text file with is encoding in Latin1 (ISO-8859-1). I can't
> > change that as I do not create those files myself. I have to read
> > those files and convert the umlauts like ö to stuff like &oumol; as
> > the text files should become html files.
> 
> umlaut-in.txt:
> 
> This file is contains data in the unicode
> character set and is encoded with utf-8.
> Viele Röhre. Macht spaß!  Tsüsch!
> 
> 
> umlaut-in.txt hexdump:
> 
> 00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
> 10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
> 20: 65 20 75 6E 69 63 6F 64  65 0D 0A 63 68 61 72 61 e unicode..chara
> 30: 63 74 65 72 20 73 65 74  20 61 6E 64 20 69 73 20 cter set and is
> 40: 65 6E 63 6F 64 65 64 20  77 69 74 68 20 75 74 66 encoded with utf
> 50: 2D 38 2E 0D 0A 56 69 65  6C 65 20 52 C3 B6 68 72 -8...Viele R..hr
> 60: 65 2E 20 4D 61 63 68 74  20 73 70 61 C3 9F 21 20 e. Macht spa..!
> 70: 20 54 73 C3 BC 73 63 68  21 0D 0A 00 00 00 00 00  Ts..sch!...
> 
> 
> umlaut.py:
> 
> # -*- coding: utf-8 -*-
> import codecs
> text=codecs.open("umlaut-in.txt",encoding="utf-8").read()
> text=text.replace(u"ö",u"oe")
> text=text.replace(u"ß",u"ss")
> text=text.replace(u"ü",u"ue")
> of=open("umlaut-out.txt","w")
> of.write(text)
> of.close()
> 
> 
> umlaut-out.txt:
> 
> This file is contains data in the unicode
> character set and is encoded with utf-8.
> Viele Roehre. Macht spass!  Tsuesch!
> 
> 
> umlaut-out.txt hexdump:
> 
> 00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
> 10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
> 20: 65 20 75 6E 69 63 6F 64  65 0D 0D 0A 63 68 61 72 e unicode...char
> 30: 61 63 74 65 72 20 73 65  74 20 61 6E 64 20 69 73 acter set and is
> 40: 20 65 6E 63 6F 64 65 64  20 77 69 74 68 20 75 74  encoded with ut
> 50: 66 2D 38 2E 0D 0D 0A 56  69 65 6C 65 20 52 6F 65 f-8Viele Roe
> 60: 68 72 65 2E 20 4D 61 63  68 74 20 73 70 61 73 73 hre. Macht spass
> 70: 21 20 20 54 73 75 65 73  63 68 21 0D 0D 0A 00 00 !  Tsuesch!.
> 
> 
> 
> 
> 
> -- 
> "The ability of the OSS process to collect and harness
> the collective IQ of thousands of individuals across
> the Internet is simply amazing." - Vinod Valloppillil
> http://www.catb.org/~esr/halloween/halloween4.html

-- 
Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate
für nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread pdpi
On Jul 7, 7:31 pm, pdpi  wrote:
> On Jul 7, 7:06 pm, Paul Rubin  wrote:
>
> > pdpi  writes:
> > > Personally, I think the code is an unreadable mess, but that's mostly
> > > because of all the micro optimizations, not the generality of it.
> > > Here's my unoptimized, but still equally generic, version:
>
> > That version doesn't use "sense" inside the binary search, i.e. it
> > relies on the function being monotonically increasing.
>
> You're right, make that:
>
> def _binary_search(lo, hi, func, target, epsilon):
>     sense = cmp(func(hi), func(lo))
>     if sense == 0:
>         return None
>     guess = (lo + hi) / 2.
>     while abs(func(guess) - target) > epsilon:
>         guess = (lo + hi) / 2.
>         if sense * func(guess) > target:
>             hi = guess
>         elif sense * func(guess) < target:
>             lo = guess
>         elif lo == hi:
>             return None
>     return guess
>
> Seems I had a serious brain cramp while posting that...

Actually, scratch that.

def _binary_search(lo, hi, func, target, epsilon):
sense = cmp(func(hi), func(lo))
if sense == 0:
return None
guess = (lo + hi) / 2.
while abs(func(guess) - target) > epsilon:
guess = (lo + hi) / 2.
if sense * func(guess) > sense * target:
hi = guess
elif sense * func(guess) < sense * target:
lo = guess
elif lo == hi:
return None
return guess
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread pdpi
On Jul 7, 7:06 pm, Paul Rubin  wrote:
> pdpi  writes:
> > Personally, I think the code is an unreadable mess, but that's mostly
> > because of all the micro optimizations, not the generality of it.
> > Here's my unoptimized, but still equally generic, version:
>
> That version doesn't use "sense" inside the binary search, i.e. it
> relies on the function being monotonically increasing.

You're right, make that:

def _binary_search(lo, hi, func, target, epsilon):
sense = cmp(func(hi), func(lo))
if sense == 0:
return None
guess = (lo + hi) / 2.
while abs(func(guess) - target) > epsilon:
guess = (lo + hi) / 2.
if sense * func(guess) > target:
hi = guess
elif sense * func(guess) < target:
lo = guess
elif lo == hi:
return None
return guess

Seems I had a serious brain cramp while posting that...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread pdpi
On Jul 7, 7:26 pm, Andre Engels  wrote:
> On Tue, Jul 7, 2009 at 8:01 PM, pdpi wrote:
> > He asserts:
> >    assert lo < hi
> > but then compares:
> >    sense = cmp(func(hi), func(lo))
>
> > sense can't ever be anything other than 1.
>
> It can - there is no necessity that func is monotonically increasing.
>
> --
> André Engels, andreeng...@gmail.com

Yes, I realized that as I was walking home.

In other news, some of you may be interested in my seminar in advanced
foot-in-mouth placement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Andre Engels
On Tue, Jul 7, 2009 at 8:01 PM, pdpi wrote:

> He asserts:
>    assert lo < hi
> but then compares:
>    sense = cmp(func(hi), func(lo))
>
> sense can't ever be anything other than 1.

It can - there is no necessity that func is monotonically increasing.

-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Paul Rubin
pdpi  writes:
> Personally, I think the code is an unreadable mess, but that's mostly
> because of all the micro optimizations, not the generality of it.
> Here's my unoptimized, but still equally generic, version:

That version doesn't use "sense" inside the binary search, i.e. it
relies on the function being monotonically increasing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where does setuptools live?

2009-07-07 Thread Inky 788
On Jul 7, 4:06 am, Chris Withers  wrote:
> David Lyon wrote:
>
> > What hasn't happened is enough testing of pypi packages and installing
> > with setuptools/pip/enstall from pypi.
>
> What needs testing?
>
> More important for me is which of these has the most active development
> community. How do we judge that?

Currently, distutils itself is being actively developed. More info
about this here: http://tarekziade.wordpress.com/

My (albeit anonymous) advice is: use distutils. Manually download
packages as-needed from PyPI and install manually using standard
distutils.

Read more about distutils here http://wiki.python.org/moin/Distutils
and of course in the Python docs.

If you want to contribute, my first guess would be that Tarek could
use help writing tests (but I don't know what distutils coverage looks
like at the moment).

When Tarek says, "For package installation that takes care of
dependencies, uninstall, etc., use $tool", then I'll start using
$tool. Until then, it's just straight distutils for me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread pdpi
On Jul 7, 2:16 am, Steven D'Aprano  wrote:
> On Mon, 06 Jul 2009 16:43:43 +0100, Tim Rowe wrote:
> > 2009/7/4 kj :
>
> >> Precisely.  As I've stated elsewhere, this is an internal helper
> >> function, to be called only a few times under very well-specified
> >> conditions.  The assert statements checks that these conditions are as
> >> intended.  I.e. they are checks against the module writer's programming
> >> errors.
>
> > Good for you. I'm convinced that you have used the assertion
> > appropriately, and the fact that so many here are unable to see that
> > looks to me like a good case for teaching the right use of assertions.
> > For what it's worth, I read assertions at the beginning of a procedure
> > as part of the specification of the procedure, and I use them there in
> > order to document the procedure. An assertion in that position is for me
> > a statement to the user of the procedure "it's your responsibility to
> > make sure that you never call this procedure in such a way as to violate
> > these conditions". They're part of a contract, as somebody (maybe you)
> > pointed out.
>
> > As somebody who works in the safety-critical domain, it's refreshing to
> > see somebody teaching students to think about the circumstances in which
> > a procedure can legitimately be called. The hostility you've received to
> > that idea is saddening, and indicative of why there's so much buggy
> > software out there.
>
> LOL.
>
> Maybe the reason for "so much buggy software" is that people
> inappropriately use assert, thus changing the behaviour of code depending
> on whether it is run with the -O flag or not.
>
> I don't know what "hostility" you're seeing. The only hostility I'm
> seeing is from the OP, which is bizarre considering that he asked for
> advice and we gave it. What I see is a bunch of people concerned that the
> OP is teaching novices a bad habit, namely, using assert for error
> checking. He claims -- angrily and over and over again -- that in his
> code, the assertions should never fail. Great. Good for him for knowing
> when to use assert. (...)

But he doesn't.

He asserts:
assert lo < hi
but then compares:
sense = cmp(func(hi), func(lo))

sense can't ever be anything other than 1. I actually find it amusing
that this threat got to 50 posts of raving discussion about assertions
without anyone spotting that.

Personally, I think the code is an unreadable mess, but that's mostly
because of all the micro optimizations, not the generality of it.
Here's my unoptimized, but still equally generic, version:

def _binary_search(lo, hi, func, target, epsilon):
sense = cmp(func(hi), func(lo))
if sense == 0:
return None
guess = (lo + hi) / 2.
while abs(func(guess) - target) > epsilon:
guess = (lo + hi) / 2.
if func(guess) > target:
hi = guess
elif func(guess) < target:
lo = guess
elif lo == hi:
return None
return guess

This is a newbie course, right? A while True loop might be faster, but
it's all sorts of wrong for teaching newbies. Likewise, calculating a
midpoint as mid = (hi + lo) * .5 is an aberration in a beginner
environment. You want your students asking why you're calculating an
average, not asking why you're multiplying by 0.5. In the same vein, I
have no words for your target_plus/target_minus cleverness.

The right way to go about it, IMO, is to give them my version, let
them digest it, make all the necessary changes to it to turn it into
your (faster) version. Present benchmarks for both, then let the
readability/performance trade-off sink in. What you achieve with this
exercise is that, instead of making your students think "I have to
read that crud!?", they'll respect that ugly code is often the result
of eking out every last drop of performance from a program as you
possibly can.
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedded Python : Why does thread lock here?

2009-07-07 Thread roschler
I have the Python Intepreter embedded in a Delphi (Object Pascal)
program.  In the Python script shown below, I have a module that
creates a thread object and starts it.  The thread's run() call calls
a function called deleteOutputVariables() declared at the module
level.  In my code's first incarnation the thread's run() call would
deadlock when trying to call the deleteOutputVariables() function
declared at Module level.  I would never see the statement
"(deleteOutputVariables) Top of Call" printed to the screen.  I now
know that I must periodically call join() with a very fast time-out to
keep Python threads happy, and that solved the problem.  However I am
curious as to why it deadlocked at the deleteOutputVariables() call?
Is it because deleteOutputVariables() is declared at the module level
or because that function deletes module level variables?  If so why?

The code with the relevant parts excerpted is shown below, hopefully
the indents hold up.

Thanks,
Robert



# MODULE: PythonThreadTest.py

# FUNCTION: Delete the variables given in the list.
def deleteOutputVariables(theModule, theOutputVariablesListOfNames):
try:
print "(deleteOutputVariables) Top of call."
for theOutputVariableName in theOutputVariablesListOfNames:
if theModule.__dict__.has_key(theOutputVariableName):
print "(Python::deleteOutputVariables) Deleting the
Output Variable named " + theOutputVariableName
del theModule.__dict__[theOutputVariableName]
except:
print "(deleteOutputVariables) Exception occurred."

# Import needed system modules
import sys, os
from threading import Thread

# - BEGIN: THREAD class to execute robodanceCommand()
class threadRun(Thread):
def __init__ (self, theJobID = None):
Thread.__init__(self)
self.jobCompleted = False
# def: __init__
def run(self):
try:
# NOTE ---> This is where the thread locks if I don't call
join(0.001) in
#  my DELPHI (not Python) loop that waits on the thread to
complete.  Once
#  theNewThread.join() is called, execution resumes in
#  deleteOutputVariables() and the thread completes.
deleteOutputVariables(Test_PYTHON, ["PyOut1"])

# Let others know we are done.
self.jobCompleted = True
except Exception, exc:
self.exceptionCaught = exc
# Let others know we are done.
self.jobCompleted = True
print("(Python::threadRun) Exception occurred.")
# end: try
# def: run()
# - END: THREAD to execute robodanceCommand()

theNewThread = None
theNewThread = threadRun("TestThread")
theNewThread.start()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Stefan Behnel
Lawrence D'Oliveiro wrote:
> I wonder how many people have been tripped up by the fact that
> 
> ++n
> 
> and
> 
> --n
> 
> fail silently for numeric-valued n.

I doubt that there are many. Plus, you misspelled them from the more obvious

n++

and

n--

which *do* fail with a SyntaxError. I think I faintly remember trying those
in my early Python days and immediately went for "+=" when I saw them fail
(as I had expected).

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


Write matrix to text file

2009-07-07 Thread Hanna Michelsen
Hi,

I'm working with both python and matlab at the moment and I was wondering if
there is an efficient way to take a 2-D array (of 1s and 0s) in python and
write it to a text file such that matlab will be able to create a sparse
matrix from it later.

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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Piet van Oostrum
> a...@pythoncraft.com (Aahz) (A) wrote:

>A> In article <85ljn0ej4h@agentultra.com>,
>A> J Kenneth King   wrote:
>>> 
>>> The iPhone is running on what? A 400Mhz ARM processor? Resources on the
>>> device are already limited; running your program on top of an embedded
>>> Python interpreter would only be adding pressure to the constraints;
>>> even if it was an optimized interpreter.

>A>   Ten years ago, a 400MHz ARM processor would have been
>A> fast, and it would have been running Python 1.5.2.

My first Python experience at home was on a 40MHz 80486 (Python 1.5.2 I
think). It was a bit slow :=(
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to get Tkinter menubar to appear under OS X

2009-07-07 Thread weforgottenuno
I'm having the same problem, though I am just using the pre-installed
python and tkinter versions that are on my OS X 10.5 computer, I did
not install them on my own. Any advice?

-Doug

On Jun 24, 9:22 am, Eric Winter  wrote:
> Hi all. I've googled this issue several times and come up dry. Here's
> the situation:
>
> I have a X-windows build of Tkinter for Python built on an OS X
> machine (10.4 or 10.5, same issue). This is not the Aqua version of
> Tk, but Tk built from source using X-Window support. I also use a from-
> source build of Python, not the system Python. I don't like this
> arrangement, but project requirements (allegedly) dictate this
> approach.
>
> When I run any application using that copy of Tkinter and that copy of
> Python, everything seems to work fine except menus - the code which
> creates the menus runs, but no menus appear, either in the window or
> at the top of the screen.
>
> Am I required to use the Aqua version of Tk on OS X? If not, do I need
> to do something special on OS X when I built Tk and/or Python? Any
> hints here would be greatly appreciated.
>
> Thanks,
> Eric Winter
> Fermi Science Support Center
> NASA Goddard Space Flight Center

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


Re: A Bug By Any Other Name ...

2009-07-07 Thread MRAB

Daniel Fetchinson wrote:

and my point is that users
are most of time correct when they assume that something will work the
same way as in C.

Oh, really ? They would surely be wrong if they'd expect the for loop to
have any similarity with a C for loop, or - a *very* common error - if
they'd expect assignment to work the same way as in C.


By the way, assignments in conditionals. Guido explicitly referred to
C when he forbade assignment in conditionals, citing common
typos/errors in C code such as if( x = 5 ){  } instead of if( x ==
5 ){ . }. So even he realized that warning people about different
usage in python and C is a good thing. Expectations from C work
sometimes, and sometimes they don't. In latter case a little warning
is useful.


I wonder whether the problem with assignment in conditionals in C is due
to the assignment operator being "=". If it was ":=", would the error
still occur?
--
http://mail.python.org/mailman/listinfo/python-list


DBI module deprecated at Python 2.5--what to use in its place?

2009-07-07 Thread dana
I have a variety of Python 2.4 scripts that utilitize the DBI and ODBC
modules together. Although I don't have Python 2.5, I've been informed
the DBI module has been deprecated at 2.5. A few questions:

1) Although deprecated, will it work at all in 2.5? Does the fact that
it is deprecrated mean it has been removed entirely, or does Python
2.5 simply issuing a warning?

2) What do I use in place of DBI for my Python 2.4. scripts that
import modules DBI and ODBC together. I don't use DBI directly. It was
simply a dependency for the ODBC module as best I knew.

Thanks.

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


Re: Problem reading file with umlauts

2009-07-07 Thread Stefan Behnel
Michiel Overtoom schrob:
> Viele Röhre. Macht spaß!  Tsüsch!

LOL! :)

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


Re: Code that ought to run fast, but can't due to Python limitations.

2009-07-07 Thread John Nagle

Stefan Behnel wrote:

John Nagle wrote:

I have a small web crawler robust enough to parse
real-world HTML, which can be appallingly bad.  I currently use
an extra-robust version of BeautifulSoup, and even that sometimes
blows up.  So I'm very interested in a new Python parser which supposedly
handles bad HTML in the same way browsers do.  But if it's slower
than BeautifulSoup, there's a problem.


Well, if performance matters in any way, you can always use lxml's
blazingly fast parser first, possibly trying a couple of different
configurations, and only if all fail, fall back to running html5lib over
the same input. 


   Detecting "fail" is difficult.  A common problem is badly terminated
comments which eat most of the document if you follow the spec.  The
document seems to parse correctly, but most of it is missing.  The
HTML 5 spec actually covers things like



and treats it as a bogus comment.  (That's because HTML 5 doesn't
include general SGML; the only directive recognized is DOCTYPE.
Anything else after "http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Daniel Fetchinson
>> and my point is that users
>> are most of time correct when they assume that something will work the
>> same way as in C.
>
> Oh, really ? They would surely be wrong if they'd expect the for loop to
> have any similarity with a C for loop, or - a *very* common error - if
> they'd expect assignment to work the same way as in C.

By the way, assignments in conditionals. Guido explicitly referred to
C when he forbade assignment in conditionals, citing common
typos/errors in C code such as if( x = 5 ){  } instead of if( x ==
5 ){ . }. So even he realized that warning people about different
usage in python and C is a good thing. Expectations from C work
sometimes, and sometimes they don't. In latter case a little warning
is useful.

Cheers,
Daniel

>> So I'd think that putting a warning in a FAQ or a Python Gotchas list
>> about ++n would be very useful for many users.
>
> Might eventually be useful, but I can't hardly recall of more than a
> couple threads on this topic in 8+ years.



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Daniel Fetchinson
 Yes, there are plenty of languages other than Java and C, but the
 influence of C is admittedly huge in Python. Why do you think loops
 are called "for", conditionals "if" or "while", functions return via
 "return", loops terminate via "break" and keep going via "continue"
 and why is comparison written as "==", etc, etc? All of these are
 coming from C (or an even earlier language) and my point is that users
>>> for, if, and return were common keywords in FORTRAN.
>>>
>>> Not to mention BASIC
>>>
>>> Both of which predate C
>>
>> Yes, hence my comment above, " coming from C (or an even earlier
>> language) ..".
>
>
> Mmm... Should we then claim that "the influence of FORTRAN is admittedly
> huge in Python" ?-)

H, your comments reached a level of pedanticism beyond which I can
not follow :)
Seriously, ask Guido about the influence of C vs. fortran. Somewhere
you can find him quoted as saying that python was originally intended
to "bridge the gap between the shell and C". I've never heard him talk
about fortran.

But this academic discussion is honestly a little pointless. The OP
was referring to a expectation, coming from C, that is not fulfilled
in python. What's wrong with mentioning it somewhere for the sake of
helping C programmers?

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: automatic multiprocessing

2009-07-07 Thread Simon Forman
On Jul 7, 11:08 am, Cheng Soon Ong  wrote:
> Hi all,
>
> I'm trying to automate the use of multiprocessing when it is available. The
> setting I have is quite simple, with a for loop where the operations inside 
> are
> independent of each other. Here's a bit of code. function_inputs is a list of
> dictionaries, each of which match the signature of function_handle.
>
>      if multiprocessing_present:
>          # Passing keyword arguments to map still doesn't work
>          cpus = multiprocessing.Pool()
>          function_outputs = cpus.map(function_handle, function_inputs)
>      else:
>          function_outputs = []
>          for kwargs in function_inputs:
>              cur_out = function_handle(**kwargs)
>              function_outputs.append(cur_out)
>
> Am I missing something here? I cannot seem to get map to pass on keyword 
> arguments.
>
> Thanks in advance,
> Cheng Soon

Pool.map() doesn't handle "**dict" keyword argument notation
automatically.  You could use a wrapper function like so:

cpus = multiprocessing.Pool()
def f(kwargs):
return function_handle(**kwargs)
function_outputs = cpus.map(f, function_inputs)

(Note that f() could be defined outside the if statement if you're
going to use it often.)

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


Re: A Bug By Any Other Name ...

2009-07-07 Thread Daniel Fetchinson
> (snip)
>> and my point is that users
>> are most of time correct when they assume that something will work the
>> same way as in C.
>
> Oh, really ? They would surely be wrong if they'd expect the for loop to
> have any similarity with a C for loop, or - a *very* common error - if
> they'd expect assignment to work the same way as in C.

Yes, really. I wrote " most of the time ." and not "all the time".

>> So I'd think that putting a warning in a FAQ or a Python Gotchas list
>> about ++n would be very useful for many users.
>
> Might eventually be useful, but I can't hardly recall of more than a
> couple threads on this topic in 8+ years.

I'm happy we agree.

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Error from Apress book

2009-07-07 Thread Dave Angel

matt0177 wrote:

Adding the python before the command line didn't work at first, but upon
moving the files to the c:\python25 it worked like a champ. Thank you both
for the help. Very frustrating to run into stuff like this when you're first
trying to learn a knew language, it really throws off your momentum!
  
I'm glad you got things working.  But you really shouldn't need to add 
your own files to the installation directory.  What you need is 
straightforward, but the details are Windows specific


The following is all at the command prompt, not inside Python.

You have a PATH environment variable, with various directories on it.  
Type it out using the PATH command.  Pick a location on it, and add a 
batch file we'll write below.  It's also possible to add a new directory 
to the PATH, using the control panel.  Normally, the first thing I do on 
a new machine is add two directories to the PATH, perhaps  c:\bin  and 
c:\bat.  The former is for the simple one-file utilities you accumulate 
over the years, and the latter is for batch files.  If you want to 
pursue this, let me know, and I'll give details.


Now that you've picked a location for your batch file, let's create it, 
calling it   Python25.bat   You could just call it Python.bat, but this 
way, you can have more than one Python installed, and choose between them.


The contents of Python25.bat are a single line:

@c:\python25\python.exe  %*

The leading @ says we don't wan the line echoed to the screen.  If 
you're unsure of yourself, you can leave it off till everything works 
well, then add it in.  The %* says to copy all the arguments you pass 
the batch file into the executable.


Once this batch file is stored in your PATH, you can just type something 
like:


 python25  myscript.py   arg1 arg2

or, to run the interpreter itself,
python25

DaveA

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


Re: ISO library ref in printed form

2009-07-07 Thread Aahz
In article , kj   wrote:
>
>Does anyone know where I can buy the Python library reference in
>printed form?  (I'd rather not print the whole 1200+-page tome
>myself.)  I'm interested in both/either 2.6 and 3.0.

There used to be one for Python 2.1, but I can't tell whether it's ever
been updated because the website isn't responding:

http://wiki.python.org/moin/ReferenceBooks
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


automatic multiprocessing

2009-07-07 Thread Cheng Soon Ong

Hi all,

I'm trying to automate the use of multiprocessing when it is available. The 
setting I have is quite simple, with a for loop where the operations inside are 
independent of each other. Here's a bit of code. function_inputs is a list of 
dictionaries, each of which match the signature of function_handle.


if multiprocessing_present:
# Passing keyword arguments to map still doesn't work
cpus = multiprocessing.Pool()
function_outputs = cpus.map(function_handle, function_inputs)
else:
function_outputs = []
for kwargs in function_inputs:
cur_out = function_handle(**kwargs)
function_outputs.append(cur_out)

Am I missing something here? I cannot seem to get map to pass on keyword 
arguments.

Thanks in advance,
Cheng Soon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2009-07-07 Thread Pablo Torres N.
On Tue, Jul 7, 2009 at 10:02,  wrote:
> Hello Gurus,
>
> Thank you for trying to help to my initial and not well written questions.  I 
> will compile more detailed information and ask again.  Btw, I am giving a 
> glimpse to: "How To Ask Questions The Smart Way".
>
> nacim

Give this one a try too: http://www.mikeash.com/getting_answers.html
It doesn't talk down to you...as much :P


-- 
Pablo Torres N.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem reading file with umlauts

2009-07-07 Thread Michiel Overtoom

Claus Hausberger wrote:


I have a text file with is encoding in Latin1 (ISO-8859-1). I can't
change that as I do not create those files myself. I have to read
those files and convert the umlauts like ö to stuff like &oumol; as
the text files should become html files.


umlaut-in.txt:

This file is contains data in the unicode
character set and is encoded with utf-8.
Viele Röhre. Macht spaß!  Tsüsch!


umlaut-in.txt hexdump:

00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
20: 65 20 75 6E 69 63 6F 64  65 0D 0A 63 68 61 72 61 e unicode..chara
30: 63 74 65 72 20 73 65 74  20 61 6E 64 20 69 73 20 cter set and is
40: 65 6E 63 6F 64 65 64 20  77 69 74 68 20 75 74 66 encoded with utf
50: 2D 38 2E 0D 0A 56 69 65  6C 65 20 52 C3 B6 68 72 -8...Viele R..hr
60: 65 2E 20 4D 61 63 68 74  20 73 70 61 C3 9F 21 20 e. Macht spa..!
70: 20 54 73 C3 BC 73 63 68  21 0D 0A 00 00 00 00 00  Ts..sch!...


umlaut.py:

# -*- coding: utf-8 -*-
import codecs
text=codecs.open("umlaut-in.txt",encoding="utf-8").read()
text=text.replace(u"ö",u"oe")
text=text.replace(u"ß",u"ss")
text=text.replace(u"ü",u"ue")
of=open("umlaut-out.txt","w")
of.write(text)
of.close()


umlaut-out.txt:

This file is contains data in the unicode
character set and is encoded with utf-8.
Viele Roehre. Macht spass!  Tsuesch!


umlaut-out.txt hexdump:

00: 54 68 69 73 20 66 69 6C  65 20 69 73 20 63 6F 6E This file is con
10: 74 61 69 6E 73 20 64 61  74 61 20 69 6E 20 74 68 tains data in th
20: 65 20 75 6E 69 63 6F 64  65 0D 0D 0A 63 68 61 72 e unicode...char
30: 61 63 74 65 72 20 73 65  74 20 61 6E 64 20 69 73 acter set and is
40: 20 65 6E 63 6F 64 65 64  20 77 69 74 68 20 75 74  encoded with ut
50: 66 2D 38 2E 0D 0D 0A 56  69 65 6C 65 20 52 6F 65 f-8Viele Roe
60: 68 72 65 2E 20 4D 61 63  68 74 20 73 70 61 73 73 hre. Macht spass
70: 21 20 20 54 73 75 65 73  63 68 21 0D 0D 0A 00 00 !  Tsuesch!.





--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: ISO library ref in printed form

2009-07-07 Thread Scott David Daniels

kj wrote:

Does anyone know where I can buy the Python library reference in
printed form?  (I'd rather not print the whole 1200+-page tome
myself.)  I'm interested in both/either 2.6 and 3.0.


Personally, I'd get the new Beazley's Python Essential Reference,
which is due out "real soon now," and then use the provided docs
as a addon.  Also consider grabbing Gruet's "Python Quick Reference"
page.  When I was working in a printer site I printed the color
version of Gruet's page two-sided; it was neither too bulky nor
too sketchy for my needs (and he uses color to distinguish
version-to-version changes).
http://rgruet.free.fr/
Sadly, I no longer work there, so my copy is gone. :-(

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


RE: Newbie needs help

2009-07-07 Thread nacim_bravo
Hello Gurus,

Thank you for trying to help to my initial and not well written questions.  I 
will compile more detailed information and ask again.  Btw, I am giving a 
glimpse to: "How To Ask Questions The Smart Way".

nacim


-Original Message-
From: Simon Forman [mailto:sajmik...@gmail.com] 
Sent: Tuesday, July 07, 2009 7:19 AM
To: BRAVO,NACIM (A-Sonoma,ex1)
Cc: python-list@python.org
Subject: Re: Newbie needs help

On Mon, Jul 6, 2009 at 7:00 PM,  wrote:
> Dear Python gurus,
>
> If I'd like to set dielectric constant for the certain material, is it 
> possible to do such in Python environment? If yes, how to do or what syntax 
> can be used?
>
> Also, I'd like to get a simulation result, like voltage, is it possible to 
> get this value in Python environment?
>
> Please let me know,
> nacim
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The answers to your first and third questions are, "yes" and "yes". :]
 (Generally speaking if something can be done by a computer it can be
done with python.)

As for your second question check out the "magnitude" package:

http://pypi.python.org/pypi/magnitude/   and
http://juanreyero.com/magnitude/

(That second link also has links to three other packages that deal
with units of measurement.)

Ii has units for the SI measurements, including volts and coulombs, so
you should be able to accomplish your goals with it.

The tricky thing is, as far as I can tell from the wikipedia entry
(http://en.wikipedia.org/wiki/Relative_static_permittivity),
"dielectric constant" seems to be a dimensionless number, i.e. C/C...
 I could be totally daft though.

HTH,
~Simon


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


Re: Python Error from Apress book

2009-07-07 Thread matt0177

Adding the python before the command line didn't work at first, but upon
moving the files to the c:\python25 it worked like a champ. Thank you both
for the help. Very frustrating to run into stuff like this when you're first
trying to learn a knew language, it really throws off your momentum!
-- 
View this message in context: 
http://www.nabble.com/Python-Error-from-Apress-book-tp24364269p24374988.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Remoting over SSH

2009-07-07 Thread Tim Harig
On 2009-07-07, Hussein B  wrote:
> I want to perform commands on a remote server over SSH.
> What do I need?

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

There are many ways to remote using ssh.  If we know what you are trying to
do, maybe we could give you a better answer.  If you just want to open the
python interpreter interactively on another host you can do something like:

ssh -t u...@host python

That will allow you send "commands" to the python interpeter.  You could
write a script and pipe it into the interpreter:

cat script.py | ssh -t u...@host python

Maybe you want to open an ssh connection and send shell commands from a
python script.  You can do that using one of the popen2 functions:

http://docs.python.org/library/popen2.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remoting over SSH

2009-07-07 Thread alex23
On Jul 8, 12:46 am, Hussein B  wrote:
> I want to perform commands on a remote server over SSH.
> What do I need?

Take a look at pexpect: http://pexpect.sourceforge.net/pexpect.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Aahz
In article <85ljn0ej4h@agentultra.com>,
J Kenneth King   wrote:
>
>The iPhone is running on what? A 400Mhz ARM processor? Resources on the
>device are already limited; running your program on top of an embedded
>Python interpreter would only be adding pressure to the constraints;
>even if it was an optimized interpreter.

  Ten years ago, a 400MHz ARM processor would have been
fast, and it would have been running Python 1.5.2.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Simon Forman
On Tue, Jul 7, 2009 at 8:51 AM, Jean-Michel
Pichavant wrote:
> Steven D'Aprano wrote:
>>
>> On Tue, 07 Jul 2009 05:13:28 +, Lie Ryan wrote:
>>
>>
>>>
>>> When people are fighting over things like `sense`, although sense may
>>> not be strictly wrong dictionary-wise, it smells of something burning...
>>>
>>
>> That would be my patience.
>>
>> I can't believe the direction this discussion has taken. Anybody sensible
>> would be saying "Oh wow, I've just learned a new meaning to the word, that's
>> great, I'm now less ignorant than I was a minute ago". But oh no, we mustn't
>> use a standard meaning to a word, heaven forbid we disturb people's
>> ignorance by teaching them something new.
>>
>> It's as simple as this: using `sense` as a variable name to record the
>> sense of a function is not a code smell, any more than using `flag` to
>> record a flag would be, or `sign` to record the sign of an object. If you
>> don't know the appropriate meanings of the words sense, flag or sign, learn
>> them, don't dumb down my language.
>>
>>
>
> Can't we just calm down ? I'm really sorry my ignorance started this thread,
> and my apologies go to Kj who's obviously more fluent in english than me.
> I've never used sense in that way before, nor I've seen used by others until
> now. However Kj is right, and my dictionary seems wrong (wordreference.com).
> I've searched through others dictionaries and find out this is actually
> applicable to functions. My bad.
>
> JM

Well met, sir.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Aahz
In article ,
Jean-Michel Pichavant   wrote:
>
>Can't we just calm down ? I'm really sorry my ignorance started this 
>thread, and my apologies go to Kj who's obviously more fluent in english 
>than me.
>I've never used sense in that way before, nor I've seen used by others 
>until now. However Kj is right, and my dictionary seems wrong 
>(wordreference.com). I've searched through others dictionaries and find 
>out this is actually applicable to functions. My bad.

You were not the first person to point out that "sense" is a poor
variable name.  Unless KJ is specifically using this code in the context
of a math class, I still think that "sense" is completely inappropriate.
Your English fluency is just fine.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching control-C

2009-07-07 Thread Simon Forman
On Jul 6, 6:02 pm, Michael Mossey  wrote:
> On Jul 6, 2:47 pm, Philip Semanchuk  wrote:
>
> > On Jul 6, 2009, at 5:37 PM, Michael Mossey wrote:
>
> > > What is required in a python program to make sure it catches a  
> > > control-
> > > c on the command-line? Do some i/o? The OS here is Linux.
>
> > You can use a try/except to catch a KeyboardInterrupt exception, or  
> > you can trap it using the signal 
> > module:http://docs.python.org/library/signal.html
>
> > You want to trap SIGINT.
>
> > HTH
> > Philip
>
> Thanks to both of you. However, my question is also about whether I
> need to be doing i/o or some similar operation for my program to
> notice in any shape or form that Control-C has been pressed. In the
> past, I've written Python programs that go about their business
> ignoring Ctrl-C. Other programs respond to it immediately by exiting.
> I think the difference is that the latter programs are doing i/o. But
> I want to understand better what the "secret" is to responding to a
> ctrl-C in any shape or form.
>
> For example, does trapping SIGINT always work, regardless of what my
> process is doing?
>
> Thanks,
> Mike

Try some experiments. ;]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2009-07-07 Thread Simon Forman
On Mon, Jul 6, 2009 at 7:00 PM,  wrote:
> Dear Python gurus,
>
> If I'd like to set dielectric constant for the certain material, is it 
> possible to do such in Python environment? If yes, how to do or what syntax 
> can be used?
>
> Also, I'd like to get a simulation result, like voltage, is it possible to 
> get this value in Python environment?
>
> Please let me know,
> nacim
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The answers to your first and third questions are, "yes" and "yes". :]
 (Generally speaking if something can be done by a computer it can be
done with python.)

As for your second question check out the "magnitude" package:

http://pypi.python.org/pypi/magnitude/   and
http://juanreyero.com/magnitude/

(That second link also has links to three other packages that deal
with units of measurement.)

Ii has units for the SI measurements, including volts and coulombs, so
you should be able to accomplish your goals with it.

The tricky thing is, as far as I can tell from the wikipedia entry
(http://en.wikipedia.org/wiki/Relative_static_permittivity),
"dielectric constant" seems to be a dimensionless number, i.e. C/C...
 I could be totally daft though.

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


Re: Problem reading file with umlauts

2009-07-07 Thread Stefan Behnel
Claus Hausberger wrote:
> Hello
> 
> I have a text file with is encoding in Latin1 (ISO-8859-1). I can't change 
> that as I do not create those files myself.
> 
> I have to read those files and convert the umlauts like ö to stuff like 
> &oumol; as the text files should become html files.
> 
> I have this code:
> 
> 
> #!/usr/bin/python
> # -*- coding: latin1 -*-
> 
> import codecs
> 
> f = codecs.open('abc.txt', encoding='latin1')
> 
> for line in f:
> print line
> for c in line: 
> if c == "ö":

You are reading Unicode strings, so you have to compare it to a unicode
string as in

if c == u"ö":

> print "oe"
> else:
> print c

Note that printing non-ASCII characters may not always work, depending on
your terminal.

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


Problem reading file with umlauts

2009-07-07 Thread Claus Hausberger
Hello

I have a text file with is encoding in Latin1 (ISO-8859-1). I can't change that 
as I do not create those files myself.

I have to read those files and convert the umlauts like ö to stuff like &oumol; 
as the text files should become html files.

I have this code:


#!/usr/bin/python
# -*- coding: latin1 -*-

import codecs

f = codecs.open('abc.txt', encoding='latin1')

for line in f:
print line
for c in line: 
if c == "ö":
print "oe"
else:
print c


and I get this error message:

$ ./read.py
Abc

./read.py:11: UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting them as being unequal
  if c == "ö":
A
b
c



Traceback (most recent call last):
  File "./read.py", line 9, in 
print line
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: 
ordinal not in range(128)




I checked the web and tried several approaches but I also get some strange 
encoding errors.
Has anyone ever done this before? 
I am currently using Python 2.5 and may be able to use 2.6 but I cannot yet 
move to 3.1 as many libs we use don't yet work with Python 3.

any help more than welcome.  This has been driving me crazy for two days now.

best wishes

Claus
-- 
Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate
für nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter.Canvas thread safety problem?

2009-07-07 Thread Peter Otten
Zdenek Maxa wrote:

> I would like to ask if you could have a look at the snippet in the
> attachment and tell me if that is actually me doing something wrong or
> indeed Tkinter thread safety problem and what the workaround could be.

http://effbot.org/zone/tkinter-threads.htm

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


Re: Semi-Newbie needs a little help

2009-07-07 Thread Nile
Thanks all for your help. I appreciate it.  The problem was in the
function.  A simple bug which I should have caught but I had my mental
blinders on and was sure the problem was outside the function.  The
answers have given me a lot to learn so thanks for that as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating alot of class instances?

2009-07-07 Thread Piet van Oostrum
> Steven D'Aprano  (SD) wrote:

>SD> On Mon, 06 Jul 2009 05:47:18 -0700, Scott David Daniels wrote:
>>> Steven D'Aprano wrote:
 ... That's the Wrong Way to do it --
 you're using a screwdriver to hammer a nail
>>> 
>>> Don't knock tool abuse (though I agree with you here). Sometimes tool
>>> abuse can produce good results.  For example, using hammers to drive
>>> screws for temporary strong holds led to making better nails.

>SD> Historically, nails were invented a long time before screws. Screws as 
>SD> fasteners weren't invented until the 1400s, nails were used thousands of 
>SD> years ago.

>SD> And hammering screws makes temporary *weak* holds, not strong, because 
>SD> the screw only touches the sides of the hole lightly. Unless the screw 
>SD> has been specifically designed to be hammered, hammering screws is pretty 
>SD> much the definition of incompetence and/or laziness!

In our language (Dutch, i.e. Guido's mother tongue) `American
screwdriver' is an expression meaning `hammer' :=)
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why re.match()?

2009-07-07 Thread pdpi
On Jul 2, 4:49 am, kj  wrote:
> In  Duncan Booth 
>  writes:
>
> >So, for example:
>  re.compile("c").match("abcdef", 2)
> ><_sre.SRE_Match object at 0x02C09B90>
>  re.compile("^c").search("abcdef", 2)
>
> I find this unconvincing; with re.search alone one could simply
> do:
>
> >>> re.compile("^c").search("abcdef"[2:])

given large enough values of "abcdef", you just allocated several megs
for no good reason, when re.compile("c").match("abcdef", 2) would
process "abcdef" in-place.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Dave Angel

Duncan Booth wrote:

Dennis Lee Bieber  wrote:

  

for, if, and return were common keywords in FORTRAN.



Really? What does 'for' do in FORTRAN?

P.S. Does FORTRAN actually have keywords these days? Back when I learned it 
there was no such thing as a reserved word though for all I know they may 
have since added them.


  
The way I remember it (last used Fortran in 1970), DO was the looping 
construct, not FOR.  Naturally it was uppercase, as keypunches of the 
time didn't have an easy way to do lowercase.  (It was possible, you 
just had to use multi-punch, and a good memory for the appropriate 
0-12-11 prefixes).



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


Re: Why re.match()?

2009-07-07 Thread Bruno Desthuilliers

Paul Rudin a écrit :

Bruno Desthuilliers  writes:


kj a écrit :

In <4a4e2227$0$7801$426a7...@news.free.fr> Bruno Desthuilliers 
 writes:


kj a écrit :
(snipo

To have a special-case
re.match() method in addition to a general re.search() method is
antithetical to language minimalism,

FWIW, Python has no pretention to minimalism.

Assuming that you mean by this that Python's authors have no such
pretensions:

"There is real value in having a small language."

Guido van Rossum, 2007.07.03

http://mail.python.org/pipermail/python-3000/2007-July/008663.html

There are some differences between "small" and "minimal"...



There's also a difference between the language and its standard
library.


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


Re: Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Dr Mephesto
Sure, I am learning Objective C already, but the syntax is really
unfriendly after python.

I think it really depends on the type of app you want to write.
Anything held back by network delays or that sits around waiting for
user input are perfectly acceptable target apps. If you need speed for
something really intensive, falling back to C is still much nicer than
coding in Objective C. I agree that having a certain basic
understanding of objective C is a must, but having the option to use a
coder-friendly language like Ruby or Python can cut development time
dramatically.

If Ruby can do it (and it generally slower than python), why can
Python also get a legal iPhone interpreter?

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


  1   2   >