xlutils 1.4.0 released!

2009-08-19 Thread Chris Withers

Hi All,

I'm pleased to announce a new release of xlutils. This is a small
collection of utilities that make use of both xlrd and xlwt to process
Microsoft Excel files. The changes for this release are as follows:

- Add sheet density information and onesheet option to
  xlutils.margins.

- Reduced the memory footprint of xlutils.filter.ColumnTrimmer at the
  expense of speed.

- Fixed incorrect warnings about boolean cells in
  xlutils.filter.ErrorFilter. xlwt has always supported boolean
  cells.

- xlutils.filter.BaseReader now opens workbooks with on_demand = True

- Added support for xlrd Books opened with on_demand as True passed to
  open_workbook.

- Fixed bug when copying error cells.

- Requires the latest versions of xlrd (0.7.1) and xlwt (0.7.2).

To find out more, please read here:

http://www.simplistix.co.uk/software/python/xlutils

In case you're not aware, xlrd and xlwt are two excellent pure-python
libraries for reading and writing Excel files. They run on any platform
and, likely, any implementation of Python without the need for horrific
things like binding to Excel via COM and so needing a Windows machine.

If you use any of xlrd, xlwt or xlutils, the following google group will
be of use:

http://groups.google.com.au/group/python-excel

Hope some of this is of interest, I'd love to hear from anyone who ends
up using it!

cheers,

Chris

--
Simplistix - Content Management, Zope  Python Consulting
   - http://www.simplistix.co.uk



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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations/


[ANN] Pyjamas 0.6 Web Widget Set and python-to-javascript Compiler released

2009-08-19 Thread Luke Kenneth Casson Leighton
Pyjamas 0.6 is finally out: many thanks to everyone who has
contributed.  Special thanks to Kees Bos; Bernd, Bernd and Jurgen from
LovelySystems.com; the people who showed an interest in Pyjamas at
EuroPython 2009; and especially to everyone who has helped during the
pre-releases, with testing and bugreports over the past few weeks.
For a full list of contributors, see CREDITS.

Downloads:
-

http://code.google.com/p/pyjamas/downloads
http://pypi.python.org/pypi/Pyjamas
http://sf.net/projects/pyjamas

Pyjamas
---

Pyjamas is a port of Google Web Toolkit to Python, and thus enables
the development of Rich Media AJAX applications in Python, with no
need for special browser plugins.  Pyjamas contains a stand-alone
python-to-javascript compiler, and also a Widget Set API that looks
very similar to Desktop Widget Set APIs (such as PyQT4 or PyGTK2).

For more information, see:

http://pyjs.org
http://pyjs.org/FAQ.html
http://pyjs.org/features.html

Known bugs: http://code.google.com/p/pyjamas/issues
#227, #228, #229, #230 and #232

Pyjamas-Desktop
---

Pyjamas runs your application in a Web Browser (as javascript); Pyjamas-Desktop
runs exactly the same python application on the Desktop (as python)

http://pyjd.org

Release 0.6 of Pyjamas also incorporates Pyjamas-Desktop directly into
the Pyjamas Distribution.  To use Pyjamas-Desktop there are three choices,
with more planned [MacOSX PyObjC; KDE's PyKHTML].

1) - XULRunner

install hulahop and python-xpcom.  hulahop is distributed with
both Debian and Ubuntu; python-xpcom is part of XULRunner and is
also distributed with both Debian and Ubuntu.  Other users should
investigate the installation instructions for python-xpcom and
hulahop for the operating system of their choice on the appropriate
web sites.

GNU/Linux, FreeBSD and other POSIX systems are strongly advised
to use XULRunner for Pyjamas-Desktop: it is the most stable of the
PyJD ports.

2) - PyWebKitGtk

you will need a patched version of pywebkitgtk:
http://code.google.com/p/pywebkitgtk/issues/detail?id=13

you will need a patched version of webkit:
http://github.com/lkcl/webkit/16401.master

Detailed build instructions are available here:
http://wiki.github.com/lkcl/webkit/helping-with-16401master

3) - MSHTML (experimental!)

For Windows users, all that's required, other than installing python
and Internet Explorer, is one further package: Win32 comtypes.

Win32 comtypes can be downloaded here:
* http://sourceforge.net/projects/comtypes/

The MSHTML version primarily works.  Reports using IE8's MSHTML
engine would be appreciated.

Known bugs: the use of Tab to cycle through Keyboard Focus elements
is ineffective; onkeyup and onkeydown events are unresponsive,
but oddly onkeypress event handling works.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: difference between 2 arrays

2009-08-19 Thread Michel Claveau - MVP
Re ! 

Juste pour signaler qu'il existe un newsgroup en français sur Python, qui 
permet de recevoir des réponses en français (donc plus complètes/détaillées).

@-salutations
-- 
Michel Claveau 

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


can't retrieve data from pyxml

2009-08-19 Thread Sakib
well, i need to retrive data from the following line of xml.

 xs:element name=tblTreacherCollins.Microtia
msdata:Caption=Microtia type=xs:string minOccurs=0 /

i need the Caption and the type data.

is any one out there help me doing that?

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


Re: Using a Callback Function - ftplib

