Re: Unyeilding a permutation generator

2008-11-04 Thread sillyhat
On 2 Nov, 22:03, Carsten Haese <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Anyway what I want to do is experiment with code similar to this (i.e.
> > same algorithm and keep the recursion) in other languages,
> > particularly vbscript and wondered what it would look like if it was
> > rewritten to NOT use the yield statement
>
> An obvious (though memory-inefficient) replacement is to accumulate a
> list and return the list. Initialize a result variable to an empty list,
> and instead of yielding elements, append them to the result variable.
> Then return the result variable at the end of the function.
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

That did it and I can still understand it!

def allperm(str):
  if len(str) <= 1:
 return str
  else:
 biglist = []
 for perm in allperm(str[1:]):
for i in xrange(len(str)): #minor change here
   biglist.append(perm[:i] + str[0:1] + perm[i:])

  return biglist

for x in allperm("ABCD"):
   print x
--
http://mail.python.org/mailman/listinfo/python-list


Re: Structures

2008-11-04 Thread Bruno Desthuilliers

Joe Strout a écrit :

On Nov 3, 2008, at 4:38 PM, Paulo J. Matos wrote:


However, I wouldn't dare to say Python needs structures to be a good
language, or anything similar. My question was more directed to : if
there aren't structures in Python, what do Pythonists use instead?


Classes.


or objects, or dicts, depending on concrete use case, personnal 
preferences and current phase of the moon.


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


Re: Unyeilding a permutation generator

2008-11-04 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:
[...]
> Thats interesting code but seems to give a different output,
> suggesting thet the underlying algorithm is different.

Yes.

Yours takes the first element out of the list and inserts it in every
position of all the permutations of the list without the first element:

> Ignoring linebreaks and case, the original code gives:
> abcd bacd bcad bcda acbd cabd cbad cbda acdb cadb cdab cdba abdc badc
> bdac bdca adbc dabc dbac dbca adcb dacb dcab dcba

Michele's takes every element out of the list in turn and appends every
permutation of the list without this element to its right:

> The output from the above program, when converted to strings is:
> abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb
> cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba
>
> Cheers, Hal.

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


Re: separate shared libraries or different Linux/Unix

2008-11-04 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> I want as much built from source as I can manage so that I know what
> is and what is not on the system.

Sounds like a job for Gentoo. :)

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


Re: storing a string data in access

2008-11-04 Thread alex23
On Nov 4, 3:53 am, "Tim Arnold" <[EMAIL PROTECTED]> wrote:
> "alex23" <[EMAIL PROTECTED]> wrote:
> > t = "string representing a datum"
> > access.Fields("Time").value = t
>
> maybe OP means t = "string representing a date", but I'm just guessing.

Oops, that totally didn't occur to me. You'd think the field's key
would've been a giveaway :)

ted: take a look at the time module, it's part of the standard
library.

  import time
  access.Fields("Time").value = time.strptime('10:00AM', '%I:%M%p')

http://www.python.org/doc/2.5.2/lib/module-time.html


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


Re: Structures

2008-11-04 Thread Arnaud Delobelle
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:

> On Mon, 03 Nov 2008 23:32:25 +, Paulo J. Matos wrote:
>
>> What's then the reason for adding named tuples if they are not
>> mutable...???
>
> Names are more descriptive than "magic numbers" as indices.  See for 
> example the "named tuple" returned by `os.stat()`.
>
> Ciao,
>   Marc 'BlackJack' Rintsch

I'm reminded of a 'struct' decorator I made some time ago:

def struct(f):
classname = f.__name__
prop_names = f.func_code.co_varnames[:f.func_code.co_argcount]
def _new(cls, *args, **kwargs):
return tuple.__new__(cls, f(*args, **kwargs))
def _repr(self):
return '%s%s' % (type(self).__name__, tuple(self))
def prop(i):
return property(lambda self: self[i])
attrs = { '__slots__': (), '__new__': _new, '__repr__': _repr }
attrs.update((name, prop(i)) for i, name in enumerate(prop_names))
return type(classname, (tuple,), attrs)


The advantage over namedtuple is that you don't have to repeat the name
of the structure and you can easily define default values.  The drawback
is that it involved some mild hackery (It won't work as is in Python 3
as f.func_code changed to f.__code__).  It worked like this:

>>> @struct
... def Point(x=0, y=0): return float(x), float(y)
...
>>> p, q = Point(2, 7), Point(y=3)
>>> p, q
(Point(2.0, 7.0), Point(0.0, 3.0))
>>> x, y = p
>>> x, y
(2.0, 7.0)
>>> p.x + p.y
9.0
>>> p.x = 3
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: can't set attribute
>>> isinstance(p, tuple)
True

It's immutable but it would be easy to make it mutable by making it
inherit from list instead of tuple.

You could even have some processing:

>>> @struct
... def Interval(start, end, size=None):
... size = end - start
... return start, end, size
... 
>>> I = Interval(2.5, 6.0)
>>> I.start, I.end, I.size
(2.5, 6.0, 3.5)

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


Using ZSI Soap libraries from behind a proxy-based firewall

2008-11-04 Thread jorma kala
Hi I'm trying to build a simple soap client using  the ZSI library.
My python script operates from behind a proxy-based firewall.
Do you know how I can specify the proxy name and port to use, when using the
ZSI client.
( using the urllib2, this can be done through ProxyHandler, for instance.
But I dont know how its done using soap libraries.
Many thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread sturlamolden
On Nov 3, 7:11 pm, "Andy O'Meara" <[EMAIL PROTECTED]> wrote:

> My hope was that the increasing interest and value associated with
> flexible, multi-core/"free-thread" support is at a point where there's
> a critical mass of CPython developer interest (as indicated by various
> serious projects specifically meant to offer this support).
> Unfortunately, based on the posts in this thread, it's becoming clear
> that the scale of code changes, design changes, and testing that are
> necessary in order to offer this support is just too large unless the
> entire community is committed to the cause.

I've been watching this debate from the side line.

First let me say that there are several solutions to the "multicore"
problem. Multiple independendent interpreters embedded in a process is
one possibility, but not the only. Unwillingness to implement this in
CPython does not imply unwillingness to exploit the next generation of
processors.

One thing that should be done, is to make sure the Python interpreter
and standard libraries release the GIL wherever they can.

The multiprocessing package has almost the same API as you would get
from your suggestion, the only difference being that multiple
processes is involved. This is however hidden from the user, and
(almost) hidden from the programmer.

Let see what multiprocessing can do:

- Independent interpreters? Yes.
- Shared memory? Yes.
- Shared (proxy) objects? Yes.
- Synchronization objects (locks, etc.)? Yes.
- IPC? Yes.
- Queues? Yes.
- API different from threads? Not really.

Here is one example of what the multiprocessing package can do,
written by yours truly:

http://scipy.org/Cookbook/KDTree

Multicore programming is also more than using more than one thread or
process. There is something called 'load balancing'. If you want to
make efficient use of more than one core, not only must the serial
algorithm be expressed as parallel, you must also take care to
distribute the work evenly. Further, one should avoid as much resource
contention as possible, and avoid races, deadlocks and livelocks.
Java's concurrent package has sophisticated load balancers like the
work-stealing scheduler in ForkJoin. Efficient multicore programming
needs other abstractions than the 'thread' object (cf. what cilk++ is
trying to do). It would certainly be possible to make Python do
something similar. And whether threads or processes is responsible for
the concurrency is not at all important. Today it it is easiest to
achieve multicore concurrency on CPython using multiple processes.

The most 'advanced' language for multicore programming today is
Erlang. It uses a 'share-nothing' message-passing strategy. Python can
do the same as Erlang using the Candygram package
(candygram.sourceforege.net). Changing the Candygram package to use
Multiprocessing instead of Python threads is not a major undertaking.

The GIL is not evil by the way. SBCL also has a lock that protects the
compiler. Ruby is getting a GIL.

So all it comes down to is this:

Why do you want multiple independent interpreters in a process, as
opposed to multiple processes?

Even if you did manage to embed multiple interpreters in a process, it
would not give the programmer any benefit over the multiprocessing
package. If you have multiple embedded interpreters, they cannot share
anything. They must communicate serialized objects or use proxy
objects. That is the same thing the multiprocessing package do.

So why do you want this particular solution?






S.M.
































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


Re: Finding the instance reference of an object

2008-11-04 Thread Craig Allen
>
> If the assert statement fails (and it does), then no copy was made and
> Python is not call-by-value.
>
> So Python is not call-by-value, and it's not call-by-reference, so ...
> either Python doesn't exist, or it uses a different calling convention.
>

coming from C/C++ Python seemed to me call by reference, for the
pragmatic reason you said, modificaitons to function arguments do
affect the variable in the caller.  The confusing part of this then
comes when immutable objects are passed in. You still get a reference,
but rather than complaining if you change the value of that parameter
at might happen if immutible was "const" and the code was const-
correct. Honestly I understand how this can change the callBy paradigm
I don't see it that way (though I've duly remembers call-by-sharing
and call-by-object) for communication purposes).  I see it as a factor
of the way variable names are rebound, that is, the "quirk" I remember
is not about how entities are passed to functions, but the quirk of
how python deals with modifications to "immutibles".

That is, python lets you change object references pointing to
immutibles, which looks like changing the value referenced,  by
rebinding.

So is that objectionable?
--
http://mail.python.org/mailman/listinfo/python-list


Re: split() and string.whitespace

2008-11-04 Thread Chaim Krause
That is a very creative solution! Thank you Scott.

> Or, for faster per-repetition (blending in to your use-case):
>
>      import string
>      SEP = string.maketrans('abc \t', '     ')
>      ...
>      parts = 'whatever, abalone dudes'.translate(SEP).split()
>      print parts
>
> ['wh', 'tever,', 'lone', 'dudes']
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread sturlamolden

If you are serious about multicore programming, take a look at:

http://www.cilk.com/

Now if we could make Python do something like that, people would
perhaps start to think about writing Python programs for more than one
processor.

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


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread Andy O'Meara
On Nov 4, 9:38 am, sturlamolden <[EMAIL PROTECTED]> wrote:


> First let me say that there are several solutions to the "multicore"
> problem. Multiple independendent interpreters embedded in a process is
> one possibility, but not the only.''

No one is disagrees there.  However, motivation of this thread has
been to make people here consider that it's much more preferable for
CPython have has few restrictions as possible with how it's used.  I
think many people here assume that python is the showcase item in
industrial and commercial use, but it's generally just one of many
pieces of machinery that serve the app's function (so "the tail can't
wag the dog" when it comes to app design).  Some people in this thread
have made comments such as "make your app run in python" or "change
your app requirements" but in the world of production schedules and
making sure payroll is met, those options just can't happen.  People
in the scientific and academic communities have to understand that the
dynamics in commercial software are can be *very* different needs and
have to show some open-mindedness there.


> The multiprocessing package has almost the same API as you would get
> from your suggestion, the only difference being that multiple
> processes is involved.

As other posts have gone into extensive detail, multiprocessing
unfortunately don't handle the massive/complex data structures
situation (see my posts regarding real-time video processing).  I'm
not sure if you've followed all the discussion, but multiple processes
is off the table (this is discussed at length, so just flip back into
the thread history).


Andy


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


Re: Which was the best Lib of GUI for python

2008-11-04 Thread Almar Klein
Hi,

If you search the newsgroup you'll find loads of similar posts.

There is not really an agreement on which GUI library is "the one".
Tkinter is a bit limited. Personally, I only have experience with
wxpython and like it a lot. But there are others like GTK, FLTK,
QT.

Cheers,
  Almar


2008/11/4 3000 billg <[EMAIL PROTECTED]>:
> Hi Guy,
> I am a leaner. for your experience. Which GUI Lib will be the best for
> Python? wxpython, Tkinter or...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which was the best Lib of GUI for python

2008-11-04 Thread Joe Strout

On Nov 3, 2008, at 10:53 PM, 3000 billg wrote:

I am a leaner. for your experience. Which GUI Lib will be the best  
for Python? wxpython, Tkinter or...


I'm sure you'll get as many opinions on this as there are libraries.   
However, I recently faced the same choice, and settled on wxPython.   
I've been very impressed with the quality and "nativeness" that's  
achievable with wx apps.  You'll find a number of demos with the  
wxPython distribution (already installed on your machine, if you're  
using OS X 10.5), and it's well worth running them to give you a feel  
for what it can do.


