Re: How Python Implements "long integer"?

2009-07-07 Thread Eric Wong
Pedram wrote:

> Hello Mr. Dickinson. Glad to see you again :)
> 
> On Jul 6, 5:46 pm, Mark Dickinson  wrote:
>> On Jul 6, 1:24 pm, Pedram  wrote:
>>
>> > OK, fine, I read longobject.c at last! :)
>> > I found that longobject is a structure like this:
>>
>> > struct _longobject {
>> > struct _object *_ob_next;
>> > struct _object *_ob_prev;
>>
>> For current CPython, these two fields are only present in debug
>> builds;  for a normal build they won't exist.
> 
> I couldn't understand the difference between them. What are debug
> build and normal build themselves? And You mean in debug build
> PyLongObject is a doubly-linked-list but in normal build it is just 
an
> array (Or if not how it'll store in this mode)?
> 
we use the macro Py_TRACE_REFS to differ the code for debug build and 
normal build, that's to say, in debug build and normal build the codes 
are actually *different*. In debug build, not only PyLongObject but 
all Objects are linked by a doubly-linked-list and it can make the 
debug process less painful. But in normal build, objects are 
seperated! After an object is created, it will never be moved, so we 
can and should refer to an object only by it's address(pointer). 
There's no one-big-container like a list or an array for objects.

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


Re: Looking for a slick way to classify relationship between two numbers, without tons of if/else

2009-07-07 Thread Paul Rubin
palewire  writes:
> In my application, I'd like to have a function that compares two values,
> either of which may be null, and then classify the result depending on
> whether one is higher or lower than the other.

Didn't we just have a huge thread about that?  Using a special null
value is often (not always) a code smell.  But anyway (untested):

def compare(a,b):
   if a is None and b is None:  # I'm guessing you meant this
   return "No data"
   if a == b:
   return "Stayed the same" if a != 0 else "Never had"
   elif a < b:
   return "gained"
   else:
   # we know here that a > b
   return "Lost some" if b > 0 else "Lost all"

I don't know what you intended to do in the case where exactly one of
(a,b) is None, so I'll leave that to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copytree with timeout in windows

2009-07-07 Thread Tim Golden

Astan Chee wrote:

Tim Golden wrote:

Astan Chee wrote:
 

Hi,
I'm trying to modify the copytree function in shutil so that any file 
being copied does not take more than 5 minutes (if it does, skip to 
the next one). 


One suggestion is to use the CopyFileEx API
exposed in the win32file module from pywin32. That
allows for a callback function which can abort
the copy (or issue a progress meter, etc.).
  
Thanks, but looking in the documentation there is no callback function. 
Did you mean */the Progress Routine?



Well, depending on which hairs you're splitting, I would
argue that the Progress Routine *is* a callback function:
it is a function which is called back. But, yes, I
did mean that. :)

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


Re: Semi-Newbie needs a little help

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

>N> I initialized the dictionary earlier in the program like this -

>N>   hashtable = {}

>N> I changed the "dict" to hashtable but I still get the same result
>N> I will try to learn about the defaultdict but I'm just trying to keep
>N> it as simple as I can for now

>N> Revised code

>N> for x in range(len(file_list)):
>N> d = open(file_list[x] , "r")
>N> data = d.readlines()
>N> k = 0
>N> k = above_or_below(data)
>N> print "here is the value that was returned ",k
>N> hashtable[k] = hashtable.get(k,0) + 1


>N> hashtable_list = hashtable.values()
>N> print "here is a list of the dictionary values ", hashtable_list
>N> print "the length of the dictionary is ", len(hashtable)

>N> Output
>N> # The first 3 lines are printed from the function
>N> # right before the return statement.  This output
>N> # snippet shows the last two stocks.  The function
>N> # SAYS it is returning the correct value but only
>N> # the last date seems to make it to the hashtable
>N> Function will return k which = 11/11/2008
>N> Function will return k which = 11/12/2008
>N> Function will return k which = 11/14/2008

>N> # this line is printed from the code above
>N> # I don't understand why all three dates don't
>N> # seem to make it to the main program.  Only
>N> # the last date seems to be recognized
>N> here is the value that was returned 11/14/2008

>N> Function will return k which = 11/11/2008
>N> Function will return k which = 11/12/2008
>N> Function will return k which = 11/14/2008
>N> here is the value that was returned 11/14/2008
>N> here is a list of the dictionary values [5]
>N> the length of the dictionary is 1
>>> Exit code: 0

Now in your code there is a 1-1 relation between printing 
"here is the value that was returned" and incrementing the hashtable
entry. In your log there are only 2 prints of "here is the value that
was returned" so how can the count be 5? Are you hiding something from
us? 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where does setuptools live?

2009-07-07 Thread Chris Withers

David Lyon wrote:

setuptools... as far as I can see isn't actually installed until you
install easyinstall...


That depends... I exclusively use buildout to manage my python packages, 
and sadly that relies on setuptools...


Pip (http://pypi.python.org/pypi/pip) and enstall 
(http://pypi.python.org/pypi/Enstaller/3.1.0) seem to be forks of 
setuptools already...


So it looks like it's already been forked to some degree..

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?



If the xmlrpc links actually "worked" on pypi...


What about it doesn't work?

Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Asun Friere
On Jul 7, 3:05 pm, Steven D'Aprano  wrote:

[snip]

> Sense is, if you like, a "signed direction".

Or to put it another way, in the graphical representation of a vector,
'direction' is the line, 'sense' is the arrowhead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Duncan Booth
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.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
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 Stefan Behnel
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. That should give you a tremendous speed-up over your
current code in most cases, while keeping things robust in the hard cases.

Note the numbers that Ian Bicking has for HTML parser performance:

http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/

You should be able to run lxml's parser ten times in different
configurations (e.g. different charset overrides) before it even reaches
the time that BeautifulSoup would need to parse a document once. Given that
undeclared character set detection is something where BS is a lot better
than lxml, you can also mix the best of both worlds and use BS's character
set detection to configure lxml's parser if you notice that the first
parsing attempts fail.

And yes, html5lib performs pretty badly in comparison (or did, at the
time). But the numbers seem to indicate that if you can drop the ratio of
documents that require a run of html5lib below 30% and use lxml's parser
for the rest, you will still be faster than with BeautifulSoup alone.

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


Re: How Python Implements "long integer"?

2009-07-07 Thread Mark Dickinson
On Jul 6, 4:13 pm, Pedram  wrote:
> On Jul 6, 5:46 pm, Mark Dickinson  wrote:
> > On Jul 6, 1:24 pm, Pedram  wrote:
>
> > > OK, fine, I read longobject.c at last! :)
> > > I found that longobject is a structure like this:
>
> > > struct _longobject {
> > >     struct _object *_ob_next;
> > >     struct _object *_ob_prev;
>
> > For current CPython, these two fields are only present in debug
> > builds;  for a normal build they won't exist.
>
> I couldn't understand the difference between them. What are debug
> build and normal build themselves? And You mean in debug build
> PyLongObject is a doubly-linked-list but in normal build it is just an
> array (Or if not how it'll store in this mode)?

No:  a PyLongObject is stored the same way (ob_size giving sign and
number of digits, ob_digit giving the digits themselves) whether or
not a debug build is in use.

A debug build does various things (extra checks, extra information) to
make it easier to track down problems.  On Unix-like systems, you can
get a debug build by configuring with the --with-pydebug flag.

The _ob_next and _ob_prev fields have nothing particularly to do with
Python longs; for a debug build, these two fields are added to *all*
Python objects, and provide a doubly-linked list that links all 'live'
Python objects together.  I'm not really sure what, if anything, the
extra information is used for within Python---it might be used by some
external tools, I guess.

Have you looked at the C-API documentation?

http://docs.python.org/c-api/index.html

_ob_next and _ob_prev are described here:

http://docs.python.org/c-api/typeobj.html#_ob_next

(These docs are for Python 2.6;  I'm not sure what version you're
working with.)

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


Re: a little wsgi framework

2009-07-07 Thread Bruno Desthuilliers

timmyt a écrit :

i'm interested in getting opinions on a small wsgi framework i
assembled from webob, sqlalchemy, genshi, and various code fragments i
found on the inter-tubes

here is the interesting glue - any comments / suggestions would be
much appreciated



Well... My first comment would be about the usefulness of yet another 
Python web framework, but let's not worry about this...




--
the wsgi app
--
def application(environ, start_response):
path = environ.get('PATH_INFO', '').lstrip('/')

for regex, callback in urls:
match = re.search(regex, path)



I don't know where these "urls" come from. But anyway : if they live in 
some sort of long-running process, you may want to precompile them.



if match:
environ['myapp.url_args'] = match.groups()
request = webob.Request(environ)

try:
return callback(request, start_response)
except Exception, ex:


How are redirect etc handled ?


start_response('500 Internal Server Error', [('Content-
Type', 'text/plain')])
return [traceback.format_exc()]


A configuration option controlling the display of the traceback would be 
fine - I surely don't want the traceback being displayed to anyone when 
 the app goes into production.


Also, logging the error and traceback might be useful.



start_response('404 Not Found', [('Content-Type', 'text/plain')])
return ["Couldn't find the URL specified."]



And in both cases, having the ability to use "custom" 500 and 404 pages 
might be nice too.




--
the controller decorator
--
def web_decorator(filename, method='html'):

>

def decorator(target):


May I suggest some renaming here ?

filename => path (or 'template_path' ?)
method   => content_type
target   => controller or function or callback or


def wrapper(request, start_response):

#genshi TemplateLoader
template = loader.load(filename)

global config


Probably not thread-safe


try:
return_dict = target(request, start_response)
return_string = template.generate(**return_dict).render
(method)



Renaming again:
return_dict => context
return_string => data or text or ???


config['database.Session'].commit()
except:
config['database.Session'].rollback()
raise
finally:
config['database.Session'].remove()


This doesn't leave much control on transactions... Sometimes you want to 
handle it manually one way or another.



#TODO: alter 'Content-Type' per method being passed
start_response('200 OK', [('Content-Type', 'text/html')])
return [return_string]


Ok, so here again, I don't understand how redirects can work. Also, if 
you do use start_response here, I don't get why you still pass it to the 
callback function.



return wrapper

return decorator


slightly OT, but preserving infos on the decorated function might help 
too (introspection, debugging etc).



My 2 cents...
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Bruno Desthuilliers

Daniel Fetchinson a écrit :
(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.



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.


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


Re: A Bug By Any Other Name ...

2009-07-07 Thread Bruno Desthuilliers

Daniel Fetchinson a écrit :

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" ?-)


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


Re: module name versus function name resolution conflict.

2009-07-07 Thread rocky
On Jul 7, 2:33 am, Peter Otten <__pete...@web.de> wrote:
> rocky wrote:
> > Someone recently reported a problem in pydb where a function defined
> > in his program was conflicting with amodulenamethat pydb uses. I
> > think I understand what's wrong, but I don't have any elegant
> > solutions to the problem. Suggestions would be appreciated.
>
> > In a nutshell, here's the problem:
>
> > In file fns:
>
> >   def foo(): print "foo"
>
> > In file pdebug.py:
>
> >   import fns, sys
>
> >   def trace_dispatch(frame, event, arg):
> >       fns.foo()
> >       print frame, event, arg
> >       return trace_dispatch
>
> >   sys.settrace(trace_dispatch)
> >   execfile('myprogram.py')
>
> > Finally file myprogram.py:
>
> >   def fns(): print "This is the *other* fns"
>
> > When you run pdebug.py you get:
>
> > $ python pdebug.py
> > foo
> >  call None
> > foo
> >  line None
> > Traceback (most recent call last):
> >   File "pdebug.py", line 7, in 
> >     execfile('myprogram.py')
> >   File "myprogram.py", line 1, in 
> >     def fns(): print "This is the *other* fns"
> >   File "pdebug.py", line 3, in trace_dispatch
> >     fns.foo()
> > AttributeError: 'function' object has no attribute 'foo'
>
> > Basically inside the trace hook, local functions are visible and take
> > precedence over (global)modulenames.

I was sloppy here. The "local" is the wrong word as suggested by the
first remedy proposed.
"entry in the global namespace dictionary" is probably closer to the
truth.

> > I could move "import fns"
> > inside trace_dispatch(), but I'd have to do that in all of the methods
> > thatmodule"fns" is used.  Also note that using the form:
> >   from fns import foo
>
> > would eliminate the conflict on "fns", but I'd still have potential
> > conflicts on "foo". Using more obscure names (e.g. pydb_fns) would
> > reduce the chance of a conflict but not eliminate it.
>
> > Suggestions?
>
> Can you run the program in another namespace?
>
> execfile("myprogram.py", {"__name__":"__main__"})
>
> Alternatively move trace_dispatch into yet anothermoduleand import it into
> pdebug.
>
> from elsewhere import trace_dispatch
>
> Peter

Both of these work. Thanks! (I haven't figured out how to adapt it to
the messier context of the program yet). The second suggestion
interesting/weird:
by putting trace_dispatch in another module, compilation and name/
function resolution of fns.foo
is done before myprogram has a chance to redefine fns.

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


Re: Method to separate unit-test methods and data?

2009-07-07 Thread Lie Ryan
Nick Daly wrote:
> Hi,
> 
> I was wondering if it's possible / if there are any simple methods
> known of storing unit-test functions and their data in separate files?
> 
> Perhaps this is a strange request, but it does an excellent job of
> modularizing code.  As far as revision control goes, it makes it
> easier to discern between new or changed test cases, and changes in
> the test data.
> 

> Does anyone have any solutions for these problems?  First, is there a
> known and simple way to separate unit-test data and methods into
> separate files?  Secondly, if not, is there a simple way to convert
> strings into other base types, like lists, dictionaries, and so forth?
> Or, am I going to have to write my own list-parsing methods?  Would
> pickling help?  I haven't yet had a chance to look into if or how that
> would work...  If there's anything else I can clarify about this
> request, feel free to let me know.
> 

It is usually not a very good idea to complicate the testing framework
with configuration files (as then you will have two things to be
tested). Unless the testing data is very huge (so huge that it
interferes with reading and writing the testing code), and huge data is
necessary for the test, it is much simpler and better to just put the
data into the test code. In cases where you want to have fairly complex
object (list, etc) you can "import" the test data. Pickling is usually
unnecessary unless you want to store instance data (classes, etc).

-- code.py --
def add(a, b):
return a + b

-- test.py --
import unittest

# import the file we're testing
import code

# imports the data from separate file
from testdata import data

class AddCase(unittest.TestCase):
def test_add():
for case in data:
self.assertEqual(code.add(case[0], case[1]), case[2])

-- testdata.py --
data = [(0, 0, 0),
(1, 0, 1),
(0, 1, 1),
(1, -1, 0),
   ]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Python Implements "long integer"?

2009-07-07 Thread Pedram
On Jul 7, 1:10 pm, Mark Dickinson  wrote:
> On Jul 6, 4:13 pm, Pedram  wrote:
>
>
>
> > On Jul 6, 5:46 pm, Mark Dickinson  wrote:
> > > On Jul 6, 1:24 pm, Pedram  wrote:
>
> > > > OK, fine, I read longobject.c at last! :)
> > > > I found that longobject is a structure like this:
>
> > > > struct _longobject {
> > > >     struct _object *_ob_next;
> > > >     struct _object *_ob_prev;
>
> > > For current CPython, these two fields are only present in debug
> > > builds;  for a normal build they won't exist.
>
> > I couldn't understand the difference between them. What are debug
> > build and normal build themselves? And You mean in debug build
> > PyLongObject is a doubly-linked-list but in normal build it is just an
> > array (Or if not how it'll store in this mode)?
>
> No:  a PyLongObject is stored the same way (ob_size giving sign and
> number of digits, ob_digit giving the digits themselves) whether or
> not a debug build is in use.
>
> A debug build does various things (extra checks, extra information) to
> make it easier to track down problems.  On Unix-like systems, you can
> get a debug build by configuring with the --with-pydebug flag.
>
> The _ob_next and _ob_prev fields have nothing particularly to do with
> Python longs; for a debug build, these two fields are added to *all*
> Python objects, and provide a doubly-linked list that links all 'live'
> Python objects together.  I'm not really sure what, if anything, the
> extra information is used for within Python---it might be used by some
> external tools, I guess.
>
> Have you looked at the C-API documentation?
>
> http://docs.python.org/c-api/index.html
>
> _ob_next and _ob_prev are described here:
>
> http://docs.python.org/c-api/typeobj.html#_ob_next
>
> (These docs are for Python 2.6;  I'm not sure what version you're
> working with.)
>
> Mark

It seems there's an island named Python!
Thanks for links, I'm on reading them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generation of keyboard events

2009-07-07 Thread RAM
On 6 July, 10:02, Simon Brunning  wrote:
> 2009/7/6 RAM :
>
> > I am trying to do this on windows. My program(executable) has been
> > written in VC++ and when I run this program, I need to click on one
> > button on the program GUI i,e just I am entering "Enter key" on the
> > key board. But this needs manual process. So i need to write a python
> > script which invokes my program and pass "Enter key" event to my
> > program so that it runs without manual intervention.
>
> Try .
>
> --
> Cheers,
> Simon B.

Thank you all for the help the below url helped me in accomplishing my
task

http://www.rutherfurd.net/python/sendkeys/index.html

regards
Sreerama V
-- 
http://mail.python.org/mailman/listinfo/python-list


ISO library ref in printed form

2009-07-07 Thread kj


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.

TIA!

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


Re: Why re.match()?

2009-07-07 Thread Bruno Desthuilliers

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"...


So there.

BTW, that's just one example.  I've seen similar sentiments expressed
by Guido over and over and over: any new proposed enhancement to
Python must be good enough in his mind to justify cluttering the
language.  That attitude counts as minimalism in my book.


And in mine, it counts as "keeping the language's evolution under 
control" - which is still not the same thing as being "minimalist". If 
Python really was on the "minimalist" side, you wouldn't even have 
"class" or "def" statements - both being mostly syntactic sugar. And 
let's not even talk about @decorator syntax...


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


Python/pyobjC Apps on iPhone now a possibility?

2009-07-07 Thread Dr Mephesto
I have been following the discussion about python and pyobjc on the
iphone, and it seemed to me that the app-store rules prohibited
embedded interpreters; so, python apps are a no-no.

But now it seems that the Rubyists have the option that we don't. It
seems there is a company, http://rhomobile.com/home, that has an SDK
that allows ruby programs to be embedded together with an interpreter
in an app! More interesting is the fact that several of these hybrid
apps seem to have been accepted on the itunes app store.

Here's a quote from a representative, found on this blog:
http://www.rubyinside.com/rhodes-develop-full-iphone-rim-and-symbian-apps-using-ruby-1475.html

"...First of all, to clarify, we precompile all framework and app code
down to Ruby 1.9 VM bytecode. This yields great performance
advantages. We also disable eval and other dynamic execution aspects
of Ruby. In the end, on all platforms your app gets compiled with our
framework all into one single executable, indistinguishable from any
other executable.

But even if we were shipping a fullon Ruby interpreter without
compiling to bytecode and leaving dynamic evaluation enabled (as has
been well remarked in the blogosphere by now) App Store rule 3.3.2
does not disallow interpreters but only downloading code to be
executed by the interpreter."

So, the question is, can the same thing be done for Python apps?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Bug By Any Other Name ...

2009-07-07 Thread Steven D'Aprano
On Mon, 06 Jul 2009 22:18:20 -0700, Chris Rebert wrote:

>> Not so rare. Decimal uses unary plus. Don't assume +x is a no-op.
[...]
> Well, yes, but when would you apply it twice in a row?

My point was that unary + isn't a no-op, and therefore neither is ++. For 
Decimal, I can't think why you'd want to apply ++x, but for other 
objects, who knows?

Here's a toy example:

>>> class Spam(str):
... def __pos__(self):
... return self.__class__("spam " + self)
...
>>> s = Spam("")
>>> s
'spam spam spam spam '



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


Re: Where does setuptools live?

2009-07-07 Thread David Lyon
On Tue, 07 Jul 2009 09:06:49 +0100, Chris Withers 
wrote:
>> What hasn't happened is enough testing of pypi packages and installing
>> with setuptools/pip/enstall from pypi.
> 
> What needs testing?

It's software... therefore it needs testing...

David


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


Re: Where does setuptools live?

2009-07-07 Thread Chris Withers

David Lyon wrote:

On Tue, 07 Jul 2009 09:06:49 +0100, Chris Withers 
wrote:

What hasn't happened is enough testing of pypi packages and installing
with setuptools/pip/enstall from pypi.

What needs testing?


It's software... therefore it needs testing...


Yes, which is why I asked WHAT needs testing? :-)

Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why re.match()?

2009-07-07 Thread Paul Rudin
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.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where does setuptools live?

2009-07-07 Thread David Lyon
On Tue, 07 Jul 2009 13:07:48 +0100, Chris Withers 
wrote:
 What hasn't happened is enough testing of pypi packages and installing
 with setuptools/pip/enstall from pypi.
>>> What needs testing?
>> 
>> It's software... therefore it needs testing...
> 
> Yes, which is why I asked WHAT needs testing? :-)

I've written a package manager gui. I think it is
orderly to comprehensively ascertain which packages will 
and won't install from pypi with the tool.

I'll run the same install test for pip, easyinstall 
and enstall. And come up with a preferred installer.

Which I will then suggest as the preferred tool.

David


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


Re: Where does setuptools live?

2009-07-07 Thread Chris Withers

David Lyon wrote:

I've written a package manager gui. I think it is
orderly to comprehensively ascertain which packages will 
and won't install from pypi with the tool.


I'll run the same install test for pip, easyinstall 
and enstall. And come up with a preferred installer.


Which I will then suggest as the preferred tool.


Cool :-)

If you can publish your results or make the raw data downloadable 
somewhere (especially which packages fail with which installers) I'm 
sure a lot of people would find that *very* interesting...


Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter.Canvas thread safety problem?

2009-07-07 Thread Zdenek Maxa
Hello,

I have started a project using Tkinter. The application performs some
regular checks in a thread and updates Canvas components. I have
observed that sometimes the application hangs when it is about to call
canvas.itemconfig() when the thread is about to terminate in the next loop.

Experimenting with this problem for a while, I have compiled a little
example which always reproduces the problem. Commenting out the line 52
(before canvas.itemconfig()), the example always finishes all right,
having the delay there, it hangs.

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.

Could you please also comment on wxPython thread safety?

I am using:

Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
[GCC 4.3.3]

2.6.26-1-amd64 #1 SMP Fri Mar 13 19:34:38 UTC 2009 x86_64 GNU/Linux

Thanks in advance,
Zdenek
import threading, time
from Tkinter import *


class MyThread(threading.Thread):
def __init__(self, action):
self.action = action
threading.Thread.__init__(self)
self.__stopFlag = False


def run(self):
print "thread started."
while True:
if self.__stopFlag: break
time.sleep(0.2)
if self.__stopFlag: break
print "thread loop running ..."
self.action()
print "thread loop finished, sleeping ..."
print "thread finished."


def setStop(self):
self.__stopFlag = True

# class MyThread 


class Application(object):
def __init__(self, tkRoot):
self.tkRoot = tkRoot
self.tkRoot.protocol("WM_DELETE_WINDOW", self.__onClose)

self.canvas = Canvas(self.tkRoot, bg = "white")
self.canvas.pack(expand = YES, fill = BOTH)

self.curCol = "red"
self.boxId = self.canvas.create_rectangle(50, 50, 120, 120,
  width = 1,
  fill = self.curCol)

self.__thChecker = MyThread(self.toggleColor)
self.__thChecker.start()


def toggleColor(self):
if self.curCol == "red": self.curCol = "green"
else: self.curCol = "red"
# delay here causes self.canvas.itemconfig() to hang on
# self.__thChecker.join()
time.sleep(2) 
self.canvas.itemconfig(self.boxId, fill = self.curCol)


def __onClose(self):
print "setting stop flag ..."
self.__thChecker.setStop()
print "terminating thread ..."
self.__thChecker.join()
if self.__thChecker.isAlive():
print "could not stop the thread."
else:
print "thread stopped successfully."

self.tkRoot.destroy()
print "application shut."


# class Application -

tkRoot = Tk()
tkRoot.geometry("200x200+200+200")
Application(tkRoot)
tkRoot.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Jean-Michel Pichavant

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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Lie Ryan
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.

Me neither.

> 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.

A meaning of a word is meaningless if nobody apart the writer
understands it. The purpose of code is 1) to communicate with the
computer, 2) to communicate with fellow programmer. The second point is
especially important if the code are written for pedantic purpose.
Teaching is largely one-way communication and often students that does
not understand about a slight point could not or would not communicate
their feelings because they think it is too silly. If the use of word is
criticized on a two-way communication channel (e.g. newsgroup), it
should raise a question of whether the word should be described first or
whether a synonym would be more suitable for the purpose. Most of these
do not apply on practical, non-pedantic purpose though, since in
non-pedantic settings you are expected to know and use the jargons
however (in)sensible they may be at first sight.

> 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.

Nobody said code smell... linguistic smell is more appropriate.

> If you 
> don't know the appropriate meanings of the words sense, flag or sign, 
> learn them, don't dumb down my language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Error from Apress book

2009-07-07 Thread Dave Angel

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


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


Re: parsing times like "5 minutes ago"?

2009-07-07 Thread Stefan Behnel
m...@pixar.com wrote:
> I'm looking for something like Tcl's [clock scan] command which parses
> human-readable time strings such as:
> 
> % clock scan "5 minutes ago"
> 1246925569
> % clock scan "tomorrow 12:00"
> 1246993200
> % clock scan "today + 1 fortnight"
> 1248135628
> 
> Does any such package exist for Python?

Is this only for English times or is I18N a concern?

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


Re: A Bug By Any Other Name ...

2009-07-07 Thread MRAB

Dennis Lee Bieber wrote:

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


FORTRAN also used "=" for assignment (and ".EQ." for comparison).

C was derived from BCPL which used ":=" for assignment and "=" for
comparison.
--
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:

> I have been following the discussion about python and pyobjc on the
> iphone, and it seemed to me that the app-store rules prohibited
> embedded interpreters; so, python apps are a no-no.
>
> But now it seems that the Rubyists have the option that we don't. It
> seems there is a company, http://rhomobile.com/home, that has an SDK
> that allows ruby programs to be embedded together with an interpreter
> in an app! More interesting is the fact that several of these hybrid
> apps seem to have been accepted on the itunes app store.
>
> Here's a quote from a representative, found on this blog:
> http://www.rubyinside.com/rhodes-develop-full-iphone-rim-and-symbian-apps-using-ruby-1475.html
>
> "...First of all, to clarify, we precompile all framework and app code
> down to Ruby 1.9 VM bytecode. This yields great performance
> advantages. We also disable eval and other dynamic execution aspects
> of Ruby. In the end, on all platforms your app gets compiled with our
> framework all into one single executable, indistinguishable from any
> other executable.
>
> But even if we were shipping a fullon Ruby interpreter without
> compiling to bytecode and leaving dynamic evaluation enabled (as has
> been well remarked in the blogosphere by now) App Store rule 3.3.2
> does not disallow interpreters but only downloading code to be
> executed by the interpreter."
>
> 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.

Might as well just suck it up and learn C/Objective-C .. it's really not
that hard. It took me about a day to pick up the language and another
two or three to finagle with the libraries.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: module name versus function name resolution conflict.

2009-07-07 Thread Dave Angel

rocky wrote:

Someone recently reported a problem in pydb where a function defined
in his program was conflicting with a module name that pydb uses. I
think I understand what's wrong, but I don't have any elegant
solutions to the problem. Suggestions would be appreciated.

In a nutshell, here's the problem:

In file fns:

  def foo(): print "foo"

In file pdebug.py:

  import fns, sys

  def trace_dispatch(frame, event, arg):
  fns.foo()
  print frame, event, arg
  return trace_dispatch

  sys.settrace(trace_dispatch)
  execfile('myprogram.py')

Finally file myprogram.py:

  def fns(): print "This is the *other* fns"

When you run pdebug.py you get:

$ python pdebug.py
foo
 call None
foo
 line None
Traceback (most recent call last):
  File "pdebug.py", line 7, in 
execfile('myprogram.py')
  File "myprogram.py", line 1, in 
def fns(): print "This is the *other* fns"
  File "pdebug.py", line 3, in trace_dispatch
fns.foo()
AttributeError: 'function' object has no attribute 'foo'


Basically inside the trace hook, local functions are visible and take
precedence over (global) module names. I could move "import fns"
inside trace_dispatch(), but I'd have to do that in all of the methods
that module "fns" is used.  Also note that using the form:
  from fns import foo

would eliminate the conflict on "fns", but I'd still have potential
conflicts on "foo". Using more obscure names (e.g. pydb_fns) would
reduce the chance of a conflict but not eliminate it.

Suggestions?


  
Some context would be useful.  For example, you may be writing pdebug.py 
as a library to be used by other developers, and you want to minimize 
the likelihood that arbitrary code they write will conflict.  If you own 
all the code, I'd just say to rename one or the other.


My preference is also for using import of myprogram, as I've never 
needed execfile().  But if you need one of the features of execfile(), 
and really want myprogram in the same namespace, then you probably ought 
to obfuscate the other import.


Instead of   import fns,try:
  import fns as _module_fns
And of course any references to the module will use the longer name.

The leading underscore is a clue that the name is not to be used outside 
of the module.  And the prefix 'module' helps to make it unlikely 
they'll make a data or function or class with that name.



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


Re: How to map size_t using ctypes?

2009-07-07 Thread Philip Semanchuk


On Jul 6, 2009, at 11:51 PM, Gabriel Genellina wrote:


En Mon, 06 Jul 2009 13:29:21 -0300, Philip Semanchuk
 escribió:

On Jul 6, 2009, at 12:10 PM, Diez B. Roggisch wrote:

Philip Semanchuk wrote:


I can't figure out how to map a C variable of size_t via Python's
ctypes module.


from ctypes import c_size_t


D'oh! [slaps forehead]

That will teach me to RTFM. [...] You'd be surprised at the amount  
of Googling I did without learning this on my own.


Yep, seems like these terms in particular are hard to find.  
Searching for
+ctypes +size_t, the first "good" result comes only at page 3. Bad  
luck...

:(


Fortunately, through my ignorance I may provide enlightenment...this  
conversation is now hit #3 on page 1 =)


If I paste the URL here, will I create an infinite loop?
http://www.google.com/search?q=%2Bctypes+%2Bsize_t


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


Re: Tkinter.Canvas thread safety problem?

2009-07-07 Thread Diez B. Roggisch
Zdenek Maxa wrote:

> Hello,
> 
> I have started a project using Tkinter. The application performs some
> regular checks in a thread and updates Canvas components. I have
> observed that sometimes the application hangs when it is about to call
> canvas.itemconfig() when the thread is about to terminate in the next
> loop.
> 
> Experimenting with this problem for a while, I have compiled a little
> example which always reproduces the problem. Commenting out the line 52
> (before canvas.itemconfig()), the example always finishes all right,
> having the delay there, it hangs.
> 
> 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.
> 
> Could you please also comment on wxPython thread safety?
> 

As a rule of thumb, GUI-toolkits aren't threadsafe. Qt being a notable
exception to this rule.

There are various ways to cope with this, mostly through injecting events
into the event-queue of the main gui thread, or using timers.

This is also true for wx (google wx python threading for a plethora of
information on this)

For Tx, I dimly remember an "after" function that can be used to invoke
timer-based code. Use that to update aggregated data from the events.

Diez
-- 
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


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: 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 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: 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: 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: 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


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


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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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


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: 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


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: 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: 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
 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: 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: 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


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: 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 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


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: 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


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: 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


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: 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


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 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: 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 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 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: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: 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 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: 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: 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


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: 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


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


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


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


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


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: 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: 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: 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: 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: 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: 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 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: 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: 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: 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


  1   2   >