Re: Software licenses and releasing Python programs for review

2005-06-04 Thread Robert Kern
Mike Meyer wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
> 
>>But this would only be a restriction if the code were to be
>>redistributed, of course. It's stil perfectly legal to use it
>>internaly without making the modified source available.
> 
> I've heard people argue otherwise on this case. In particular, if you
> allow an employee to use your GPL'ed-but-not-distributed software,
> they are the end user, and have all the rights granted by the GPL. So
> they can distribute the software - possibly to your
> competitors. Employment contracts can't prohibit this, because the GPL
> specifically disallows "distribution" (allowing your employee to use
> the software) under licenses that restrict the rights granted by the
> GPL.
> 
> I don't know whether this would hold water in court. I'd certainly
> hate to be the one responsible for a company finding out the hard way.

Well, the FSF at least thinks that internal use within an organization 
does not constitute distribution.

http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic

"""Does the GPL require that source code of modified versions be posted 
to the public?

 The GPL does not require you to release your modified version. You 
are free to make modifications and use them privately, without ever 
releasing them. This applies to organizations (including companies), 
too; an organization can make a modified version and use it internally 
without ever releasing it outside the organization.

 But if you release the modified version to the public in some way, 
the GPL requires you to make the modified source code available to the 
program's users, under the GPL.

 Thus, the GPL gives permission to release the modified program in 
certain ways, and not in other ways; but the decision of whether to 
release it is up to you."""

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Help with pythonpath

2005-06-04 Thread Tim Roberts
Observer <[EMAIL PROTECTED]> wrote:
>
>Hi, im a newbie both to python and this list.
>I hope someone can help me whith this:
>
>I have a directory structure like this:
>.
>|-- src
>|   `-- pkg
>|   |-- __init__.py
>|   |-- main.py
>|   `-- spkg1
>|   |-- __init__.py
>|   `-- config.py
>`-- src2
>`-- pkg
>|-- __init__.py
>`-- spkg2
>|-- __init__.py
>`-- config2.py
>
>and main.py is a python script that contains this imports:
>
>from pkg.spkg1 import config
>from pkg.spkg2 import config2
>
>executed in linux whith this:
>
>env PYTHONPATH=src:src2 src/pkg/main.py
>Traceback (most recent call last):
>  File "src/pkg/main.py", line 4, in ?
>from pkg.spkg2 import config2
>ImportError: No module named spkg2
>
>changing the order of the python path only inverts the problem, is there
>any way to solve this without changing the directory structure?

Nope.  When Python goes to look for a package called "pkg", it starts at
the beginning of PYTHONPATH and stops as soon as it finds one.  You either
need to use different names for the two packages (pkg1, pkg2), or use a
symbolic link to link spkg2 into the src directory.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


error in usin list with boost

2005-06-04 Thread GujuBoy
i have created a "cpp" file which has the followin code and when i try
to compile it..it does not know what "list" is..it says its
undefined..i also tried using #include 

but no differe...can someone please help.

thanks

static list retrieval_as_list(SplitText &self, int position,
 int retrieveLength) {
list result;

int *characters = new int[retrieveLength];
int lenRet = self.RetrieveUTF32(position, characters,
 retrieveLength);
for (int i=0;ihttp://mail.python.org/mailman/listinfo/python-list


Re: BUG pythonw vs subprocess

2005-06-04 Thread Tim Roberts
Robin Becker <[EMAIL PROTECTED]> wrote:
>John J. Lee wrote:
>> Paul Rubin  writes:
>> 
>>>I thought pythonw didn't provide a console and so it could be that
>>>stdin and stdout aren't connected to anything.  Popen therefore doesn't
>>>make sense.  You have to use sockets or something.
>> 
>> Yeah... I don't know about module subprocess, but I recall there's a
>> known bug where pythonw actually crashes on win9x when you write to
>> sys.stdout, since it's not connected to anything...
>> 
>So then it's not possible to get pythonw apps eg tkinter guis to use 
>subprocess properly? Seems a bit daft to me.

There's no absolute requirement that a tkinter app use pythonw.  If you
call them with python.exe, they'll get a stdin and stdout.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Steven Bethard
Nicolas Fleury wrote:
> I prefer the optional-indentation syntax.  The reason is simple (see my 
> discussion with Andrew), most of the time the indentation is useless, 
> even if you don't have multiple with-statements.  So in my day-to-day 
> work, I would prefer to write:
> 
> def getFirstLine(filename):
> with opening(filename) as file
> return file.readline()
> 
> than:
> 
> def getFirstLine(filename):
> with opening(filename) as file:
> return file.readline()

One of the beauties of PEP 343 is that it can be explained simply in 
terms of current Python syntax.  The expression:

 with EXPR as VAR:
 BLOCK

is equivalent to:

 abc = EXPR
 exc = (None, None, None)
 VAR = abc.__enter__()
 try:
 try:
 BLOCK
 except:
 exc = sys.exc_info()
 raise
 finally:
 abc.__exit__(*exc)

Can you do the same thing for your proposal?  As I understand it you 
want some sort of implicitly-defined BLOCK that starts the line after 
the with statement and runs to the end of the current block...

Do you think the benefit of less indentation outweighs the added 
complexity of explaining the construct?  I still can't think of a good 
way of explaining the semantics you want.  If you could provide an 
explanation that's simple and as explicit as Guido's explanation in PEP 
343, I think that would help your case a lot.

STeVe

P.S.  I think it's a great sign that people are mainly squabbling about 
syntax here.  More likely than not, Guido's already made his mind up 
about the syntax.  So, since no one seems to have any real problems with 
the semantics, I'm hopeful that we'll get a direct implementation of PEP 
343 in the next Python release. =)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Andrew Dalke wrote:
> Consider the following
>
> server = open_server_connection()
> with abc(server)
> with server.lock()
> do_something(server)
>
> server.close()
>
> it would be translated to
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
> do_something(server)
> server.close()
>
> when I meant for the first code example to be implemented
> like this
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
> do_something(server)
>
> server.close()

That's an interesting point.  But I'm not sure if it is a realistic
error.  It would be like using a with-statement without knowing what it
does.  Also, and it seems we agree, these cases are very rare.

>
> (It should probably use the with-block to handle the server open
> and close, but that's due to my lack of imagination in coming up
> with a decent example.)
>
> Because of the implicit indentation it isn't easy to see that
> the "server.close()" is in an inner block and not at the outer
> one that it appears to be in.  To understand the true scoping
> a reader would need to scan the code for 'with' lines, rather
> than just looking at the layout.

But with both syntaxes you only look at the indentation layout, no?  If
you want to know the "scope" of something as you said, it means you have
already scan its "with" statement.  You only need after that to look at
the indentation layout, as with indentation syntax.

It's however less obvious at first look that with-statements implies
some scope, but I feel that Python newcomers usually do the opposite
error instead, thinking their variables have a defined scope as in some
other languages.

> A test for how often this is needed would be to look in existing
> code for the number of try/finally blocks.  I have seen and
> written some gnarly deeply stacked blocks but not often - once
> a year?
>
> That's not to say it's a good indicator.  A lot of existing code
> looks like this

I agree.  It's hard to find a good indicator.  In my case I use both my
Python code (with try/finally typically ending a function) and my C++
code (with typically no {} block created for RAII object scope).  So, my
conclusion, most of the time the indentation will be useless.

> What I mean by all of this is that the new PEP may encourage
> more people to use indented blocks, in a way that can't be
> inferred by simply looking at existing code.  In that case
> your proposal, or the one written

Totally agree.  The with-statement will open the door to new programming
patterns in Python and it's hard to tell from status quo how much it
will be used.

Regards,
Nicolas


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


Re: Easy way to detect hard drives and partitions in Linux

2005-06-04 Thread Mike Meyer
Jeff Epler <[EMAIL PROTECTED]> writes:

>> I need a way to detect hard drives and their partitions... labels would
>> be nice too... I did some googling but did not find anything all too
>> useful. This will strictly be on Linux / Unix so any help would be
>> greatly appreciated.
> You're not going to find a single portable "unix" way of doing this.
> The format of /etc/fstab and /etc/mtab are pretty portable, but they
> only list mountable/mounted partitions, not all partitions.

Worse yet, part of what he asks for - labels - may not exist. Either
that, or may be something different from what he thinks they are. Unix
predates MSDOS, and many Unix systems don't support the MSDOS
partition table. Some make use of them optional on disks.

/etc/fstab and /etc/mtab have worse problems than not listing all
partitions. They list mountable "things", not all of which are
partitions on hard drives. For example, my fstab has entries for a
memory card reader, a floppy drive, a cdr and a cdrw, as well as two
different implementations of procfs.

Checking for MSDOS style partitions will miss a lot of things. Unix
predates MSDOS, and many Unices don't use MSDOS style partitions, or
make their use optional.

It's possible you have hard drives hanging off the system that aren't
visible to the system *at all*. For instance, the device nodes may
never have been created. As others have indicated, some systems expose
information about what's on the various system busses via special file
systems. Those are system-dependent, and are the only way to find
drives that don't have device nodes.  Assuming the device nodes have
been created, they may not be used otherwise, so the only way to find
out about them is groveling through /dev (or /devices, depending on
the Unix in question). However, figuring out which are hard disks and
which are not will be system-dependent.

You could start on this by groveling over the output of mount, or
/etc/fstab (to bad getfsent isn't in the standard library). That
provides clues about what disk drive file names look like, which could
be usefull in looking through /dev. But even then, you're going to
pretty quickly run into the differences between systems.

I'd recommend deciding which Unix you want this to work for, and then
asking the question again for that system. For Linux, you may want to
specify a distribution. And then don't be surprised if the answer
chances with releases of the underlying system.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are OOP's Jargons and Complexities?

2005-06-04 Thread Dale King
Anno Siegel wrote:
> Tassilo v. Parseval <[EMAIL PROTECTED]> wrote in comp.lang.perl.misc:
> 
>>Also sprach Dale King:
>>
>>
>>>David Formosa (aka ? the Platypus) wrote:
>>>
On Tue, 24 May 2005 09:16:02 +0200, Tassilo v. Parseval
<[EMAIL PROTECTED]> wrote: 


>[...] I haven't yet come across a language that is both statically and
>strongly typed, in the strictest sense of the words. I wonder whether
>such a language would be usable at all.


Modula2 claims to be both statically typed and strongly typed.  And
your wonder at its usablity is justified.
>>>
>>>I used a variant of Modula-2 and it was one of the best languages I have 
>>>ever used. That strong, static type checking was a very good thing. It 
>>>often took a lot of work to get the code to compile without error. 
>>>Usually those errors were the programmers fault for trying to play fast 
>>>and loose with data. But once you got it to compile it nearly always worked.
>>
>>I am only familiar with its successor Modula-3 which, as far as I
>>understand, is Modula-2 with uppercased keywords and some OO-notion
>>bolted onto it (I still recall 'BRANDED' references). 
>>
>>I have to say that doing anything with this language was not exactly a
>>delight.
> 
> 
> I've been through Pascal, Modula2 and Oberon, and I agree.
> 
> These languages had an axe to grind.  They were designed (by Niklas
> Wirth) at a time of a raging discussion whether structured programming
> (goto-less programming, mostly) is practical.  Their goal was to prove
> that it is, and in doing so the restrictive aspects of the language
> were probably a bit overdone.

I fail to see how they were that different in terms of structured 
programming than C. The main benefit I was talking had more to do with 
types. It had types that were not compatible just because they had the 
same base type. For example you could have a type inches that was an 
integer and a type ounces that was also integral. Just because they were 
both integral did not make them type compatible. You couldn't just 
assign one to the other without you as the programmer explicitly saying 
that it was OK (by casting).

In the environment I was programming in (engine controls for cars) where 
safety was a critical thing and a programming bug could kill people that 
safety was a very good thing. I think that also has a lot to do with why 
  the government uses Ada.

> In the short run they succeeded.  For a number of years, languages of
> that family were widely used, primarily in educational programming
> but also in implementing large real-life systems.
> 
> In the long run, the languages have mostly disappeared from the scene.

I've posted before that hardly any language that has ever been somewhat 
popular has actually died (depending on your definition of that word). 
When asked for someone to name one once I got Simula for example (the 
forerunner of OO languages). Turns out that it continues to actually 
grow in popularity.

> It has been discovered that "structured programming" is possible in
> about any language.  It turns out that programmers prefer the
> self-discipline it takes to do that in a liberal language over the
> enforced discipline exerted by Papa Pascal and his successors.

There are lots of reasons they have not taken over, although Ada is 
still in wide use. It seems to me that too many people like playing with 
dangerous power tools without the guards in place.

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Ilpo Nyyssönen wrote:
> Nicolas Fleury <[EMAIL PROTECTED]> writes:
>>What about making the ':' optional (and end implicitly at end of current 
>>block) to avoid over-indentation?
>>
>>def foo():
>>with locking(someMutex)
>>with opening(readFilename) as input
>>with opening(writeFilename) as output
>>...
> 
> 
> How about this instead:
> 
> with locking(mutex), opening(readfile) as input:
> ...
> 
> So there could be more than one expression in one with.

I prefer the optional-indentation syntax.  The reason is simple (see my 
discussion with Andrew), most of the time the indentation is useless, 
even if you don't have multiple with-statements.  So in my day-to-day 
work, I would prefer to write:

def getFirstLine(filename):
 with opening(filename) as file
 return file.readline()

than:

def getFirstLine(filename):
 with opening(filename) as file:
 return file.readline()

But I agree that in the case of only one with-statement, that's no big deal.

Also, if multiple with-statements are separated by other indentating 
statements, your proposal doesn't help:

with locking(lock)
if condition:
 with opening(filename) as file
 for line in file:
 ...

would still be needed to be written:

with locking(lock):
 if condition:
 with opening(filename) as file:
 for line in file:
 ...

Regards,
Nicolas

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


Re: any macro-like construct/technique/trick?

2005-06-04 Thread Mike Meyer
Andrew Dalke <[EMAIL PROTECTED]> writes:

> Mac wrote:
>> Is there a way to mimic the behaviour of C/C++'s preprocessor for
>> macros?
>
> There are no standard or commonly accepted ways of doing that.
>
> You could do as Jordan Rastrick suggested and write your own sort
> of preprocessor, or use an existing one.

I've never tried it with python, but the C preprocessor is available
as 'cpp' on most Unix systesm. Using it on languages other than C has
been worthwhile on a few occasions. It would certainly seem to
directly meet the OP's needs.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementtree and CDATA handling

2005-06-04 Thread uche . ogbuji
"If, instead, you want to keep track of where the CDATA sections are,
and output them again without change, you'll need to use an
XML-handling interface that supports this feature. Typically, DOM
implementations do - the default Python minidom does, as does pxdom.
DOM is a more comprehensive but less friendly/Python-like interface for
XML processing. "

Amara in CVS makes it easy to perform the output part of this:

text="""
Document



// 0) then
   {
   return 1
   }
}

//]]>



"""

from amara.binderytools import bind_string
doc = bind_string(text)
print doc.xml(cdataSectionElements=[u'script'])

Output:



Document


 0) then
   {
   return 1
   }
}

//
]]>



Unfortunately, in cooking up this example I did find a bug in the Amara
1.0b1 release that requires a workaround.  I should be releasing 1.0b2
this weekend, which fixes this bug (among other fixes and
improvements).

"If you're generating output for legacy browsers, you might want to
just
use a 'real' HTML serialiser. "

Amara does provide for this, e.g.:

from amara.binderytools import bind_string
doc = bind_string(text)
print doc.xml(method=u"html")

Which automatically and transparently brings to bear the full power of
the XSLT HTML output method.

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Use CSS to display XML, part 2 -
http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html
XML Output with 4Suite & Amara -
http://www.xml.com/pub/a/2005/04/20/py-xml.htmlUse XSLT to prepare XML
for import into OpenOffice Calc -
http://www.ibm.com/developerworks/xml/library/x-oocalc/
Schema standardization for top-down semantic transparency -
http://www-128.ibm.com/developerworks/xml/library/x-think31.html

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


Re: Software licenses and releasing Python programs for review

2005-06-04 Thread Mike Meyer
Steve Holden <[EMAIL PROTECTED]> writes:
> But this would only be a restriction if the code were to be
> redistributed, of course. It's stil perfectly legal to use it
> internaly without making the modified source available.

I've heard people argue otherwise on this case. In particular, if you
allow an employee to use your GPL'ed-but-not-distributed software,
they are the end user, and have all the rights granted by the GPL. So
they can distribute the software - possibly to your
competitors. Employment contracts can't prohibit this, because the GPL
specifically disallows "distribution" (allowing your employee to use
the software) under licenses that restrict the rights granted by the
GPL.

I don't know whether this would hold water in court. I'd certainly
hate to be the one responsible for a company finding out the hard way.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Python & XML

2005-06-04 Thread uche . ogbuji
"I have a situation at work.  Will be receiving XML file which contains
quote information for car insurance.  I need to translate this file
into a flat comma delimited file which will be imported into a software
package.  Each XML file I receive will contain information on one quote
only.  I have documentation on layout of flat file and examples of XML
file (lot of fields but only container tags and field tags no
DTD's,look easy enough).  I am just starting to learn python and have
never had to work with XML files before.  Working in MS Windows
environment.  I have Python 2.4 with win32 extensions. "

Sounds like the sort of thing I and others have done very easily with
Amara:

http://www.xml.com/pub/a/2005/01/19/amara.html

Overall, if you're new to Python and XML, here are some resources:

http://www.xml.com/pub/at/24
http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/general-section

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Use CSS to display XML, part 2 -
http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html
XML Output with 4Suite & Amara -
http://www.xml.com/pub/a/2005/04/20/py-xml.htmlUse XSLT to prepare XML
for import into OpenOffice Calc -
http://www.ibm.com/developerworks/xml/library/x-oocalc/
Schema standardization for top-down semantic transparency -
http://www-128.ibm.com/developerworks/xml/library/x-think31.html

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


Re: Sorted List (binary tree) why no built-in/module?

2005-06-04 Thread =?iso-8859-1?Q?Fran=E7ois?= Pinard
[Alex Stapleton]

> Unless I've totally missed it, there isn't a binary tree/sorted list
> type arrangement in Python.  Sometimes it might be preferable over
> using a list and calling list.sort() all the time ;)

Well, after `some_list.sort()', `some_list' is indeed a sorted list. :-)
You can use the `bisect' module after that for sorted insertion.

Lists can also be used for representing binary trees, and with a bit of
imagination, the `heapq' module might help you at keeping a binary tree
"half-sorted".  This is sometimes sufficient for some applications.  Or
else, you have to resort to "avl" tree modules, available separately!