In addition to the quality apparent to the end-user (which I think is  
the most important thing), I find the wx API to be quite sensible and  
easy to work with too.


HTH,
- Joe


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


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread sturlamolden
On Nov 4, 4:27 pm, "Andy O'Meara" <[EMAIL PROTECTED]> wrote:

> People
> in the scientific and academic communities have to understand that the
> dynamics in commercial software are can be *very* different needs and
> have to show some open-mindedness there.

You are beware that BDFL's employer is a company called Google? Python
is not just used in academic settings.

Furthermore, I gave you a link to cilk++. This is a simple tool that
allows you to parallelize existing C or C++ software using three small
keywords. This is the kind of tool I believe would be useful. That is
not an academic judgement. It makes it easy to take existing software
and make it run efficiently on multicore processors.



> As other posts have gone into extensive detail, multiprocessing
> unfortunately don't handle the massive/complex data structures
> situation (see my posts regarding real-time video processing).  

That is something I don't believe. Why can't multiprocessing handle
that? Is using a proxy object out of the question? Is putting the
complex object in shared memory out of the question? Is having
multiple copies of the object out of the question (did you see my kd-
tree example)? Using multiple independent interpreters inside a
process does not make this any easier. For Christ sake, researchers
write global climate models using MPI. And you think a toy problem
like 'real-time video processing' is a show stopper for using multiple
processes.




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


Re: Finding the instance reference of an object

2008-11-04 Thread Mel
Craig Allen wrote:
> That is, python lets you change object references pointing to
> immutibles, which looks like changing the value referenced,  by
> rebinding.
> 
> So is that objectionable?

OK once in a while, but it wouldn't do for everyday.

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
# Case A:
>>> a=2
>>> b=3
>>> a+b
5
# Case B:
>>> id(a)
135720748
>>> id(b)
135720736
>>> id(a+b)
135720712
>>> id(a)+id(b)
271441484

In talking about Python programs, we'd really like to talk like case A. 
Meaningful values are tagged with names, passed around, operated on.  We
get our result and leave.  Case B adds a level of indirection that, if we
mention it, just obscures our actual task of summing two numbers.

Consider the fragment

def f (x, y):
return x+y
a=2
b=3
c = f(a, b)

We can imagine a cross-namespace assignment operator (which we could write
=\= if we needed more weird glyphs.)  It works exactly like ordinary
assignment except that the LHS is evaluated in a different namespace from
the RHS.  We could use our new operator to trace the execution of this code
fragment.  The core of it would be

x =\= a # outer to inner assignment
y =\= b
c =/= x+y   # inner to outer assignment

It's ordinary assignment all the way, except for being from an outer to an
inner, or from an inner to an outer namespace.  Note how changing to
mutable arguments makes no difference (literal arguments this time):

c = f ([2], [3])

x =\= [2]
y =\= [3]
c =/= x+y

Replacing =\= and =/= with = loses us our cross-namespace conceit, but the
code still runs and does what Python code does.

So why import the wrong terminology from some other field, then try to save
it by mangling the definition of 'value' so that it's no use in discussing 
what a program is supposed to do?

ob: Python, I refer you to the _Beyond the Fringe_ sketch "Portrait from
Memory", a reminiscence by a pseudo Bertrand Russell ("Moore, have you some
apples in that basket?".)  You want to have to talk like this all the time? 
See what I mean?

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


Re: Finding the instance reference of an object

2008-11-04 Thread Joe Strout

On Nov 4, 2008, at 7:42 AM, Craig Allen wrote:


coming from C/C++ Python seemed to me call by reference, for the
pragmatic reason you said, modificaitons to function arguments do
affect the variable in the caller.  The confusing part of this then
comes when immutable objects are passed in.


Yes, you stepped in the wrong direction right away and led yourself  
into a morass of contradictions.


The correct way to look at it is that a Python reference is like a C++  
pointer.  C++ pointers are passed by value (unless you add & to  
explicitly make a parameter by-reference), yet you can still use them  
to mutate the objects they point to, right?  Same thing in Python.   
Nothing at all mysterious going on here.  Compare this:


typedef Spam* SpamPtr;   // (where Spam is some class)
// ...
void foo(SpamPtr spam)
{
spam->count = 4;
}

When you call foo, it modifies the spam object passed in, even though  
the parameter is by-value.  How?  Because (looking more carefully),  
you didn't actually pass in a Spam object; you passed in a POINTER TO  
a Spam object.  That pointer remained unchanged.  You just used the  
pointer to change some other data living on the heap.  This is the  
case exactly equivalent to Python:


def foo(spam):
spam.count = 4;

Same thing here; the variable you pass in is a reference to a Spam  
object, and while that reference remains unchanged by the call, it is  
used to change some other data that lives on the heap.


Here's a C++ example that has no analog in Python, because it uses  
call-by-reference:


void throwOut(SpamPtr &spam)
{
printf("throwing out %s\n", spam->brand);
delete spam;
spam = nil;
}

Now here, when you invoke throwOut on a SpamPtr, your own SpamPtr  
variable (the one that you pass in) actually gets set to nil.  That's  
because the formal parameter here is just an alias of the actual  
parameter.  You can't do that in Python; this attempt:


def throwOut(spam):
print "throwing out %s\n", spam.brand
spam = nil

would entirely fail to have any effect whatsoever on the Spam  
reference you pass in.  "spam" here is just a local variable within  
the throwOut function, which has no connection to the variable passed  
in other than it gets a copy of its value (i.e., it initially refers  
to the same object as the actual parameter).  This doesn't work, and  
the C++ throwOut function has no analog in Python, because Python has  
no call-by-reference.


Here's another C++ example that has no analog in Python, because it  
passes an object directly on the stack rather than a reference to it:


void bar(Spam spam)
{
spam.count = 5;
}

This is the one that I know particularly confuses some users, because  
it LOOKS like what you could do in Python, and has the same behavior  
on the surface.  But it's not analogous at all, because the "spam"  
local variable here (and presumably the one in the calling context) is  
an object stored directly on the stack, rather than a reference to an  
object on the heap.  Python can't do that (nor can Java, nor  
REALbasic, etc.).  This example is also call-by-value, but the value  
in this case is a type that has no analog in Python.  Python object  
variables are references to objects on the heap, just like pointers in  
C++ to objects created with "new".  So this example is a red herring.


I'd be very interested in hearing whether, as a C/C++ user, the above  
explanation is clear and makes sense to you.


Thanks,
- Joe


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


Re: Which was the best Lib of GUI for python

2008-11-04 Thread Mike Driscoll
On Nov 4, 9:39 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Nov 3, 2008, at 10:53 PM, 3000 billg wrote:
>
> > I am a leaner. for your experience. Which GUI Lib will be the best  
> > for Python? wxpython, Tkinter or...
>
> I'm sure you'll get as many opinions on this as there are libraries.  
> However, I recently faced the same choice, and settled on wxPython.  
> I've been very impressed with the quality and "nativeness" that's  
> achievable with wx apps.  You'll find a number of demos with the  
> wxPython distribution (already installed on your machine, if you're  
> using OS X 10.5), and it's well worth running them to give you a feel  
> for what it can do.
>
> In addition to the quality apparent to the end-user (which I think is  
> the most important thing), I find the wx API to be quite sensible and  
> easy to work with too.
>
> HTH,
> - Joe

And the really cool thing about wxPython is that it has a fun and
helpful community. Be sure to join the wxPython mailing list if you go
with this toolkit. You'll learn a lot there.

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


Re: Finding the instance reference of an object

2008-11-04 Thread Bruno Desthuilliers

Joe Strout a écrit :

On Nov 3, 2008, at 5:27 PM, Marc 'BlackJack' Rintsch wrote:


Maybe this is a surprise for you, because we haven't discussed this in
much detail in this group lately, but it applies to Python which does
call-by-object or call-by-sharing.  ;-)


There's no such thing.  Those are just terms made up by the Python 
community


Did you read *any* of the many answers in this thread ? This term comes 
from lisp, and existed years before Python.


to in place of the more standard "call-by-value" terminology 
to make Python seem more mysterious than it really is.


Looks a bit paranoid to me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Structures

2008-11-04 Thread George Sakkis
On Nov 3, 10:26 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Tue, 04 Nov 2008 00:19:16 +, Marc 'BlackJack' Rintsch wrote:
> > On Mon, 03 Nov 2008 23:32:25 +, Paulo J. Matos wrote:
>
> >> What's then the reason for adding named tuples if they are not
> >> mutable...???
>
> > Names are more descriptive than "magic numbers" as indices.  See for
> > example the "named tuple" returned by `os.stat()`.
>
> I have no objection to named tuples, but I've sometimes
> missed having an equivalent to the Pascal record or C
> struct: essentially a named mutable tuple.

+1. FWIW, I posted a recipe along these lines, following closely the
functionality and implementation of namedtuple: 
http://code.activestate.com/recipes/576555/

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


Re: script that parses command line, and execfile('')

2008-11-04 Thread Sandip Bhattacharya
On Nov 4, 12:43 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> def main(argv=None):
>      if argv is None: argv = sys.argv[1:]
>      ...

Wouldn't that make optparse miss the first parameter sys.argv[1]
mistaking it to be the name of the current program?

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


Parse each line by character location

2008-11-04 Thread Tyler
Hello All:

I hope this is the right place to ask, but I am trying to come up with
a way to parse each line of a file. Unfortunately, the file is neither
comma, nor tab, nor space delimited. Rather, the character locations
imply what field it is.

For example:

The first ten characters would be the record number, the next
character is the client type, the next ten characters are a volume,
and the next three are order type, and the last character would be an
optional type depending on the order type.

The lines are somewhat more complicated, but they work like that, and
not all have to be populated, in that they may contain spaces. For
example, the order number may be 2345, and it is space padded at the
beginning of the line, and other might be zero padded in the front.
Imagine I have a line:

__2345H30_NC_

where the underscores indicate a space. I then want to map this to:

2345,H,30,NC,

In other words, I want to preserve ALL of the fields, but map to
something that awk could easily cut up afterwords, or open in a CSV
editor. I am unsure how to place the commas based on character
location.

Any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which PostgreSQL adapter to use?

2008-11-04 Thread D'Arcy J.M. Cain
On Tue, 04 Nov 2008 17:13:43 +0100
Thomas Guettler <[EMAIL PROTECTED]> wrote:
> Hussein B schrieb:
> > Hey,
> > Which Adapter to use with PostgreSQL:
> > PyPgSQL, psycopg or PyGreSQL?
> > Thanks.
> 
> I think psycopg2 is a good choice. Never tried anything else.

PyGreSQL 4.0 is currently in beta and should be released shortly.  Here
is the changelog so far.

- Dropped support for Python below 2.3 and PostgreSQL below 7.2
- Added new method to get parameter settings.
- Added row_factory as suggested by Simon Pamies.
- Separated between mandatory and additional type objects.
- Added keyword args to insert, update and delete methods.
- Added exception handling for direct copy.
- Release the GIL while making a connection
  (as suggested by Peter Schuller).
- If available, use decimal.Decimal for numeric types.
- Allow DB wrapper to be used with DB-API 2 connections
  (as suggested by Chris Hilton).
- Made private attributes of DB wrapper accessible.

http://www.PyGreSQL.org/

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: separate shared libraries or different Linux/Unix

2008-11-04 Thread chris
>
> Just don't even think of passing --enable-shared to Python's configure,
> and it will all work fine, and you won't need to use ldconfig.
>
Well I've done --enable-shared so that I can compile mod_python as a
shared object within apache.
Created /etc/ld.so.conf.d/python2.5.conf on a redhat system, and put /
opt/python/lib
and it works no probs.

>
> Installing *other* stuff (but Python) from source is something that you
> should completely avoid. Instead of installing zlib, you should have
> just installed Debian's zlib1g-dev package. Likewise for any other
> header files that you will need. The libraries provided by Debian are
> sufficient for building Python 2.6 with all extension modules (that
> can possibly work on Linux).

Each to their own.  I have a hosted virtual server, and I would like
to get another one for another project.
I want as much built from source as I can manage so that I know what
is and what is not on the system.
zlib is compiled with --enable-shared in /opt/zlib-1.2.3 and I've
ldconfig -n /opt/zlib-1.2.3/lib

I'm compiling python from source, because the server is running redhat
5 which comes with python 2.4
To run trac you need python2.5
I'm running into a problem where zlib is not available even though
there is a copy in /usr/lib/ of the version I compiled.

In /usr/local/src/Python2.5.2 I'm doing:
./configure --enable-shared --prefix=/opt/python --with-zlib=/opt/
zlib-1.2.3
make
make install
When running the setuptools egg, it says zlib unavailable.

Back in the config.log of the Python2.5.2 source directory, it shows
that it's passed in, but in that file there is a --with-system-zlib
How do I get zlib available to python?

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


Re: Parse each line by character location

2008-11-04 Thread Giorgio Gentili

Tyler ha scritto:

Hello All:

I hope this is the right place to ask, but I am trying to come up with
a way to parse each line of a file. Unfortunately, the file is neither
comma, nor tab, nor space delimited. Rather, the character locations
imply what field it is.

For example:

The first ten characters would be the record number, the next
character is the client type, the next ten characters are a volume,
and the next three are order type, and the last character would be an
optional type depending on the order type.

The lines are somewhat more complicated, but they work like that, and
not all have to be populated, in that they may contain spaces. For
example, the order number may be 2345, and it is space padded at the
beginning of the line, and other might be zero padded in the front.
Imagine I have a line:

__2345H30_NC_

where the underscores indicate a space. I then want to map this to:

2345,H,30,NC,

In other words, I want to preserve ALL of the fields, but map to
something that awk could easily cut up afterwords, or open in a CSV
editor. I am unsure how to place the commas based on character
location.

Any ideas?


A solution can be
line_new = (line[0:10] +  ',' + line[10] + ',' + line[11:21] + ',' + 
line[22:25]+',').replace(' ','')


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


Re: Finding the instance reference of an object

2008-11-04 Thread Craig Allen
On Nov 4, 11:06 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Nov 4, 2008, at 7:42 AM, Craig Allen wrote:
>
> > coming from C/C++ Python seemed to me call by reference, for the
> > pragmatic reason you said, modificaitons to function arguments do
> > affect the variable in the caller.  The confusing part of this then
> > comes when immutable objects are passed in.
>
> Yes, you stepped in the wrong direction right away and led yourself  
> into a morass of contradictions.
>
> The correct way to look at it is that a Python reference is like a C++  
> pointer.  C++ pointers are passed by value (unless you add & to  
...
> I'd be very interested in hearing whether, as a C/C++ user, the above  
> explanation is clear and makes sense to you.
>

joe, yes, it makes perfect sense. In my defense my priority was
figuring out what was going on in terms of what happens passing in
various types of arguments, rather than what things are called. Also,
as a C/C++ programmer my perspective is that the program is the
interpreter, and so I try to think what the interpreter is doing.
This is ke because after 15 years of statically linked languages (no
one calls them this any more due to dynamically linked libraries) you
get used to things evaporating at compile time, the name "x" for a
variable has no status as a real entity at run time. It is a name
through which you communicate with the compiler only, the compiler has
no need to represent it in the runtime program.  I think a lot of this
language history is based on terminology that does not have to
consider this name as a real entity at runtime.

When you consider the status of the entity "x" in "x=1" in python, it
is a pointer, and python looks like pass by value.

The need for a different name comes from the fact that using pointers
ubiquitously like this leads to behavior much more like pass by
reference.

I'm open to pass-by-sharing, or pass-by-object, but neither is
perticularly intuitive, not as obvious in meaning as pass-by-val or
pass-by-reference (or call-by-xxx). I suppose I'd like pass-by-name as
more a description, as "name" to me has a similar sense to pointer, at
least in a language that preserves the name as a runtime entitity
(making C/C++ languages which compile away names).

What happens in python is clear to me, I think I understand what the
program, CPython is doing... the language still needs to settle.

Thanks for the reply, it does help me find a better way to discuss
what I understand about python and calling mechanics in general.

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


Re: Parse each line by character location

2008-11-04 Thread Tim Chase

I hope this is the right place to ask, but I am trying to come up with
a way to parse each line of a file. Unfortunately, the file is neither
comma, nor tab, nor space delimited. Rather, the character locations
imply what field it is.

For example:

The first ten characters would be the record number, the next
character is the client type, the next ten characters are a volume,
and the next three are order type, and the last character would be an
optional type depending on the order type.


Sounds like you could do something like

  recno_idx = slice(0,10)
  client_idx = slice(10, 11)
  volume_idx = slice(11,11+10)
  order_type_idx = slice(11+10, 11+10+3)

  out = file('out.txt', 'w')
  for line in file('in.txt'):
out.write(','.join([
  s[recno_idx],
  s[client_idx],
  s[volume_idx],
  s[order_type_idx],
  s[11+10+3:],
  ]))
  out.close()

-tkc




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


Re: Which PostgreSQL adapter to use?

2008-11-04 Thread Thomas Guettler
Hussein B schrieb:
> Hey,
> Which Adapter to use with PostgreSQL:
> PyPgSQL, psycopg or PyGreSQL?
> Thanks.

I think psycopg2 is a good choice. Never tried anything else.

  Thomas

-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python on iPhone actually rather good

2008-11-04 Thread Michael Torrie
Python Nutter wrote:
> I'll be giving iPhone Python 2.5.1 a workout on on of Mark Lutz's
> books and report any more gotchas that I come across.

Are there any good books on python and objc?  I doubt you'll be able to
make any decent iPhone apps without having a good working knowledge of
Objective C and the python-objc bridge.  In my mind that's one of the
cool parts of doing cocoa development in python, but also the biggest
curse of cocoa.



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


Re: Python on iPhone actually rather good

2008-11-04 Thread Joe Strout

On Nov 4, 2008, at 10:33 AM, Michael Torrie wrote:

Are there any good books on python and objc?  I doubt you'll be able  
to

make any decent iPhone apps without having a good working knowledge of
Objective C and the python-objc bridge.  In my mind that's one of the
cool parts of doing cocoa development in python, but also the biggest
curse of cocoa.


I've found "Cocoa Programming for Mac OS X", in combination with the  
PyObjC tutorials on the web, to be a very accessible combination.   
I've gone about halfway through the book, just translating the  
tutorials from ObjC to PyObjC as I go, and it's worked out fine.


When I need help, I post to the pythonmac-sig list, which is a  
friendly and helpful bunch.  (I would think that iPhone development  
would be welcome there as well, since the iPhone is more or less a  
tiny Mac, at least from a development point of view).


Best,
- Joe

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


Re: Parse each line by character location

2008-11-04 Thread George Sakkis
On Nov 4, 11:45 am, Tyler <[EMAIL PROTECTED]> wrote:

> Hello All:
>
> I hope this is the right place to ask, but I am trying to come up with
> a way to parse each line of a file. Unfortunately, the file is neither
> comma, nor tab, nor space delimited. Rather, the character locations
> imply what field it is.
>
> For example:
>
> The first ten characters would be the record number, the next
> character is the client type, the next ten characters are a volume,
> and the next three are order type, and the last character would be an
> optional type depending on the order type.
>
> The lines are somewhat more complicated, but they work like that, and
> not all have to be populated, in that they may contain spaces. For
> example, the order number may be 2345, and it is space padded at the
> beginning of the line, and other might be zero padded in the front.
> Imagine I have a line:
>
> __2345H30_NC_
>
> where the underscores indicate a space. I then want to map this to:
>
> 2345,H,30,NC,
>
> In other words, I want to preserve ALL of the fields, but map to
> something that awk could easily cut up afterwords, or open in a CSV
> editor. I am unsure how to place the commas based on character
> location.
>
> Any ideas?

Here's a general solution for fixed size records:

>>> def slicer(*sizes):
... slices = len(sizes) * [None]
... start = 0
... for i,size in enumerate(sizes):
... stop = start+size
... slices[i] = slice(start,stop)
... start = stop
... return lambda string: [string[s].strip() for s in slices]
...
>>> order_slicer = slicer(10,1,10,4)
>>> order_slicer('__2345H30_NC_'.replace('_',' '))
['2345', 'H', '30', 'NC']

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


Re: script that parses command line, and execfile('')

2008-11-04 Thread Tim Chase

Sandip Bhattacharya wrote:

On Nov 4, 12:43 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

def main(argv=None):
 if argv is None: argv = sys.argv[1:]
 ...


Wouldn't that make optparse miss the first parameter sys.argv[1]
mistaking it to be the name of the current program?


Nope...optparse uses argv[1:] as documented at [1].  The "prog" 
argument can be specified in the constructor to OptionParser, but 
defaults to sys.argv[0] if it's not been explicitly specified.[2]


-tkc


[1]
http://www.python.org/doc/2.5.2/lib/optparse-parsing-arguments.html

[2]
http://www.python.org/doc/2.5.2/lib/optparse-creating-parser.html
(at the "prog" entry at the bottom)
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread Paul Boddie
On 4 Nov, 16:00, sturlamolden <[EMAIL PROTECTED]> wrote:
> If you are serious about multicore programming, take a look at:
>
> http://www.cilk.com/
>
> Now if we could make Python do something like that, people would
> perhaps start to think about writing Python programs for more than one
> processor.

The language features look a lot like what others have already been
offering for a while: keywords for parallelised constructs (clik_for)
which are employed by solutions for various languages (C# and various C
++ libraries spring immediately to mind); spawning and synchronisation
are typically supported in existing Python solutions, although
obviously not using language keywords. The more interesting aspects of
the referenced technology seem to be hyperobjects which, as far as I
can tell, are shared global objects, along with the way the work
actually gets distributed and scheduled - something which would
require slashing through the white paper aspects of the referenced
site and actually reading the academic papers associated with the
work.

I've considered doing something like hyperobjects for a while, and
this does fit in somewhat with recent discussions about shared memory
and managing contention for that resource using the communications
channels found in, amongst other solutions, the pprocess module. I
currently have no real motivation to implement this myself, however.

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


PEP 249 - DB API question

2008-11-04 Thread k3xji
Hi all,

As development goes on for a server project, it turns out that I am
using the MySQLDB and DB interactions excessively. One questions is
just bothering me, why don't we have a timeout for queries in PEP 249
(DB API)?

Is it really safe to wait for a query to finish, means, is it always
returning, even if the DB server goes down?

And, also from my point view, it may be a good feature. We may use
long/non-critical DB queries with a timeout and slow/critical without
a timeout. This will give us a little chance to prioritize/consume
queries on their criticality? And, I don't see so much effort in
implementing this. One has to change the socket logic in the related
DB's API source code?

What do you think?

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


Re: Finding the instance reference of an object

2008-11-04 Thread Marc 'BlackJack' Rintsch
On Tue, 04 Nov 2008 09:16:05 -0800, Craig Allen wrote:

> I'm open to pass-by-sharing, or pass-by-object, but neither is
> perticularly intuitive, not as obvious in meaning as pass-by-val or
> pass-by-reference (or call-by-xxx). I suppose I'd like pass-by-name as
> more a description, as "name" to me has a similar sense to pointer, at
> least in a language that preserves the name as a runtime entitity
> (making C/C++ languages which compile away names).

But call-by-name has a very different meaning from call-by-value, call-by-
reference, or call-by-object or call-by-sharing.  Call-by-name "injects" 
the expression used to call into the called function and evaluates it 
every time the argument is accessed within the function.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: wrapping a method function call?

2008-11-04 Thread Goldfish
Spring Python provides an AOP solution (http://
springpython.webfactional.com/reference/html/aop.html). You can define
regexp patterns of what you want to intercept.

Imagine having this service:
class SampleService:
def method(self, data):
return "You sent me '%s'" % data
def do_something(self):
return "Okay, I'm doing something"

You can write a simple interceptor that wraps the results:

from springpython.aop import *
class WrappingInterceptor(MethodInterceptor):
"""Interceptor that is called before the real method, and has
access afterwards to the results
def invoke(self, invocation):
print "BEFORE..."
results = "" + invocation.proceed() + ""
print "AFTER"
return results

Simply creating an instance of your base class acts as you would
expect:
service = SampleService()
print service.method("something")

>>> "You sent me 'something'"

Change one line, and your interceptor is plugged in:
service = ProxyFactoryComponent(target = SampleService(), interceptors
= [WrappingInterceptor()])
print service.method("something")

>>> "You sent me 'something'"

Visit the website at http://springpython.webfactional.com, and read
about AOP, along with the other features provided by this library.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse each line by character location

2008-11-04 Thread Tyler
Wow! Thanks for the suggestions everyone.

Cheers,

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


Re: PEP 249 - DB API question

2008-11-04 Thread James Mills
On Wed, Nov 5, 2008 at 3:52 AM, k3xji <[EMAIL PROTECTED]> wrote:
> As development goes on for a server project, it turns out that I am
> using the MySQLDB and DB interactions excessively. One questions is
> just bothering me, why don't we have a timeout for queries in PEP 249
> (DB API)?

Because not all database engines support this ?

> Is it really safe to wait for a query to finish, means, is it always
> returning, even if the DB server goes down?

Try using the non-blocking features (may be RDBMS specific)

> And, also from my point view, it may be a good feature. We may use
> long/non-critical DB queries with a timeout and slow/critical without
> a timeout. This will give us a little chance to prioritize/consume
> queries on their criticality? And, I don't see so much effort in
> implementing this. One has to change the socket logic in the related
> DB's API source code?

Patches are welcome. A suggestion:

Try spawning a new process to run your query
in. Use the multiprocessing library. Your main
application can then just poll the db/query processes
to see if they're a) finished and b) have a result

Your application server can also c0 kill long running
queries that are "deemed" to be taking "too long"
and may not finish (eg: Cartesian Joins).

--JamesMills

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: python_and_WSDL

2008-11-04 Thread Stefan Behnel
Dejan Pangercic wrote:
> question is, does anyone know about any up2date equivalent for
> connecting to WSDL from python?

It seems like you missed soaplib. Compared to other Python SOAP libraries,
it's pretty easy to use.

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


A challenge for help and change: New Energy?

2008-11-04 Thread MG2008
Would you mind?;

View (and Rate if you really like) 30 sec vids on proposal for change
and help:

Ride by G-Force Infinitely Free:
http://www.youtube.com/watch?v=SOTlogoPYZs&feature=related

Future Energy : The Gravity, free !:
http://www.youtube.com/watch?v=Tf7urAWuiu8&feature=related

Thank you indeed.

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


Re: PEP 249 - DB API question

2008-11-04 Thread M.-A. Lemburg
On 2008-11-04 18:52, k3xji wrote:
> Hi all,
> 
> As development goes on for a server project, it turns out that I am
> using the MySQLDB and DB interactions excessively. One questions is
> just bothering me, why don't we have a timeout for queries in PEP 249
> (DB API)?
> 
> Is it really safe to wait for a query to finish, means, is it always
> returning, even if the DB server goes down?
> 
> And, also from my point view, it may be a good feature. We may use
> long/non-critical DB queries with a timeout and slow/critical without
> a timeout. This will give us a little chance to prioritize/consume
> queries on their criticality? And, I don't see so much effort in
> implementing this. One has to change the socket logic in the related
> DB's API source code?
> 
> What do you think?

This would be a question for the Python DB-SIG mailing list.

Things like timeouts and handling of these is generally something
that is very database specific. It is difficult to provide a reliable
way of configuring this and may very well not even be within the
scope of a database API (e.g. because the timeout has to be
configured in the database server using some config file).

I'd suggest you check whether MySQL provides a way to set timeouts
and you then just use that for your project.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Nov 04 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Wholesale 100%sony ps3 ...ipod...wii....NOKIA Website: http://www.sonyecvv.com

2008-11-04 Thread 008
hi
We are the most professional with the biggest wholesale electronics
merchandise supply merchandise
..We have a lot of very nice quality merchandises with the
very special price
  They are all brand new with full accessories and 1 year
international warranty, unlocked, work effectively with any network
worldwide and come with user manual guide in various languages.
Ipod nano Ipod Nano II  1G 45$ ,2G 55$, 4G 65$,8G 70$, 30G 100$ ,60G
120$
 Ipod Itouch 4GB 60$ 8gb 80$  16gb 120$ 32gb   200$
ps3  60GB 280$  20GB 180$  80GB 300$
psp  100$
wii  250$
x360  250$
Apple Iphone  180$
Robot Dog  150$
We have all models of nokia
VERTU 250$
NOKIA N96 $280
NOKIA 8600 $260
NOKIA N800  $230
NOKIA N95 8G  $260
NOKIA N95 $220
NOKIA N93 $150
NOKIA N92 $130
NOKIA N91 $130
NOKIA N90 $120
Nokia N70 $160
NOKIA N73 $180
NOKIA 7600 (UNLOCK) $150
Nokia 8800 Sirocco Gold Edtion -$250
Nokia 8800 Sirocco Black$250
Garmin Nuvi GPS
Garmin Nuvi 770 250$Garmin Nuvi 760  220$  Garmin Nuvi 750  280$Garmin
Nuvi 680  210$ Garmin Nuvi 710 290$ Garmin Nuvi 670 190$ Garmin Nuvi
660 150$ Garmin Nuvi 610 180$ Garmin Nuvi 250W 160$ Garmin Nuvi 300
180$
(1).all products are all original and new
(2).they have 1year international warranty.
(3).free shipping include ems, tnt, dhl, ups. you may choose one kind
(4).deliver time is in 5days to get your door
We insist the principia: Prestige first,high-quality,competitive
price,
best services,and timely delivery.
Website:  http://www.sonyecvv.com
 msn: [EMAIL PROTECTED]
Fa-Fa  Co., Ltd.
--
http://mail.python.org/mailman/listinfo/python-list


python_and_WSDL

2008-11-04 Thread Dejan Pangercic
Hi all,

I am trying to establish a communication between a client and a server
where the client shall talk python and the server provides an
interface over the WSDL (Web Services Description Language). Test case
I am working on is available here:
http://utum6.unternehmertum.de:8080/CityMobServer/CityMobWebPageService?wsdl.

So far I have been able to find a http://pywebsvcs.sourceforge.net/
page that provides two client libraries:
a)Zolera SOAP Infrastructure (ZSI)
b)SOAPpy

that both by the way raise following exception when I try to create
the connection to my server:
http://paste.plone.org/24771

The thing that scares me however at most is that both of these project
have been apparently deprecated  for more than 2 years. So the
question is, does anyone know about any up2date equivalent for
connecting to WSDL from python?

thx for the feedback,

greets, Dejan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple textual calendar

2008-11-04 Thread Jorgen Grahn
On Mon, 3 Nov 2008 18:02:19 -0800 (PST), Mensanator <[EMAIL PROTECTED]> wrote:
...
>> <[EMAIL PROTECTED]> wrote:
...
>> >I'm trying to write out a calendar for a year, in this form (imaginary

...
> Personally, I find the tradtional format
> worthless. I want to see the year represented as a single block
> of 52 weeks so I can tell at a glance how many weeks seperate
 
Or 53 weeks.

> Mar 1 and Sep 13.

...
> ## program output
> ## Mo Tu We Th Fr Sa Su
> ##   1  2  3  4 January 2009
> ##  5  6  7  8  9 10 11
> ## 12 13 14 15 16 17 18
> ## 19 20 21 22 23 24 25
> ## 26 27 28 29 30 31  1February 2009
> ##  2  3  4  5  6  7  8
> ##  9 10 11 12 13 14 15
...

This is completely unrelated to Python, but damn, you are right!
Now that I see it, it's obviously better than the traditional format
you mention, the one that the Unix utility "cal -y" has used since
the 1980s or something.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Structures

2008-11-04 Thread Bruno Desthuilliers

Paulo J. Matos a écrit :
(snip)


However, I wouldn't dare to say Python needs structures to be a good
language, or anything similar. My question was more directed to : if
there aren't structures in Python, what do Pythonists use instead?
(I have seen dicts might be an alternative,


Yes, and the most obvious one - at least when all you need is a kind of 
data transfert object. Else, well, C++ structs are just a survival of a 
C feature kept for compatibility reasons - technically speaking, you 
just don't need structs when you have classes.



but as I said in previous
post, they seem to flexible [making them a canon to shoot a fly,


Err... I'm afraid you'll find Python way to flexible and dangerous, 
then. You may not be aware of the fact that you can add / remove / 
replace objects attributes (and methods) at runtime ? FWIW, and a couple 
corner cases set asides, Python objects are mostly glorified dicts.



and
they probably lack constant-time access, right?]


AFAIK, it's almost constant-time access. But you won't get anything 
better using classes, since attributes are stored in a dict anyway.


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


Re: Parse each line by character location

2008-11-04 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Tim Chase  <[EMAIL PROTECTED]> wrote:
>> I hope this is the right place to ask, but I am trying to come up with
>> a way to parse each line of a file. Unfortunately, the file is neither
>> comma, nor tab, nor space delimited. Rather, the character locations
>> imply what field it is.
>> 
>> For example:
>> 
>> The first ten characters would be the record number, the next
>> character is the client type, the next ten characters are a volume,
>> and the next three are order type, and the last character would be an
>> optional type depending on the order type.
>
>Sounds like you could do something like
>
>   recno_idx = slice(0,10)
>   client_idx = slice(10, 11)
>   volume_idx = slice(11,11+10)
>   order_type_idx = slice(11+10, 11+10+3)
.
.
.
!?  That seems to me confusingly far from a working solution,
at least in comparison to

recno_idex = the_line[0:10]
client_idx = the_line[10:11]
...

What am I missing?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to call this dll in python

2008-11-04 Thread Diez B. Roggisch

Shark schrieb:

On Nov 3, 4:22 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

Shark schrieb:


I have a windows dll1.dll with a export function:
int f1(char filename,char **buf,int *bufLen)
{
int len;
//got the length of file anyway,such as 100
len = 100;//len = getLen(filename);
*buf = (char*)calloc(100);
*bufLen = len;
return 0;
}
then how can I call the f1 function with python.
thanks for your response.

If the above is *really* what you want to access from python, you
shouldn't bother & write it new in python itself. You could either use

bufLen = len(open(filename).read())

or make a os.stat-call.

If it serves only as a rather ugly illustrative example, then you should
investigate the ctypes-module of python, which is made for accessing
arbitrary dlls from python.

Diez


Yes,the function is rather ugly, but how can python get the memory
alloced by a dll through the dll function's parameter.
I am facing the problem in my project, I try ctypes all over, but can
not get the correct solution.


But it *will* work with ctypes. However, without you disclosing your 
actual attempts, how do you think we can help you? Mind-reading is on my 
list to learn next, but until then you will need to provide code & 
tracebacks.


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


Re: problem with single-quote and double-quote when using subprocess.

2008-11-04 Thread Marc 'BlackJack' Rintsch
On Tue, 04 Nov 2008 03:26:21 -0800, MRAB wrote:

> On Nov 3, 10:47 pm, Evan <[EMAIL PROTECTED]> wrote:
>> i'm trying to call subprocess.popen on the 'command-based' function in
>> linux.  When I run the command from the shell, like so:
>>
>> goset -f ' "%s %s" name addr ' file_name
>>
>> it works fine
>
> It looks like there are _4_ items on the command line:
> 
> goset
> -f
> ' "%s %s" name addr '
> file_name
> 
> so the call should be:
> 
> p = subprocess.Popen(["goest", "-f", "' \"%s %s\" name addr '",
> "file_name"], shell=True)

The argument after '-f' doesn't have the single quotes at both ends.  
They tell the shell that it is just one argument and the shell removes 
them before calling ``goset`` (or ``goest``).

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse each line by character location

2008-11-04 Thread Benjamin Kaplan
On Tue, Nov 4, 2008 at 11:45 AM, Tyler <[EMAIL PROTECTED]> wrote:

> Hello All:
>
> I hope this is the right place to ask, but I am trying to come up with
> a way to parse each line of a file. Unfortunately, the file is neither
> comma, nor tab, nor space delimited. Rather, the character locations
> imply what field it is.
>
> For example:
>
> The first ten characters would be the record number, the next
> character is the client type, the next ten characters are a volume,
> and the next three are order type, and the last character would be an
> optional type depending on the order type.
>
> The lines are somewhat more complicated, but they work like that, and
> not all have to be populated, in that they may contain spaces. For
> example, the order number may be 2345, and it is space padded at the
> beginning of the line, and other might be zero padded in the front.
> Imagine I have a line:
>
> __2345H30_NC_
>
> where the underscores indicate a space. I then want to map this to:
>
> 2345,H,30,NC,
>
> In other words, I want to preserve ALL of the fields, but map to
> something that awk could easily cut up afterwords, or open in a CSV
> editor. I am unsure how to place the commas based on character
> location.
>
> Any ideas?


Everyone seems to be using replace(' ',''). However that will get rid of any
spaces in there, even if it is within the field. You should probably use
strip or lstrip on each field instead. lstrip will only remove leading
spaces, not trailing.


>>> line = '__2345H30_NC_'.replace('_',' ')
>>> print line
  2345H30 NC
>>> print line[0:10]
  2345
>>> print line[0:10].lstrip()
2345
>>> print line[10].lstrip()
H
>>> ",".join((line[:10].lstrip(), line[10].lstrip()))
'2345,H'






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


Re: Parse each line by character location

2008-11-04 Thread Arnaud Delobelle
[EMAIL PROTECTED] (Cameron Laird) writes:

> In article <[EMAIL PROTECTED]>,
> Tim Chase  <[EMAIL PROTECTED]> wrote:
>>> I hope this is the right place to ask, but I am trying to come up with
>>> a way to parse each line of a file. Unfortunately, the file is neither
>>> comma, nor tab, nor space delimited. Rather, the character locations
>>> imply what field it is.
>>> 
>>> For example:
>>> 
>>> The first ten characters would be the record number, the next
>>> character is the client type, the next ten characters are a volume,
>>> and the next three are order type, and the last character would be an
>>> optional type depending on the order type.
>>
>>Sounds like you could do something like
>>
>>   recno_idx = slice(0,10)
>>   client_idx = slice(10, 11)
>>   volume_idx = slice(11,11+10)
>>   order_type_idx = slice(11+10, 11+10+3)
>   .
>   .
>   .
> !?  That seems to me confusingly far from a working solution,
> at least in comparison to
>
> recno_idex = the_line[0:10]
> client_idx = the_line[10:11]
>   ...
>
> What am I missing?

I suppose in your case the slice objects will be re-created for each
line, whereas with Tim's solution they are created once and for all
before the parsing starts.  This may result in speedier parsing.

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


Re: python_and_WSDL

2008-11-04 Thread Dejan Pangercic
Dear all,

I appologize for the misleading email below - Banibrata is completely
right. However on the http://pywebsvcs.sourceforge.net/ page there is
also a link to the very old mailing list and that confused me.

greets, D.

On Tue, Nov 4, 2008 at 1:09 PM, Banibrata Dutta
<[EMAIL PROTECTED]> wrote:
> From a quick look at the pywebsvcs mailing-list archive here
> (http://sourceforge.net/mailarchive/forum.php?forum_name=pywebsvcs-talk)
> looks like pywebsvcs (http://pywebsvcs.sourceforge.net/)is not dead !
> On Tue, Nov 4, 2008 at 5:25 PM, Dejan Pangercic <[EMAIL PROTECTED]>
> wrote:
>>
>> Hi all,
>>
>> I am trying to establish a communication between a client and a server
>> where the client shall talk python and the server provides an
>> interface over the WSDL (Web Services Description Language). Test case
>> I am working on is available here:
>>
>> http://utum6.unternehmertum.de:8080/CityMobServer/CityMobWebPageService?wsdl.
>>
>> So far I have been able to find a http://pywebsvcs.sourceforge.net/
>> page that provides two client libraries:
>> a)Zolera SOAP Infrastructure (ZSI)
>> b)SOAPpy
>>
>> that both by the way raise following exception when I try to create
>> the connection to my server:
>> http://paste.plone.org/24771
>>
>> The thing that scares me however at most is that both of these project
>> have been apparently deprecated  for more than 2 years. So the
>> question is, does anyone know about any up2date equivalent for
>> connecting to WSDL from python?
>>
>> thx for the feedback,
>>
>> greets, Dejan
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> regards,
> Banibrata
> http://www.linkedin.com/in/bdutta
> http://octapod.wordpress.com
>



-- 
MSc. Dejan Pangercic
PhD Student/Researcher
Computer Science IX
Technische Universität München
Telephone: +49 (89) 289-17780
WWW: http://www9.cs.tum.edu/people/pangercic/
E-Mail: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


[2.5.1] Building loop with some exceptions?

2008-11-04 Thread Gilles Ganault
Hello

I need to call a URL through a loop that starts at 01 and ends at 99,
but some of the steps must be ignored:

=
url = "http://www.acme.com/list?code=";
p = re.compile("^(\d+)\t(.+)$")

for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
f = urllib.urlopen(url + i)
page = f.read()
f.close()

for line in page:
m = p.search(line)
if m:
code = m.group(1)
label = m.group(2)

print "Code=" + code + " # Label=" + label
=

I'm clueless at what the Python way is to do this :-/

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


Re: Building loop with some exceptions?

2008-11-04 Thread Aaron Brady
On Nov 4, 1:20 pm, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> Hello
>
> I need to call a URL through a loop that starts at 01 and ends at 99,
> but some of the steps must be ignored:
>
> =
> url = "http://www.acme.com/list?code=";
> p = re.compile("^(\d+)\t(.+)$")
>
> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:

sorted( list( set( domain ) - set( exceptions ) ) )

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


Re: Building loop with some exceptions?

2008-11-04 Thread Gilles Ganault
On Tue, 4 Nov 2008 11:22:27 -0800 (PST), Aaron Brady
<[EMAIL PROTECTED]> wrote:
>> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
>
>sorted( list( set( domain ) - set( exceptions ) ) )
>
>Set subtraction.

Thanks a lot but... I don't know what the above means :-/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unyeilding a permutation generator

2008-11-04 Thread Jorgen Grahn
On 3 Nov 2008 22:13:42 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 03 Nov 2008 21:09:58 +, Jorgen Grahn wrote:
>
>> Why multi-threading?  I see no concurrency in the original algorithm.
>> There is, in my mind, nothing concurrent about 'yield'.
>
> No "real" concurrency but a generator can be seen as independent thread 
> of code where the generator code is allowed to run when `next()` is 
> called and stops itself when it ``yield``\s an object.  Sort of 
> cooperative multitasking.

Sort of ... I find it more useful to see it as an object, or something
with a state.  And I think it's a bad idea to rewrite an algorithm
using threads in order to simulate generators.

> The name "yield" is often used in concurrent 
> code like Java's or Io's `yield()` methods.

That's a completely unrelated yield, isn't it?

Meanings (1) and (3) respectively in http://en.wiktionary.org/wiki/yield:
- To give way; to allow another to pass first.
- To produce as return, as from an investment.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Regexp parser and generator

2008-11-04 Thread George Sakkis
Is there any package that parses regular expressions and returns an
AST ? Something like:

>>> parse_rx(r'i (love|hate) h(is|er) (cat|dog)s?\s*!+')
Regex('i ', Or('love', 'hate'), ' h', Or('is', 'er'), ' ', Or('cat',
'dog'), Optional('s'), ZeroOrMore(r'\s'), OneOrMore('!'))

Given such a structure, I want to create a generator that can generate
all strings matched by this regexp. Obviously if the regexp contains a
'*' or '+' the generator is infinite, and although it can be
artificially constrained by, say, a maxdepth parameter, for now I'm
interested in finite regexps only. It shouldn't be too hard to write
one from scratch but just in case someone has already done it, so much
the better.

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


Re: Parse each line by character location

2008-11-04 Thread Tim Chase

  recno_idx = slice(0,10)
  client_idx = slice(10, 11)
  volume_idx = slice(11,11+10)
  order_type_idx = slice(11+10, 11+10+3)

.
!?  That seems to me confusingly far from a working solution,
at least in comparison to

recno_idex = the_line[0:10]
client_idx = the_line[10:11]
...

What am I missing?


The "11+10" and "11+10+3" are to help show where the magic 
numbers come from...that they're column-offsets from the previous 
position...I suppose to have been consistent, I should have used


  client_idx = the_line[10:10+1]

Somewhat like a kludgy version of George Sakkis's more elegant 
version of slicing, but with the advantage of associating names 
with the slice-boundaries.


It would be possible to write it as something like

  for line in file('in.txt'):
out.write(','.join([
  line[0:10],  # recno
  line[10:11], # client
  line[11:21], # volume
  line[21:24], # order
  line[24:],   # remainder
  ]))

but it's harder to verify that the slicing doesn't incur a 
fence-posting error, and makes it harder to follow if 
manipulations need further checking like


  if line[client_idx] == 'F': continue # skip this client

There are a number of ways to slice & dice the line.  I recommend 
whichever is easiest to read/understand.


-tkc




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


Creating custom Database or file type

2008-11-04 Thread Abah Joseph
i searched on google on the above subject (
http://delphi.about.com/od/fileio/a/fileof_delphi.htm). what does it take to
create a custom database or file type? something like mini-Sqlite or some
other way that the file will look secure and can be read on my application
runing platform.

I already knew and used a lot of file formats/Database (Pickle, MySql, XML)
but for learning purpose i want create a very simple one that i can, add,
update and delete.

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


Re: Building loop with some exceptions?

2008-11-04 Thread Benjamin Kaplan
On Tue, Nov 4, 2008 at 2:26 PM, Gilles Ganault <[EMAIL PROTECTED]> wrote:

> On Tue, 4 Nov 2008 11:22:27 -0800 (PST), Aaron Brady
> <[EMAIL PROTECTED]> wrote:
> >> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
> >
> >sorted( list( set( domain ) - set( exceptions ) ) )
> >
> >Set subtraction.
>
> Thanks a lot but... I don't know what the above means :-/
> --
>

domain = xrange(100) # this is all of the numbers
exceptions = [04,34,40,44,48,54,57,67,76,83,99] #this is the stuff you don't
want

new_set = set(domain) - set(exceptions) # removes all of the stuff in
exceptions from the domain
 new_list = sorted(list(new_set)) : turns the set into a list and then sorts
it. Calling sorted ensures that the list is in ascending order
for i in new_list : #new_list just contains the stuff you need.

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


Re: Regexp parser and generator

2008-11-04 Thread skip

George> Is there any package that parses regular expressions and returns
George> an AST ?

Maybe not directly, but this might provide a starting point for building
such a beast:

>>> import re
>>> re.compile("[ab]", 128)
in
  literal 97
  literal 98
<_sre.SRE_Pattern object at 0x47b7a0>
>>> re.compile("ab*c[xyz]", 128)
literal 97
max_repeat 0 65535
  literal 98
literal 99
in
  literal 120
  literal 121
  literal 122
<_sre.SRE_Pattern object at 0x371f90>

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


Re: Structures

2008-11-04 Thread Duncan Booth
Michele Simionato <[EMAIL PROTECTED]> wrote:

> I did not expect such a large difference in instantiation time.
> However I was thinking about
> access time, and then the difference is not impressive (~20-25%):
> 

The difference in time is because when you create a normal instance Python 
has to create at least two objects: the instance itself, and a dict for its 
attributes. If you use __slots__ for all of the attributes then you no 
longer have a separate __dict__ so you save that extra object creation.

As soon as you allow other attributes (which happens for example if you 
have a base class without __slots__) I think you'll find the object 
creation time goes back up to normal.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: split() and string.whitespace

2008-11-04 Thread bearophileHUGS
MRAB:
> It's interesting, if you think about it, that here we have someone who
> wants to split on a set of characters but 'split' splits on a string,
> and others sometimes want to strip off a string but 'strip' strips on
> a set of characters (passed as a string).

That can be seen as a little inconsistency in the language. But with
some practice you learn it.


> You could imagine that if
> Python had had (character) sets from the start then 'split' and
> 'strip' could have accepted a string or a set depending on whether you
> wanted to split on or stripping off a string or a set.

Too bad you haven't suggested this when they were designing Python
3 :-)
This may be suggested for Python 3.1.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building loop with some exceptions?

2008-11-04 Thread Matimus
On Nov 4, 11:20 am, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> Hello
>
> I need to call a URL through a loop that starts at 01 and ends at 99,
> but some of the steps must be ignored:
>
> =
> url = "http://www.acme.com/list?code=";
> p = re.compile("^(\d+)\t(.+)$")
>
> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
>         f = urllib.urlopen(url + i)
>         page = f.read()
>         f.close()
>
>         for line in page:
>                 m = p.search(line)
>                 if m:
>                         code = m.group(1)
>                         label = m.group(2)
>
>                         print "Code=" + code + " # Label=" + label
> =
>
> I'm clueless at what the Python way is to do this :-/
>
> Thank you for any help.

I would just do something like this (not tested):

url_tmpl = "http://www.acme.com/list?code=%02d";
p = re.compile("^(\d+)\t(.+)$")
EXCLUDED_VALUES = 4, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89

for i in xrange(1,100):
if i in EXCLUDED_VALUES:
continue
f = urllib.urlopen(url_tmpl % i)
try:
for line in f:
m = p.search(line)
if m:
code = m.group(1)
label = m.group(2)

print "Code=", code, "# Label=", label
finally:
f.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 249 - DB API question

2008-11-04 Thread k3xji

> Try spawning a new process to run your query
> in. Use the multiprocessing library. Your main
> application can then just poll the db/query processes
> to see if they're a) finished and b) have a result
>
> Your application server can also c0 kill long running
> queries that are "deemed" to be taking "too long"
> and may not finish (eg: Cartesian Joins).

Just thinking loudly:...

More backward-compatible way to do that is to have a thread
pool of threads running queries and the main pool thread is
polling to see if the child threads are taking too long to
complete? However, from performance point of view this will
be a nightmare? You have a good reason to suggest
multiprocessing, right? But at least I can implement my
critical queries with this kind of design, as they are not
so many.

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


Re: separate shared libraries or different Linux/Unix

2008-11-04 Thread Martin v. Löwis
> How do I get zlib available to python?

Edit Modules/Setup, and uncomment the zlib line. At your choice, also
uncomment the *shared* line (otherwise, zlib would become a builtin
module).

When you install shared libraries somewhere that also live in /usr/lib,
do use ldd to verify that it always picks up the libraries you want.

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


Re: Regexp parser and generator

2008-11-04 Thread Peter Otten
George Sakkis wrote:

> Is there any package that parses regular expressions and returns an
> AST ? Something like:
> 
 parse_rx(r'i (love|hate) h(is|er) (cat|dog)s?\s*!+')
> Regex('i ', Or('love', 'hate'), ' h', Or('is', 'er'), ' ', Or('cat',
> 'dog'), Optional('s'), ZeroOrMore(r'\s'), OneOrMore('!'))

Seen today, on planet python:

>>> import sre_parse
>>> sre_parse.parse("a|b")
[('in', [('literal', 97), ('literal', 98)])]


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


Re: Parse each line by character location

2008-11-04 Thread bearophileHUGS
George Sakkis:
> Here's a general solution for fixed size records:
> >>> def slicer(*sizes):
>
> ...     slices = len(sizes) * [None]
> ...     start = 0
> ...     for i,size in enumerate(sizes):
> ...         stop = start+size
> ...         slices[i] = slice(start,stop)
> ...         start = stop
> ...     return lambda string: [string[s].strip() for s in slices]
> ...>>> order_slicer = slicer(10,1,10,4)
> >>> order_slicer('__2345H30_NC_'.replace('_',' '))
> ['2345', 'H', '30', 'NC']


Nice. Here's a little modified version:

from collections import namedtuple

def slicer(names, sizes):
"""
>>> sl = slicer(["code", "p1", "progressive", "label"], (10, 1,
10, 4))
>>> txt = "__2345H30_NC_"
>>> print sl(txt.replace('_', ' '))
Sliced(code='2345', p1='H', progressive='30', label='NC')
"""
# several input controls can be added here
slices = []
start = 0
for size in sizes:
stop = start + size
slices.append(slice(start, stop))
start = stop
Sliced = namedtuple("Sliced", names)
return lambda txt: Sliced(*(txt[s].strip() for s in slices))

if __name__ == "__main__":
import doctest
doctest.testmod()
print "Doctests done.\n"

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ordering python sets

2008-11-04 Thread Lie Ryan
On Sun, 02 Nov 2008 02:08:37 +, Steven D'Aprano wrote:

> On Sat, 01 Nov 2008 18:58:59 +, Tim Rowe wrote:
> 
>> 2008/10/27  <[EMAIL PROTECTED]>:
>>> Lie Ryan:
>>>
Oh no, the two dict implementation would work _exactly_ the same from
the outside, they are transparently interchangeable. Only the
performance characteristic differs because of the different
implementation.<
>>>
>>> I don't agree with the general idea. If the operations done by your
>>> data structure have different computational complexity, then they are
>>> fit for different usages. When you program you must know what
>>> computational complexity has each of the operations of your data
>>> structyre, otherwise there's no way to know the complexity of your
>>> whole program, so instead of programming you are just become a mage
>>> that tries magical spells and hopes for the better.
>> 
>> No, when you program you know how you will be using the data structure,
>> so you can choose the implementation that's right for the application.
> 
> I don't understand why you have prefixed that sentence with "No". It
> seems like you are agreeing with bearophile's point.

On linguistic note: As a non-native speaker of English, I've never relied 
on the correct usage of Yes and No and would instead rely on the 
following text. In some languages, situations where English-people 
usually use Yes is answered with No and vice versa.

>> That's what the container libraries for other languages do. At the
>> moment, you just have one implementation, and have to hope it's right
>> for the job.
> 
> To the extent that this is true, it is a sign of the poverty of the
> standard Python library. But in fact it isn't true. Python has quite a
> decent collection of collection types. Just off the top of my head:
> 
> tuple, namedtuple, list, set, frozenset, dict, defaultdict, queue, deque
> 
> set, list and dict are highly optimized for general use, and are very
> suitable for building new data structures. And you are wrong to say that
> we have to "hope it's right for the job", we can build perfectly
> acceptable pure-Python data structures from these building blocks, or
> add our own C extensions. You're never forced to use a standard library
> data structure, it's a trade-off of your time and effort against runtime
> efficiency. And because the standard library types are generally so
> excellent, that trade-off is often (but not always) a no-brainer.

There are cases where the algorithm you uses ignited the standard 
library's data structure's worst case scenario.

>> Adding an *optional* parameter that says, in effect, "I want this list
>> optimised for writes and reads at both ends" or "I want this list
>> optimised for fully random reads but writes only at the end" doesn't
>> *lose* you any information about what you're programming with.
> 
> It might not lose information, but it does obfuscate it.
> 
> Right now, we can do this:


I've repelled this same argument multiple times. How often do you think 
you'd need to do check for an object's implementation? Compare that to 
how often we need to ensure that the object we're handling is a list-
replacement.

> That's assuming the implementation is available at runtime at all; if
> it's not, then you have lost information.

The implementation property is always available, because it's a non-
optional argument when registering the data structure.
 
>> Of course it's essential that the data structure has identican
>> /functional/ behaviour whatever optimisation you use.
> 
> "Essential"? That's an interesting point. Let's look at an actual
> example.
> 
> Consider one of Lie's initial examples (paraphrased):
> 
> D1 = dict({1: 'a', 2: 'b'})  # standard hash-table D2 = dict({1: 'a', 2:
> 'b'}, implementation="binary tree")
> 
> You say it's "essential" that the binary tree implementation has
> identical functional behaviour to standard hash-table implementation of
> dict. Okay, let's see where that leads us. The functional behaviour of
> hash-tables is that they are O(1) for reads, while binary trees are
> O(log(N)). The only way for them to have identical functional behaviour
> is to *artificially* slow down dicts to the lowest common speed. That is
> a Bad Thing, and I don't understand why you think it is essential.

I can't think why you consider a function's performance characteristic as 
its behavior, a "characteristic" of something means it is a it's property/
character. Not behavior.

> we no longer have to 
> artificially change the behaviour of the type -- be we do have to 
> artificially cripple the API of the type!

I don't get why you think we've got to restrict it to the lowest common 
denominator. We expect people that messes with a field called 
"implementation" to know enough about the limitations of the 
implementation he chose. Regular python programmers nowadays have to be 
aware that the limitation of the (hashed) dict is its key must be 
immutable. A true dict/mapping type doesn

Re: Building loop with some exceptions?

2008-11-04 Thread bearophileHUGS
Gilles Ganault:
> Thanks a lot but... I don't know what the above means :-/

set(iterable) just builds a set, then you use the really usual set
semantics.

Anyway, maybe you may find this more easy to understand:

refused_indexes = set([4, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89])
for i in xrange(1, 100):
if i not in refused_indexes:
print i

Note: never put a zero before an integer number (because it will give
you troubles, defining octal numbers).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


False and 0 in the same dictionary

2008-11-04 Thread Prateek
I've been using Python for a while (4 years) so I feel like a moron
writing this post because I think I should know the answer to this
question:

How do I make a dictionary which has distinct key-value pairs for 0,
False, 1 and True.
As I have learnt, 0 and False both hash to the same value (same for 1
and True).

>>> b = {0:'xyz', False:'abc'}
>>> b
{0: 'abc'}  # Am I the only one who thinks this is weird?

This obviously stems from the fact that 0 == False but 0 is not False
etc. etc.

That doesn't help my case where I need to distinguish between the two

The same issue applies in a list:

Suppose I do:

>>> a = [0, 1, True, False]
>>> a.index(False)
0

Wha??? Help.


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


Re: False and 0 in the same dictionary

2008-11-04 Thread Duncan Booth
Prateek <[EMAIL PROTECTED]> wrote:

> I've been using Python for a while (4 years) so I feel like a moron
> writing this post because I think I should know the answer to this
> question:
> 
> How do I make a dictionary which has distinct key-value pairs for 0,
> False, 1 and True.

How about using (x, type(x)) as the key instead of just x?



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


Re: Exact match with regular expression

2008-11-04 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Mr.SpOOn
wrote:

> On Sat, Nov 1, 2008 at 1:57 AM, Lawrence D'Oliveiro
> <[EMAIL PROTECTED]> wrote:
>
>> Funny how you never get a thank-you when you tell people to RTFM.
> 
> My fault :\
> I said "thank you" to Rob, but I just sent a private message. It's
> just that I did a reply and not reply to all.

That's OK. My fault for not realizing. :)
--
http://mail.python.org/mailman/listinfo/python-list


cxfreeze

2008-11-04 Thread luca72
Hello
i try to use cxfreeze under linux with a easy project made with qt i
run this :
cxfreeze --install-dir=dist  main.py
and i get the error
ImportError: No module named PyQt4._qt

so i try : cxfreeze --install-dir=dist --include-modules='PyQt4._qt'
main.py
but i get the same error
i try also including the sip module but i get the same error.

Can you help me

Thaks

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


Sieve of Zakiya

2008-11-04 Thread jzakiya
Update: 2008/11/03

Architecture & coding improvements. Renamed generators.

I am 90% finished writing up a mathematical analysis of my method.
In the process I found an architectural optimization to the sieve
process which is incorporated in the new code. Complexity analysis
showing other interesting stuff for each generator.

When I finish I will post paper here with the code:

www.4shared.com/account/dir/7467736/97bd7b71/sharing

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


Re: False and 0 in the same dictionary

2008-11-04 Thread Prateek
On Nov 5, 1:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Prateek <[EMAIL PROTECTED]> wrote:
> > I've been using Python for a while (4 years) so I feel like a moron
> > writing this post because I think I should know the answer to this
> > question:
>
> > How do I make a dictionary which has distinct key-value pairs for 0,
> > False, 1 and True.
>
> How about using (x, type(x)) as the key instead of just x?

Yup. I thought of that. Although it seems kinda unpythonic to do so.
Especially since the dictionary is basically a cache mostly containing
strings. Adding all the memory overhead for the extra tuples seems
like a waste just for those four keys.

Is there a better way?
I also thought of using a custom __eq__  method in a custom class
which extends the dict type but decided that was even worse.

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


Problem in PDF version of current docs - no title

2008-11-04 Thread Sandip Bhattacharya
(docs AT python.org doesn't like non-subscribers. Probably that is why
my mail didn't get through. Sending to this list instead.)

I just downloaded the PDF (tar.gz) version of the docs at  
http://docs.python.org/download.html.

All the howtos seem to be titled "HOWTO". I am certain this is an
error
and unintended.

- Sandip

PS. Do cc me in replies.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sending multi-part MIME package via HTTP-POST

2008-11-04 Thread [EMAIL PROTECTED]
Sadly, there is no way to increase the log verbosity.

On Oct 17, 2:42 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>,
>
>
>
> [EMAIL PROTECTED] wrote:
> > On Oct 15, 2:42 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> > central.gen.new_zealand> wrote:
>
> >> In message
> >> <[EMAIL PROTECTED]>,
>
> >> [EMAIL PROTECTED] wrote:
> >> > ... but I'm getting a very vague server error message ...
>
> >> Which is?
>
> > In this case it's not really something that will be readily recognized
> > here, nor is it extremely helpful diagnostic-wise. This is the only
> > debug output I can get from the logs or stdout:
>
> > "Failed to parse content as JDF."
>
> I may not recognize it, but I can Google:
> .
>
> Does the server log contain any more information? If not, is it possible to
> increase the log verbosity level in the server?

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


Re: Unyeilding a permutation generator

2008-11-04 Thread Gerard Flanagan
On Nov 3, 11:45 pm, [EMAIL PROTECTED] wrote:
>
> Thats interesting code but seems to give a different output,
> suggesting thet the underlying algorithm is different.
> Ignoring linebreaks and case, the original code gives:
> abcd bacd bcad bcda acbd cabd cbad cbda acdb cadb cdab cdba abdc badc
> bdac bdca adbc dabc dbac dbca adcb dacb dcab dcba
>
> The output from the above program, when converted to strings is:
> abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb
> cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba
>

Note:

items = [''.join(p) for p in  perm('abcd') ]
assert items == sorted(items)
items = list(all_perms('abcd'))
assert items != sorted(items)


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


Is there a better/simpler way to filter blank lines?

2008-11-04 Thread tmallen
I'm parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?

lines = filter(lambda line: len(line.strip()) > 0, lines)

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


Re: locating the chorus in a MIDI song?

2008-11-04 Thread Banibrata Dutta
Without pretending to be an expert on the subject of music-theory or
audio-processing, my n00b'ish doubt is -- MIDI, unlike MP3 would be devoid
of voice... and in my overtly simplistic thinking --  presence / absence of
which (i.e. voice) could be a "brute-force" way of detecting refrain/chorus
... unless a lot of "grammar" (i.e. semantic constraints) of music-theory
are enforced, and I am afraid such a grammer could only be made for a small
subset of a particular genre at best.
IMHO, some heuristics could be used to "train" a statistical model, to
identify refrain sections, s.a. a Bayesian model. You use some heuristic
parameters to detect refrain, and then use a large corpus of human responses
to validate the identification, there by tuning the model.

On Tue, Nov 4, 2008 at 3:11 PM, alex23 <[EMAIL PROTECTED]> wrote:

> On Nov 4, 2:20 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> > We've got a need to generate short "samples" of songs that are in MIDI
> > format, to provide a preview function in a web app.  We'd like to do
> > something more clever than just taking the middle 20 seconds (or
> > whatever) of the song -- ideally, we'd like to find the chorus, since
> > that's likely to be the most easily recognized part of the song.
> >
> > I believe this could be done fairly reliably by looking for patterns
> > in the MIDI file, though I'm sure there are plenty of complications to
> > this simple idea.
>
> My first thought is that would be incredibly difficult, but a quick
> google search pulled up a couple of papers:
>
> "Music Scene Description Project:
> Toward Audio-based Real-time Music Understanding"
> http://ismir2003.ismir.net/papers/Goto.PDF
>
>  The RefraiD (Refrain Detecting Method) detects sections
>  being repeated and identifies the chorus (refrain) sections
>  of songs in popular-music CDs. Most previous methods
>  detected as a chorus a repeated section of a given length
>  (Logan and Chu, 2000; Cooper and Foote, 2002) and had
>  difficulty identifying both ends of a chorus section and
>  dealing with modulations (key changes) (Peeters et al.,
>  2002; Dannenberg and Hu, 2002). By analyzing relation-
>  ships between various repeated sections, RefraiD can de-
>  tect all the chorus sections in a song and identify both
>  ends of each section. It can also detect modulated chorus
>  sections by introducing a similarity measure that enables
>  modulated repetition to be judged correctly.
>
> The paper doesn't go into much detail beyond that, but does refer to
> more that do.
>
> "A chorus-section detecting method for musical audio signals"
>
> http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?tp=&arnumber=120&isnumber=26996
>
> By the same authors, I believe. Although they're talking about audio,
> I would expect the technique used could be readily applied to midi as
> well (probably more easily, in fact).
>
> Note that: "Experimental results with a popular-music database show
> that this method detects the correct chorus sections in 80 of 100
> songs." So it's going to be wrong 1 in 5 times, if that's an
> influencing factor in trying to do this programmatically. How many
> MIDI files are you talking about here? Could it be easier to just
> manually mark the chorus for each?
>
> > 2. Anybody have an interest in music theory, as well as mad Python
> > skills?  Want a paying contract job?  If so, please contact me off-
> > list.  I'd enjoy pursuing this myself, but if you think you can do a
> > better job at a reasonable rate, I'm happy to let you do so.
>
> Give me a few days to see what my upcoming schedule is like and I may
> get back to you on this. I have a friend who has worked on
> computationally generating emotional expression with MIDI just
> recently, I'll pass this on to him as well.
>
> Is Python a strict requirement for this?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-11-04 Thread Hendrik van Rooyen
"Aaron Brady" <[EMAIL PROTECTED]> wrote:

>I think we can conclude that Python passes by reference, since a
>function can modify objects that were passed in to it.

Sort of - if the modification is by "side effect" - so you
can append to a list, for instance.

However, if you use the passed param name on the left
of an assignment statement, you get a new local object.
I think it is this that lies at the root of the confusion.

- Hendrik



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


Re: Iphone Going 3G!

2008-11-04 Thread Shafiq
apalah kau ni tak belajar ke bahasa menunjukkan bangsa
"news.tm.net.my" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> relic wrote:
>> fizzi wrote:
>>> For the Iphone lovers out there,
>>
>> Wrong group. No weirdos here.
> testtt 


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


Re: 2.6, 3.0, and truly independent intepreters

2008-11-04 Thread lkcl
On Oct 30, 6:39 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Their professor is Lars Bak, the lead architect of the Google 
> V8Javascriptengine. They spent some time working on V8 in the last couple
> months.

 then they will be at home with pyv8 - which is a combination of the
pyjamas python-to-javascript compiler and google's v8 engine.

 in pyv8, thanks to v8 (and the judicious application of boost) it's
possible to call out to external c-based modules.

 so not only do you get the benefits of the (much) faster execution
speed of v8, along with its garbage collection, but also you still get
access to external modules.

 so... their project's done, already!

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-04 Thread bearophileHUGS
tmallen:
> I'm parsing some text files, and I want to strip blank lines in the
> process. Is there a simpler way to do this than what I have here?
> lines = filter(lambda line: len(line.strip()) > 0, lines)

xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: locating the chorus in a MIDI song?

2008-11-04 Thread alex23
On Nov 4, 2:20 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> We've got a need to generate short "samples" of songs that are in MIDI  
> format, to provide a preview function in a web app.  We'd like to do  
> something more clever than just taking the middle 20 seconds (or  
> whatever) of the song -- ideally, we'd like to find the chorus, since  
> that's likely to be the most easily recognized part of the song.
>
> I believe this could be done fairly reliably by looking for patterns  
> in the MIDI file, though I'm sure there are plenty of complications to  
> this simple idea.

My first thought is that would be incredibly difficult, but a quick
google search pulled up a couple of papers:

"Music Scene Description Project:
Toward Audio-based Real-time Music Understanding"
http://ismir2003.ismir.net/papers/Goto.PDF

  The RefraiD (Refrain Detecting Method) detects sections
  being repeated and identifies the chorus (refrain) sections
  of songs in popular-music CDs. Most previous methods
  detected as a chorus a repeated section of a given length
  (Logan and Chu, 2000; Cooper and Foote, 2002) and had
  difficulty identifying both ends of a chorus section and
  dealing with modulations (key changes) (Peeters et al.,
  2002; Dannenberg and Hu, 2002). By analyzing relation-
  ships between various repeated sections, RefraiD can de-
  tect all the chorus sections in a song and identify both
  ends of each section. It can also detect modulated chorus
  sections by introducing a similarity measure that enables
  modulated repetition to be judged correctly.

The paper doesn't go into much detail beyond that, but does refer to
more that do.

"A chorus-section detecting method for musical audio signals"
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?tp=&arnumber=120&isnumber=26996

By the same authors, I believe. Although they're talking about audio,
I would expect the technique used could be readily applied to midi as
well (probably more easily, in fact).

Note that: "Experimental results with a popular-music database show
that this method detects the correct chorus sections in 80 of 100
songs." So it's going to be wrong 1 in 5 times, if that's an
influencing factor in trying to do this programmatically. How many
MIDI files are you talking about here? Could it be easier to just
manually mark the chorus for each?

> 2. Anybody have an interest in music theory, as well as mad Python  
> skills?  Want a paying contract job?  If so, please contact me off-
> list.  I'd enjoy pursuing this myself, but if you think you can do a  
> better job at a reasonable rate, I'm happy to let you do so.

Give me a few days to see what my upcoming schedule is like and I may
get back to you on this. I have a friend who has worked on
computationally generating emotional expression with MIDI just
recently, I'll pass this on to him as well.

Is Python a strict requirement for this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with single-quote and double-quote when using subprocess.

2008-11-04 Thread MRAB
On Nov 3, 10:47 pm, Evan <[EMAIL PROTECTED]> wrote:
> Hello -
>
> i'm trying to call subprocess.popen on the 'command-based' function in
> linux.  When I run the command from the shell, like so:
>
> goset -f ' "%s %s" name addr ' file_name
>
> it works fine
>
> however when I try to do it in python like so:
>
> p = subprocess.Popen(["goest",'-f \'\"%s %s\" name addr\' ',
> 'file_name'], shell=True)
>
> It always failed.
>
> I also try like so:
>
> p = subprocess.Popen(["goest","-f '\"%s %s\" name addr' ",
> 'file_name'], shell=True)
>
> It also failed.
>
> Does anybody have a good suggestion for this matter? thanks in
> advance.
>
It looks like there are _4_ items on the command line:

goset
-f
' "%s %s" name addr '
file_name

so the call should be:

p = subprocess.Popen(["goest", "-f", "' \"%s %s\" name addr '",
"file_name"], shell=True)

(Untested)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-11-04 Thread Steven D'Aprano
On Mon, 03 Nov 2008 19:33:52 -0700, Joe Strout wrote:

> On Nov 3, 2008, at 5:27 PM, Marc 'BlackJack' Rintsch wrote:
> 
>> Maybe this is a surprise for you, because we haven't discussed this in
>> much detail in this group lately, but it applies to Python which does
>> call-by-object or call-by-sharing.  ;-)
> 
> There's no such thing.  Those are just terms made up by the Python
> community to in place of the more standard "call-by-value" terminology
> to make Python seem more mysterious than it really is.

I call bullshit on you. We've already shown you that the term call-by-
sharing (a.k.a. call-by-object or call-by-object-sharing) goes back to 
the 1970s and such computer scientists as Barbara Liskov. The language 
CLU used the term back in 1974, and it is possible that CLU wasn't the 
first language to use it. That's over fifteen years before the first 
release of Python.

This is not the first time it's been pointed out to you. And it won't be 
the last. And I predict that it will make no difference to you at all: 
you will still continue to pretend that Liskov et al aren't even worth 
acknowledging, and you will continue to make the asinine definition that 
the "value" of x following "x = 1" is 0x97b3250 rather than 1.



> I guess you can
> call it "purple bananas" if you want, but the behavior is exactly the
> same as what every other language calls call-by-value.

Again, I call bullshit. Python's behaviour is not the same as what 
Pascal, or C, calls call-by-value. It is what many Java people call "call-
by-value", because they make the same idiotic definition that the value 
of a variable is some arbitrary and hidden reference to the thing of 
interest:

"Java is call-by-value, where value means a reference to the actual 
value, except for primitives, where the value is the actual value."

It is an idiotic definition, the sort of thing that only a very smart 
person can make, twisting the plain and intuitive meaning of value ("what 
is denoted by a symbol") just to avoid having to accept that there are 
more things in reality than their pet theory includes.

It's not we Python folk who are guilty of misusing terminology, it is you 
and your fellow VB and Java folk who are misusing the term call-by-value 
to describe something which is nothing like call-by-value in Pascal and 
C. There is a simple test you can do: pass a value to a function, and 
have the function mutate that value. If the mutation appears in the 
caller's environment, then the value wasn't copied and it is not call-by-
value. In Python:

def mutate(alist):
alist.append(1)

L = [1, 2]
mutate(L)  # supposedly call by value
assert L == [1, 2]

If the assert statement fails (and it does), then no copy was made and 
Python is not call-by-value.

So Python is not call-by-value, and it's not call-by-reference, so ... 
either Python doesn't exist, or it uses a different calling convention.


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


Re: Is there a better/simpler way to filter blank lines?

2008-11-04 Thread Larry Bates

[EMAIL PROTECTED] wrote:

tmallen:

I'm parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?
lines = filter(lambda line: len(line.strip()) > 0, lines)


xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile


Of if you want to filter/loop at the same time, or if you don't want all the 
lines in memory at the same time:


fp = open(filename, 'r')
for line in fp:
if not line.strip():
continue

#
# Do something with the non-blank like:
#


fp.close()

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


Re: False and 0 in the same dictionary

2008-11-04 Thread bdbull
On Nov 4, 4:21 pm, Prateek <[EMAIL PROTECTED]> wrote:
> On Nov 5, 1:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
>
> > Prateek <[EMAIL PROTECTED]> wrote:
> > > I've been using Python for a while (4 years) so I feel like a moron
> > > writing this post because I think I should know the answer to this
> > > question:
>
> > > How do I make a dictionary which has distinct key-value pairs for 0,
> > > False, 1 and True.
>
> > How about using (x, type(x)) as the key instead of just x?
>
> Yup. I thought of that. Although it seems kinda unpythonic to do so.
> Especially since the dictionary is basically a cache mostly containing
> strings. Adding all the memory overhead for the extra tuples seems
> like a waste just for those four keys.
>
> Is there a better way?
> I also thought of using a custom __eq__  method in a custom class
> which extends the dict type but decided that was even worse.
>
> Prateek

Hmm, my original reply didn't show up.

I'm curious as to what you're trying to accomplish.

Bear in mind that I type this response not knowing your application.
While Python is not a statically typed language, 0 and False are
essentially different types (int and bool).  Storing them both as keys
of a dictionary just doesn't seem like a good design.
--
http://mail.python.org/mailman/listinfo/python-list


Re: False and 0 in the same dictionary

2008-11-04 Thread Arnaud Delobelle
Prateek <[EMAIL PROTECTED]> writes:

> On Nov 5, 1:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
>> Prateek <[EMAIL PROTECTED]> wrote:
>> > I've been using Python for a while (4 years) so I feel like a moron
>> > writing this post because I think I should know the answer to this
>> > question:
>>
>> > How do I make a dictionary which has distinct key-value pairs for 0,
>> > False, 1 and True.
>>
>> How about using (x, type(x)) as the key instead of just x?
>
> Yup. I thought of that. Although it seems kinda unpythonic to do so.
> Especially since the dictionary is basically a cache mostly containing
> strings. Adding all the memory overhead for the extra tuples seems
> like a waste just for those four keys.
>
> Is there a better way?
> I also thought of using a custom __eq__  method in a custom class
> which extends the dict type but decided that was even worse.
>
> Prateek

You could use currying on Duncan's solution :).  It would
give something like this (minimal implementation):

from collections import defaultdict

class DictByType(object):
  def __init__(self):
self.dicts = defaultdict(dict)
  def __setitem__(self, key, val):
self.dicts[type(key)][key] = val
  def __getitem__(self, key):
return self.dicts[type(key)][key]


Then:

>>> d = DictByType()
>>> d[1]='foo'
>>> d[True]='bar'
>>> d[1.0] = 'foobar'
>>> d[1], d[True], d[1.0]
('foo', 'bar', 'foobar')

If, as seems to be the case, you have many keys with few types, then the
memory overhead will be smaller.  Access time might suffer though.

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


Python on iPhone actually rather good

2008-11-04 Thread Python Nutter
Mini install guide for python on the iPhone:

Cydia => Install SSH helps make initial configuration easier until you
get used to MobileTerminal
Cydia => Install MobileTerminal (closest to a bash shell you get on
your iPhone currently)
Cydia => Install Finder (graphical alternative to using
SSH/MobileTerminal for setting permissions, navigating file system,
moving/copying files, etc.)
Cydia => Install Python (currently installs CPython 2.5.1)
Cydia => Install PyObjC (this is your hook into iPhone API)
Cydia => Install Setuptools (currently install 0.6c7)
Cydia => Install iPhone/Python (examples, the hello world is a PyObjC
call into the iPhone API to load and scroll the contacts list in the
phone)

Not much left to have a fast running python implementation in your
pocket except IMHO ipython. Now that you have Setuptools installed,
you can run easy_install directly on your iPhone and download iPython
over the air.

The iPhone OS X architecture is of course a BSD Unix Userland
environment so you should feel right at home.

The two accounts, root and mobile both share the same default password
'alpine'. So once you setup your phone I recommend you change the
password for each account right away just to secure your phone a
little more. Root you won't need, Mobile is what the default account
is on the current iPhone OS implementation for the standard user
(you).

Easiest way to access your phone is SSH from your Mac, Linux, or
Windows box. (or just use MobileTerminal.app on the iphone directly
keeping in mind you will default to the mobile account in the shell)
Simply join your iPhone over wifi to your wireless access point or
ad-hoc-network, and display your iPhone's ip address. Now you are
ready to ssh into it.
$ssh root@
password: alpine
$chpass

while you are here might as well install ipython
$easy_install ipython
$exit

now same for mobile
$ssh root@
password: alpine
$chpass


$ipython


$cd .ipython
$nano ipy_user_conf.py


CTRL+W (find)
Where: #import ipy_editors

Delete the # comment character

Scroll down 

Add your new line below the text "# Or roll your own"
ipy_editors.install_editors("nano +$line $file")

CTRL+X (exit)
Y to save

Now test your ipython link to nano editor
$ipython
In [1]: edit test.py

In [2]: exit()
$cat test.py

$rm test.py 

Its up to you where you want to save your python scripts. I would
suggest in Documents under your account (mobile).

$cd ~
$cd D* 
$mkdir python 


What is missing? Tkinter, iPhone uses its own API, Desktop Manager
(Springboard), etc.
What is different? PyObjC, this is where you get to use those iPhone
API calls from within your python script on the iPhone including GUI
API calls.

Now you have Python in your Pocket that you can take anywhere and whip
it out anytime the Python bug hits you and you want to work on some
code.

You can use SSH to move/copy/sync your files to your desktop.
Or other ways: AirSharing app over wifi, etc.

I'll be giving iPhone Python 2.5.1 a workout on on of Mark Lutz's
books and report any more gotchas that I come across.

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


developing python extensions with CDT and Pydev in Eclipse

2008-11-04 Thread Joachim Dahl
Has anyone been able to use both Pydev and CDT to debug extension
modules?

The question was asked about a year ago on this list,  and I am hoping
that
someone has figured it out in meantime.

Joachim

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


Re: Building loop with some exceptions?

2008-11-04 Thread Aaron Brady
On Nov 4, 1:26 pm, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> On Tue, 4 Nov 2008 11:22:27 -0800 (PST), Aaron Brady
>
> <[EMAIL PROTECTED]> wrote:
> >> for i=01 to 99 except 04, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89:
>
> >sorted( list( set( domain ) - set( exceptions ) ) )
>
> >Set subtraction.
>
> Thanks a lot but... I don't know what the above means :-/

This example produces the numbers 0..9, except 3, 5, and 9.

>>> sorted( list( set( range( 10 ) ) - set( [ 3, 5, 9 ] ) ) )
[0, 1, 2, 4, 6, 7, 8]

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


Which PostgreSQL adapter to use?

2008-11-04 Thread Hussein B
Hey,
Which Adapter to use with PostgreSQL:
PyPgSQL, psycopg or PyGreSQL?
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building loop with some exceptions?

2008-11-04 Thread Gilles Ganault
On Tue, 4 Nov 2008 12:10:28 -0800 (PST), Matimus <[EMAIL PROTECTED]>
wrote:
>I would just do something like this (not tested):

Thanks a lot guys :-) Worked first time.

I just have the usual issue with ASCII/Unicode:

===
cursor.execute(sql)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position
53: ordinal
 not in range(128)
===

Is there a way to get rid of this error once and for all?

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


Which PostgreSQL adapter to use?

2008-11-04 Thread Hussein B
Hi,
Which PostgreSQL adapter to use:
PyGreSQL, PyPgSQL or psycopg?
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Error loading modules

2008-11-04 Thread BL
I am very new to python.  I am installing it as part of a bazzar
version control installation.
I have installed the Crypto, paramiko and cElementTree modules.  I am
running Solaris10x86.
When testing the modules I get the following results.

 python -c "import Crypto"
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named Crypto

Here is the path setups and the modules have been verified to be in
those directories.
Python 2.5.1 (r251:54863, May 16 2007, 19:39:00)
[GCC 3.4.6] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/
local/lib/python2.5/plat-sunos5', '/usr/local/lib/python2.5/lib-tk', '/
usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-
packages']

Any assistance would be appreciated
--
http://mail.python.org/mailman/listinfo/python-list


Re: Structures

2008-11-04 Thread Michele Simionato
On Nov 4, 11:20 am, [EMAIL PROTECTED] wrote:
> Michele Simionato:
>
> > No, slots have nothing to do with speed, they are a memory optimization.
>
> In many languages, often in Python too, the less memory you use/
> allocate the faster you go.
>
> In fact slots allow a speed increase too (in new style classes):
>
> from timeit import default_timer as clock
>
> class C1(object):
>     __slots__ = ["a", "b"]
>     def __init__(self, a, b):
>         self.a = a
>         self.a = b
>
> class C2(object):
>     def __init__(self, a, b):
>         self.a = a
>         self.a = b
>
> def main(N, test):
>     t0 = clock()
>
>     if test == 1:
>         [C1(ab, ab) for ab in xrange(N)]
>     elif test == 2:
>         [C2(ab, ab) for ab in xrange(N)]
>
>     t1 = clock()
>     print round(t1 - t0, 2)
>
> main(N=700*1000, test=1)
>
> Core duo 2 GHz:
> test=1 ==> 1.06 s
> test=2 ==> 3.0 s
>
> (700*1000 is the way I have found to write the 700_000 I was talking
> about, until we'll have a syntax for it.)
>
> Bye,
> bearophile

I did not expect such a large difference in instantiation time.
However I was thinking about
access time, and then the difference is not impressive (~20-25%):

from timeit import default_timer as clock

class C1(object):
__slots__ = ["a", "b"]
def __init__(self, a, b):
self.a = a
self.b = b

class C2(object):
def __init__(self, a, b):
self.a = a
self.b = b

def main(N, test):
t0 = clock()
if test == 'with slots':
c = C1(1, 2)
for _ in xrange(N):
(c.a, c.b)
elif test == 'without slots':
c = C2(1, 2)
for _ in xrange(N):
(c.a, c.b)
t1 = clock()
print test, round(t1 - t0, 3)

main(N=700*1000, test='with slots') # 0.152s
main(N=700*1000, test='without slots') #  0.195s

I mantain that one should use slots only as last resort, if the
speedup really justify having nonstandard classes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python_and_WSDL

2008-11-04 Thread Banibrata Dutta
>From a quick look at the pywebsvcs mailing-list archive here (
http://sourceforge.net/mailarchive/forum.php?forum_name=pywebsvcs-talk)looks
like pywebsvcs (http://pywebsvcs.sourceforge.net/)is not dead !

On Tue, Nov 4, 2008 at 5:25 PM, Dejan Pangercic
<[EMAIL PROTECTED]>wrote:

> Hi all,
>
> I am trying to establish a communication between a client and a server
> where the client shall talk python and the server provides an
> interface over the WSDL (Web Services Description Language). Test case
> I am working on is available here:
>
> http://utum6.unternehmertum.de:8080/CityMobServer/CityMobWebPageService?wsdl
> .
>
> So far I have been able to find a http://pywebsvcs.sourceforge.net/
> page that provides two client libraries:
> a)Zolera SOAP Infrastructure (ZSI)
> b)SOAPpy
>
> that both by the way raise following exception when I try to create
> the connection to my server:
> http://paste.plone.org/24771
>
> The thing that scares me however at most is that both of these project
> have been apparently deprecated  for more than 2 years. So the
> question is, does anyone know about any up2date equivalent for
> connecting to WSDL from python?
>
> thx for the feedback,
>
> greets, Dejan
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list


Distributed unit testing on condor?

2008-11-04 Thread gardnerpomper
Hi,

I have a system where I would like to run unittests over our condor
distributed cluster. My thoughts have been to write tests which take a
list of files, and distribute each file and that test out as a condor
job. I have briefly looked at nose and its plugins to see if I could
set something up like that, but it isn't clear.

My goal is to make this as transparent for the developer as possible.
I would like the programmer to just have to write a simple unittest
function, which is unaware of condor, that he can run on his own
system, but then also be able to run the tests across a larger data
set on the condor cluster.

Is anyone aware of a system set up to do this? If not, I am anxious to
entertain ideas on the cleanest way of implementing it.

Thanks,
- Gardner

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


  1   2   >