2009-08-19 Thread seldan24
On Aug 18, 6:02 am, Nitebirdz nitebi...@sacredchaos.com wrote:
 On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote:

  I didn't even notice the higher level methods.  I changed the
  retrieval line to:

  ftp.nlst(testfile*.txt)

  This works great.  The result is even captured in an array.  I really
  have no idea what the difference between a LIST and NLST is within
  FTP.  Never delved that deep into it.  I did notice that an NLST will
  return a specific FTP code if a file doesn't exist, whereas a LIST
  doesn't.  So, I ended up using NLST as that'll generate an
  ftplib.error_perm exception.  Based on if the job cares if a file is
  not available or not (some do, some don't), I'll either exit, or
  continue on with the file loop.

 The following thread from a NetBSD mailing list may help clarify this
 issue:

 http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html

 NLST returns a machine-readable list of names, while LIST returns a
 human-readable list.  Hene the presence of the FTP code in the case of
 NLST.  

Nitebirdz,

Thanks for the information.  I knew it stood for 'named list' but had
no idea how that differed from the standard.  I appreciate the link.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't retrieve data from pyxml

2009-08-19 Thread Diez B. Roggisch

Sakib schrieb:

well, i need to retrive data from the following line of xml.

 xs:element name=tblTreacherCollins.Microtia
msdata:Caption=Microtia type=xs:string minOccurs=0 /

i need the Caption and the type data.

is any one out there help me doing that?


That's not XML. It lacks namespace-declarations. So no XML-parser will 
(or should) grok it.


Also, to get help here it's better to show what you already tried, 
instead of simply asking others to do your work for you.


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


Re: Code formatting question: conditional expression

2009-08-19 Thread Diez B. Roggisch
 BTW, from the (admittedly few) responses to my original post, it seems
 there's some sentiment that conditional expressions are a non-Pythonic
 misfeature. Interesting ...

No. I love them. But not if they are so large that they stretch over several
lines (or to many columns).

 foo = bar if cond else baz

is more than fine for me. But

 foo = I_need_to_do_something_really_complicated_here() if cond else baz

isn't, because one doesn't grasp as easily in one look that we're talking a
ternary operator here.

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


Re: Need cleanup advice for multiline string

2009-08-19 Thread Ben Finney
Simon Forman sajmik...@gmail.com writes:

 On Tue, Aug 18, 2009 at 8:42 PM, Ben Finneyben+pyt...@benfinney.id.au wrote:
  We're all unified by our humanity. Bringing any god into the picture
  is surely counter to any goals of unity.

 Unity in humanity is, to my way of thinking, the same as Unity in
 God.

Then you're playing Humpty-Dumpty games with words. You know very well
that “God” has established meanings entirely different from “humanity”,
and those meanings played a part in your choice of that word.

I maintain that you can't consistently make a declaration in favour of
human unity and unfounded religious assertions.

 I think Unity, like None, is a built-in singleton, so to speak.

This is white noise.

  We are one family.
 
  Agreed.

 3

I think we can peaceably leave it at that.

-- 
 \“Spam will be a thing of the past in two years' time.” —Bill |
  `\ Gates, 2004-01-24 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code formatting question: conditional expression

2009-08-19 Thread Bruno Desthuilliers

Richard Brodie a écrit :
John Posner jjpos...@optimum.net wrote in message 
news:mailman.26.1250604346.2854.python-l...@python.org...



 if total  P.BASE:
 excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True)
 else:
 excessblk = None


I wonder if it is appropriate to replace the None sentinel with one that is an 
instance
of Block() e.g.

size = total - P.BASE
excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size 
= 0) )


In which case the last param is possibly redundant - the Block object 
knows its size, so it might be able to know by itself if it's empty.


NB : please notice the 'possibly' and 'might' cautions !-)
--
http://mail.python.org/mailman/listinfo/python-list


NOOB: Developing using python on two different computers

2009-08-19 Thread Smeagol
Hi there,

Occasionally I have to develop on two different computers, and I was
wondering if there was a way to copy the python environment from one
to the other?

Access to the data is trivial (networked database) but various
packages etc exist on one computer, and I want to ensure I have
everything package-wise on the other.

Both are windows machines (native windows box and a Macbook with
VMWare running XP)...

Is it as simple as copying the Python directory, or is there a script
I can run that will tell me what packages are installed on the native
windows box and then I can use easy_install to update the VM partition
on the Macbook?

Much obliged for any help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create functors?

2009-08-19 Thread Bruno Desthuilliers

Terry Reedy a écrit :

Robert Dailey wrote:


I'm using Python 2.6. And using the legacy syntax in the lambda does
not work either. I want to avoid using a def if possible. Thanks.


In Python, writing

name = lambda arg: expr

instead of

def name(arg): return expr

is all negative and no positive and should be avoided.


Except that def is a statement, and as such can't be used as a named 
params when calling a function expecting a callback, ie:


vroom = some_dead('parrot', name=lambda arg: exp)

(notice the 'name = lambda arg: exp' ?-)

Ok, nitpicking. Me ---[]

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


Re: difference between 2 arrays

2009-08-19 Thread John Machin
On Aug 19, 6:56 pm, Michel Claveau -
MVPenleverlesx_xx...@xmclavxeaux.com wrote:

 See the module sets

See especially the notice at the front of the current sets doc which
says deprecated since 2.6 and the comparison down the end which
explains why the built-in set() and frozenset() are better than the
sets module. Starting now to use the sets module is not a good idea
unless the OP is stuck on using Python 2.3 .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with libxml2dom

2009-08-19 Thread Paul Boddie
On 19 Aug, 13:55, Nuno Santos nuno.hespan...@gmail.com wrote:
 I have just started using libxml2dom to read html files and I have some
 questions I hope you guys can answer me.

[...]

   table = body.firstChild
   table.nodeName
 u'text' #?! Why!? Shouldn't it be a table? (1)

You answer this yourself just below.

   table = body.firstChild.nextSibling #why this works? is there a
 text element hidden? (2)
   table.nodeName
 u'table'

Yes, in the DOM, the child nodes of elements include text nodes, and
even though one might regard the whitespace before the first child
element and that appearing after the last child element as
unimportant, the DOM keeps it around in case it really is important.

[...]

 It seems like sometimes there are some text elements 'hidden'. This is
 probably a standard in DOM I simply am not familiar with this and I
 would very much appreciate if anyone had the kindness to explain me this.

Well, the nodes are actually there: they're whitespace used to provide
the indentation in your example. I recommend using XPath to get actual
elements:

table = body.xpath(*)[0] # get child elements and then select the
first

Although people make a big song and dance about the DOM being a
nasty API, it's quite bearable if you use it together with XPath
queries.

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


Re: Parallelization in Python 2.6

2009-08-19 Thread Grant Edwards
On 2009-08-19, Stefan Behnel stefan...@behnel.de wrote:
 Dennis Lee Bieber wrote:

  If they are number crunchers (CPU-bound) and don't make use of
 binary extension libraries that release the GIL (for the most common
 Python implementation), they'll run faster being called in sequence
 since you won't have the overhead of task switching.

 ... unless, obviously, the hardware is somewhat up to date
 (which is not that uncommon for number crunching environments)
 and can execute more than one thing at once.

Even with multiple processors, it'll still be faster to call
them sequentially in a single thread than run them sequentially
in multiple threads with the GIL serializing them.

-- 
Grant Edwards   grante Yow! Gibble, Gobble, we
  at   ACCEPT YOU ...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between 2 arrays

2009-08-19 Thread baalu aanand
On Aug 19, 1:48 pm, Pierre pierre.gaill...@gmail.com wrote:
 Hello,

 I would like to know how to find the difference (set operation)
 between 2 arrays :

 a = array([1,2, 3,2,5,2])
 b = array([1,2])
 I want a - b = [3,5]

 Well, the equivalence of setdiff in matlab...

 I thought a.difference(b) could work, but no : AttributeError:
 'numpy.ndarray' object has no attribute 'difference'

 Thanks !



Hi,

  Here I have given my logic, check whether it helps for you

a = [1,2, 3,2,5,2]
b = [1,2]
j = 0
dif = []
for i in range(len(a)) :
   if a[i] not in b:
 dif.append(a[i])
 j += 1

print dif[k]



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


Re: difference between 2 arrays

2009-08-19 Thread baalu aanand
On Aug 19, 1:48 pm, Pierre pierre.gaill...@gmail.com wrote:
 Hello,

 I would like to know how to find the difference (set operation)
 between 2 arrays :

 a = array([1,2, 3,2,5,2])
 b = array([1,2])
 I want a - b = [3,5]

 Well, the equivalence of setdiff in matlab...

 I thought a.difference(b) could work, but no : AttributeError:
 'numpy.ndarray' object has no attribute 'difference'

 Thanks !

Hi,

  Here I have given my logic, check whether it helps for you

a = [1,2, 3,2,5,2]
b = [1,2]
j = 0
dif = []
for i in range(len(a)) :
   if a[i] not in b:
 dif.append(a[i])
 j += 1

print dif

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


Re: difference between 2 arrays

2009-08-19 Thread Matthias Huening

Pierre (19.08.2009 10:48):

Hello,

I would like to know how to find the difference (set operation)
between 2 arrays :

a = array([1,2, 3,2,5,2])
b = array([1,2])
I want a - b = [3,5]



What about set()?

 a = set([1,2, 3,2,5,2])
 b = set([1,2])
 a.difference(b)
set([3, 5])


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


New message

2009-08-19 Thread La Vie Spirituelle
Test
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between 2 arrays

2009-08-19 Thread David Robinow
On Wed, Aug 19, 2009 at 4:48 AM, Pierrepierre.gaill...@gmail.com wrote:
 Hello,

 I would like to know how to find the difference (set operation)
 between 2 arrays :

 a = array([1,2, 3,2,5,2])
 b = array([1,2])
 I want a - b = [3,5]

 Well, the equivalence of setdiff in matlab...

 I thought a.difference(b) could work, but no : AttributeError:
 'numpy.ndarray' object has no attribute 'difference'

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


import numpy
a = numpy.array([1,2,3,2,5,2])
b = numpy.array([1,2])
c = list(set(a)-set(b))
# or c = numpy.array(list(set(a)-set(b)))   if you want to continue w/ arrays
print c
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read C++ enum in python

2009-08-19 Thread Ludo

Neil Hodgson a écrit :


   For some headers I tried it didn't work until the .* was changed to a
non-greedy .*? to avoid removing from the start of the first comment to
the end of the last comment.

file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data))


Thank you ! I adopt it !

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


Re: difference between 2 arrays

2009-08-19 Thread Diez B. Roggisch
baalu aanand wrote:

 On Aug 19, 1:48 pm, Pierre pierre.gaill...@gmail.com wrote:
 Hello,

 I would like to know how to find the difference (set operation)
 between 2 arrays :

 a = array([1,2, 3,2,5,2])
 b = array([1,2])
 I want a - b = [3,5]

 Well, the equivalence of setdiff in matlab...

 I thought a.difference(b) could work, but no : AttributeError:
 'numpy.ndarray' object has no attribute 'difference'

 Thanks !
 
 
 
 Hi,
 
   Here I have given my logic, check whether it helps for you
 
 a = [1,2, 3,2,5,2]
 b = [1,2]
 j = 0
 dif = []
 for i in range(len(a)) :
if a[i] not in b:
  dif.append(a[i])
  j += 1
 
 print dif[k]


EEEK, quadratic behavior!!

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


Re: difference between 2 arrays

2009-08-19 Thread Robert Kern

On 2009-08-19 01:48 AM, Pierre wrote:

Hello,

I would like to know how to find the difference (set operation)
between 2 arrays :

a = array([1,2, 3,2,5,2])
b = array([1,2])
I want a - b = [3,5]

Well, the equivalence of setdiff in matlab...


You will want to ask numpy questions on the numpy mailing list.

  http://www.scipy.org/Mailing_Lists

Using set() is frequently a good option, but for large arrays, you will want to 
avoid the overhead of converting to and from sets and use numpy.setdiff1d(a, b):


In [2]: a = array([1,2, 3,2,5,2])

In [3]: b = array([1,2])

In [4]: numpy.setdiff1d(a, b)
Out[4]: array([3, 5])

--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: How do I convert an iterator over bytes into a str?

2009-08-19 Thread markscottwright
On Aug 18, 6:52 pm, Jan Kaliszewski z...@chopin.edu.pl wrote:
 19-08-2009 o 00:24:20 markscottwright markscottwri...@gmail.com wrote:

  What's the correct way to turn an iterator over bytes into a string?
  This works, but, ewww:
      In [8]: .join(iter(four score and seven years ago))
      Out[8]: 'four score and seven years ago'

 But it is the correct way (and even recommended over s=s+t or s+=t, when
 applicable
 -- see:  
 http://docs.python.org/library/stdtypes.html#sequence-types-str-unico...).

 Cheers,
 *j

 --
 Jan Kaliszewski (zuo) z...@chopin.edu.pl

Thanks Jan (and all other responders).  I suppose I shouldn't be
surprised - it's a known wart (http://wiki.python.org/moin/
PythonWarts), but it just looks so darn wrong.  It is, as you point
out, much faster than better looking alternatives, though -
http://www.skymind.com/~ocrow/python_string/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-19 Thread Aahz
In article mailman.18.1250595423.2854.python-l...@python.org,
Jean-Michel Pichavant  jeanmic...@sequans.com wrote:
MRAB wrote:
 Carl Banks wrote:
 On Aug 17, 10:03 am, Jean-Michel Pichavant jeanmic...@sequans.com
 wrote:

 I'm no English native, but I already heard women/men referring to a
 group as guys, no matter that group gender configuration. It's even
 used for group composed exclusively of women. Moreover it looks like a
 *very* friendly form, so there is really nothing to worry about it.

 I like how being very friendly means calling people after a guy who
 tried to blow up the English Parliament.

 Guy Fawkes adopted the name Guido while fighting for the Spanish in the
 Low Countries:

 http://en.wikipedia.org/wiki/Guy_Fawkes

I didn't get Carl's reference. The only thing I know about blowing the 
parliament is from the movie V for Vendetta (no comment please !).

You should read the original comic book, it's much more interesting (and
clearly mentions the Guy Fawkes connection).
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

I saw `cout' being shifted Hello world times to the left and stopped
right there.  --Steve Gonedes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between 2 arrays

2009-08-19 Thread sturlamolden
On 19 Aug, 01:48, Pierre pierre.gaill...@gmail.com wrote:

 Well, the equivalence of setdiff in matlab...

That would be numpy.setdiff1d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recording input from USB port and write to text file

2009-08-19 Thread Simon Forman
On Aug 18, 7:33 pm, Allan af2...@gmail.com wrote:
 Hi! I'm fairly new to Python.  I understand the basics basics but I'm
 been trying to write a simple python code that will let me read input
 data (such as mouse movement) from my USB port and write it in a text
 file and I am so lost.  Can anyone help or direct me to some
 resources?  Thank you!

This isn't exactly what you were looking for, but maybe it will give
you some ideas:


from Tkinter import *

def printMotionEvents(event):
print mouse coords: %i x %i % (event.x, event.y)

t = Tk()
t.bind('Motion', printMotionEvents)
t.mainloop()


This script creates a little Tkinter window and then makes it so that
when you move the mouse over the window the mouse coordinates are
printed to stdout.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Database query execution times in Python?

2009-08-19 Thread Aahz
In article mailman.108.1250247672.2903.python-l...@python.org,
pwnedd  keith.hugh...@gmail.com wrote:

 Look up EXPLAIN

Thanks for the suggestion. I don't see any option to have EXPLAIN display
the query time though?

My suggestion was partly a gentle push toward a database forum to get
more information -- this isn't really a Python question.  Unless all you
want to do is get the wall-clock time, in which case just use
time.time().
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

Given that C++ has pointers and typecasts, it's really hard to have a
serious conversation about type safety with a C++ programmer and keep a
straight face.  It's kind of like having a guy who juggles chainsaws
wearing body armor arguing with a guy who juggles rubber chickens wearing
a T-shirt about who's in more danger.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-19 Thread Simon Forman
On Aug 19, 12:05 am, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Simon Forman sajmik...@gmail.com writes:
  On Tue, Aug 18, 2009 at 8:42 PM, Ben Finneyben+pyt...@benfinney.id.au 
  wrote:
   We're all unified by our humanity. Bringing any god into the picture
   is surely counter to any goals of unity.

  Unity in humanity is, to my way of thinking, the same as Unity in
  God.

 Then you're playing Humpty-Dumpty games with words. You know very well
 that “God” has established meanings entirely different from “humanity”,
 and those meanings played a part in your choice of that word.

 I maintain that you can't consistently make a declaration in favour of
 human unity and unfounded religious assertions.

  I think Unity, like None, is a built-in singleton, so to speak.

 This is white noise.

   We are one family.

   Agreed.

  3

 I think we can peaceably leave it at that.

Hear hear!

(FWIW, I've always admired Humpty Dumpty's attitude to words.  Have
you ever read R.A. Wilson's Quantum Psychology?)

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


Re: httplib incredibly slow :-(

2009-08-19 Thread Aahz
In article mailman.133.1250270175.2903.python-l...@python.org,
Chris Withers  ch...@simplistix.co.uk wrote:
Aahz wrote:

 What do you need to know for a decent example?

Simple download of a file from a url with some auth headers added would 
do me.

Well, I've hacked up some sample code from my company's codebase:

# !!! UNTESTED !!!
c = pycurl.Curl()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.USERPWD, %s:%s % (user, pwd))
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.CONNECTTIMEOUT, 30)
f = StringIO()
c.setopt(pycurl.WRITEDATA, f)
c.perform()
c.close()
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

Given that C++ has pointers and typecasts, it's really hard to have a
serious conversation about type safety with a C++ programmer and keep a
straight face.  It's kind of like having a guy who juggles chainsaws
wearing body armor arguing with a guy who juggles rubber chickens wearing
a T-shirt about who's in more danger.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate keyboard/mouse event under windows

2009-08-19 Thread Ray
On Aug 19, 2:07 pm, yaka gu.yakahug...@gmail.com wrote:
 Read this and see if it helps:

 http://kvance.livejournal.com/985732.html

is there a way to generate a 'true' keyboard event? (works like user
pressed a key on keyboard)
not send the 'send keyboard event to application' ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and PHP encryption/decryption

2009-08-19 Thread Jean-Claude Neveu
I'm looking for a recommendation about encryption/decryption packages 
for Python.


I'm working on a project that will require me to store some values in 
a database in encrypted format. I'll be storing them from a PHP 
script and retrieving them (decrypting them) using Python. I'm 
currently using PHP's mcrypt package to encrypt the values, and I'm 
using AES for encryption, so something AES-compatible would be ideal. 
However, the project is at the development stage so I can easily 
change how I'm encrypting things in PHP if there is a compelling 
reason on the Python side of things to do so.


Many Thanks,
Jean-Claude

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


Re: Any way to adjust difflib algorithm?

2009-08-19 Thread Aahz
In article fmqdncomnpg-jrjxnz2dnuvz_tti4...@posted.visi,
Grant Edwards  inva...@invalid wrote:
On 2009-08-14, Grant Edwards inva...@invalid wrote:

 In my particular usage, no lines have ever been
 inserted/deleted, so perhaps I should be running diffs on
 individual lines instead?  If I do that, I can't figure out
 how to generate HTML output.

I ended up using the SequenceMatcher on individual pairs of
lines and generating my own HTML based on the results of
get_matching_blocks().

That produced the desired results.

Good work!  Note that IME most diff software shows changed lines as a
delete-and-add.  For example, diff -u
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

Given that C++ has pointers and typecasts, it's really hard to have a
serious conversation about type safety with a C++ programmer and keep a
straight face.  It's kind of like having a guy who juggles chainsaws
wearing body armor arguing with a guy who juggles rubber chickens wearing
a T-shirt about who's in more danger.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NOOB: Developing using python on two different computers

2009-08-19 Thread Jonathan Gardner
On Aug 19, 6:50 am, Smeagol mczwhin...@yahoo.com wrote:
 Hi there,

 Occasionally I have to develop on two different computers, and I was
 wondering if there was a way to copy the python environment from one
 to the other?

 Access to the data is trivial (networked database) but various
 packages etc exist on one computer, and I want to ensure I have
 everything package-wise on the other.

 Both are windows machines (native windows box and a Macbook with
 VMWare running XP)...

 Is it as simple as copying the Python directory, or is there a script
 I can run that will tell me what packages are installed on the native
 windows box and then I can use easy_install to update the VM partition
 on the Macbook?


Simple copy won't do it.

Check out virtualenv (http://pypi.python.org/pypi/virtualenv).
Reinstalling each env from scratch is usually the best bet. List your
dependencies in your packages and all you have to do is easy_install
your packages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to adjust difflib algorithm?

2009-08-19 Thread Grant Edwards
On 2009-08-19, Aahz a...@pythoncraft.com wrote:
 In article fmqdncomnpg-jrjxnz2dnuvz_tti4...@posted.visi,
 Grant Edwards  inva...@invalid wrote:
On 2009-08-14, Grant Edwards inva...@invalid wrote:

 In my particular usage, no lines have ever been
 inserted/deleted, so perhaps I should be running diffs on
 individual lines instead?  If I do that, I can't figure out
 how to generate HTML output.

I ended up using the SequenceMatcher on individual pairs of
lines and generating my own HTML based on the results of
get_matching_blocks().

That produced the desired results.

 Good work!  Note that IME most diff software shows changed
 lines as a delete-and-add.  For example, diff -u

Right -- though difflib did show _some_ lines as changed rather
than deleted/added, it wasn't obvious how it decided between
the two.  I suspect it used some sort of percentage-changed
threshold.

For this application both files had all the same lines (by
definition), so what I was interested in was what parts of each
line changed.

-- 
Grant Edwards   grante Yow! I just heard the
  at   SEVENTIES were over!!  And
   visi.comI was just getting in touch
   with my LEISURE SUIT!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python doc available in emacs info format?

2009-08-19 Thread A.Politz
On Aug 17, 6:43 am, Xah Lee xah...@gmail.com wrote:
 btw, is there still [no] info format for python doc?

 i feel kinda sad [...]
 Part of this is due to [other peoples fault]

Someone started a rst2info project (google it), maybe you want to help
this guy out.

Though, he might be a techgeeker, so watch out !

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


Dictionary from a list

2009-08-19 Thread iu2
Hi all,

I need to create a dictionary out of a list.

Given the list [1, 2, 3, 4, 5, 6]

I need the dictionary: {1:2, 3:4, 5:6}

I'll appreciate your help
Thanks
iu2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code formatting question: conditional expression

2009-08-19 Thread John Posner

Diez wrote:

No. I love them. But not if they are so large that they stretch over several
lines (or to many columns).

 foo = bar if cond else baz

is more than fine for me. But

 foo = I_need_to_do_something_really_complicated_here() if cond else baz

isn't, because one doesn't grasp as easily in one look that we're talking a
ternary operator here.
  


But the right side of my brain (see Peter Keller's discussion in the 
recent importance of syntax thread) finds it quite easy to recognize 
this as a ternary op:


 foo = (I_need_to_do_something_really_complicated_here()
   if cond else
   baz)

The whitespace below foo provides a visual hint, which is confirmed by 
the nearby appearance of if on the second line. De gustibus non est 
disputandum! (or not)


Many thanks to all responders!

-John

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


Re: Dictionary from a list

2009-08-19 Thread Diez B. Roggisch

iu2 schrieb:

Hi all,

I need to create a dictionary out of a list.

Given the list [1, 2, 3, 4, 5, 6]

I need the dictionary: {1:2, 3:4, 5:6}


dict(zip(l[::2], l[1::2]))

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


Re: Python and PHP encryption/decryption

2009-08-19 Thread Diez B. Roggisch

Jean-Claude Neveu schrieb:
I'm looking for a recommendation about encryption/decryption packages 
for Python.


I'm working on a project that will require me to store some values in a 
database in encrypted format. I'll be storing them from a PHP script and 
retrieving them (decrypting them) using Python. I'm currently using 
PHP's mcrypt package to encrypt the values, and I'm using AES for 
encryption, so something AES-compatible would be ideal. However, the 
project is at the development stage so I can easily change how I'm 
encrypting things in PHP if there is a compelling reason on the Python 
side of things to do so.


With PyCrypto[1] you have a wide range of choices, amongst others AES.

If that's the best algorithm, or even the best python-package to 
implement it, I don't know.



[1] http://www.dlitz.net/software/pycrypto/


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


Re: recording input from USB port and write to text file

2009-08-19 Thread Diez B. Roggisch

Simon Forman schrieb:

On Aug 18, 7:33 pm, Allan af2...@gmail.com wrote:

Hi! I'm fairly new to Python.  I understand the basics basics but I'm
been trying to write a simple python code that will let me read input
data (such as mouse movement) from my USB port and write it in a text
file and I am so lost.  Can anyone help or direct me to some
resources?  Thank you!


This isn't exactly what you were looking for, but maybe it will give
you some ideas:


from Tkinter import *

def printMotionEvents(event):
print mouse coords: %i x %i % (event.x, event.y)

t = Tk()
t.bind('Motion', printMotionEvents)
t.mainloop()


This script creates a little Tkinter window and then makes it so that
when you move the mouse over the window the mouse coordinates are
printed to stdout.


If it has focus.

The overall problem is hard - see e.g. this:

http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx

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


Re: Dictionary from a list

2009-08-19 Thread iu2
On Aug 19, 11:39 pm, Diez B. Roggisch de...@nospam.web.de wrote:
 iu2 schrieb:

  Hi all,

  I need to create a dictionary out of a list.

  Given the list [1, 2, 3, 4, 5, 6]

  I need the dictionary: {1:2, 3:4, 5:6}

 dict(zip(l[::2], l[1::2]))

 Diez

Wow, this is cool!

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


Re: recording input from USB port and write to text file

2009-08-19 Thread Diez B. Roggisch

Diez B. Roggisch schrieb:

Simon Forman schrieb:

On Aug 18, 7:33 pm, Allan af2...@gmail.com wrote:

Hi! I'm fairly new to Python.  I understand the basics basics but I'm
been trying to write a simple python code that will let me read input
data (such as mouse movement) from my USB port and write it in a text
file and I am so lost.  Can anyone help or direct me to some
resources?  Thank you!


This isn't exactly what you were looking for, but maybe it will give
you some ideas:


from Tkinter import *

def printMotionEvents(event):
print mouse coords: %i x %i % (event.x, event.y)

t = Tk()
t.bind('Motion', printMotionEvents)
t.mainloop()


This script creates a little Tkinter window and then makes it so that
when you move the mouse over the window the mouse coordinates are
printed to stdout.


If it has focus.

The overall problem is hard - see e.g. this:

http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx 


But then, there is a solution :)

http://pypi.python.org/pypi/pyHook/1.4/

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


What file is foo in package bar in ?

2009-08-19 Thread northof40
Hi - I think this is a pretty basic question but it's never worried me
before.

To improve my skills I'm reading the source code of a library written
by someone else.

I've come across a problem doing that.

Commonly a function is called like this:

thepackage.theclass.foo

The problem is that 'theclass' is implemented in a file called
nothingliketheclass.py so finding the implemention of foo is a bit
boring.

Now I can grep for foo and depending on how common the method name is
that helps ... or not but I'm sure there must be a better way.

Given an arbitary package is there some programmatic way to 'ask' what
file the method/function is implemented in ?

thanks

R.




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


Re: How to create functors?

2009-08-19 Thread J. Cliff Dyer
On Wed, 2009-08-19 at 15:56 +0200, Bruno Desthuilliers wrote:
 Terry Reedy a écrit :
  Robert Dailey wrote:
  
  I'm using Python 2.6. And using the legacy syntax in the lambda does
  not work either. I want to avoid using a def if possible. Thanks.
  
  In Python, writing
  
  name = lambda arg: expr
  
  instead of
  
  def name(arg): return expr
  
  is all negative and no positive and should be avoided.
 
 Except that def is a statement, and as such can't be used as a named 
 params when calling a function expecting a callback, ie:
 
 vroom = some_dead('parrot', name=lambda arg: exp)
 
 (notice the 'name = lambda arg: exp' ?-)
 

Which offers no added functionality over:

  def name_func(arg):
  return exp

  vroom = some_dead('parrot', name=name_func)

except for confusion in debugging. :)  (See other excessively long
threads on lambda for further discussion of the debugging headaches
caused by lambdas.


 Ok, nitpicking. Me ---[]
 
 g

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


Re: What file is foo in package bar in ?

2009-08-19 Thread Christian Heimes

northof40 wrote:

Given an arbitary package is there some programmatic way to 'ask' what
file the method/function is implemented in ?


Indeed, the inspect module contains several useful functions for the 
job, for example

http://docs.python.org/library/inspect.html#inspect.getfile

Christian

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


#elements of seq A in seq B

2009-08-19 Thread Neal Becker
What would be a time efficient way to count the number of occurrences of 
elements of sequence A in sequence B?  (in this particular case, these 
sequences are strings, if that matters).

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


Re: difference between 2 arrays

2009-08-19 Thread Jan Kaliszewski

19-08-2009 o 10:56:20 Michel Claveau -
MVPenleverLesX_XXmcX@xmclavxeaux.com wrote:


(envoyé via news:\\news.wanadoo.fr\comp.lang.python)

Hi!

See the module sets


No, see the builtin set type. Module sets is deprecated (removed in Py 3.x)

--
Jan Kaliszewski (zuo) z...@chopin.edu.pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: What file is foo in package bar in ?

2009-08-19 Thread northof40
On Aug 20, 11:06 am, Christian Heimes li...@cheimes.de wrote:
 northof40 wrote:
  Given an arbitary package is there some programmatic way to 'ask' what
  file the method/function is implemented in ?

 Indeed, the inspect module contains several useful functions for the
 job, for examplehttp://docs.python.org/library/inspect.html#inspect.getfile

 Christian

That's really great thanks - just what I was after.

regards

R.

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


Re: Barcodes

2009-08-19 Thread Ronn Ross
On Wed, Aug 19, 2009 at 9:19 AM, Ronn Ross ronn.r...@gmail.com wrote:

 I was hoping that python would have a library to help me print my own bar
 codes? We will need labels in all sizes and most label printer just work
 with 1 or 2 sizes. I would like to just print a grid of different sizes on
 standard paper. Does python have a bar code printing library?



 On Mon, Aug 17, 2009 at 4:55 PM, Tim Chase 
 python.l...@tim.thechases.comwrote:

  My company needs a small inventory management app. Does
 python have any libraries to help with reading and writing
 bar codes?


 I've written bar code apps and python really doesn't enter
 into that part of things.  Printers generally have bar code
 printing capabilities so you just send the right escape
 sequences and you get the bar codes. To read them, bar code
 readers scan and translate before sending the values through
 typically a keyboard wedge or serial port.


 To add to what Emile mentions, most barcode readers present a
 keyboard-wedge interface, so that scanning a barcode merely appears as if
 you typed it at the keyboard (USB readers show up as a HID profile).  Often
 they'll have configuration barcodes that you can scan to tweak the profile
 (such as pressing enter, tab or an arrow-key after sending the barcode;
 controlling beep tone  volume, etc).

 For printing barcodes, you can use any number of solutions -- the most
 popular usually just involves installing a barcode font and then rendering
 text in that font to your desired output canvas.  I believe there are some
 native rendering solutions as well, but I've not investigated since the font
 method was more than sufficient for my wants.

 -tkc




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


 I found this library, but no documentation(
https://cybernetics.hudora.biz/projects/wiki/huBarcode). Has anyone used
this or know of a similar library with better documentation?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary from a list

2009-08-19 Thread Jan Kaliszewski

19-08-2009 o 22:52:54 iu2 isra...@elbit.co.il wrote:


On Aug 19, 11:39 pm, Diez B. Roggisch de...@nospam.web.de wrote:

iu2 schrieb:

 Hi all,

 I need to create a dictionary out of a list.

 Given the list [1, 2, 3, 4, 5, 6]

 I need the dictionary: {1:2, 3:4, 5:6}

dict(zip(l[::2], l[1::2]))


Or (for long lists, when memory becomes expensive):

dict(li[i:i+2] for i in xrange(0, len(li), 2))

Or probably better:

from itertools import islice, izip
dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2)))

Cheers,
*j

--
Jan Kaliszewski (zuo) z...@chopin.edu.pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: #elements of seq A in seq B

2009-08-19 Thread Jan Kaliszewski

20-08-2009 o 01:19:24 Neal Becker ndbeck...@gmail.com wrote:


What would be a time efficient way to count the number of occurrences of
elements of sequence A in sequence B?  (in this particular case, these
sequences are strings, if that matters).


If you mean: to count occurences of each element of A (separately) in B...

Hm, maybe something like this:

  # result as a dict {element of A: how many occurences in B, ...}
  dict((element, B.count(element)) for element in A)


If you mean: to count non overlaping occurences of string A in B
-- simply:

  B.count(A)


Regards,
*j

--
Jan Kaliszewski (zuo) z...@chopin.edu.pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary from a list

2009-08-19 Thread Jan Kaliszewski

20-08-2009 o 02:05:57 Jan Kaliszewski z...@chopin.edu.pl wrote:


Or probably better:

 from itertools import islice, izip
 dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2)))


Or similarly, perhaps more readable:

iterator = iter(li)
dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2))

--
Jan Kaliszewski (zuo) z...@chopin.edu.pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying a class type - bad practice?

2009-08-19 Thread greg

James Harris wrote:

I don't know yet whether it will be
easier to modify the tree or to create a new one for each phase.


You can create a new tree using this style as
well. Just have each method create and return a
new node instead of modifying the existing one.

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


Re: python doc available in emacs info format?

2009-08-19 Thread Nathan Keel
A.Politz wrote:

 On Aug 17, 6:43 am, Xah Lee xah...@gmail.com wrote:
 btw, is there still [no] info format for python doc?

 i feel kinda sad [...]
 Part of this is due to [other peoples fault]
 
 Someone started a rst2info project (google it), maybe you want to help
 this guy out.
 
 Though, he might be a techgeeker, so watch out !
 
 -ap

Don't bother with this Xah Lee clown.  He posts random crap because he
thinks everyone wants to hear what he has to say about unrelated
subject material and thinks he looks smart for doing it. Unfortunately,
he usually lacks a clue about any topic he brings up (and he always
starts a new thread like he's some authority).  His goals are nothing
more than to post arrogant, clueless rants thinking he's showing off. 
this is why he ALWAYS cross posts to the same groups (Emacs, Python,,
Perl, etc.), even when the topic or content has nothing to do with
those things.  He thinks people in these groups automatically respect
him, when most have killfiled him.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create functors?

2009-08-19 Thread Paul Rubin
Robert Dailey rcdai...@gmail.com writes:
 I want to simply wrap a function up into an object so it can be called
 with no parameters. 

Nitpick: what you are asking for is called a closure.  Functor means
something completely different.  As a few other people have explained,
print in python 2.x is a statement rather than a function.  You could
use sys.stdout.write instead of print. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and PHP encryption/decryption

2009-08-19 Thread Paul Rubin
Jean-Claude Neveu jcn-france1...@pobox.com writes:
 I'm working on a project that will require me to store some values in
 a database in encrypted format. I'll be storing them from a PHP script
 and retrieving them (decrypting them) using Python. I'm currently
 using PHP's mcrypt package to encrypt the values, and I'm using AES
 for encryption, so something AES-compatible would be ideal.

There are several python libraries that support AES in the standard
operating modes.  If you are doing something sensible on the PHP side,
you should be able to get Python to interoperate with it.  Be careful
that you are doing the right things algorithmically in terms of modes,
IV's, etc.  If you don't know what you're doing in this area, it's
best to (at minimum) seek more specific advice.

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


Re: #elements of seq A in seq B

2009-08-19 Thread Simon Forman
On Aug 19, 8:17 pm, Jan Kaliszewski z...@chopin.edu.pl wrote:
 20-08-2009 o 01:19:24 Neal Becker ndbeck...@gmail.com wrote:

  What would be a time efficient way to count the number of occurrences of
  elements of sequence A in sequence B?  (in this particular case, these
  sequences are strings, if that matters).

 If you mean: to count occurences of each element of A (separately) in B...

 Hm, maybe something like this:

    # result as a dict {element of A: how many occurences in B, ...}
    dict((element, B.count(element)) for element in A)

 If you mean: to count non overlaping occurences of string A in B
 -- simply:

    B.count(A)

 Regards,
 *j

 --
 Jan Kaliszewski (zuo) z...@chopin.edu.pl

You don't want to use count() in a case like this because it iterates
through B len(A) times, i.e. this algorithm is O(A x B).

If all you want is the total you can do it like this:

def f(a, b):
a = set(a)
return sum(item in a for item in b)


A = 'some string'
B = 'another string'

print f(A, B) # prints 12


If you want to know the count for each element you can use this:

from collections import defaultdict

def g(a, b):
a = set(a)
d = defaultdict(int)
for item in b:
if item in a:
d[item] += 1
return d

print g(A, B)

# prints defaultdict(type 'int', {' ': 1, 'e': 1, 'g': 1, 'i': 1,
'o': 1, 'n': 2, 's': 1, 'r': 2, 't': 2})

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


Re: How do I convert an iterator over bytes into a str?

2009-08-19 Thread alex23
markscottwright markscottwri...@gmail.com wrote:
 Thanks Jan (and all other responders).  I suppose I shouldn't be
 surprised - it's a known wart (http://wiki.python.org/moin/
 PythonWarts), but it just looks so darn wrong.

Don't forget that it's exceptionally easy to create your own mechanism
for doing this:

  def join(seq, sep):
 return sep.join(map(str, seq))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #elements of seq A in seq B

2009-08-19 Thread Tomasz Rola
On Wed, 19 Aug 2009, Neal Becker wrote:

 What would be a time efficient way to count the number of occurrences of 
 elements of sequence A in sequence B?  (in this particular case, these 
 sequences are strings, if that matters).

If A and B are rather lengthy, then maybe build a tree from elements of A 
and use it to count elements of B. I.e., tree nodes would be counters. 
Building trees in Python, however, I guess it is a little bit tricky. Of 
course it is possible. But maybe you would rather have this tree 
maintained in C.

Regards
Tomasz Rola

--
** A C programmer asked whether computer had Buddha's nature.  **
** As the answer, master did rm -rif on the programmer's home**
** directory. And then the C programmer became enlightened...  **
** **
** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE is not as interactive as Maple

2009-08-19 Thread laser
In the future, will Python provide programe enviroment like Maple
does? In Maple, you can remove anything unneeded in the editor. And
the code execution order are not necessary in one direction. You can
run any command line on the screen by
push Enter key. These functions gave a lot of flaxibility for users to
start with programming something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #elements of seq A in seq B

2009-08-19 Thread John Machin
On Aug 20, 12:12 pm, Simon Forman sajmik...@gmail.com wrote:
 On Aug 19, 8:17 pm, Jan Kaliszewski z...@chopin.edu.pl wrote:
  If you mean: to count non overlaping occurences of string A in B
  -- simply:

     B.count(A)

 You don't want to use count() in a case like this because it iterates
 through B len(A) times, i.e. this algorithm is O(A x B).

There's seems to be multiple confusion here. Jan was talking about
counting non-overlapping occurrences of string A in [string] B. In
that case B.count(A) is nowhere near O(A*B)... in fact in reasonable
cases it is sub-linear i.e. O(B/A)

See 
http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=68811view=markup

And even a naive implementation of str.count() would not iterate
through B len(A) times.

and list.count() can't be used on its own to solve Neal's problem; its
arg is a single element so it would have to be wrapped in a loop: sum
(B.count(a) for a in A) which would of course be O(A*B)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read C++ enum in python

2009-08-19 Thread Mark Tolonen


Mark Tolonen metolone+gm...@gmail.com wrote in message 
news:h6g9ig$vh...@ger.gmane.org...

[snip]


This is what 3rd party library pyparsing is great for:

begin code--
from pyparsing import *

# sample string with enums and other stuff
sample = '''
   stuff before

   enum hello {
   Zero,
   One,
   Two,
   Three,
   Five=5,
   Six,
   Ten=10
   }

   in the middle

   enum blah
   {
   alpha,
   beta,
   gamma = 10 ,
   zeta = 50
   }

   at the end
   '''

# syntax we don't want to see in the final parse tree
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_equal = Suppress('=')
_comma = Suppress(',')
_enum = Suppress('enum')

identifier = Word(alphas,alphanums+'_')
integer = Word(nums)

enumValue = Group(identifier('name') + Optional(_equal + 
integer('value')))

enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl

# find instances of enums ignoring other syntax
for item,start,stop in enum.scanString(sample):
   id = 0
   for entry in item.list:
   if entry.value != '':
   id = int(entry.value)
   print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
   id += 1
--end code

Output:
HELLO_ZERO = 0
HELLO_ONE = 1
HELLO_TWO = 2
HELLO_THREE = 3
HELLO_FIVE = 5
HELLO_SIX = 6
HELLO_TEN = 10
BLAH_ALPHA = 0
BLAH_BETA = 1
BLAH_GAMMA = 10
BLAH_ZETA = 50


Paul McGuire (pyparsing author) reminded me that:

   enum.ignore(cppStyleComment)

before scanString will skip commented out sections as well.

-Mark


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


Re: basic thread question

2009-08-19 Thread Sean DiZazzo
On Aug 18, 4:58 pm, birdsong david.birds...@gmail.com wrote:
 On Aug 18, 3:18 pm, Derek Martin c...@pizzashack.org wrote:



  On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote:
   I have some simple threaded code...  If I run this
   with an arg of 1 (start one thread), it pegs one cpu, as I would
   expect.  If I run it with an arg of 2 (start 2 threads), it uses both
   CPUs, but utilization of both is less than 50%.  Can anyone explain
   why?  

  Ah, searching while waiting for an answer (the e-mail gateway is a bit
  slow, it seems...) I discovered that the GIL is the culprate.
  Evidently this question comes up a lot.  It would probably save a lot
  of time on the part of those who answer questions here, as well as
  those implementing solutions in Python, if whoever is maintaining the
  docs these days would put a blurb about this in the docs in big bold
  letters...  Concurrency being perhaps the primary reason to use
  threading, essentially it means that Python is not useful for the
  sorts of problems that one would be inclined to solve they way my code
  works (or rather, was meant to).  It would be very helpful to know
  that *before* one tried to implement a solution that way... especially
  for solutions significantly less trivial than mine. ;-)

  Thanks

  --
  Derek D. Martinhttp://www.pizzashack.org/
  GPG Key ID: 0x81CFE75D

   application_pgp-signature_part
   1KViewDownload

 I would still watch that video which will explain a bit more about the
 GIL.

Thank you for the video!  It's good to know, but it raises lots of
other questions in my mind.  Lots of examples would have helped.

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


Re: Read C++ enum in python

2009-08-19 Thread Brian
pygccxml http://www.language-binding.net/pygccxml/pygccxml.html

It uses gccxml to compile your source code into xml, and then makes all of
your source code available to you via a high level and convenient query
interface in python.

On Tue, Aug 18, 2009 at 5:03 PM, Ludo 
olivier.anospamrnospamnnospamanospamenosp...@affaires.net wrote:

 Hello,

 I work in a very large project where we have C++ packages and pieces of
 python code.

 I've been googleing for days but what I find seems really too complicated
 for what I want to do.

 My business is, in python, to read enum definitions provided by the header
 file of an c++ package.
 Of course I could open the .h file, read the enum and transcode it by hand
 into a .py file but the package is regularly updated and thus is the enum.

 My question is then simple : do we have :
- either a simple way in python to read the .h file, retrieve the
 c++ enum and provide an access to it in my python script
- either a simple tool (in a long-term it would be automatically run
 when the c++ package is compiled) generating from the .h file a .py file
 containing the python definition of the enums ?

 Thank you for any suggestion.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: How to create functors?

2009-08-19 Thread Steven D'Aprano
On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote:

 Robert Dailey rcdai...@gmail.com writes:
 I want to simply wrap a function up into an object so it can be called
 with no parameters.
 
 Nitpick: what you are asking for is called a closure.  Functor means
 something completely different.


I'm glad somebody else noticed this. I would have said something about it 
myself, except I wasn't entirely sure my understanding of functor is 
correct. As near as I can tell, a functor is just an object which is 
callable like a function without actually being implemented as a 
function, e.g.:

class Functor:
def __call__(self):
return None

f = Functor()
result = f()



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


starting selenium rc server from python code

2009-08-19 Thread jo
Hi,
Is there anyway to start the selenium rc server within python code?

Thank you
Jo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert an iterator over bytes into a str?

2009-08-19 Thread Steven D'Aprano
On Wed, 19 Aug 2009 20:04:12 -0700, alex23 wrote:

 markscottwright markscottwri...@gmail.com wrote:
 Thanks Jan (and all other responders).  I suppose I shouldn't be
 surprised - it's a known wart (http://wiki.python.org/moin/
 PythonWarts), but it just looks so darn wrong.
 
 Don't forget that it's exceptionally easy to create your own mechanism
 for doing this:
 
   def join(seq, sep):
  return sep.join(map(str, seq))

Oh oh oh my brain hurts!!! Neither seq nor sep are real words, both 
are abbreviations, they differ by a single letter, and the two letters 
are mirror images of each other!!!

This is a recipe for confusion when people get the order of sep and seq 
mixed up. Hopefully in real life code, you'd use a less easily confused 
function signature -- even just spelling out sequence and separator in 
full would reduce confusion to essentially zero.



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


Re: Converting DD MM YYYY into YYYY-MM-DD?

2009-08-19 Thread Mark Tolonen


Gilles Ganault nos...@nospam.com wrote in message 
news:rtqk859vm3rkdfor0gd2u2pq5sftl8m...@4ax.com...

I find it odd that the regex library can't handle European characters


It can.  Read the documentation about the re.LOCALE flag.

-Mark


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


Re: starting selenium rc server from python code

2009-08-19 Thread Steven D'Aprano
On Wed, 19 Aug 2009 21:34:22 -0700, jo wrote:

 Hi,
 Is there anyway to start the selenium rc server within python code?



How would you start the selenium rc server outside of Python code?



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


Re: #elements of seq A in seq B

2009-08-19 Thread Simon Forman
On Aug 19, 11:34 pm, John Machin sjmac...@lexicon.net wrote:
 On Aug 20, 12:12 pm, Simon Forman sajmik...@gmail.com wrote:

  On Aug 19, 8:17 pm, Jan Kaliszewski z...@chopin.edu.pl wrote:
   If you mean: to count non overlaping occurences of string A in B
   -- simply:

      B.count(A)

  You don't want to use count() in a case like this because it iterates
  through B len(A) times, i.e. this algorithm is O(A x B).

 There's seems to be multiple confusion here. Jan was talking about
 counting non-overlapping occurrences of string A in [string] B. In
 that case B.count(A) is nowhere near O(A*B)... in fact in reasonable
 cases it is sub-linear i.e. O(B/A)

 Seehttp://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch

 And even a naive implementation of str.count() would not iterate
 through B len(A) times.

 and list.count() can't be used on its own to solve Neal's problem; its
 arg is a single element so it would have to be wrapped in a loop: sum
 (B.count(a) for a in A) which would of course be O(A*B)

First, thanks for pointing out str.count().  I didn't know of it and I
didn't notice that that was what was being used in Jan's code. (It's
blindingly obvious-- now that you've pointed it out. :] )


Second, I was referring to this:

   dict((element, B.count(element)) for element in A)

not B.count(A). Sorry for not interspersing my comment better.

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


Re: Setuptools - help!

2009-08-19 Thread ryles
On Aug 7, 3:04 pm, Peter Chant rempete...@petezilla.co.uk wrote:
 Robert Kern wrote:
  You need to put main.py into the pphoto package.

  $ mkdir pphoto/
  $ mv main.py pphoto/
  $ touch pphoto/__init__.py

 Thanks, it worked.  Any ideas how to run the resulting scripts without
 installing or running as root?

 Pete

 --http://www.petezilla.co.uk

If you are using Python 2.6+ you have your own site-packages
directory, e.g. ~/.local/lib/python2.6/site-packages. So, if this
package is only for your own use, you can use easy_install's --install-
dir option to have setuptools install it there, and can also set --
script-dir to ~/bin, where your console script will go. This, and
other options are discussed here:

http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing Python Opcodes

2009-08-19 Thread greg

Sreejith K wrote:


I know this is not the best way to do it. But I have to do it at least
to make it *hard* to decompile the python bytecode.
So I compiled Python from source changing some opcode values


It probably wouldn't be all that hard for someone to
figure this out. A possible avenue of attack would be
to use your python to compile a known piece of code
that exercises all the opcodes, and compare the result
with that from a standard python.

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


Re: define class over 2 files

2009-08-19 Thread greg

naveen wrote:

Is it possible to split up a class definition over multiple files?


Not exactly, but you can do variations of this:


... [subclass a class]


Multiple inheritance can also be useful:

# A_Part1.py

class A_Part1:
  ...

# A_Part2.py

class A_Part2:
  ...

# A.py

from A_Part1 import A_Part1
from A_Part2 import A_Part2

class A(A_Part1, A_Part2):
  ...

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


Re: Read C++ enum in python

2009-08-19 Thread AggieDan04
On Aug 18, 6:03 pm, Ludo
olivier.anospamrnospamnnospamanospamenosp...@affaires.net wrote:
 Hello,

 I work in a very large project where we have C++ packages and pieces of
 python code.

 I've been googleing for days but what I find seems really too
 complicated for what I want to do.

 My business is, in python, to read enum definitions provided by the
 header file of an c++ package.
 Of course I could open the .h file, read the enum and transcode it by
 hand into a .py file but the package is regularly updated and thus is
 the enum.

 My question is then simple : do we have :
         - either a simple way in python to read the .h file, retrieve the c++
 enum and provide an access to it in my python script

Try something like this:



file_data = open(filename).read()
# Remove comments and preprocessor directives
file_data = ' '.join(line.split('//')[0].split('#')[0] for line in
file_data.splitlines())
file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data))
# Look for enums: In the first { } block after the keyword enum
enums = [text.split('{')[1].split('}')[0] for text in re.split(r'\benum
\b', file_data)[1:]]

for enum in enums:
last_value = -1
for enum_name in enum.split(','):
if '=' in enum_name:
enum_name, enum_value = enum_name.split('=')
enum_value = int(enum_value, 0)
else:
enum_value = last_value + 1
last_value = enum_value
enum_name = enum_name.strip()
print '%s = %d' % (enum_name, enum_value)
print

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


Re: Diversity in Python

2009-08-19 Thread Hendrik van Rooyen
On Tuesday 18 August 2009 12:38:36 Ben Finney wrote:
 Hendrik van Rooyen hend...@microcorp.co.za writes:
  On Tuesday 18 August 2009 06:45:39 Aahz wrote:
   Mainly an opportunity to flog the new diversity list.
 
  Here my English fails me - flog as in whip, or flog as in sell?

 Yes :-)

Thank you that clears it up.

:-)

- Hendrik

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


Re: recording input from USB port and write to text file

2009-08-19 Thread Diez B. Roggisch

Allan schrieb:

Hi! I'm fairly new to Python.  I understand the basics basics but I'm
been trying to write a simple python code that will let me read input
data (such as mouse movement) from my USB port and write it in a text
file and I am so lost.  Can anyone help or direct me to some
resources?  Thank you!


This isn't as easy as you think. And dependend on your operating-system.

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


Re: Parallelization in Python 2.6

2009-08-19 Thread Stefan Behnel
Dennis Lee Bieber wrote:
 On Tue, 18 Aug 2009 13:45:38 -0700 (PDT), Robert Dailey wrote:
 Really, all I'm trying to do is the most trivial type of
 parallelization. Take two functions, execute them in parallel. This
 type of parallelization is called embarrassingly parallel, and is
 the simplest form. There are no dependencies between the two
 functions. They do requires read-only access to shared data, though.
 And if they are being spawned as sub-processes this could cause
 problems, unless the multiprocess module creates pipelines or other
 means to handle this situation.

It wouldn't be much worth if it didn't, as the subprocess module handles
everything else nicely. See the Queue classes.


   If they are number crunchers (CPU-bound) and don't make use of
 binary extension libraries that release the GIL (for the most common
 Python implementation), they'll run faster being called in sequence
 since you won't have the overhead of task switching.

... unless, obviously, the hardware is somewhat up to date (which is not
that uncommon for number crunching environments) and can execute more than
one thing at once.

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


Re: Inheriting dictionary

2009-08-19 Thread Hendrik van Rooyen
On Tuesday 18 August 2009 21:44:55 Pavel Panchekha wrote:
 I want a dictionary that will transparently inherit from a parent
 dictionary. So, for example:

 
 a = InheritDict({1: one, 2: two, 4: four})
 b = InheritDict({3: three, 4: foobar}, inherit_from=a)

 a[1] # one
 a[4] # four
 b[1] # one
 b[3] # three
 b[4] # foobar
 

 I've written something like this in Python already, but I'm wondering
 if something like this already exists, preferably written in C, for
 speed.

Its not inheritance, but have you looked at the update method?

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


Re: Parallelization in Python 2.6

2009-08-19 Thread Hendrik van Rooyen
On Tuesday 18 August 2009 22:45:38 Robert Dailey wrote:

 Really, all I'm trying to do is the most trivial type of
 parallelization. Take two functions, execute them in parallel. This
 type of parallelization is called embarrassingly parallel, and is
 the simplest form. There are no dependencies between the two
 functions. They do requires read-only access to shared data, though.
 And if they are being spawned as sub-processes this could cause
 problems, unless the multiprocess module creates pipelines or other
 means to handle this situation.

Just use thread then and thread.start_new_thread.
It just works.

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


Re: Read C++ enum in python

2009-08-19 Thread Mark Tolonen


MRAB pyt...@mrabarnett.plus.com wrote in message 
news:4a8b3e2d.7040...@mrabarnett.plus.com...

Ludo wrote:

Hello,

I work in a very large project where we have C++ packages and pieces of 
python code.


I've been googleing for days but what I find seems really too complicated 
for what I want to do.


My business is, in python, to read enum definitions provided by the 
header file of an c++ package.
Of course I could open the .h file, read the enum and transcode it by 
hand into a .py file but the package is regularly updated and thus is the 
enum.


My question is then simple : do we have :
- either a simple way in python to read the .h file, retrieve the c++ 
enum and provide an access to it in my python script
- either a simple tool (in a long-term it would be automatically run 
when the c++ package is compiled) generating from the .h file a .py file 
containing the python definition of the enums ?


Thank you for any suggestion.


Speaking personally, I'd parse the .h file using a regular expression
(re module) and generate a .py file. Compilers typically have a way of
letting you run external scripts (eg batch files in Windows or, in this
case, a Python script) when an application is compiled.


This is what 3rd party library pyparsing is great for:

begin code--
from pyparsing import *

# sample string with enums and other stuff
sample = '''
   stuff before

   enum hello {
   Zero,
   One,
   Two,
   Three,
   Five=5,
   Six,
   Ten=10
   }

   in the middle

   enum blah
   {
   alpha,
   beta,
   gamma = 10 ,
   zeta = 50
   }

   at the end
   '''

# syntax we don't want to see in the final parse tree
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_equal = Suppress('=')
_comma = Suppress(',')
_enum = Suppress('enum')

identifier = Word(alphas,alphanums+'_')
integer = Word(nums)

enumValue = Group(identifier('name') + Optional(_equal + integer('value')))
enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl

# find instances of enums ignoring other syntax
for item,start,stop in enum.scanString(sample):
   id = 0
   for entry in item.list:
   if entry.value != '':
   id = int(entry.value)
   print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
   id += 1
--end code

Output:
HELLO_ZERO = 0
HELLO_ONE = 1
HELLO_TWO = 2
HELLO_THREE = 3
HELLO_FIVE = 5
HELLO_SIX = 6
HELLO_TEN = 10
BLAH_ALPHA = 0
BLAH_BETA = 1
BLAH_GAMMA = 10
BLAH_ZETA = 50

-Mark


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


socket bug or not?

2009-08-19 Thread Gabriel Rossetti

Hello everyone,

I found what was not working in my code (see Twisted mailing list topics 
self.socket.accept() in doRead() in tcp.py has (11, 'Resource 
temporarily unavailable') error, Twisted, PushProducer, Words  big 
msgs, any limit? and Python mailing list topic socket.send : (11, 
'Resource temporarily unavailable')). I was just wondering if this was 
a bug or not, so here it is, I wrote aserver using twisted words' 
xmlstream class. When a client connects, it sends stream and the 
server also sends it, so a bi-directional xmlstream communication is 
established. This works fine, I at some point wrote a webservice to send 
msgs to my system, not using any twisted code, that sends a message to 
my server in this format : streammessage./message/stream. 
This worked fine as long as the messages were small, but if it send 
larger msgs (I tried +128k msgs) the server only received part of the 
msg and then the parser died because of this, so my msg appeared to be 
dropped. I discovered that it was because my webservice did not read the 
stream element sent by the server when it connected (since I was not 
interested in having a bidirectional xml stream communication with it), 
when I added the code to read it, everything worked as expected. I 
tested the webservice to without the server to see if it had a problem, 
using netcat, and it does, so I wonder if there is a bug in the socket 
code or not. Here is the test code :



## Listing 1 Start ##
import socket, time
STREAM_START = stream
STREAM_END = /stream

def sendTestMessage(host, port):
   msg = message + ('a' * 175177) + /message
   burstSize = 4096
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   sock.connect((host, port))
   sock.send(STREAM_START)
   time.sleep(5)
   while msg:
   sent = sock.send(msg[:burstSize])
   print Sending %d bytes... % sent
   if sent == 0:
   raise RuntimeError, socket connection broken
   msg = msg[burstSize:]
   sock.send(STREAM_END)
   sock.close()
## Listing 1 End ##

To test it:

1) open a python interpretor, copy-past the code above
2) open another terminal and run netcat using the following command : 
nc -v -l -p 
3) call the above function using : sendTestMessage(localhost, ), 
it will wait 5 seconds after having sent the stream, for the first 
test, just wait.


The message will be completely send and received by the netcat server, 
now let's test the case I have, where the server sends a stream, to do 
that, repeat the above steps (you have to re-run netcat as it exits when 
the client disconnects), except in step 3 instead of just waiting, type 
stream and press enter in the netcat terminal after having received 
the stream element from the sending code. This time you will see that 
the message is incomplete.


If you send a smaller message, like by replacing the following line :

msg = message + ('a' * 175177) + /message

with :

msg = message + ('a' * (175177/4)) + /message

it works in both cases.

Now test the fixed code :

## Listing 2 Start ##
import socket
STREAM_START = stream
STREAM_END = /stream

def sendTestMessage(host, port):
   msg = message + ('a' * 175177) + /message
   burstSize = 4096
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   sock.connect((host, port))
   sock.send(STREAM_START)
   sock.recv(len(STREAM_START)+1)
   while msg:
   sent = sock.send(msg[:burstSize])
   print Sending %d bytes... % sent
   if sent == 0:
   raise RuntimeError, socket connection broken
   msg = msg[burstSize:]
   sock.send(STREAM_END)
   sock.close()
## Listing 2 End ##

This time the code reads for the stream element after sending the 
stream element so it works, just try the steps described above, the 
ones where you have to type stream and press enter in the netcat 
terminal and this time it works.


Is this a bug in the sockets code, or is this normal? If it's normal I 
think it should be mentioned somewhere. Oh, by the way, I use linux and 
this code was tested only on linux, I don't know if the problem also 
occurs on other platforms.


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


expandtabs acts unexpectedly

2009-08-19 Thread digisat...@gmail.com
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type help, copyright, credits or license for more information.
 ' test\ttest'.expandtabs(4)
' test   test'
 'test \ttest'.expandtabs(4)
'testtest'

1st example: expect returning 4 spaces between 'test', 3 spaces
returned
2nd example: expect returning 5 spaces between 'test', 4 spaces
returned

Is it a bug or something, please advice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: expandtabs acts unexpectedly

2009-08-19 Thread Xavier Ho
On Wed, Aug 19, 2009 at 5:57 PM, digisat...@gmail.com
digisat...@gmail.comwrote:

 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
 [GCC 4.3.3] on linux2
 Type help, copyright, credits or license for more information.
  ' test\ttest'.expandtabs(4)
 ' test   test'
  'test \ttest'.expandtabs(4)
 'testtest'

 Is it a bug or something, please advice.
 --


 It is completely working as intended. What were you expecting instead?

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


Re: Parallelization in Python 2.6

2009-08-19 Thread Paul Rubin
Hendrik van Rooyen hend...@microcorp.co.za writes:
 Just use thread then and thread.start_new_thread.
 It just works.

The GIL doesn't apply to threads made like that?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read C++ enum in python

2009-08-19 Thread Neil Hodgson
AggieDan04:

 file_data = open(filename).read()
 # Remove comments and preprocessor directives
 file_data = ' '.join(line.split('//')[0].split('#')[0] for line in
 file_data.splitlines())
 file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data))

   For some headers I tried it didn't work until the .* was changed to a
non-greedy .*? to avoid removing from the start of the first comment to
the end of the last comment.

file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data))

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


Re: expandtabs acts unexpectedly

2009-08-19 Thread Peter Brett
digisat...@gmail.com digisat...@gmail.com writes:

 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
 [GCC 4.3.3] on linux2
 Type help, copyright, credits or license for more information.
 ' test\ttest'.expandtabs(4)
 ' test   test'
 'test \ttest'.expandtabs(4)
 'testtest'

 1st example: expect returning 4 spaces between 'test', 3 spaces
 returned
 2nd example: expect returning 5 spaces between 'test', 4 spaces
 returned

 Is it a bug or something, please advice.

Consider where the 4-space tabstops are relative to those strings:

 test   test
testtest
^   ^   ^

So no, it's not a bug.

If you just want to replace the tab characters by spaces, use:

test\ttest.replace(\t, )
  ' testtest'
   test \ttest.replace(\t, )
  'test test'

HTH,

   Peter

-- 
Peter Brett pe...@peter-b.co.uk
Remote Sensing Research Group
Surrey Space Centre
-- 
http://mail.python.org/mailman/listinfo/python-list


reading a text file

2009-08-19 Thread superpollo

hi clp

what's the difference between:

while True:
input_line = sys.stdin.readline()
if input_line:
sys.stdout.write(input_line.upper())
else:
break

and:


while True:
try:
sys.stdout.write(sys.stdin.next().upper())
except StopIteration:
break

???

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


Re: reading a text file

2009-08-19 Thread Paul Rubin
superpollo u...@example.net writes:
 while True:
  try:
  sys.stdout.write(sys.stdin.next().upper())
  except StopIteration:
  break

Maybe there is some subtle difference, but it looks like you really mean

   for line in sys.stdin:
   sys.stdout.write(line.upper())
-- 
http://mail.python.org/mailman/listinfo/python-list


difference between 2 arrays

2009-08-19 Thread Pierre
Hello,

I would like to know how to find the difference (set operation)
between 2 arrays :

a = array([1,2, 3,2,5,2])
b = array([1,2])
I want a - b = [3,5]

Well, the equivalence of setdiff in matlab...

I thought a.difference(b) could work, but no : AttributeError:
'numpy.ndarray' object has no attribute 'difference'

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


Re: Identifying a class type - bad practice?

2009-08-19 Thread James Harris
On 18 Aug, 21:50, Chris Rebert c...@rebertia.com wrote:
 On Tue, Aug 18, 2009 at 10:09 AM, James

 Harrisjames.harri...@googlemail.com wrote:
  I am writing some code to form a tree of nodes of different types. The
  idea is to define one class per node type such as

  class node_type_1(node):
   specific properties by name including other node types
  class node_type_2(node):
   specific properties by name including other node types
  etc

  (Class node would hold any common properties).

  When walking the tree I need to know what type of node I'm dealing
  with so polymorphism isn't generally useful. The action to be taken
  depends on the node type.

 I'm sure it relates to the exact type of tree you're walking and the
 calculation you're doing on it, but what is the reason why your code,
 which in the abstract sounds like it will vaguely resemble this:

 def walk_tree(tree):
     if isinstance(tree, node_type_1):
         #code
         walk_tree(subtree)
     elif isinstance(tree, node_type_2):
         #code
         walk_tree(subtree)
     #etc...

 can't be written instead as:

 class node_type_1:
     def walk_tree(self):
         #code
         self.subtree.walk()

 class node_type_2:
     def walk_tree(self):
         #code
         self.subtree.walk()

 #etc

Interesting idea. This may be a better and a more OO solution than
what I had in mind. I'm not sure if I can use this but I'll see how it
fits in as the work progresses.

The tree is for a compiler. Initially the tree is for parsing of
source code. Then it will need to be processed and changed as further
compiler phases are written. I don't know yet whether it will be
easier to modify the tree or to create a new one for each phase.

So I guess whether I use the idea depends on the commonality of
operations.

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


Re: difference between 2 arrays

2009-08-19 Thread Diez B. Roggisch
Pierre wrote:

 Hello,
 
 I would like to know how to find the difference (set operation)
 between 2 arrays :
 
 a = array([1,2, 3,2,5,2])
 b = array([1,2])
 I want a - b = [3,5]
 
 Well, the equivalence of setdiff in matlab...
 
 I thought a.difference(b) could work, but no : AttributeError:
 'numpy.ndarray' object has no attribute 'difference'

Not sure if this works with numpy-arrays, but

set(a) - set(b)

might just work if the arrays are iterable.

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


Re: difference between 2 arrays

2009-08-19 Thread Michel Claveau - MVP
(envoyé via news:\\news.wanadoo.fr\comp.lang.python)

Hi!

See the module sets

@-salutations 
-- 
Michel Claveau 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a text file

2009-08-19 Thread Peter Otten
superpollo wrote:

 hi clp
 
 what's the difference between:
 
 while True:
  input_line = sys.stdin.readline()
  if input_line:
  sys.stdout.write(input_line.upper())
  else:
  break
 
 and:
 
 
 while True:
  try:
  sys.stdout.write(sys.stdin.next().upper())
  except StopIteration:
  break

You should write the latter as

for line in sys.stdin:
sys.stdout.write(line.upper())

or 

sys.stdout.writelines(line.upper() for line in sys.stdin)

You seem to know already that next() and readline() use different ways to 
signal I'm done with the file. Also, after the first StopIteration 
subsequent next() calls are guaranteed to raise a StopIteration. But the 
main difference is that file.next() uses an internal buffer, file.readline() 
doesn't. That means you would lose data if you tried to replace the 
readline() call below with next()

first_line = f.readline()
read_of_the_file = f.read()

In newer Python versions you will get a ValueError when mixing next() and 
read()/readline() but in older Pythons (before 2.5 I think) you are in for a 
surprise.

As 

for line in file: ...

is both the fastest and most readable approach if you want to access a file 
one line at a time I recommend that you use it unless there is a specific 
reason not to.

Peter

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


Re: Scope and classes

2009-08-19 Thread Bruno Desthuilliers

Chris Rebert a écrit :
(snip)

To access class-level variables from within instance methods of the
class, you have 2 options:
A. Use the class name, i.e. Abc.message
B. Reference the class indirectly, i.e. self.__class__.message


Or even simpler - *if* there's no synonym instance attribute:

= self.message

Attribute lookup will try to resolve the attribute name on the class 
(and it's parent classes) if it's not found on the instance.


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


How to create ones own lib

2009-08-19 Thread Horst Jäger

Hi,

I would like to create my own lib hotte.py which I can import like


import string,hotte

. How do I do that?

I'm working on MacOS 10.5.6 .

Thanks in advance

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


Re: How to create ones own lib

2009-08-19 Thread Xavier Ho
On Wed, Aug 19, 2009 at 7:00 PM, Horst Jäger h.jae...@medienkonzepte.dewrote:

 Hi,

 I would like to create my own lib hotte.py which I can import like


import string,hotte

 . How do I do that?


1) Have the hotte.py in the same directory of any of your other Python code
that imports it, or
2) Put the hotte.py file in the Python import directive, whose location I do
not know in Mac.. someone else will know, I'm sure =]

All in all, I'm pretty sure you don't have to compile it or anything, but it
can be an option.

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


Re: How to create ones own lib

2009-08-19 Thread Francesco Bochicchio
On 19 Ago, 11:00, Horst Jäger h.jae...@medienkonzepte.de wrote:
 Hi,

 I would like to create my own lib hotte.py which I can import like

         import string,hotte

 . How do I do that?

 I'm working on MacOS 10.5.6 .

 Thanks in advance

Just create the file 'hotte.py' and place it somewhere python can find
it, that is:
- in the same directory of the code using it (which is most probablyt
what you want to do )
- in a directory listed in  sys.path variable (which you can extend
using sys.path.append(full_path_of_my_library_directory) before
doing import hotte

There are other options, but these should cover your needs.

Ciao
-
FB

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


Re: Scope and classes

2009-08-19 Thread Bruno Desthuilliers

David a écrit :
(snip)


Out of 'Abc.message' and 'self.message', which is the favoured
convention? It would be very easy to accidentally override
'self.messages' with an instance attribute!


Only use 'Abc.message' if you want to make sure you get the Abc class 
'message' attribute - that is, if you want to skip possible overrides in 
subclasses. As far as I'm concerned, I'd tend to consider this bad style 
 unless it's a very very specific implementation point of an abstract 
class (in which case it would probably be named '__message' to prevent 
accidental override) - but YMMV of course.


Use 'self.__class__.message' (or 'type(self).message') if you want to 
make sure you get the class 'message' attribute - that is, if you want 
to honor possible overrides in subclasses, but not per-instance 
override. But then - at least in your example code - I'd use a classmethod:


class Abc:
message = 'Hello World'

@classmethod
def print_message(cls):
print cls.message


Now the most common idiom - that is, outside classmethods - is to just 
use 'self.message'. Someone (even you) might have a very valid reason to 
 override the 'message' attribute on a per-instance basis. FWIW, if you 
start to worry about possible accidental overrides here, then Python 
might not be the right language for you - nothing prevents accidental 
overrides of method and even the class (the '__class__' attribute) 
itself - yes, they are all attributes, and you can dynamically override 
them !-)

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


Re: Read C++ enum in python

2009-08-19 Thread Bill Davy
Mark Tolonen metolone+gm...@gmail.com wrote in message 
news:mailman.89.1250666942.2854.python-l...@python.org...

 MRAB pyt...@mrabarnett.plus.com wrote in message 
 news:4a8b3e2d.7040...@mrabarnett.plus.com...
 Ludo wrote:
 Hello,

 I work in a very large project where we have C++ packages and pieces of 
 python code.

 I've been googleing for days but what I find seems really too 
 complicated for what I want to do.

 My business is, in python, to read enum definitions provided by the 
 header file of an c++ package.
 Of course I could open the .h file, read the enum and transcode it by 
 hand into a .py file but the package is regularly updated and thus is 
 the enum.

 My question is then simple : do we have :
 - either a simple way in python to read the .h file, retrieve the 
 c++ enum and provide an access to it in my python script
 - either a simple tool (in a long-term it would be automatically run 
 when the c++ package is compiled) generating from the .h file a .py file 
 containing the python definition of the enums ?

 Thank you for any suggestion.

 Speaking personally, I'd parse the .h file using a regular expression
 (re module) and generate a .py file. Compilers typically have a way of
 letting you run external scripts (eg batch files in Windows or, in this
 case, a Python script) when an application is compiled.

 This is what 3rd party library pyparsing is great for:

 begin code--
 from pyparsing import *

 # sample string with enums and other stuff
 sample = '''
stuff before

enum hello {
Zero,
One,
Two,
Three,
Five=5,
Six,
Ten=10
}

in the middle

enum blah
{
alpha,
beta,
gamma = 10 ,
zeta = 50
}

at the end
'''

 # syntax we don't want to see in the final parse tree
 _lcurl = Suppress('{')
 _rcurl = Suppress('}')
 _equal = Suppress('=')
 _comma = Suppress(',')
 _enum = Suppress('enum')

 identifier = Word(alphas,alphanums+'_')
 integer = Word(nums)

 enumValue = Group(identifier('name') + Optional(_equal + 
 integer('value')))
 enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
 enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl

 # find instances of enums ignoring other syntax
 for item,start,stop in enum.scanString(sample):
id = 0
for entry in item.list:
if entry.value != '':
id = int(entry.value)
print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
id += 1
 --end code

 Output:
 HELLO_ZERO = 0
 HELLO_ONE = 1
 HELLO_TWO = 2
 HELLO_THREE = 3
 HELLO_FIVE = 5
 HELLO_SIX = 6
 HELLO_TEN = 10
 BLAH_ALPHA = 0
 BLAH_BETA = 1
 BLAH_GAMMA = 10
 BLAH_ZETA = 50

 -Mark




Python and pythoneers are amazing! 


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


Re: Need cleanup advice for multiline string

2009-08-19 Thread Jean-Michel Pichavant

Grant Edwards wrote:

On 2009-08-18, Simon Forman sajmik...@gmail.com wrote:

  

Sexism, racism, homophobia, religious intolerance, etc., all
stem from a fundamental forgetfulness of our Unity in God (as
I would put it) and this is perhaps the single greatest cause
of human misery.



You mean the single greatest cause of human misery isn't
Microsoft Windows?

  

No, emacs is responsible ! Hail to Vi !

JM

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


  1   2   >