> On a somewhat unrelated note, does anyone know how python searches
> lists when you do things list list.index(n), is it a binary search, or
> does it just scan the list?

As Python does not know if a list is sorted or not, it cannot binary
search them by default.  But you, as a programmer, know.  Then, the
`bisect' module might be helpful for binary searches.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv and iterator protocol

2005-06-04 Thread Kent Johnson
Philippe C. Martin wrote:
> Can I initialize csv with input data stored in RAM (ex: a string) ? - so far
> I cannot get that to work. Or to rephrase the question, what Python "RAM"
> structure supports the "iterator protocol" ?

Many, including strings, lists and dicts. For your needs, a list of strings 
will work, or a cStringIO initialized from your data.

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


Re: Newbie Python & XML

2005-06-04 Thread Kent Johnson
LenS wrote:
> I have a situation at work.  Will be receiving XML file which contains
> quote information for car insurance.  I need to translate this file
> into a flat comma delimited file which will be imported into a software
> package.  Each XML file I receive will contain information on one quote
> only.  I have documentation on layout of flat file and examples of XML
> file (lot of fields but only container tags and field tags no
> DTD's,look easy enough).  I am just starting to learn python and have
> never had to work with XML files before.  Working in MS Windows
> environment.  I have Python 2.4 with win32 extensions.
> 
> 1. What else do I need

I recommend ElementTree for XML processing in Python
http://effbot.org/zone/element-index.htm

and the Python-tutor mailing list for getting started with Python:
http://mail.python.org/mailman/listinfo/tutor

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


Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Steven Bethard
Erik Max Francis wrote:
> For instance, for a chat network bot framework, a certain form of bot 
> will look for any attribute in its instance that starts with verb_ and a 
> command and execute it when it hears it spoken:
> 
> def verb_hello(self, convo):
> "Respond to a greeting."
> convo.respond(random.choice(self.greetings))
> 
> If you'd like it to respond to more than one word like this, then you 
> only need to assign the additional verbs, rather than redefine them:
> 
> verb_hi = verb_hello
> verb_yo = verb_hello
> verb_wazzup = verb_hello

Well if you want these to work with subclasses that change verb_hello to 
do something else, one option is to write a simple decorator, and then 
your lines above become something like:

 verb_hi = caller(verb_hello)
 verb_yo = caller(verb_hello)
 verb_wazzup = caller(verb_hello)

or if you prefer to only create one such function:

 _verb_hello_caller = caller(verb_hello)
 verb_hi = _verb_hello_caller
 verb_yo = _verb_hello_caller
 verb_wazzup = _verb_hello_caller

Here's a simple example in action:

py> def caller(func):
... def wrapper(self, *args, **kwargs):
... return getattr(self, func.__name__)(*args, **kwargs)
... return wrapper
...
py> class C(object):
... def verb_hello(self):
... print "C: hello"
... verb_hi = caller(verb_hello)
...
py> class D(C):
... def verb_hello(self):
... print "D: hello"
...
py> D().verb_hi()
D: hello

Notice that verb_hi() still calls verb_hello() in the subclass.

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


Re: Looking for help with a python-mode/pdbtrack/gdb patch

2005-06-04 Thread =?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=
Unfortunatly the only tip I can give you is that there's a list for
mode-python in http://mail.python.org/mailman/listinfo/python-mode, but
you probably already know about it.

Regards,
Tiago S DaitxOn 6/4/05, Skip Montanaro <[EMAIL PROTECTED]> wrote:
Can someone who uses Emacs's python-mode, pdbtrack and gdb take a look atthis simple but ancient patch:
http://sourceforge.net/tracker/index.php?func=detail&aid=785816&group_id=86916&atid=581351As you'll see from the discussion, Barry had problems with it from XEmacsand was thinking of rejecting it way back when.  I'd like to resolve it one
way or the other, but I've never used pdb, let alone pdbtrack.Thanks,Skip--http://mail.python.org/mailman/listinfo/python-list

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

Why Eric3 does not have any documentation or FAQ?

2005-06-04 Thread Hsuan-Yeh Chang
Dear All,

Does anyone know why?

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


Re:

2005-06-04 Thread =?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=
That depends on what "using" a file means. You could check the thread "executing a command" (
http://mail.python.org/pipermail/python-list/2005-June/283963.html)
and see if there's something related there, otherwise it would help if
you could post what exactly you are trying to do (execute a file, open
a file, write into a file, etc).

Regards,
Tiago S DaitxOn 6/4/05, Jatinder Singh <[EMAIL PROTECTED]> wrote:
Hi guysI am working in a complex directory structure. I want to use a file (not .py)which is in some other directory. I couldn't do it.but if I copy the file inthe same directory then it is working fine. Can anybody guide me how and where
to add the path of the file. I have tried it with sys.path but it is not forthat.--Regards,Jatinder Singh" Everyone needs to be loved... especially when they do not deserve it."--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: executing a command

2005-06-04 Thread =?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=
Hello,When you use one of the os.exec*p fnnctions python looks
for the specified file in the directories refered by
os.environ['PATH']. If and _only_ if your os.enviroment['PATH'] isn't
set then it looks in os.defpath - you can check this at
http://www.python.org/doc/current/lib/os-path.html#l2h-1557So, my advice is that you first try printing your os.environ['PATH']to
check wheter it includes the program that you are calling or not (and
then you will have to include it). In the case that it isn't set, then
check os.defpath.Also, when you use one of the functions
os.exec that requires a path variable to be passed (ie. the ones that
doesn't have 'p' in their names) the path can be relative or absolute,
but it must include the file name (and not only the dir where the file
is).And for each one of these os.exec* functions the first
argument will always be used as the program "name" (argv[0]), so unless
you a reason to do otherwise, pass the same name as the file that you
are calling.Regards,Tiago S DaitxOn 6/4/05, andrea valle <[EMAIL PROTECTED]> wrote:> Hi to all,> I need to run a program from inside python (substantially, algorithmic
> batch processing).> I'm on mac osx 10.3.8 with python 2.3 framework and macpython.> > Trying to use exec*, I checked references, Brueck & Tanner, and then> grab this code from effbot:
> >  >>> program = "python">  >>> def run(program, *args):> os.execvp(program, (program,) +  args)> print "ok"> >  >>> run("python", "/Users/apple/Desktop/prova.py")
> > Traceback (most recent call last):>File "", line 1, in -toplevel->  run("python", "/Users/apple/Desktop/prova.py")>File "", line 2, in run
>  os.execvp(program, (program,) +  args)>File> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/> python2.3/os.py", line 336, in execvp>  _execvpe(file, args)
>File> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/> python2.3/os.py", line 374, in _execvpe>  func(fullname, *argrest)> OSError: [Errno 45] Operation not supported
> > This OSError seems to be consistend with all exec family. What does it> mean and how to use exec?> > I also tried with. os.system. It works if I invoke python, but it fails> (in a way I don't know) when I invoke other programs.
> > For example:> command = "python /Users/apple/Desktop/test.py">  >>> os.system(command)> 0> (test.py write a string in a file. It works)> > But with lilypond or with latex I have no output (and in fact it
> doesn't give 0 as result):> >  >>> command = "lilypond /Users/apple/Desktop/test.ly">  >>> os.system(command)> 32512>  >>> command = "latex /Users/apple/Desktop/test.tex"
>  >>> os.system(command)> 32512> > Any help is much appreciated> > Thanks a lot> > -a-> > --> 
http://mail.python.org/mailman/listinfo/python-list> 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Erik Max Francis
Steven Bethard wrote:

> John J. Lee wrote:
>
>> It seems nice to do this
>> 
>> class Klass:
>> 
>> def _makeLoudNoise(self, *blah):
>> ...
>> 
>> woof = _makeLoudNoise
> 
> Out of curiosity, why do you want to do this?

There aren't too many clear use cases, but I've found it useful from 
time to time.  Usually it comes in handy when you're specializing some 
predefined behavior, often when relying on introspection in some fashion.

For instance, for a chat network bot framework, a certain form of bot 
will look for any attribute in its instance that starts with verb_ and a 
command and execute it when it hears it spoken:

def verb_hello(self, convo):
"Respond to a greeting."
convo.respond(random.choice(self.greetings))

If you'd like it to respond to more than one word like this, then you 
only need to assign the additional verbs, rather than redefine them:

verb_hi = verb_hello
verb_yo = verb_hello
verb_wazzup = verb_hello

It actually does more than this, where a builtin help system (verb_help) 
which relies on the docstrings of the verb_... methods will allow you to 
get help on any defined verb automatically, and list the known verbs 
when supplied without arguments.  But this would list duplicate verbs 
for the aliases (hi, yo, wazzup) above, which isn't optimal.  So instead 
I have another prefix, alias_, which acts as a verb, but won't be 
automatically scanned as a verb when help is finding the list of valid 
verbs:

alias_hi = verb_hello
...

That way, you get maximum effectiveness for minimum clutter.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Things are as they are because they were as they were.
   -- Thomas Gold
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Alternative history

2005-06-04 Thread Mike Meyer
[EMAIL PROTECTED] (Cameron Laird) writes:

> In article <[EMAIL PROTECTED]>, Mike Meyer  <[EMAIL PROTECTED]> wrote:
>   .
>>If it isn't a homework assignment, and you're honestly in such, then
>>you should know there's been a lot of research in this area, because
>>primes are important in cryptographic applications. Once again, google
>   .
> There's been a lot of research in this area because some minds
> burn to grasp the beauty of number theory, and can't stop think-
> ing of Number despite blindness, hunger, family, political 
> oppression, and the other frailties to which humans are prone.

Good point. Similar reasons seem to cause a lot of software to get
written.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorted List (binary tree) why no built-in/module?

2005-06-04 Thread Robert Kern
Alex Stapleton wrote:
> Unless I've totally missed it, there isn't a binary tree/sorted list  
> type arrangement in Python. Is there a particular reason for this?  
> Sometimes it might be preferable over using a list and calling  
> list.sort() all the time ;)

Well, I believe that list.sort() has been optimized for the case where 
an item has been appended to the end of a sorted list.

Also, look at the bisect module.

> On a somewhat unrelated note, does anyone know how python searches  
> lists when you do things list list.index(n), is it a binary search,  
> or does it just scan the list?

It just scans the list since there is no guarantee that it is sorted. 
The bisect module has a binary search for sorted lists.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Grand Challenge Pegasus Team: Programming Pegasus Bridge 1 ?

2005-06-04 Thread Alex Stapleton
I'm thinking that with a decent dynamics engine (PyODE?) you could  
write a reasonably realistic simulator to test this sort of code on.  
Obviously it won't be as good as actually you know, driving a Jeep  
around by wire, but it'd be a tad cheaper and more time efficient for  
anyone interested in this sort of thing. There the time involved in  
actually writing a simulator which you can experiment on your DBW  
code on though. You could probably get one going within a year though  
I imagine. Unfortunately from what i've seen of it, the Open Dynamics  
Engine is less than accurate under some situations. Unfortunately I  
believe all the really awesome ones cost huge amounts of money. Just  
a thought. I don't have any actual experience with DBW stuff :P

On 4 Jun 2005, at 21:13, [EMAIL PROTECTED] wrote:

> Folks,
>
> In a previous post[*] we made an announcement about the release of the
> drive-by-wire code for our entry in the DARPA Grand Challenge. We will
> do more in the future (including more data and more code). With  
> regards
> to our building the full autonomous code, things are going along well.
> However, the somewhat large traffic on our web site had us thinking:
>
> Provided we give a good HOW-TO/API, would there be any interest from
> anybody to try their code on our vehicle as long as it is in Python  
> and
> safe to run ?
>
> Many people think of way to deal with the programming side of
> road-following and collision avoidance at 60 mph, but very few have  
> the
> time to build a vehicle that can make these concepts a reality. In
> order to respond to this, I was thinking of a possibility where
> somebody would submit a code, pay $200 and we would try it on a closed
> circuit. Then the programmer would be getting all the data  
> attendant to
> the vehicle driving itself through the course following their  
> programs?
>
>
> The pros for us:
> - raise some money for the vehicle
> - identify potentially better algorithms -> identify people we would
> like to associate ourselves with.
>
> The cons for us:
> - this is time not dedicated to focusing on the race
> - issues with proprietary code/IP
> - issues with safety
> - coordination with many parties
>
> Right now I am thinking the cons are overwhelming, what do y'all think
> ?
>
>
> Igor.
>
> [*]
> http://groups-beta.google.com/group/comp.lang.python/browse_frm/ 
> thread/5f78e2ecb3e9139d/af28daca5e385af3#af28daca5e385af3
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>
>

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


Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Jeff Epler
On Sat, Jun 04, 2005 at 10:43:39PM +, John J. Lee wrote:
> 1. In derived classes, inheritance doesn't work right:

Did you expect it to print 'moo'?  I'd have been surprised, and expected
the behavior you got.

> 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
>this.

In all the versions of Python I've used, classes are pickled by name.
This example you wrote doesn't pose any special problem when pickling.

>>> pickle.dumps(A)
'c__main__\nA\np0\n.'
>>> pickle.dumps(B)
'c__main__\nB\np0\n.'

Jeff


pgpIxRuaKzVxS.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Sorted List (binary tree) why no built-in/module?

2005-06-04 Thread Alex Stapleton
Unless I've totally missed it, there isn't a binary tree/sorted list  
type arrangement in Python. Is there a particular reason for this?  
Sometimes it might be preferable over using a list and calling  
list.sort() all the time ;)

On a somewhat unrelated note, does anyone know how python searches  
lists when you do things list list.index(n), is it a binary search,  
or does it just scan the list?
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: wxPython 2.6.1.0

2005-06-04 Thread Robin Dunn

Announcing
--

The 2.6.1.0 release of wxPython is now available for download at
http://wxpython.org/download.php.  Anybody keeping track will probably
notice that the prior release (2.6.0.1) was released just about a week
ago.  This short turn-around time is because I was slow getting the
last release done, and the wxWidgets team was uncharacteristically
early with the 2.6.1 release!  This release consists of a few bug
fixes made since 2.6.0.1.


What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK or GTK2, and Mac OS X.


Changes in 2.6.1.0
--

wx.ListCtrl: patch #1210352, fixes editing in generic wx.ListCtrl with
wx.LC_EDIT_LABELS.

Applied patch #208286, MediaCtrl DirectShow rewrite.

DocView patches from Morgan Hua: bug fixes, and additional SVN
commands, also added a default template that uses the text editor for
any unknown file type.

wxMSW: Use the system IDC_HAND cursor for wx.CURSOR_HAND and only fallback
to the strange wxWidgets version if the system one is not available.

wx.grid.Grid: Merge the cell size attribute the same way that other
attributes are merged, e.g., if it is already set to a non-default
value in the current GridCellAttr object then don't merge from the
other.

wx.lib.evtmgr: Fixed to use wx._core._wxPyDeadObject

wx.lib.gridmovers: Don't scroll when the mouse is dragged outside of
the grid, unless the mouse is kept in motion.

wxMSW:  Applied patch #1213290 incorrect logic in
wx.TopLevelWindow.ShowFullScreen.

Applied patch #1213066 correct device names for Joystick in Linux.

wxGTK: Applied patch #1207162 wx.TextCtrl.SetStyle fix for overlapping
calls.

wx.FileConfig: fixed DeleteEntry to set the dirty flag properly so the
change will get written at the next flush.



-- 
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!


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


Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Leif K-Brooks
John J. Lee wrote:
> class Klass:
> 
> def _makeLoudNoise(self, *blah):
> ...
> 
> woof = _makeLoudNoise
>
> [...]
>
> At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
> this.

Works for me:

 Python 2.3.5 (#2, May  4 2005, 08:51:39)
 [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import pickle
 >>> class Foo:
 ... def foo(self):
 ... print "Hello, world!"
 ... bar = foo
 ...
 >>> pickle.dumps(Foo)
 'c__main__\nFoo\np0\n.'
 >>> pickle.dumps(Foo())
 '(i__main__\nFoo\np0\n(dp1\nb.'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Steven Bethard
John J. Lee wrote:
> It seems nice to do this
> 
> class Klass:
> 
> def _makeLoudNoise(self, *blah):
> ...
> 
> woof = _makeLoudNoise

Out of curiosity, why do you want to do this?

> 1. In derived classes, inheritance doesn't work right:
> 
> 
class A:
> ...  def foo(s):print 'foo'
> ...  bar = foo
> ...
class B(A):
> ...  def foo(s):print 'moo'
> ...
b = B()
b.bar()
> foo

Depends on what you mean by "work right".  It does do what you asked it 
to do.  You asked class A to store the "foo" object under the name 
"bar".  When you create an instance of B, and ask for the "bar" 
attribute, it isn't found in class B, so Python looks to the parent 
class.  The parent class, A, does have an object named "bar", so Python 
returns that.  And that object is the same object that you asked be 
named bar, namely the "foo" function.

If you want "bar" to be a function that *calls* the "foo" function, 
declare it as such:

py> class A(object):
... def foo(self):
... print 'foo'
... def bar(self):
... return self.foo()
...
py> class B(A):
... def foo(self):
... print 'moo'
...
py> B().bar()
moo


> 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
>this.

In Python 2.4:

py> class A(object):
... def foo(self):
... print 'foo'
... bar = foo
...
py> import pickle
py> pickle.loads(pickle.dumps(A)).bar

py> pickle.loads(pickle.dumps(A())).bar()
foo

Or maybe I misunderstand you?

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


[no subject]

2005-06-04 Thread Robin Dunn

Announcing
--

The 2.6.1.0 release of wxPython is now available for download at
http://wxpython.org/download.php.  Anybody keeping track will probably
notice that the prior release (2.6.0.1) was released just about a week
ago.  This short turn-around time is because I was slow getting the
last release done, and the wxWidgets team was uncharacteristically
early with the 2.6.1 release!  This release consists of a few bug
fixes made since 2.6.0.1.


What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK or GTK2, and Mac OS X.


Changes in 2.6.1.0
--

wx.ListCtrl: patch #1210352, fixes editing in generic wx.ListCtrl with
wx.LC_EDIT_LABELS.

Applied patch #208286, MediaCtrl DirectShow rewrite.

DocView patches from Morgan Hua: bug fixes, and additional SVN
commands, also added a default template that uses the text editor for
any unknown file type.

wxMSW: Use the system IDC_HAND cursor for wx.CURSOR_HAND and only fallback
to the strange wxWidgets version if the system one is not available.

wx.grid.Grid: Merge the cell size attribute the same way that other
attributes are merged, e.g., if it is already set to a non-default
value in the current GridCellAttr object then don't merge from the
other.

wx.lib.evtmgr: Fixed to use wx._core._wxPyDeadObject

wx.lib.gridmovers: Don't scroll when the mouse is dragged outside of
the grid, unless the mouse is kept in motion.

wxMSW:  Applied patch #1213290 incorrect logic in
wx.TopLevelWindow.ShowFullScreen.

Applied patch #1213066 correct device names for Joystick in Linux.

wxGTK: Applied patch #1207162 wx.TextCtrl.SetStyle fix for overlapping
calls.

wx.FileConfig: fixed DeleteEntry to set the dirty flag properly so the
change will get written at the next flush.



-- 
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!

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


Re: weird cgi problem w/ apache

2005-06-04 Thread Rick Kwan
If it is umask, then that would be umask for the Apache process,
not the second script (which I presume doesn't run as Apache).

The CGI script can explicitly set the permissions when creating
the folder using mkdir() or makedirs() so that others can write
into it.  (Depending on how public or private the machine is,
this may or may not  be a security issue.)

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


Problem on python 2.3.x was: [ANN] Snakelets 1.41 and Frog 1.6

2005-06-04 Thread Irmen de Jong
...darn, some users have reported that a strange problem
occurs when running Snakelets 1.41 on Python 2.3.x
(Python 2.4 is fine!)

It seems that there is a bug in older versions of
inspect.getmodule() and that bug causes Snakelets to stop
working correctly on Python 2.3.x

If you experience this bug (you can see it in the server.log
"arg is not a module, class, method, function, traceback, frame,
or code object") please upgrade to Python 2.4.1 if possible.

In the meantime I will try to make a workaround so that Snakelets
will work again on older Python versions.

Sorry for the trouble,

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


method = Klass.othermethod considered PITA

2005-06-04 Thread John J. Lee
It seems nice to do this

class Klass:

def _makeLoudNoise(self, *blah):
...

woof = _makeLoudNoise


One probably wants the above to work as if you'd instead defined woof
in the more verbose form as follows:

def woof(self, *blah): return self._makeLoudNoise(self, *blah)

It doesn't, though.  Two problems:

1. In derived classes, inheritance doesn't work right:

>>> class A:
...  def foo(s):print 'foo'
...  bar = foo
...
>>> a = A()
>>> a.bar()
foo
>>> class B(A):
...  def foo(s):print 'moo'
...
>>> b = B()
>>> b.bar()
foo
>>>

2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
   this.


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


Re: Controlling source IP address within urllib2

2005-06-04 Thread John J. Lee
"Dan" <[EMAIL PROTECTED]> writes:

> Does anybody know how to control the source IP address (IPv4) when
> using the urllib2 library?  I have a Linux box with several IP
> addresses in the same subnet, and I want to simulate several
> individuals within that subnet accessing web pages independently.  I
> need the functionality of urllib2 because there will be redirects and
> other HTTP-type functions to implement.  It would be nice if I could
> create (and bind) sockets myself and then tell the urllib functions to
> use those sockets.  Perhaps there is some sort of "back-door" way of
> doing this??? Any hints are appreciated!

There's no built-in support, but I expect it's very easy to do.  I
suppose the easiest way would be to derive from
httplib.HTTPConnection, overriding .connect() to call .bind() on the
socket.  Call it BindingHTTPConnection, then define:

class BindingHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(BindingHTTPConnection, req)


Same goes for https:

if hasattr(httplib, 'HTTPS'):
class BindingHTTPSHandler(urllib2.HTTPSHandler):
def https_open(self, req):
return self.do_open(BindingHTTPSConnection, req)


Personally, I probably wouldn't use build_opener(), but since the
above classes derive from the corresponding urllib2 classes, you can
do:

opener = urllib2.build_opener(BindingHTTPHandler, BindingHTTPSHandler)
response = opener.open('http://www.example.com/')


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


Re: weird cgi problem w/ apache

2005-06-04 Thread Chris Curvey
could it be the umask?

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


Re: using boost to return list

2005-06-04 Thread Neil Hodgson
GujuBoy:

> i am trying to make a "cpp" file which will make an array and pass it
> to python as a list.
> 
> how is this possible...i am using BOOST...please can someone point me
> at some examples

This returns a list when called from Python.

static list retrieval_as_list(SplitText &self, int position,
 int retrieveLength) {
list result;

int *characters = new int[retrieveLength];
int lenRet = self.RetrieveUTF32(position, characters,   
 retrieveLength);
for (int i=0;ihttp://mail.python.org/mailman/listinfo/python-list


csv and iterator protocol

2005-06-04 Thread Philippe C. Martin
Hi,

I have the following working program:

1) I import data in csv format into internal data structures (dict + list)
2) I can export back to csv
3) I can store my internal data using pickle+bz2
4) I can reload it.


Hovever I notice a factor 10 size loss using pickle.

So I would like to bzip/store in csv format but am not certain how to read
the data back as the csv module as described uses a file name in its
constructor. I would like to avoid reading the data and writing it into a
file prior to re-importing it.

Can I initialize csv with input data stored in RAM (ex: a string) ? - so far
I cannot get that to work. Or to rephrase the question, what Python "RAM"
structure supports the "iterator protocol" ?

Thanks,

Philippe

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


Q: functional/equational language, smells a little of Python

2005-06-04 Thread John J. Lee
Saw this on LWN:

http://q-lang.sourceforge.net/


Looks interesting, and reminiscent of symbolic algebra systems like
Mathematica.  Also, the website mentions dynamic typing and "Batteries
Included", which made me think of Python.  Damned silly name, though
(perhaps pre-Google?).

Anybody here used it?

Snippet from the FAQ:


 2. Yet another "Haskell for the poor"?

Not quite. Even though the syntax and some of the stuff in the
standard library looks superficially similar, Q is different in a
number of ways:

* First and foremost, Q is an equational rather than just a
  functional language, meaning that it is based on general term
  rewriting instead of the lambda calculus (which is just one, and
  very special, rewriting system). In particular, Q has no a
  priori distinction between "constructors" and "defined" function
  symbols, and argument patterns are not restricted to
  "constructor terms". This allows you to have symbolic evaluation
  rules like the following distributivity rule: X*(Y+Z) =
  X*Y+X*Z. Such rules are not allowed in ML and Haskell because
  they violate the "constructor discipline". Moreover, the Q
  interpreter also happily reduces expressions involving
  variables, so that you can try your definitions with symbolic
  inputs (e.g., map F [X,Y] will evaluate to [F X,F Y]), which is
  quite useful for debugging purposes.

* While other functional languages are either "eager" or "lazy", Q
  tries to give you the best of both worlds: It uses eager
  (call-by-value) evaluation by default (which lends itself to an
  efficient implementation), but also allows you to define your
  own special forms, which can be used to implement both
  call-by-name functions and lazy data constructors. Using special
  forms you can also define your own "meta functions" which
  manipulate arbitrary (not necessarily irreducible) expressions
  as literal terms. This gives you full control over the reduction
  strategy, where this is desired, as well as a kind of "macros"
  and "self-modifying programs", since constructs like lambda
  abstractions can be analyzed, transformed and constructed in
  many ways before they are actually evaluated.

* Q uses dynamic typing. This has become a rare feature in
  contemporary functional languages, which usually employ a
  Hindley/Milner type system which offers more safety at the
  expense of restricting polymorphism. Q gives you back the
  flexibility of good old Lisp-style ad-hoc polymorphism and even
  allows you to extend the definition of existing operations
  (including built-in functions and operators) to your own data
  types. Moreover, Q has a Smalltalk-like object-oriented type
  system which supports data encapsulation and (single)
  inheritance. This makes it possible to manage complex,
  polymorphic data with ease.

* Q takes the pragmatic route in that it provides (monad-free)
  imperative programming features such as imperative I/O and
  mutable data cells, similar to the corresponding facilities in
  ML. While one may argue about these, they certainly make life
  easier when programming complex I/O stuff such as graphical user
  interfaces.

* Last but not least, the Q programming system comes with
  batteries included. There are quite a few add-on modules
  interfacing to third-party libraries which, while not as
  comprehensive as the facilities provided by traditional
  scripting languages like Perl and Python, allow you to tackle
  most practical programming problems with ease. In particular,
  multimedia and computer music is an area where Q shines,
  providing facilities to handle graphics, digital audio and MIDI
  in a convenient and efficient manner (efficient enough for soft
  realtime applications), which go well beyond what is currently
  being offered for other functional languages.


Some of Q's flexibility comes at a price. In particular, Q's symbolic
evaluation capabilities as a term rewriting language dictate that the
language is essentially exception-free. This means that an
"ill-formed" expression (such as "division by zero" or, more
generally, the application of a function to data for which there is no
corresponding definition) does not, by default, raise an exception,
but instead the expression is already in "normal form", i.e., it
evaluates to itself. As a remedy, Q provides facilities to add
explicit error rules which raise exceptions, and to handle exceptions
in a suitable manner. Another limitation is that Q does not allow you
to have arbitrary local definitions in the style of Haskell and ML's
"let" and "where" clauses. In Q, "where" clauses are limited to
variable definitions (similar to Haskell's pattern bindings), but
local rewriting rules are not supported as they would wreak havoc on
the term rewriting seman

Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Andrew Dalke
Steven Bethard wrote:
> Ahh, so if I wanted the locking one I would write:
> 
>  with locking(mutex) as lock, opening(readfile) as input:
>  ...

That would make sense to me.

> There was another proposal that wrote this as:
> 
>  with locking(mutex), opening(readfile) as lock, input:
>  ...
> 
> which is what was confusing me.  Mirroring the 'as' from the import 
> statement seems reasonable.

Ahh, you're right.  That was an earlier proposal.

> 
> But it doesn't address my other concern, namely, is
> 
>  with locking(mutex), opening(readfile) as input:
>  ...
> 
> equivalent to the nested with-statements, e.g.:

I would think it's the same as

with locking(mutex):
  with opening(readfile) as input:
...

which appears to map to the first of your alternatives

> Or is it equivalent to something different, perhaps:
> 
>  _locking = locking(mutex)
>  _opening = opening(readfile)
>  _exc = (None, None, None)
>  _locking.__enter__()
>  input = _opening.__enter__()
>  try:
>  try:
>  ...
>  except:
>  _exc = sys.exc_info()
>  raise
>  finally:
>  _opening.__exit__(*exc)
>  _locking.__exit__(*exc)

That wouldn't work; consider if _opening.__enter__() raised
an exception.  The _locking.__exit__() would never be called,
which is not what anyone would expect from the intent of
this PEP.

> Or maybe:
> 
>  _locking = locking(mutex)
>  _opening = opening(readfile)
>  _exc = (None, None, None)
>  _locking.__enter__()
>  input = _opening.__enter__()

Same problem here

>  finally:
>  # same order as __enter__ calls this time!!
>  _locking.__exit__(*exc)
>  _opening.__exit__(*exc)

and the order would be wrong since consider multiple
statements as

with server.opening() as connection, connection.lock(column) as C:
  C.replace("X", "Y")

The inner with depends on the outer and must be closed
in inverted order.


> And if it *is* just equivalent to the nested with-statements, how often 
> will this actually be useful?  Is it a common occurrence to need 
> multiple with-statements?  Is the benefit of saving a level of 
> indentation going to outweigh the complexity added by complicating the 
> with-statement?

Agreed.

Andrew
[EMAIL PROTECTED]

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


Re: Scope

2005-06-04 Thread Steven Bethard
Peter Dembinski wrote:
> AFAIK inc is builtin function.  And builtin functions doesn't have to
> be real functions, they can be just aliases to Python's VM bytecodes
> or sets of bytecodes.

Wrong on both counts. ;)

py> inc
Traceback (most recent call last):
   File "", line 1, in ?
NameError: name 'inc' is not defined
py> __builtins__.inc
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'module' object has no attribute 'inc'

There is no builtin 'inc'.  To verify, check:
 http://docs.python.org/lib/built-in-funcs.html
 http://docs.python.org/lib/non-essential-built-in-funcs.html


And while builtin functions may not have to be real *functions*, they do 
have to be real *callables*:

py> type(abs)

py> help(type(abs))
Help on class builtin_function_or_method in module __builtin__:

class builtin_function_or_method(object)
  |  Methods defined here:
  |
  |  __call__(...)
  |  x.__call__(...) <==> x(...)
...
py> type(bool)

py> help(type(bool))
Help on class type in module __builtin__:

class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type
  |
  |  Methods defined here:
  |
  |  __call__(...)
  |  x.__call__(...) <==> x(...)
...

Note that both  and  
have a __call__ method, which means they are callable objects.  They're 
not just bytecodes; they're real objects, just like everything else in 
Python. =)

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


Re: how to get name of function from within function?

2005-06-04 Thread Steven Bethard
Christopher J. Bottaro wrote:
> Kent Johnson wrote:
>>class C(object):
>>@in_try
>>def func_a(self):
>>print "func_a"
>>
>>@in_try
>>def func_b(self):
>>print "func_b"
>>raise Exception
>>
>>You could probably create a metaclass to apply the wrappers automatically
>>but I like having it explicit as above.
> 
> Another good solution, thank you.  Maybe a reason to upgrade to 2.4...=)

If you can't upgrade, you can write Kent's code like:

class C(object):
def func_a(self):
print "func_a"
func_a = in_try(func_a)

def func_b(self):
print "func_b"
raise Exception
func_b = in_try(func_b)

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


Re: idiom for constructor?

2005-06-04 Thread Steven Bethard
Peter Dembinski wrote:
> From the other side: what are the usual uses of 'exec'?

I have to say, I have yet to find a use for it.

My intuition is that the good use cases for 'exec' have something to do 
with writing programs that allow users to interactively script the 
program actions.  But I've never written such a program, so I can't 
speak much about it.

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Steven Bethard
Andrew Dalke wrote:
> On Sat, 04 Jun 2005 10:43:48 -0600, Steven Bethard wrote:
> 
>>Ilpo Nyyssönen wrote:
>>
>>>How about this instead:
>>>
>>>with locking(mutex), opening(readfile) as input:
>>>...
> 
>>I don't like the ambiguity this proposal introduces.  What is input 
>>bound to?
> 
> It would use the same logic as the import statement, which already
> supports an 'as' like this

Ahh, so if I wanted the locking one I would write:

 with locking(mutex) as lock, opening(readfile) as input:
 ...

There was another proposal that wrote this as:

 with locking(mutex), opening(readfile) as lock, input:
 ...

which is what was confusing me.  Mirroring the 'as' from the import 
statement seems reasonable.


But it doesn't address my other concern, namely, is

 with locking(mutex), opening(readfile) as input:
 ...

equivalent to the nested with-statements, e.g.:

 _locking = locking(mutex)
 _exc1 = (None, None, None)
 _locking.__enter__()
 try:
 try:
 _opening = opening(readfile)
 _exc2 = (None, None, None)
 input = _opening.__enter__()
 try:
 try:
 ...
 except:
 _exc2 = sys.exc_info()
 raise
 finally:
 _opening.__exit__(*exc)
 except:
 _exc1 = sys.exc_info()
 raise
 finally:
 _locking.__exit__(*exc)

Or is it equivalent to something different, perhaps:

 _locking = locking(mutex)
 _opening = opening(readfile)
 _exc = (None, None, None)
 _locking.__enter__()
 input = _opening.__enter__()
 try:
 try:
 ...
 except:
 _exc = sys.exc_info()
 raise
 finally:
 _opening.__exit__(*exc)
 _locking.__exit__(*exc)

Or maybe:

 _locking = locking(mutex)
 _opening = opening(readfile)
 _exc = (None, None, None)
 _locking.__enter__()
 input = _opening.__enter__()
 try:
 try:
 ...
 except:
 _exc = sys.exc_info()
 raise
 finally:
 # same order as __enter__ calls this time!!
 _locking.__exit__(*exc)
 _opening.__exit__(*exc)

All I'm saying is that any of these are possible given the syntax.  And 
I don't see a precedent in Python for preferring one over another. 
(Though perhaps there is one somewhere that I'm missing...)

And if it *is* just equivalent to the nested with-statements, how often 
will this actually be useful?  Is it a common occurrence to need 
multiple with-statements?  Is the benefit of saving a level of 
indentation going to outweigh the complexity added by complicating the 
with-statement?

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


Re: decimal and trunkating

2005-06-04 Thread Facundo Batista
On 2 Jun 2005 23:34:52 -0700, Raymond Hettinger <[EMAIL PROTECTED]> wrote:

> >> i want to trunkate 199.999 to 199.99
> >> getcontext.prec = 2 isn't what i'm after either, all that does
> >> is E's  the value. do i really have to use floats to do this?
> 
> The precision is the total number of digits (i.e 199.99 has 5 digit
> precision).  Either round to that precision level or use the quantize
> method to round to a fixed number of places after the decimal point:

God, I must stop sending mails at 2AM. I replied doing the remark that
some burden should be taken at the beggining of the program, and I
repeated that mistake, confusing everybody.

Sorry, :(

.Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking through a mysql db

2005-06-04 Thread Jeff Elkins
Thanks for the replies!

I went ahead and used the fetchall() approach and work with the array,  
writing changes back to the database. It's working fine.

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


Re: [Baypiggies] potluck for google meeting?

2005-06-04 Thread Shannon -jj Behrens
I'm a huge fan of potlucks, but I'm not entirely sure I'd trust the
cooking of a bunch of engineers ;)

-jj

On 6/4/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I know that typically you all meet somewhere for dinner beforehand.. or
> afterhand.. but I'd like to propose we try a potluck at the meeting.. if
> google will allow it.
> 
> I'm volunteering to coordinate the potluck for the july google meeting..
> we can just see how it goes..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If - Or statements

2005-06-04 Thread Ognjen Bezanov
Robert Kern wrote:

> Ognjen Bezanov wrote:
>
>> Robert Kern wrote:
>>
>>
>>> Ognjen Bezanov wrote:
>>>
>>>
 Another newbie-ish question.

 I want to create an if statement which will check if a particular
 variable matches one of the statements, and willl execute the
 statement
 if the variable matches any of the statements.

 I have tried the following (the pass is just used for testing)


 if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] ==
 "aac" or ext[1] != "wma":
   print "we have a valid extension: " + ext[1] #here would go the
 code for decoding the above
   pass
>>>
>>>
>>>
>>> It works fine for me. Could you post the smallest complete program
>>> (one that defines ext) that displays the behavior and its entire
>>> output?
>>>
>>> As an aside, is 'ext[1] != "wma"' correct or should it be ==? As
>>> written, you could collapse the whole thing to 'if ext[1] != "wma":'
>>> but I presume it is a typo.
>>
>>
>> filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom
>> drive
>> for thefile in filelist[:]:   #for each file in the filelist
>> if thefile.find(".") != -1:   #if the file has an extenstion
>> at all
>> ext = thefile.split('.') #get the file extension
>> ext[1] =  ext[1].lower() #convert to lowercase
>> print ext[1] #debugging, to see the variable before
>> passed to if statement
>>
>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg"
>> or ext[1] == "aac" or ext[1] == "wma":
>> print "we have a valid extension: " + ext[1] #here
>> would go the code for decoding the above
>> pass
>
>
> It works just fine for me. Note that you could (and probably should)
> write the if statement as
>
>   if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'):
>
> but I really don't think that's your problem. Could you also post the
> output, too?
>
> In [1]:filelist = os.listdir('./')
>
> In [2]:for thefile in filelist:
>...:if '.' in thefile:
>...:ext = thefile.split('.')
>...:ext[1] = ext[1].lower()
>...:print ext[1]
>...:if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] ==
> 'ogg' or ext[1] == 'aac' or ext[1] == 'wma'):
>...:print 'We have a valid extension: %s' % ext[1]
>...:
> ogg
> We have a valid extension: ogg
> [etc.]
>
I dont know what the problem was, but before posting the output i replaced:

if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] == 'ogg' or ext[1] ==
'aac' or ext[1] == 'wma'):


with:

if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'):

And it worked perfectly, thanks for that tip. Not only does it work, but
it is less messy to look at.

And re. some other posts, yes the code is quite a hack, but once I get
it working i will resort to cleaning it up and stripping all the
unrequired blocks of code. Cheers everyone who helped! you made my life
easier :)



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


Grand Challenge Pegasus Team: Programming Pegasus Bridge 1 ?

2005-06-04 Thread [EMAIL PROTECTED]
Folks,

In a previous post[*] we made an announcement about the release of the
drive-by-wire code for our entry in the DARPA Grand Challenge. We will
do more in the future (including more data and more code). With regards
to our building the full autonomous code, things are going along well.
However, the somewhat large traffic on our web site had us thinking:

Provided we give a good HOW-TO/API, would there be any interest from
anybody to try their code on our vehicle as long as it is in Python and
safe to run ?

Many people think of way to deal with the programming side of
road-following and collision avoidance at 60 mph, but very few have the
time to build a vehicle that can make these concepts a reality. In
order to respond to this, I was thinking of a possibility where
somebody would submit a code, pay $200 and we would try it on a closed
circuit. Then the programmer would be getting all the data attendant to
the vehicle driving itself through the course following their programs?


The pros for us:
- raise some money for the vehicle
- identify potentially better algorithms -> identify people we would
like to associate ourselves with.

The cons for us:
- this is time not dedicated to focusing on the race
- issues with proprietary code/IP
- issues with safety
- coordination with many parties

Right now I am thinking the cons are overwhelming, what do y'all think
?


Igor.

[*]
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/5f78e2ecb3e9139d/af28daca5e385af3#af28daca5e385af3

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


Looking for help with a python-mode/pdbtrack/gdb patch

2005-06-04 Thread Skip Montanaro

Can someone who uses Emacs's python-mode, pdbtrack and gdb take a look at
this simple but ancient patch:


http://sourceforge.net/tracker/index.php?func=detail&aid=785816&group_id=86916&atid=581351

As you'll see from the discussion, Barry had problems with it from XEmacs
and was thinking of rejecting it way back when.  I'd like to resolve it one
way or the other, but I've never used pdb, let alone pdbtrack.

Thanks,

Skip

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


Komodo ide font color issue

2005-06-04 Thread meissnersd


Komodo ide font color issue

I prefer a dark back ground with light text.
So I edited my preferences and made a dark color scheme.
I am using python and komodo is dumping exceptions out in the
output window in red.

Red text on a black background is awful.

This does not change even when I set the color of stderr in my scheme
in the Preferences dialog.

So how can I change the text color of exceptions in the Komodo output
window?

Thanks
Karl

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Andrew Dalke
Nicolas Fleury wrote:
> I think it is simple and that the implementation is as much 
> straight-forward.  Think about it, it just means that:

Okay, I think I understand now.

Consider the following

server = open_server_connection()
with abc(server)
with server.lock()
do_something(server)

server.close()

it would be translated to

server = open_server_connection()
with abc(server):
  with server.lock()
do_something(server)
server.close()

when I meant for the first code example to be implemented
like this

server = open_server_connection()
with abc(server):
  with server.lock()
do_something(server)

server.close()


(It should probably use the with-block to handle the server open
and close, but that's due to my lack of imagination in coming up
with a decent example.)

Because of the implicit indentation it isn't easy to see that
the "server.close()" is in an inner block and not at the outer
one that it appears to be in.  To understand the true scoping
a reader would need to scan the code for 'with' lines, rather
than just looking at the layout.


> Good point.  As a C++ programmer, I use RAII a lot.

And I've used it a few times in Python, before I found
out it wasn't a guaranteed behavior by the language.

> So I come to another conclusion: the indentation syntax will most of the 
> time result in a waste of space.  Typically a programmer would want its 
> with-block to end at the end of the current block.

A test for how often this is needed would be to look in existing
code for the number of try/finally blocks.  I have seen and
written some gnarly deeply stacked blocks but not often - once
a year?

That's not to say it's a good indicator.  A lot of existing code
looks like this

def get_first_line(filename):
  f = open(filename)
  return f.readline()

depending on the gc to clean up the code.  A more ... not
correct, but at least finicky ... implementation could be

def get_first_line(filename):
  f = open(filename)
  try:
return f.readline()
  finally:
f.close()

Almost no one does that.  With the PEP perhaps the idiomatic
code would be

def get_first_line(filename):
  with open(filename) as f:
return f.readline()


(Add __enter__/__exit__ semantics to the file object?  Make
a new 'opening' function?  Don't know.)

What I mean by all of this is that the new PEP may encourage
more people to use indented blocks, in a way that can't be
inferred by simply looking at existing code.  In that case
your proposal, or the one written

  with abc, defg(mutex) as D, server.lock() as L:
..

may be needed.

Andrew
[EMAIL PROTECTED]

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


Re: calling ksh script from python

2005-06-04 Thread Sven Mascheck
(fup'2 set) In comp.unix.shell Donn Cave wrote:

> Portability [ksh]
> "echo" seems to mimic the behavior of sh on its host platform.

Rather: both usually mimic echo(1) - some shells even inspect PATH
(e.g. /usr/ucb/, /usr/5bin/ vs. /usr/bin/) and act accordingly.
-- 
http://mail.python.org/mailman/listinfo/python-list


potluck for google meeting?

2005-06-04 Thread donna
I know that typically you all meet somewhere for dinner beforehand.. or
afterhand.. but I'd like to propose we try a potluck at the meeting.. if
google will allow it.

I'm volunteering to coordinate the potluck for the july google meeting..
we can just see how it goes..

Best Regards,
Donna M. Snow,Owner
C Squared Technologies
technology at the speed of innovation
http://www.csquaredtech.com
  
-- 
http://mail.python.org/mailman/listinfo/python-list


BayPIGgies: June 9, 7:30pm (IronPort)

2005-06-04 Thread Aahz
The next meeting of BayPIGgies will be Thurs, June 9 at 7:30pm at
IronPort.

Drew Perttula will discuss his Python-based lighting system controller.
The system includes a music player, a variety of programs to design and
time light cues, and drivers for hardware that outputs the DMX protocol
used by most theatrical lighting gear.


BayPIGgies meetings alternate between IronPort (San Bruno, California)
and Google (Mountain View, California).  For more information and
directions, see http://www.baypiggies.net/


Before the meeting, we may meet at 6pm for dinner.  Discussion of dinner
plans is handled on the BayPIGgies mailing list.


Advance notice: The July 14 meeting will be Alex Martelli's "Black Magic"
talk.

Advance notice: The August 11 meeting agenda has not been set.  Please send
e-mail to [EMAIL PROTECTED] if you want to suggest an agenda (or
volunteer to give a presentation).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"The only problem with Microsoft is they just have no taste." --Steve Jobs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for constructor?

2005-06-04 Thread Volker Grabsch
Peter Dembinski wrote:
>> This is not a good use case for exec.  Use setattr:
> 
> OK, true.
> From the other side: what are the usual uses of 'exec'?

An interactive Python interpreter. :-)

No, seriously: Introspection is always better than exec.
It is far less error phrone, especially because you don't need
to deal with quoting issues, and because you have an initial
syntax check of your Python code which is bypassed when using exec.

Similarly, try to avoid system() whenever possible.


Greets,

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get name of function from within function?

2005-06-04 Thread Christopher J. Bottaro
Kent Johnson wrote:

...snip...

>> I guess I'm just lazy, but I don't want to write the wrapper func for
>> each
>> new func I want to add.  I want it done automatically.
> 
> You can do this almost automatically with a decorator:
> 
> def in_try(func):
> def wrapper(*args, **kwargs):
> try:
> return func(*args, **kwargs)
> except:
> print "entered except"
> raise
> return wrapper
> 
> class C(object):
> @in_try
> def func_a(self):
> print "func_a"
> 
> @in_try
> def func_b(self):
> print "func_b"
> raise Exception
> 
> You could probably create a metaclass to apply the wrappers automatically
> but I like having it explicit as above.

Another good solution, thank you.  Maybe a reason to upgrade to 2.4...=)
 
> Kent

-- C

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


using boost to return list

2005-06-04 Thread GujuBoy
i am trying to make a "cpp" file which will make an array and pass it
to python as a list.

how is this possible...i am using BOOST...please can someone point me
at some examples

thanks

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


Re: how to get name of function from within function?

2005-06-04 Thread Christopher J. Bottaro
Steven Bethard wrote:

...snip... 

> Something like this might work:
> 
> py> class C(object):
> ... def func_a(self):
> ... print "func_a"
> ... def func_b_impl(self):
> ... print "func_b"
> ... raise Exception
> ... def __getattr__(self, name):
> ... func = getattr(self, '%s_impl' % name)
> ... wrapped_func = self._impl_wrapper(func)
> ... setattr(self, name, wrapped_func)
> ... return wrapped_func
> ... def _impl_wrapper(self, func):
> ... def wrapper(*args, **kwargs):
> ... try:
> ... return func(*args, **kwargs)
> ... except:
> ... print "entered except"
> ... raise
> ... return wrapper
> ...
> py> c = C()
> py> c.func_a()
> func_a
> py> c.func_b()
> func_b
> entered except
> Traceback (most recent call last):
>File "", line 1, in ?
>File "", line 15, in wrapper
>File "", line 6, in func_b_impl
> Exception
> 
> The idea here is that __getattr__ is called whenever the class doesn't
> have a particular function.  The __getattr__ method then tries to find a
> corresponding _impl function, wraps it with appropriate try/except code,
> and returns the wrapped function.
> 
> HTH,

Yes, it does!  Thats perfect, and it works with Python 2.3 (which I'm
using).  Thank you very much.

> STeVe

-- C

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


Re: [ANN] Snakelets 1.41 and Frog 1.6

2005-06-04 Thread Irmen de Jong
thinfrog wrote:
> It's very interesting, i'm glad to try.
> 
> And it can access data by MYSQL/SQL or other database software?

"it" meaning Snakelets, I assume.
(because Frog, the blog server, doesn't use any database for storage)

Snakelets does not contain ANY database connector.
You can therefore use any database you like, but you have
to write your own database access connector.
Which can be a bit troublesome because you have to make
it work in a multi-user multi-thread environment.

I plan to add a few examples to Snakelets that show how
a database connection could be made (for mysql and/or sqlite
perhaps, to name a few) but for now, no example code is
available, sorry.

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Andrew Dalke
On Sat, 04 Jun 2005 10:43:48 -0600, Steven Bethard wrote:
> Ilpo Nyyssönen wrote:
>> How about this instead:
>> 
>> with locking(mutex), opening(readfile) as input:
>> ...

> I don't like the ambiguity this proposal introduces.  What is input 
> bound to?

It would use the same logic as the import statement, which already
supports an 'as' like this

>>> import sys, math, cStringIO as StringIO, xml.sax.saxutils as su
>>> 

> But the point is 
> that, whatever decision you make, I now have to *memorize* that decision.

It's the same rule so the rule would be "ahh, uses the 'as' form".

Andrew
[EMAIL PROTECTED]

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


Re: Scope

2005-06-04 Thread Peter Dembinski
Elliot Temple <[EMAIL PROTECTED]> writes:

> I want to write a function, foo, so the following works:
>
> def main():
>  n = 4
>  foo(n)
>  print n
>
> #it prints 7
>
> if foo needs to take different arguments, that'd be alright.
>
> Is this possible?

It is possible, but the more natural way would be to use function
return value:

   n = f(n)

or, if you need many assignments:

   a, b, c, d = f(a, b, c, d)

and, respectively:
   
   return a, b, c, d

in the function's body.

> I already tried this (below), which doesn't work.  foo only changes
> the global n.
>
>
> n = 3
> def main():
>  def foo(var, context, c2):
>  exec var + " = 7" in context, c2
>
>  n = 4
>  foo("n", locals(), globals())
>  print n
>
> if __name__ == '__main__': main()
>
> print n

You need to make 'n' globally visible.  See the 'global' keyword 
in Python user manual.

> And of course I tried:
>
>  >>> def inc(n):
> ...  n += 3
> ...
>  >>> a = 4
>  >>> inc(a)
>  >>> a
> 4

AFAIK inc is builtin function.  And builtin functions doesn't have to
be real functions, they can be just aliases to Python's VM bytecodes
or sets of bytecodes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking through a mysql db

2005-06-04 Thread Heiko Wundram
Am Samstag, 4. Juni 2005 17:23 schrieb Jeff Elkins:
> Within this same app, I've got a search function working, but I need the
> rownumber when a record is fetched.
>
>   sql = """select * from address where %s = %%s""" % arg1.lower()
> cursor.execute(sql, (arg2,))
>  item = cursor.fetchone ()
>  index = cursor.rownumber
>
> At this point, the record is on the screen, but cursor.rownumber doesn't
> reflect the actual rownumber...it always returns 1. How can I obtain the
> actual row number for the displayed record?

You're relying on the fact that rows never move... And IMHO this premise is 
false (at least it's not what a relational database has to guarantee for a 
table).

What you might do:

sql = """select prim_key from address where %s = %%s""" % arg1.lower()
cursor.execute(sql,(arg2,))
prim_key = cursor.fetchone()[0]

And then pass prim_key to the actual display function:

def fetch_item(prim_key=None,row_number=None):
if prim_key:
sql = """select * from address where prim_key = %s"""
args = (prim_key,)
# We fetch by primary key, only one row of one in table as 
primary
# key is unique.
row_number, rows = 1, 1
elif row_number:
sql = """select * from address limit %i,1""" % (row_number,)
args = ()
# We fetch a specified row_number, we already know number of 
rows in
# query.
rows = None
else:
sql = """select * from address"""
args = ()
# We fetch everything to get row count. Returned value is row 1,
# after query rows contains number of rows fetched.
row_number = 1
rows = 0
cursor.execute(sql,args)
if rows == 0:
# I don't know what MySQLdb uses, probably something like 
this...
rows = cursor.rowcount
return cursor.fetchone(), row_number, rows

Now, to use the function in your script, just test for certain parameters, 
such as a passed primary key (in response to a search operation), or a passed 
total row count and current row_number. The function takes care of the rest 
of processing.

HTH!

-- 
--- Heiko.
  see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/


pgpkcWN8yLuZq.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Walking through a mysql db

2005-06-04 Thread Scott David Daniels
Jeff Elkins wrote:
> On Saturday 04 June 2005 09:24 am, Jeff Elkins wrote:
...
>>Now, how do I step through the dataset one row at a time?  My form has 
>>'next' and 'back' buttons, and I'd like them to step forward or back,
>>fetching the appropriate row in the table. I've tried setting
>>cursor.rownumber by incrementing it prior to the fetchone() w/o effect.

Conceptually RDB queries produce sets, not lists.  The "row number" is
more an artifact than a property, and (in general) the only way to get
to the fifty-third is to step through the first fifty-two.  If you need
to go forward and back, pull the results into a python list (using
fetchmany or fetchall) and walk through that list.

> Within this same app, I've got a search function working, but I need the 
> rownumber when a record is fetched.
> 
>   sql = """select * from address where %s = %%s""" % arg1.lower()
> cursor.execute(sql, (arg2,))
>  item = cursor.fetchone ()
>  index = cursor.rownumber
> 
> At this point, the record is on the screen, but cursor.rownumber doesn't 
> reflect the actual rownumber...it always returns 1. How can I obtain the 
> actual row number for the displayed record?

The "normal" way to do this is to make sure your query includes the
key of the table you are querying.  It is generally considered bad
style (in the DB world) to use "SELECT *" above.  Name the fields you
are grabbing, and your code will survive more schema changes.  The
contents of the table's key column(s) _is_ the unique identifier of
that row, not a "row number" (which may well change on a backup-restore
for example).

--Scott David [EMAIL PROTECTED]
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Axon 1.1.0 has been released!

2005-06-04 Thread Michael Sparks
Axon 1.1.0 has been released!

What is it?
===
Axon is a collection of pure python modules from the Kamaelia project
which allow you to build concurrent systems in a compositional manner
using communicating python generators. Components are python generators
are augmented by inbox and outbox queues (lists) for communication in a
CSP like fashion. Version 1.1.0 also adds in the facility for writing
components using threads as well as using generators.

Put another way this allows you to build complex systems easily out of
small concurrent components in a fashion similar to unix pipelines, except
rather than being limited to just stdin/stdout you can have whatever
inputs/outputs you desire. (The defaults are inbox/outbox,
control/signal)

Axon works under Linux, Mac OS X, Windows and a subset has been ported
to Series 60 mobiles.

Documentation is largely generated directly from the test suite output.

Also, a presentation on Kamaelia (which may help put Axon in context)
was give at ACCU/Python UK conference in April this year. The slides
are available here:
   * http://kamaelia.sourceforge.net/Kamaelia-ACCU-20050422.pdf

This is due to be released as a BBC R&D White Paper shortly. 

What's Kamaelia? (for context :-)

Kamaelia is a project that aims to allow the BBC and others to create and
test open protocols for large scale streaming. Substantial subsystems
include a core concurrency subsystem and the beginnings of an RTSP/RTP
streaming server. Existing functionality in Kamaelia that uses Axon
includes a generic TCP & Multicast client and server framework that
allows protocols to be trivially created, a number of example protocols,
and an Ogg Vorbis decoding subsystem for client site testing
(libvorbissimple). 

What's new in Axon 1.1.0?
=
This release features support for components to be threads as well as
python generators has been added, allowing the integration of arbitrary
code blocking or non-blocking. Other changes include microprocesses (and
hence components) can now be run without a scheduler in standalone mode
and the debug subsystem has been reactivated system wide. 

Threaded components:
   * Inherit from threadedcomponent rather than Component
   * Rather than have a generator method called "main" you have a main
 thread method called "run". (This will change to "main" at some later
 point in time)
   * May be blocking. (This was the primary reason for creating them - Nokia
 Series 60 sockets cannot be used in a nonblocking manner, requiring the
 use of threads to avoid blocking)

Platforms
=
Axon has been used successfully under both Linux, Windows and Mac OS
X. A separate release branch exists for Series 60 Nokia mobiles.

Where can I get it?
===
Axon is a sub-project of the BBC R&D Kamaelia project, which means Axon is
downloadable from http://sourceforge.net/projects/kamaelia/

Web pages are here:
   http://kamaelia.sourceforge.net/Docs/Axon.html
   http://kamaelia.sourceforge.net/ ;(includes info on mailing lists)

ViewCVS access is available here:
   http://cvs.sourceforge.net/viewcvs.py/kamaelia/

Licensing
=
Kamaelia (and hence Axon) is released under the Mozilla tri-license
scheme (MPL/GPL/LGPL). Specifically you may choose to accept either
the Mozilla Public License 1.1, the GNU General Public License
2.0 or the Lesser General Public License 2.1. Proprietary terms
and conditions available upon request.

Best Regards,


Michael.
--
[EMAIL PROTECTED], http://kamaelia.sourceforge.net/
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically state
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Scope

2005-06-04 Thread Ron Adam
Elliot Temple wrote:

> I want to write a function, foo, so the following works:
> 
> def main():
> n = 4
> foo(n)
> print n
> 
> #it prints 7
> 
> if foo needs to take different arguments, that'd be alright.
> 
> Is this possible?

It is possible if you pass mutable objects to foo such as lists or 
dictionaries.

Is this what you are looking for?

def main():
 d = [3,]
 foo(d)
 print d[0]

def foo(var):
 var[0] = 7

main()


Cheers,
_Ron

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


Re: idiom for constructor?

2005-06-04 Thread Peter Dembinski
Steven Bethard <[EMAIL PROTECTED]> writes:

> Peter Dembinski wrote:
>>class A:
>>def __init__(self, a, b, c, d):
>>initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d}
>>for param in initial.keys():
>>exec "self.%s = initial['%s']" % (param, param)
>
> This is not a good use case for exec.  Use setattr:

OK, true.
>From the other side: what are the usual uses of 'exec'?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Python & XML

2005-06-04 Thread Jerry Sievers
"LenS" <[EMAIL PROTECTED]> writes:

> I have a situation at work.  Will be receiving XML file which contains
> quote information for car insurance.  I need to translate this file
> into a flat comma delimited file which will be imported into a software
> package.  Each XML file I receive will contain information on one quote
> only.  I have documentation on layout of flat file and examples of XML
> file (lot of fields but only container tags and field tags no
> DTD's,look easy enough).  I am just starting to learn python and have
> never had to work with XML files before.  Working in MS Windows
> environment.  I have Python 2.4 with win32 extensions.
> 
> 1. What else do I need

Well, if the XML file format is going to be fixed, there's no
difficulty here.

import the parseString from dom.minidom

Figure out how many levels of container the XMl doc has.  and descend
using the childNodes one or more times till you reach the data.

Data nodes are of nodeType == 3.  Iterate over them using nodeValue on
each.  Put them into a list and then paste you list together using
COMMAS or other delimiter.

This is the quick and dirty way!   Will barf totally if your upstream
data source throws you a curve.

HTH


> 2. Any examples of program doing the same.
> 3. Have read some stuff that indicates I may need ? schema of XML
> layout 

Perhaps.  But probably not unless you are trying to build a highly
flexible parser.

> 
> The rating company will ftp a quote realtime to a dir on my system.
> the python program will then have to poll the dir for new files and
> automaticly translate and initiate import.

A more elegant way of doing this is to pipe the FTP server log data
through a running process and if the file matches one that requires
this XML treatment, do it in real time.

May not be worth the trouble to implement in a low volume system
however.


-- 
---
Jerry Sievers   305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobilehttp://www.JerrySievers.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Andrew Dalke wrote:
> The implementation would need to track all the with/as forms
> in a block so they can be __exit__()ed as appropriate.  In this
> case ghi.__exit() is called after jkl.__exit__() and
> before defg.__exit__
> 
> The PEP gives an easy-to-understand mapping from the proposed
> change to how it could be implemented by hand in the existing
> Python.  Can you do the same?

I think it is simple and that the implementation is as much 
straight-forward.  Think about it, it just means that:

 > with abc
 >
 > with defg:
 >   with ghi
 >   with jkl:
 > 1/0

is equivalent to:

 > with abc:
 >
 >   with defg:
 > with ghi:
 >   with jkl:
 > 1/0

That's it.  Nothing more complex.  It's only about syntax.

> I have not idea if the problem you propose (multiple with/as
> blocks) will even exist so I can't comment on which solution
> looks good.  It may not be a problem in real code, so not needing
> any solution.

Good point.  As a C++ programmer, I use RAII a lot.  However, there's 
situations in C++ that don't apply, like allocating dynamic memory in a 
scope.  However, I still expect some Python programmers to use it enough 
to ask for that syntax to be added, in the same way operators like += 
have been added.

But there's another point that has nothing to do with how many "with" 
statements you have in a function.  In C++, very very rarely I've seen 
something like:

void foo() {
 {  // (define a scope for the Lock object)
Lock locking(myMutex);
...
 }
 ...
 {
Lock locking(myMutex);
...
 }
}

So I come to another conclusion: the indentation syntax will most of the 
time result in a waste of space.  Typically a programmer would want its 
with-block to end at the end of the current block.

So basically, there's two 10-90% points, one in favor of my proposal, 
one against:

- Most of the time, you don't have a lot of with-statements in a single 
function, so not so much indentation.
- Most of the time, a with-statement ends at the end of current block, 
so indentation-syntax most of the time result in a waste of space.

The way to see my proposal is not "to be used when you have multiple 
with-blocks" but instead "never use the ':' syntax, unless necessary". 
The day some code need it, it's very easy to add a ':' and indent some 
code with our favorite editor.

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


Re: idiom for constructor?

2005-06-04 Thread Steven Bethard
Peter Dembinski wrote:
>class A:
>def __init__(self, a, b, c, d):
>initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d}
>for param in initial.keys():
>exec "self.%s = initial['%s']" % (param, param)

This is not a good use case for exec.  Use setattr:

for param in initial:
 setattr(self, param, initial[param])

Or better yet, just update the instance dict:

self.__dict__.update(initial)

But this misses the OP's point.  The issues was that the OP didn't want 
to write a, b, c and d again.  Not only does this proposal make you 
write them again, it makes you write them again twice!

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Steven Bethard
Ilpo Nyyssönen wrote:
> How about this instead:
> 
> with locking(mutex), opening(readfile) as input:
> ...
> 

I don't like the ambiguity this proposal introduces.  What is input 
bound to?  The return value of locking(mutex).__enter__() or the return 
value of opening(readfile).__enter__()?  Seems ambiguous to me.  And is 
the file opened with the mutex held, or not?  Sure, all of these 
questions can be answered with an arbitrary decision.  But the point is 
that, whatever decision you make, I now have to *memorize* that decision.

Note that if I wrote:

with locking(mutex):
 with opening(readfile) as input:
 ...

it's clear that input is the return value of 
opening(readfile).__enter__(), and that the mutex is held while the file 
is opened.  I don't need to memorize these things; they are explicit in 
the syntax.

I can see making the with-statement proposal more complex if you had 
some very good motivating examples for wanting the multiple-expressions 
extension.  But you have yet to provide a real-world use case.  Go 
search your codebase, and find some examples of where you would actually 
use this.  For the complexity that you want to add to the 
with-statement, you need to show that there's a *large* advantage to a 
*variety* of use cases in *real-world* code.

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


Newbie Python & XML

2005-06-04 Thread LenS
I have a situation at work.  Will be receiving XML file which contains
quote information for car insurance.  I need to translate this file
into a flat comma delimited file which will be imported into a software
package.  Each XML file I receive will contain information on one quote
only.  I have documentation on layout of flat file and examples of XML
file (lot of fields but only container tags and field tags no
DTD's,look easy enough).  I am just starting to learn python and have
never had to work with XML files before.  Working in MS Windows
environment.  I have Python 2.4 with win32 extensions.

1. What else do I need
2. Any examples of program doing the same.
3. Have read some stuff that indicates I may need ? schema of XML
layout 

The rating company will ftp a quote realtime to a dir on my system.
the python program will then have to poll the dir for new files and
automaticly translate and initiate import.

Any help appreciated
Len Sumnler

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


Re: Walking through a mysql db

2005-06-04 Thread Jeff Elkins
On Saturday 04 June 2005 09:24 am, Jeff Elkins wrote:
> I'm writing a small wxpython app to display and update a dataset. So far, I
> get the first record for display:
>
>  try:
>   cursor = conn.cursor ()
>   cursor.execute ("SELECT * FROM dataset")
>   item = cursor.fetchone ()
>
> Now, how do I step through the dataset one row at a time?  My form has 
> 'next' and 'back' buttons, and I'd like them to step forward or back,
> fetching the appropriate row in the table. I've tried setting
> cursor.rownumber by incrementing it prior to the fetchone() w/o effect.

Thanks for the responses!  The buttons are working now.

Within this same app, I've got a search function working, but I need the 
rownumber when a record is fetched.

  sql = """select * from address where %s = %%s""" % arg1.lower()
cursor.execute(sql, (arg2,))
 item = cursor.fetchone ()
 index = cursor.rownumber

At this point, the record is on the screen, but cursor.rownumber doesn't 
reflect the actual rownumber...it always returns 1. How can I obtain the 
actual row number for the displayed record?

Jeff


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


Re: Walking through a mysql db

2005-06-04 Thread wes weston
Jeff Elkins wrote:
> I'm writing a small wxpython app to display and update a dataset. So far, I 
> get the first record for display:
> 
>  try:
>   cursor = conn.cursor ()
>   cursor.execute ("SELECT * FROM dataset")
>   item = cursor.fetchone ()
> 
> Now, how do I step through the dataset one row at a time?  My form has  
> 'next' 
> and 'back' buttons, and I'd like them to step forward or back, fetching the 
> appropriate row in the table. I've tried setting cursor.rownumber by 
> incrementing it prior to the fetchone() w/o effect.
> 
> Thanks for any pointers.
> 
> Jeff Elkins
> 
> 
> 
> 
> 
> 
Jeff,
You just check for a fetchone return of None. "list" is a list
of tuples here.
 ...
 cursor.execute( sql )
 list = []
 while 1:
 row = cursor.fetchone()
 if not row:
 break
 list.append(row)
 ...
wes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking through a mysql db

2005-06-04 Thread Benjamin Niemann
Jeff Elkins wrote:

> I'm writing a small wxpython app to display and update a dataset. So far,
> I get the first record for display:
> 
>  try:
>   cursor = conn.cursor ()
>   cursor.execute ("SELECT * FROM dataset")
>   item = cursor.fetchone ()
> 
> Now, how do I step through the dataset one row at a time?  My form has 
> 'next' and 'back' buttons, and I'd like them to step forward or back,
> fetching the appropriate row in the table. I've tried setting
> cursor.rownumber by incrementing it prior to the fetchone() w/o effect.
You could either execute N-1 fetchone()s before you fetch the Nth dataset
(with N starting at 1)
or use the 'LIMIT' feature of MySQL:
cursor.execute ("SELECT * FROM dataset LIMIT %s,1", n)
where n is the index of the requested dataset (starting at 0)

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If - Or statements

2005-06-04 Thread tiissa
Ognjen Bezanov wrote:
> ext = thefile.split('.') #get the file extension
> ext[1] =  ext[1].lower() #convert to lowercase

As a side note, ext[1] will be the first extension:

  >>> 'foo.bar.ogg'.split('.')[1]
  'bar'

I'd advise ext[-1], the last element of the splitted list.

  >>> 'foo.bar.ogg'.split('.')[-1]
  'ogg'
-- 
http://mail.python.org/mailman/listinfo/python-list


Walking through a mysql db

2005-06-04 Thread Jeff Elkins
I'm writing a small wxpython app to display and update a dataset. So far, I 
get the first record for display:

 try:
  cursor = conn.cursor ()
  cursor.execute ("SELECT * FROM dataset")
  item = cursor.fetchone ()

Now, how do I step through the dataset one row at a time?  My form has  'next' 
and 'back' buttons, and I'd like them to step forward or back, fetching the 
appropriate row in the table. I've tried setting cursor.rownumber by 
incrementing it prior to the fetchone() w/o effect.

Thanks for any pointers.

Jeff Elkins






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


Re: If - Or statements

2005-06-04 Thread rzed
Ognjen Bezanov <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Robert Kern wrote:
> 
>> Ognjen Bezanov wrote:
>>
>>> Another newbie-ish question.
>>>
>>> I want to create an if statement which will check if a
>>> particular variable matches one of the statements, and willl
>>> execute the statement if the variable matches any of the
>>> statements. 
>>>
>>> I have tried the following (the pass is just used for testing)
>>>
>>>
>>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or
>>> ext[1] == "aac" or ext[1] != "wma":
>>>print "we have a valid extension: " + ext[1] #here
>>>would go the 
>>> code for decoding the above
>>>pass
>>
>>
>> It works fine for me. Could you post the smallest complete
>> program (one that defines ext) that displays the behavior and
>> its entire output? 
>>
>> As an aside, is 'ext[1] != "wma"' correct or should it be ==?
>> As written, you could collapse the whole thing to 'if ext[1] !=
>> "wma":' but I presume it is a typo.
>>
> filelist = os.listdir('/mnt/cdrom/') #get a list of files from
> the cdrom drive
> for thefile in filelist[:]:   #for each file in the
> filelist 
> if thefile.find(".") != -1:   #if the file has an
> extenstion 
> at all
> ext = thefile.split('.') #get the file extension
> ext[1] =  ext[1].lower() #convert to lowercase
> print ext[1] #debugging, to see the variable
> before 
> passed to if statement
> 
> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1]
> == "ogg" 
> or ext[1] == "aac" or ext[1] == "wma":
> print "we have a valid extension: " + ext[1]
> #here 
> would go the code for decoding the above
> pass

Though this may sidetrack the issue, another way of doing multiple 
checks like that is to make a list and check for inclusion in the 
list. Something like this:
exts = ['mp3','mp4','ogg','aac','wma']
if ext[1] not in exts:
# do whatever

or
if ext[1] in exts:
print 'we have a valid extension:',ext[1]

It's easier to add to the list than to add another explicit test, 
particularly if the tests occur in several places.
-- 
rzed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are OOP's Jargons and Complexities?

2005-06-04 Thread Andrea Griffini
On Wed, 01 Jun 2005 23:25:00 +0200, Matthias Buelow <[EMAIL PROTECTED]>
wrote:

>Of course it is a language, just not a standardized one (if you include
>Borland's extensions that make it practical).

The history of "runtime error 200" and its handling from
borland is a clear example of what I mean with a product.

You are of course free to call even Microsoft Access a
language (and make long term investment on it) if you want.

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


Re: any macro-like construct/technique/trick?

2005-06-04 Thread =?iso-8859-1?Q?Fran=E7ois?= Pinard
[Paddy]

> If you still must have something like the c preprocessor
> then unix has m4 (and it seems there is a windows version
> http://gnuwin32.sourceforge.net/packages/m4.htm).

The difficulty of `m4' for Python source is that macro expansions should
be accompanied with proper adjustment of indentation, for adapting to
the context where macros are getting expanded.

René Seindal's `m4' is surprisingly powerful, so maybe that with enough
trickery (I really mean: a _lot_ of trickery), adjustment of indentation
could be possible.  And maybe that a simpler `m4' approach to Python
macro-expansion could be made available through the later pluggin
features which René added to `m4'.  (Yet I do not know if the pluggin
features have been integrated in the `m4' distribution mainstream.)

It would be much easier using `m4' for Python, if there was a way
to invoke it after Python lexer and before further parsing, because
 and  tokens would already been identified.  If this was
possible, `m4' would be a breeze to use as a pre-processor for Python.

Still in this dreaming mode, there would also be one necessary detail
missing for full comfort: that is, the recognition of `#line' like
directives as generated by `m4' so Python tracebacks, for example, would
correctly refer to the Python source lines before macro-expansion.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any macro-like construct/technique/trick?

2005-06-04 Thread =?iso-8859-1?Q?Fran=E7ois?= Pinard
[Georges JEGO]
> Mac a écrit :
> > #  do some stuff
> > if debug:
> > emit_dbg_obj(DbgObjFoo(a,b,c))

> Assuming your debug functions always return true, you could use:

>  assert emit_dbg_obj(DbgObjFoo(a,b,c))

> and have this code executed -or not- depending on the use of "-O"

Dirty, dirty trick :-).

`assert' is quite useful in its real and genuine purpose.  There is
something heretic in allowing side effects in `assert' statements.  A
few centuries ago, Python programmers doing this were burnt in public,
and this is how Python got forgotten for so long.  (Guido rediscovered
it a dozen years ago, the wise guy attributed all the merit to himself!)

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software licenses and releasing Python programs for review

2005-06-04 Thread Steve Holden
Andreas Kostyrka wrote:
> On Thu, Jun 02, 2005 at 01:57:25AM -0700, Robert Kern wrote:
> 
>>And for thoroughness, allow me to add "even if they have no intention or 
>>desire to profit monetarily." I can't explain exactly why this is the 
>>case, but it seems to be true in the overwhelming majority of cases. 
>>Academic projects with non-commercial clauses languish in obscurity 
>>while academic Open Source projects thrive. The contributors to the Open 
> 
> Well, it's easily explained. (Well at least my motivation in this case)
> I do not touch things that I cannot use "generally" and being a
> "commercial" IT consultant this basically means:
> *) opensource is better than commercial payware.
>(because "for free" (as in beer) is usable in more contexts)
> *) GPL is acceptable for much stuff, because I can install GPL'ed
>stuff for a customer.
> *) GPL is not acceptable for "library" stuff, because as a software
>developer I'm sometimes forced to do "closed" stuff.
>(Yep, even nowadays there are place where it's basically a legal
> requirement.)
> 
> Implications:
> 
> *) qt is a bordercase: GPL for free, or commercial for pay. Not perfect but
>good enough. 
> *) A number of O-R mappers for Python are of no relevance to me,
>because they are GPL. O-R mappers are development libraries.
> 
But this would only be a restriction if the code were to be 
redistributed, of course. It's stil perfectly legal to use it internaly 
without making the modified source available.

> The idea is that I'm mostly not interested in learning tools that are
> not of general use.
> 
> So basically, stuff not meeting this criteria, is only interesting if
> it's unique:
> 
> *) commercial stuff is only interesting if there is no competing
>open-source project.
> *) GPL'ed "building blocks" are only interesting when there is no
>competing LGPL version. Example: OCR on Linux/Unix. There are no
>perfect solutions there so a GPL'ed solution might be
>ok. (Especially because one can use OCR without linking with a lib
>*grin*)
> 
> Andreas

regards
  Steve
-- 
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread oren . tirosh
Ilpo Nyyssönen wrote:
> Nicolas Fleury <[EMAIL PROTECTED]> writes:
> > def foo():
> > with locking(someMutex)
> > with opening(readFilename) as input
> > with opening(writeFilename) as output
> > ...
>
> How about this instead:
>
> with locking(mutex), opening(readfile) as input:
> ...

+1, and add PEP-328-like parentheses for multiline.

  Oren

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Robin Becker
Kent Johnson wrote:
> Robin Becker wrote:
> 
>> Ilpo Nyyssönen wrote:
>>
>>>
>>> with locking(mutex), opening(readfile) as input:
>>> ...
>>
>>
>> with EXPR as x:
>>  BLOCK
>>
>> EXPR can be a tuple so the above would be ambiguous.
> 
> 
> I don't think EXPR can be a tuple; the result of evaluating EXPR must 
> have __enter__() and __exit__() methods. *x* can be a tuple.
> 
> Kent

Well perhaps this would fly then. I reread the PEP and it says EXPR is 
arbitrary, but cannot be an expression list so maybe this was already 
considered and rejected.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any macro-like construct/technique/trick?

2005-06-04 Thread Georges JEGO
Mac a écrit :
> #  do some stuff
> if debug:
> emit_dbg_obj(DbgObjFoo(a,b,c))

Assuming your debug functions always return true, you could use:

 assert emit_dbg_obj(DbgObjFoo(a,b,c))

and have this code executed -or not- depending on the use of "-O"

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


ANN: eric3 3.7.0 released

2005-06-04 Thread Detlev Offenbach
Hi,

this is to let all of you know about the release of eric3 3.7.0. Next to
a bunch of bugfixes, it adds these features.

- support for Ruby projects (debugger, syntax highlighting)
- support for the generation of KDE UIs
- introduction of watchpoints
- added class browsers for Ruby and CORBA IDL files
- added bookmark capability to the file browser
- added context menus for directories to the various browsers
- added tasks and a task viewer

and a bunch of little improvements.

As usual it is available via
http://www.die-offenbachs.de/detlev/eric3.html

Go get it and enjoy working with it.

Many thanks to all people who have tested the snapshots, send bug reports
and supported the development by sending patches and translating the
eric3 UI.

What is it
--
Eric3 is a full featured development environment for Python and Ruby
released under the conditions of the GPL. Please see above URL for more
information and download.

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If - Or statements

2005-06-04 Thread Robert Kern
Ognjen Bezanov wrote:
> Robert Kern wrote:
> 
> 
>>Ognjen Bezanov wrote:
>>
>>
>>>Another newbie-ish question.
>>>
>>>I want to create an if statement which will check if a particular
>>>variable matches one of the statements, and willl execute the statement
>>>if the variable matches any of the statements.
>>>
>>>I have tried the following (the pass is just used for testing)
>>>
>>>
>>>if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] ==
>>>"aac" or ext[1] != "wma":
>>>   print "we have a valid extension: " + ext[1] #here would go the
>>>code for decoding the above
>>>   pass
>>
>>
>>It works fine for me. Could you post the smallest complete program
>>(one that defines ext) that displays the behavior and its entire output?
>>
>>As an aside, is 'ext[1] != "wma"' correct or should it be ==? As
>>written, you could collapse the whole thing to 'if ext[1] != "wma":'
>>but I presume it is a typo.
> 
> filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom
> drive
> for thefile in filelist[:]:   #for each file in the filelist
> if thefile.find(".") != -1:   #if the file has an extenstion
> at all
> ext = thefile.split('.') #get the file extension
> ext[1] =  ext[1].lower() #convert to lowercase
> print ext[1] #debugging, to see the variable before
> passed to if statement
> 
> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg"
> or ext[1] == "aac" or ext[1] == "wma":
> print "we have a valid extension: " + ext[1] #here
> would go the code for decoding the above
> pass

It works just fine for me. Note that you could (and probably should) 
write the if statement as

   if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'):

but I really don't think that's your problem. Could you also post the 
output, too?

In [1]:filelist = os.listdir('./')

In [2]:for thefile in filelist:
...:if '.' in thefile:
...:ext = thefile.split('.')
...:ext[1] = ext[1].lower()
...:print ext[1]
...:if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] == 
'ogg' or ext[1] == 'aac' or ext[1] == 'wma'):
...:print 'We have a valid extension: %s' % ext[1]
...:
ogg
We have a valid extension: ogg
[etc.]

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: idiom for constructor?

2005-06-04 Thread Peter Dembinski
Peter Dembinski <[EMAIL PROTECTED]> writes:

[snap]

Eh, sorry, it should look like this:

> #v+
>
> class A:
> def __init__(self, a, b, c, d):
> initial = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}  
  initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d}
>
> for param in initial.keys():
> exec "self.%s = initial['%s']" % (param, param)
>
> #v-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for constructor?

2005-06-04 Thread Peter Dembinski
Steven Bethard <[EMAIL PROTECTED]> writes:

> Mac wrote:
>> Is there a nice Python idiom for constructors which would expedite
>> the following?
>> class Foo:
>>   def __init__(self, a,b,c,d,...):
>> self.a = a
>> self.b = b
>> self.c = c
>> self.d = d
>> ...
>
> py> class Foo(object):
> ... def __init__(self, a, b, c, d):
> ... params = locals()
> ... del params['self']
> ... self.__dict__.update(params)
> ...
> py> vars(Foo(1, 2, 3, 4))
> {'a': 1, 'c': 3, 'b': 2, 'd': 4}
>
> Just make sure that "params = locals()" is the first line in
> __init__ method.  (Otherwise you might have other local variables
> slip in there.)

Or write it like this, using Python's dynamic code execution:

#v+

class A:
def __init__(self, a, b, c, d):
initial = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}

for param in initial.keys():
exec "self.%s = initial['%s']" % (param, param)

#v-

-- 
http://www.peter.dembinski.prv.pl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get name of function from within function?

2005-06-04 Thread Kent Johnson
Christopher J. Bottaro wrote:
> Steven Bethard wrote:
> [...snip...]
> 
>>Yes, has's suggestion is probably the right way to go here.  I'm still
>>uncertain as to your exact setup here.  Are the functions you need to
>>wrap in a list you have?  Are they imported from another module?  A
>>short clip of your current code and what you want it to do would help.
> 
> 
> But I want to avoid having to write each wrapper myself.  As it is now, when
> I want to add a public method to my class named myFunc, I first write
> myFunc which is a wrapper to the implementation:
> 
> def myFunc(self):
>   try: self.myFuncIMPL()
>   except: # error handling code
> 
> def myFuncIMPL(self):
>   # do the real stuff here, no need to worry about error handling stuff
>   # cuz its done in the wrapper
> 
> I guess I'm just lazy, but I don't want to write the wrapper func for each
> new func I want to add.  I want it done automatically.

You can do this almost automatically with a decorator:

def in_try(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
print "entered except"
raise
return wrapper

class C(object):
@in_try
def func_a(self):
print "func_a"

@in_try
def func_b(self):
print "func_b"
raise Exception

You could probably create a metaclass to apply the wrappers automatically but I 
like having it explicit as above.

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


Re: how to get name of function from within function?

2005-06-04 Thread Raymond Hettinger
[Christopher J. Bottaro]
>> def myFunc():
>>   print __myname__
>> >>> myFunc()
>> 'myFunc'

Perhaps the __name__ attribute is what you want:


>>> def myFunc():
print myFunc.__name__

>>> myFunc()
myFunc

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


[no subject]

2005-06-04 Thread Jatinder Singh
Hi guys
I am working in a complex directory structure. I want to use a file (not .py)
which is in some other directory. I couldn't do it.but if I copy the file in
the same directory then it is working fine. Can anybody guide me how and where
to add the path of the file. I have tried it with sys.path but it is not for
that.


-- 
Regards,
Jatinder Singh

“ Everyone needs to be loved... especially when they do not deserve it.”
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Kent Johnson
Robin Becker wrote:
> Ilpo Nyyssönen wrote:
>>
>> with locking(mutex), opening(readfile) as input:
>> ...
> 
> with EXPR as x:
>  BLOCK
> 
> EXPR can be a tuple so the above would be ambiguous.

I don't think EXPR can be a tuple; the result of evaluating EXPR must have 
__enter__() and __exit__() methods. *x* can be a tuple.

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


Re: If - Or statements

2005-06-04 Thread Ognjen Bezanov
Robert Kern wrote:

> Ognjen Bezanov wrote:
>
>> Another newbie-ish question.
>>
>> I want to create an if statement which will check if a particular
>> variable matches one of the statements, and willl execute the statement
>> if the variable matches any of the statements.
>>
>> I have tried the following (the pass is just used for testing)
>>
>>
>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] ==
>> "aac" or ext[1] != "wma":
>>print "we have a valid extension: " + ext[1] #here would go the
>> code for decoding the above
>>pass
>
>
> It works fine for me. Could you post the smallest complete program
> (one that defines ext) that displays the behavior and its entire output?
>
> As an aside, is 'ext[1] != "wma"' correct or should it be ==? As
> written, you could collapse the whole thing to 'if ext[1] != "wma":'
> but I presume it is a typo.
>
filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom
drive
for thefile in filelist[:]:   #for each file in the filelist
if thefile.find(".") != -1:   #if the file has an extenstion
at all
ext = thefile.split('.') #get the file extension
ext[1] =  ext[1].lower() #convert to lowercase
print ext[1] #debugging, to see the variable before
passed to if statement

if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg"
or ext[1] == "aac" or ext[1] == "wma":
print "we have a valid extension: " + ext[1] #here
would go the code for decoding the above
pass

Just tell me if you need more info/code snippets

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


SimpleXMLRPCServer security

2005-06-04 Thread Robin Becker
What are the security issues for an xmlrpc server with 127.0.0.1 as 
host? Clearly anyone with local access can connect to the server so we 
should protect the server and client code, but in my particular case the 
client starts as a cgi script and in general must be world 
readable/executable. Switching uid at startup allows the client code to 
be private; so is that a strategy for protecting the 
encryption/decryption which obfuscates the xmlrpc channel?

Anyone done this sort of thing before?
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Robin Becker
Ilpo Nyyssönen wrote:
...
> 
> with locking(mutex), opening(readfile) as input:
> ...


with EXPR as x:
  BLOCK

EXPR can be a tuple so the above would be ambiguous.

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


Re: If - Or statements

2005-06-04 Thread Robert Kern
Ognjen Bezanov wrote:
> Another newbie-ish question.
> 
> I want to create an if statement which will check if a particular
> variable matches one of the statements, and willl execute the statement
> if the variable matches any of the statements.
> 
> I have tried the following (the pass is just used for testing)
> 
> 
> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] ==
> "aac" or ext[1] != "wma":
>print "we have a valid extension: " + ext[1] #here would go the
> code for decoding the above
>pass

It works fine for me. Could you post the smallest complete program (one 
that defines ext) that displays the behavior and its entire output?

As an aside, is 'ext[1] != "wma"' correct or should it be ==? As 
written, you could collapse the whole thing to 'if ext[1] != "wma":' but 
I presume it is a typo.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


If - Or statements

2005-06-04 Thread Ognjen Bezanov
Another newbie-ish question.

I want to create an if statement which will check if a particular
variable matches one of the statements, and willl execute the statement
if the variable matches any of the statements.

I have tried the following (the pass is just used for testing)


if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] ==
"aac" or ext[1] != "wma":
   print "we have a valid extension: " + ext[1] #here would go the
code for decoding the above
   pass


but it does not work, running the program the if statement is totally
ignored. if the variable (ext[1]) matches it does not execute the
instructions under the if statement, but also does not return anyerrors.

So how do you create proper if statements using the 'or' function (or
something similar).

thx.


P.S Please CC me as i am having email-list troubles.

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


Re: [ANN] Snakelets 1.41 and Frog 1.6

2005-06-04 Thread thinfrog
It's very interesting, i'm glad to try.

And it can access data by MYSQL/SQL or other database software?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing a warnings filter?

2005-06-04 Thread Torsten Bronger
Hallöchen!

Dave Benjamin <[EMAIL PROTECTED]> writes:

> Torsten Bronger wrote:
>
>> When I add a warning filter with warnings.filterwarnings, how can
>> I get rid of it?  I've read about resetwarnings(), but it removes
>> all filters, even those that I didn't install in a certain
>> function.
>
> I have never used this module, but judging by a quick glance of
> the source to "warnings.py", it appears that warning filters are
> added to a list called "warnings.filters".

Thank you, I'll use it in my program.  However, I don't like it very
much, because warnings.filters isn't mentioned in the reference, and
in other languages that I've used, internal features are not
guaranteed to work across different versions.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >