sum and strings

2006-08-17 Thread Paddy
I was browsing the Voidspace blog item on "Flattening Lists", and
followed up on the use of sum to do the flattening.
A solution was:

>>> nestedList = [[1, 2], [3, 4], [5, 6]]
>>> sum(nestedList,[])
[1, 2, 3, 4, 5, 6]

I would not have thought of using sum in this way. When I did help(sum)
the docstring was very number-centric: It went further, and precluded
its use on strings:

>>> help(sum)
Help on built-in function sum in module __builtin__:

sum(...)
sum(sequence, start=0) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start'.  When the sequence is empty, returns start.

The string preclusion would not help with duck-typing (in general), so
I decided to consult the ref doc on sum:

sum( sequence[, start])

Sums start and the items of a sequence, from left to right, and returns
the total. start defaults to 0. The sequence's items are normally
numbers, and are not allowed to be strings. The fast, correct way to
concatenate sequence of strings is by calling ''.join(sequence). Note
that sum(range(n), m) is equivalent to reduce(operator.add, range(n),
m) New in version 2.3.


The above was a lot better description of sum for me, and with an
inquisitive mind, I like to think that I might have come up with using
sum to flatten nestedList :-)
But there was still that warning about using strings.

I therefore  tried sum versus their reduce "equivalent" for strings:

>>> import operator
>>> reduce(operator.add, "ABCD".split(), '')
'ABCD'
>>> sum("ABCD".split(), '')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>>

Well, after all the above, there is a question:

  Why not make sum work for strings too?

It would remove what seems like an arbitrary restriction and aid
duck-typing. If the answer is that the sum optimisations don't work for
the string datatype, then wouldn't it be better to put a trap in the
sum code diverting strings to the reduce equivalent?

Just a thought,

- Paddy.

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


Re: os.path.normpath

2006-08-17 Thread placid

placid wrote:
> Hi all,
>
> I was just wondering if there is a anti-os.path.normpath function? For
> example if i have the path "C:\Program Files\Games" i want to
> anti-os.path.normpath is so that it becomes "C:\\Program Files\\Games"
> ?
>
> Cheers

Ahh ignore my post. I was using abspath, and normpath is what i what.

Doh, stupid me!

Cheers

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


os.path.normpath

2006-08-17 Thread placid
Hi all,

I was just wondering if there is a anti-os.path.normpath function? For
example if i have the path "C:\Program Files\Games" i want to
anti-os.path.normpath is so that it becomes "C:\\Program Files\\Games"
?

Cheers

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


Http client to POST using multipart/form-data

2006-08-17 Thread Bruno Dilly
Hi,

I'm implementing a http client to POST using multipart/form-data. It
uses urllib2 module, and files are uploaded correctly.

But I need to know how much has been uploaded at a given moment, to
inform the user the proportion of the file already uploaded.

Anybody knows how could I do that?

Thanks,

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Greg R. Broderick
"Iain King" <[EMAIL PROTECTED]> wrote in news:1155827943.041208.51220
@i3g2000cwc.googlegroups.com:

> I'm confused - I thought Xah Lee loved Perl?  Now he's bashing it?
> Huh?

That's his other personality.

-- 
-
Greg R. Broderick[EMAIL PROTECTED]

A. Top posters.
Q. What is the most annoying thing on Usenet?
-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import module with non-standard file name

2006-08-17 Thread Ben Finney
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

> Ben Finney schrieb:
> > Question: I have Python modules named without '.py' as the extension,
> > and I'd like to be able to import them. How can I do that?
> 
> I recommend to use imp.load_module.

I've tried this; as Patrick Maupin alludes to, it compiles the module
leaving a strangely-named file behind.

Program in a file named 'frob_foo'; no other file names needed nor
desired.

import imp

file_name = "frob_foo"
module_name = 'frob_foo'

module_file = open(file_name, 'r')
module_desc = ("", 'r', imp.PY_SOURCE)
module = imp.load_module(module_name, module_file, file_name, module_desc)

Result: two files, 'frob_foo' and 'frob_fooc'. I can see why this
happens, but it's not what's desired. Currently I'm going with:

file_name = "frob_foo"
module_name = 'frob_foo'

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__

Still, the purpose is simply to get a module object out, with a named
file as input. If the 'imp' module can do that without leaving
unwanted turds behind, it seems more elegant. Can anyone suggest a way
to get the same result as the above 'exec' method, using the 'imp'
module?

-- 
 \  "...one of the main causes of the fall of the Roman Empire was |
  `\that, lacking zero, they had no way to indicate successful |
_o__)   termination of their C programs."  -- Robert Firth |
Ben Finney

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

Which field is Python suitable to do some tasks?

2006-08-17 Thread many_years_after
hello , members:
  I have basic knowledge of python programming. But i don't know
what to do next step.
I don't know in which field I should learn more about python and
finally finish some tasks.
Can you give me some ideas?

Thanks.

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


python and poplib

2006-08-17 Thread 叮叮当当
Hi, all.

i have two question with poplib:

1. How to judge if a mail is or not a new mail ?

2. How Can i get the send-mailbox's mail?


thanks .

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Mark E. Fenner
danielx wrote:

> 
> Mark E. Fenner wrote:
>> Mark E. Fenner wrote:
>>
>> > John Machin wrote:
>> >
>> >>
>> >> Mark E. Fenner wrote:
>> >>
>> >>> Here's my class of the objects being copied:
>> >>
>> >> Here's a couple of things that might help speed up your __init__
>> >> method, and hence your copy method:
>> >>
>> >>>
>> >>> class Rule(list):
>> >>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):
>> >>
>> >> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0):
>> >>
>> >>> self.nClasses = nClasses
>> >>> self.nCases = nCases
>> >>>
>> >>> if lhs is not None:
>> >>> self.extend(lhs)
>> >> what does the extend method do? If it is small, perhaps inline a copy
>> >> of its code here.
>> >>>
>> >>> if rhs is None:
>> >>> self.rhs=tuple()
>> >>> else:
>> >>> self.rhs=rhs
>> >>
>> >> Replace the above 4 lines by:
>> >> self.rhs = rhs
>> >>
>> >> HTH,
>> >> John
>> >
>> > John,
>> >
>> > Thanks.  I thought of those at the same you did!  I also incorporated
>> > one other use of the default=() + no conditional:
>> >
>> > class Rule(list):
>> > def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0):
>> > self.nClasses = nClasses
>> > self.nCases = nCases
>> > self.extend(lhs) # note, self is a list so this is list.extend
>> > self.rhs=rhs
>> >
>> > def copy(self):
>> > return Rule(self,
>> > self.rhs,
>> > self.nClasses,
>> > self.nCases)
>>
>>
>> Actually, I also removed the "passthrough" that copy was doing and just
>> called the constructor directly.  So, at the top level code, we have:
>>
>> allNew = []
>> for params in cases:
>> # newobj = initialObject.copy()
>> newObj = Rule(initialObject, initialObject.rhs,
>>   initialObject.nClasses,
>>   initialObject.nCases)
>> newObj.modify(params)
>> allNew.append(newObj)
>> return allNew
>>
>> Regards,
>> Mark
> 
> I'm not sure how much this will help, but another thing you can do is
> put this line before the "for":
> 
> append = allNew.append
> 
> Then, replace the last line in the loop with
> 
> append(newObj)
> 
> Check out this doc for more info on optimizing Python, and the section
> which talks about eliminating dots:
> 
> http://wiki.python.org/moin/PythonSpeed/PerformanceTips
>
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-aa6c07c46a630a2fa10bd6502510e532806f1f62

I've read these, but they do yield additional nuggets upon rereading (does
that make them generators?).  In reality, my loop has several lines of code
instead of a newObj.modify(args) method.  I localised the obvious functions
and attributes that I was using.  In reality, the Rule.copy/Rule.__init__
is swamping everything else ... humm, unless ... I'll get back to you.

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


Re: How to fill a form

2006-08-17 Thread Justin Ezequiel
Sulsa wrote:
> On Tue, 15 Aug 2006 03:37:02 -
> Grant Edwards <[EMAIL PROTECTED]> wrote:
>
> > On 2006-08-15, Sulsa <[EMAIL PROTECTED]> wrote:
> >
> > > I want to fill only one smiple form so i would like not to use
> > > any non standard libraries.
> >
> > Then just send the HTTP "POST" request containing the fields
> > and data you want to submit.
>
> but i don't know how to post these data if i knew there there would
> be no topic.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread danielx

Mark E. Fenner wrote:
> Mark E. Fenner wrote:
>
> > John Machin wrote:
> >
> >>
> >> Mark E. Fenner wrote:
> >>
> >>> Here's my class of the objects being copied:
> >>
> >> Here's a couple of things that might help speed up your __init__
> >> method, and hence your copy method:
> >>
> >>>
> >>> class Rule(list):
> >>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):
> >>
> >> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0):
> >>
> >>> self.nClasses = nClasses
> >>> self.nCases = nCases
> >>>
> >>> if lhs is not None:
> >>> self.extend(lhs)
> >> what does the extend method do? If it is small, perhaps inline a copy
> >> of its code here.
> >>>
> >>> if rhs is None:
> >>> self.rhs=tuple()
> >>> else:
> >>> self.rhs=rhs
> >>
> >> Replace the above 4 lines by:
> >> self.rhs = rhs
> >>
> >> HTH,
> >> John
> >
> > John,
> >
> > Thanks.  I thought of those at the same you did!  I also incorporated one
> > other use of the default=() + no conditional:
> >
> > class Rule(list):
> > def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0):
> > self.nClasses = nClasses
> > self.nCases = nCases
> > self.extend(lhs) # note, self is a list so this is list.extend
> > self.rhs=rhs
> >
> > def copy(self):
> > return Rule(self,
> > self.rhs,
> > self.nClasses,
> > self.nCases)
>
>
> Actually, I also removed the "passthrough" that copy was doing and just
> called the constructor directly.  So, at the top level code, we have:
>
> allNew = []
> for params in cases:
> # newobj = initialObject.copy()
> newObj = Rule(initialObject, initialObject.rhs,
>   initialObject.nClasses,
>   initialObject.nCases)
> newObj.modify(params)
> allNew.append(newObj)
> return allNew
>
> Regards,
> Mark

I'm not sure how much this will help, but another thing you can do is
put this line before the "for":

append = allNew.append

Then, replace the last line in the loop with

append(newObj)

Check out this doc for more info on optimizing Python, and the section
which talks about eliminating dots:

http://wiki.python.org/moin/PythonSpeed/PerformanceTips
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-aa6c07c46a630a2fa10bd6502510e532806f1f62

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Michael Spencer
Mark E. Fenner wrote:
> Michael Spencer wrote:
> 
>> Mark E. Fenner wrote:
>>
>>> and the copy is taking the majority (42%) of my execution time.
>>> So, I'd like to speed up my copy.  I had an explicit copy method that did
>>> what was needed and returned a new object, but this was quite a bit
>>> slower than using the standard lib copy.copy().
>>>
>> How are you measuring? It seems to me that your Rule.copy method is a lot
>> faster than copy.copy:
>>
>>  >>> r=  Rule(range(100))
>>  >>> shell.timefunc(r.copy)
>> 'copy(...)  36458 iterations, 13.71usec per call'
>>  >>> from copy import copy
>>  >>> shell.timefunc(copy, r)
>> 'copy(...)  4498 iterations, 111.17usec per call' 
> 
> 
> 
>> Michael
> 
> Michael,
> 
> Thank you.  I misinterpreted something somewhere ... the program is indeed
> faster using Rule.copy.  I need to look over the rest of my profiling data,
> to see if I screwed up elsewhere as well.
> 
> So, how to optimize Rule.copy()?
> 
> Regards,
> Mark

You're not doing much in the loop, so there isn't much to change:

 def copy2(self):
 new_rule = list.__new__(Rule)
 new_rule[:] = self
 new_rule.__dict__.update(self.__dict__)
 return new_rule

measures slightly (5-10%) faster for me - but hardly worth the obscurity

You could bind allNew.append outside the loop, and perhaps merge the 
Rule.modify 
method into Rule.copy to save a call.

Given that a no-op method call, takes 2.7 usec on my machine, and you have 3 or 
4 method calls per copy, I suspect you're near the limit of a pure-Python 
solution with this object structure.

 >>> shell.timefunc(r.nop)
'nop(...)  185488 iterations, 2.70usec per call'

Assuming you're going to be doing some material work with these rules, I wonder 
if it's actually worth your the effort to make the copying go faster.

(Sorry no better ideas)

Michael






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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Mark E. Fenner
Mark E. Fenner wrote:

> John Machin wrote:
> 
>> 
>> Mark E. Fenner wrote:
>> 
>>> Here's my class of the objects being copied:
>> 
>> Here's a couple of things that might help speed up your __init__
>> method, and hence your copy method:
>> 
>>>
>>> class Rule(list):
>>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):
>> 
>> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0):
>> 
>>> self.nClasses = nClasses
>>> self.nCases = nCases
>>>
>>> if lhs is not None:
>>> self.extend(lhs)
>> what does the extend method do? If it is small, perhaps inline a copy
>> of its code here.
>>>
>>> if rhs is None:
>>> self.rhs=tuple()
>>> else:
>>> self.rhs=rhs
>> 
>> Replace the above 4 lines by:
>> self.rhs = rhs
>>  
>> HTH,
>> John
> 
> John,
> 
> Thanks.  I thought of those at the same you did!  I also incorporated one
> other use of the default=() + no conditional:
> 
> class Rule(list):
> def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0):
> self.nClasses = nClasses
> self.nCases = nCases
> self.extend(lhs) # note, self is a list so this is list.extend
> self.rhs=rhs
> 
> def copy(self):
> return Rule(self,
> self.rhs,
> self.nClasses,
> self.nCases)


Actually, I also removed the "passthrough" that copy was doing and just
called the constructor directly.  So, at the top level code, we have:

allNew = []
for params in cases:
# newobj = initialObject.copy()
newObj = Rule(initialObject, initialObject.rhs,
  initialObject.nClasses, 
  initialObject.nCases)
newObj.modify(params)
allNew.append(newObj)
return allNew

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Mark E. Fenner
John Machin wrote:

> 
> Mark E. Fenner wrote:
> 
>> Here's my class of the objects being copied:
> 
> Here's a couple of things that might help speed up your __init__
> method, and hence your copy method:
> 
>>
>> class Rule(list):
>> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):
> 
> def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0):
> 
>> self.nClasses = nClasses
>> self.nCases = nCases
>>
>> if lhs is not None:
>> self.extend(lhs)
> what does the extend method do? If it is small, perhaps inline a copy
> of its code here.
>>
>> if rhs is None:
>> self.rhs=tuple()
>> else:
>> self.rhs=rhs
> 
> Replace the above 4 lines by:
> self.rhs = rhs
>  
> HTH,
> John

John,

Thanks.  I thought of those at the same you did!  I also incorporated one
other use of the default=() + no conditional:

class Rule(list):
def __init__(self, lhs=(), rhs=(), nClasses=0, nCases=0):
self.nClasses = nClasses
self.nCases = nCases
self.extend(lhs) # note, self is a list so this is list.extend
self.rhs=rhs

def copy(self):
return Rule(self,
self.rhs,
self.nClasses,
self.nCases)

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


Re: Looking For mp3 ID Tag Module

2006-08-17 Thread Tim Daneliuk
Iñigo Serna wrote:
> On 8/18/06, Tim Daneliuk <[EMAIL PROTECTED]> wrote:
>> > try mutagen. 
>> http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen
>>
>> This module is more-or-less exactly what I needed.  However, I am running
>> into problems when the filenames or ID tags have unicode characters in 
>> them.
>>
>> Typically, I do something like:
>>
>> from mutagen.easyid3 import EasyID3
>>
>> audio["title'] = Something based on the filename that has unicode 
>> chars in it
>>
>> I then get this:
>>
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 
>> 56: ordinal not in range(128)
> 
>> From the docs:
> """Mutagen has full Unicode support for all formats. When you assign
> text strings, we strongly recommend using Python unicode objects
> rather than str objects. If you use str objects, Mutagen will assume
> they are in UTF-8."""
> 
> So I suppose the value you try to assign as title is not unicode,
> check the encoding used in the file system.
> 
> Iñigo

I am trying to set the title based on the filename.  The file is in a Win32
NTFS filesystem, so it could have non-ASCII chars in it.  What I am stumbling
on it how to coerce it into unicode.  I have tried:

name = filename.split() blah blah blah
audio["title"] = unicode(name)

But I still get this error.  I am not real up to speed on the whole unicode
end of things, so any kind suggestions would be most welcome.

By the way, I believe the offending string contains a German umlaut, at least 
in one
of the cases.


Similarly, when I just try to *read* a tag, I get these kinds of errors:

print audio["title"]

Will sometimes choke ...

Thanks for the help..

-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Interactive display of trace.py output?

2006-08-17 Thread Diane Jaquay
I've been using trace.py to get code coverage results for my unit tests, and
like it.  Now I'm trying to use it for code coverage of the GUI parts of my
wxPython-based program, and I realized how nice it would be to be able to see
what lines I'd covered and what remained to be exercised, without having to
stop the trace to get the output updated.

It occurred to me that accepting the "--trace" output from trace.py as input to
another program would allow that other program to show a source file and show
what lines remain to be tested as you're performing the tests.  It also
occurred to me that someone may have already done this.

Does such a thing exist, or do I get to write it?

Thanks,
Dave (djaquay at yahoo, dot-com)

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread John Machin

Mark E. Fenner wrote:

> Here's my class of the objects being copied:

Here's a couple of things that might help speed up your __init__
method, and hence your copy method:

>
> class Rule(list):
> def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):

def __init__(self, lhs=None, rhs=(), nClasses=0, nCases=0):

> self.nClasses = nClasses
> self.nCases = nCases
>
> if lhs is not None:
> self.extend(lhs)
what does the extend method do? If it is small, perhaps inline a copy
of its code here.
>
> if rhs is None:
> self.rhs=tuple()
> else:
> self.rhs=rhs

Replace the above 4 lines by:
self.rhs = rhs

>
>  # as I mentioned, Rule.copy is slower than copy.copy
>  def copy(self):
>  r = Rule(self,
>   self.rhs,
>   self.nClasses,
>   self.nCases)
>  return r
> 

HTH,
John

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


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Mark E. Fenner
Michael Spencer wrote:

> Mark E. Fenner wrote:
> 
>> 
>> and the copy is taking the majority (42%) of my execution time.
>> So, I'd like to speed up my copy.  I had an explicit copy method that did
>> what was needed and returned a new object, but this was quite a bit
>> slower than using the standard lib copy.copy().
>> 
> How are you measuring? It seems to me that your Rule.copy method is a lot
> faster than copy.copy:
> 
>  >>> r=  Rule(range(100))
>  >>> shell.timefunc(r.copy)
> 'copy(...)  36458 iterations, 13.71usec per call'
>  >>> from copy import copy
>  >>> shell.timefunc(copy, r)
> 'copy(...)  4498 iterations, 111.17usec per call' 



> Michael

Michael,

Thank you.  I misinterpreted something somewhere ... the program is indeed
faster using Rule.copy.  I need to look over the rest of my profiling data,
to see if I screwed up elsewhere as well.

So, how to optimize Rule.copy()?

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


Re: re.sub() backreference bug?

2006-08-17 Thread jeff emminger
thanks - that's the trick.

On 8/17/06, Tim Chase <[EMAIL PROTECTED]> wrote:
> Looks like you need to be using "raw" strings for your
> replacements as well:
>
> s = re.sub(r'([A-Z]+)([A-Z][a-z])', r"\1_\2", s)
> s = re.sub(r'([a-z\d])([A-Z])', r"\1_\2", s)
>
> This should allow the backslashes to be parsed as backslashes,
> not as escape-sequences (which in this case are likely getting
> interpreted as octal numbers)
>
> -tkc
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie SQL ? in python.

2006-08-17 Thread John Machin
len wrote:
> I have tried both the pyodbc and mxODBC and with help from the ng been
> able to do what I want using either.  My needs are pretty basic some
> simple selects and inserts.
>
> The current problem I have hit is the database I am inserting into have
> a special ODBC driver that using the files natively has an
> autoincrement feature.  However, through the ODBC driver the
> autoincrement does not work.  (The explanation I got was the creators
> did not anticapate a great need for insert.)

The creators of what? The ODBC driver for the database? Care to tell us
which database software this is?

> Anyway, I figured not a
> problem I will just do a select on the table ordered by the ID field in
> descending order and fetch the first record and do the autoincrementing
> within the python program.  The code , using pyodbc is as follows.
>
> c.execute("select state_sid from statecode order by state_sid DESC")
> sid = c.fetchone()
> newsid = sid.state_sid + 1
>
> This code works fine and I get what I want.

Are you sure? Have you tested what happens if somebody comes along
after you and inserts some rows using the native auto-increment feature
-- do their blahblah_sid numbers start where you finished or do they
overlap with yours?

>  My concern is that this
> technique used on large files may cause problem.  I really just want to
> get what is the last record in the database to get the last ID used.

FWIW,
c.execute("select max(state_sid) from statecode")
should give you the same answer
should not be slower
may be faster

> Is there a better way.  I realize this may be more of an SQL question
> but I figured I would try here first.

Tell us which RDBMS software you are using, and someone who is familiar
with that may be able to help you -- otherwise you'd better ask in a
forum specialised to that RDBMS.

You may find that you can't use ODBC at all to insert those rows. You
may be restricted to using ODBC only to do some preparatory read-only
checking work. To insert you will probably have two options:
(a) use Python to write a script of SQL insert statements. Run this
using a script runner tool that comes with the RDBMS.
(b) use Python to write a file (typically one per table) of data rows
in (e.g.) CSV format. Load this using a bulk-load-from-text-file tool
that comes with the RDBMS.

HTH,
John

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


Re: Best IDE for Python

2006-08-17 Thread Simone Murdock
On 14 Aug 2006 15:04:41 -0700, "Tryker" <[EMAIL PROTECTED]> wrote:

>Gotta love PyScripter. Light, easy to use, free.
>http://mmm-experts.com/Products.aspx?ProductID=4

I agree: I'm trying it only from 4 days the beta version 1.6 and it's
good (some little problems, normal for a beta version, that I'll write
them).

Simon
___
 
Sperm: To be fastest doesn't imply that you are smartest.
   ( by Enrique Herranz )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optimizing Inner Loop Copy

2006-08-17 Thread Michael Spencer
Mark E. Fenner wrote:

> 
> and the copy is taking the majority (42%) of my execution time.
> So, I'd like to speed up my copy.  I had an explicit copy method that did
> what was needed and returned a new object, but this was quite a bit slower
> than using the standard lib copy.copy().
> 
How are you measuring? It seems to me that your Rule.copy method is a lot 
faster 
than copy.copy:

 >>> r=  Rule(range(100))
 >>> shell.timefunc(r.copy)
'copy(...)  36458 iterations, 13.71usec per call'
 >>> from copy import copy
 >>> shell.timefunc(copy, r)
'copy(...)  4498 iterations, 111.17usec per call'
 >>>


where shell.timefunc is:
def _get_timer():
 if sys.platform == "win32":
 return time.clock
 else:
 return time.time
 return

def timefunc(func, *args, **kwds):
 timer = _get_timer()
 count, totaltime = 0, 0
 while totaltime < 0.5:
 t1 = timer()
 res = func(*args, **kwds)
 t2 = timer()
 totaltime += (t2-t1)
 count += 1
 if count > 1000:
 unit = "usec"
 timeper = totaltime * 100 / count
 else:
 unit = "msec"
 timeper = totaltime * 1000 / count
 return "%s(...)  %s iterations, %.2f%s per call" % \
 (func.__name__, count, timeper, unit)


Michael

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


Re: re.sub() backreference bug?

2006-08-17 Thread Tim Chase
> Tim's given you the solution to the problem: with the re module,
> *always* use raw strings  in regexes and substitution strings.


"always" is so...um...carved in stone.  One can forego using raw 
strings if one prefers having one's strings looked like they were 
trampled by a stampede of creatures with backslash-shaped hooves...

uh...yeah...stick with raw strings. :)

-tkc



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


plpython and pickle

2006-08-17 Thread Gerardo Herzig
Hi all, sory if this is kind of [OT], but cannot find the answer for
this behaviour

Im programming a db function using plpython...i have a db called
'sessions', and a postgres 8.1.2 database called 'test'. In 'sessions',
i store several values in a `pickled' way so
If a do
"""
You are now connected to database "sessions".
sessions=# select * from 
getsessiondata('QQtEpLoKHnvbKGSpgJgYMPyCdHgXSi');


 getsessiondata 




 
(dp0--ENTER--S---alucod-ENTER--p1--ENTER--S---32009436-ENTER--p2--ENTER--sS---respuestas_1-ENTER--p3--ENTER--S---3-ENTER--p4--ENTER--sS---respuestas_2-ENTER--p5--ENTER--S---2-ENTER--p6--ENTER--sS---respuestas_3-ENTER--p7--ENTER--S---4-ENTER--p8--ENTER--sS---submit-ENTER--p9--ENTER--S---Responder-ENTER--p10--ENTER--s.
(1 row)
"""
Perfect. Thats what i spect to see.


Now, if i do (in 'test' database)
"""
data = plpy.execute("SELECT * from dblink('dbname=sessions', 'select * from 
getsessiondata(\'\'%s\'\')') as t1(session_data name); " % 
session_id)[0]["session_data"];
plpy.notice(data)
"""
i got this
NOTICE:  ("'(dp0--ENTER--S---alucod-ENTER--p1--ENTER--S---32009436-'",)

The pickled string as been truncated at some point, and when i try to unpickle 
it, i got error.

Now, the question: 
What da hell can i do?

-Postgresql 8.1.2
-Python 2.4.2

Im not even sure if this is a pickle, plpython nor postgresql issue, so
im sory if this is [OT] here.

Thanks!!
Gerardo

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


Re: Looking For mp3 ID Tag Module

2006-08-17 Thread Iñigo Serna
On 8/18/06, Tim Daneliuk <[EMAIL PROTECTED]> wrote:
> > try mutagen. http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen
>
> This module is more-or-less exactly what I needed.  However, I am running
> into problems when the filenames or ID tags have unicode characters in them.
>
> Typically, I do something like:
>
> from mutagen.easyid3 import EasyID3
>
> audio["title'] = Something based on the filename that has unicode chars in it
>
> I then get this:
>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 56: 
> ordinal not in range(128)

>From the docs:
"""Mutagen has full Unicode support for all formats. When you assign
text strings, we strongly recommend using Python unicode objects
rather than str objects. If you use str objects, Mutagen will assume
they are in UTF-8."""

So I suppose the value you try to assign as title is not unicode,
check the encoding used in the file system.

Iñigo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.sub() backreference bug?

2006-08-17 Thread John Machin

[EMAIL PROTECTED] wrote:
> using this code:
>
> import re
> s = 'HelloWorld19-FooBar'
> s = re.sub(r'([A-Z]+)([A-Z][a-z])', "\1_\2", s)
> s = re.sub(r'([a-z\d])([A-Z])', "\1_\2", s)
> s = re.sub('-', '_', s)
> s = s.lower()
> print "s: %s" % s
>
> i expect to get:
> hello_world19_foo_bar
>
> but instead i get:
> hell☺_☻orld19_fo☺_☻ar
>
> (in case the above doesn't come across the same, it's:
> hellX_Yorld19_foX_Yar, where X is a white smiley face and Y is a black
> smiley face !!)
>
> is this a bug, or am i doing something wrong?
>

Tim's given you the solution to the problem: with the re module,
*always* use raw strings  in regexes and substitution strings.

Here's a simple diagnostic tool that you can use when the visual
presentation of a result leaves you wondering [did you get smiley faces
on Windows in IDLE? on Linux?]:

|>>> print repr(s)
'hell\x01_\x02orld19_fo\x01_\x02ar'
|>>> print "s: %r" % s
s: 'hell\x01_\x02orld19_fo\x01_\x02ar'

HTH,
John

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

Re: How to delete a directory tree in FTP

2006-08-17 Thread tobiah
I thought that the plain ftp command 'mdel' would do that.

T wrote:
> I connect to a FTP server which can be either unix or windows server.
> Once in the FTP session, I would like to delete a directory tree on the
> server.  Is there a command that will do this?  If not, can someone
> point me to a right direction?
> 
> Thanks!
> 

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: How to fill a form

2006-08-17 Thread Philippe Martin
Sulsa wrote:

> On Tue, 15 Aug 2006 03:37:02 -
> Grant Edwards <[EMAIL PROTECTED]> wrote:
> 
>> On 2006-08-15, Sulsa <[EMAIL PROTECTED]> wrote:
>> 
>> > I want to fill only one smiple form so i would like not to use
>> > any non standard libraries.
>> 
>> Then just send the HTTP "POST" request containing the fields
>> and data you want to submit.
> 
> but i don't know how to post these data if i knew there there would
> be no topic.
You forgot thanks and regards

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


Optimizing Inner Loop Copy

2006-08-17 Thread Mark E. Fenner
Hello all,

I have a code where my inner loop looks like:

allNew = []
for params in cases:
newObj = copy(initialObject)
newObj.modify(params)
allNew.append(newObj)
return allNew

and the copy is taking the majority (42%) of my execution time.
So, I'd like to speed up my copy.  I had an explicit copy method that did
what was needed and returned a new object, but this was quite a bit slower
than using the standard lib copy.copy().

Here's my class of the objects being copied:

class Rule(list):
def __init__(self, lhs=None, rhs=None, nClasses=0, nCases=0):
self.nClasses = nClasses
self.nCases = nCases

if lhs is not None:
self.extend(lhs)

if rhs is None:
self.rhs=tuple()
else:
self.rhs=rhs

 # as I mentioned, Rule.copy is slower than copy.copy
 def copy(self):
 r = Rule(self,
  self.rhs,
  self.nClasses,
  self.nCases)
 return r

Basically, the left hand side of a rule (e.g., a rule is a & b & c -> d) is
self and three other pieces of information are kept around, two ints and a
right hand side (e.g., (d, 5) meaning that d takes the value five ... all
the LHS elements are tuples as well).

As far as optimization goes, it seems I could write a custom __copy__
method, but a c.l.python search (sorry, forgot to bookmark the reference)
seemed to indicate that a special purpose __copy__ that copies all the
objects's attributes would lose out to the generic copy.copy().  This
doesn't seem quite right ... ideas?

Next option would be to rewrite the whole class in C.  I haven't done C
extensions before and since most of the class is already a builtin list,
that seems like a lot of work for little gain.  Would Pyrex be a help here? 
I don't think the relevant typing information (on the ints alone, I guess)
would get me very far ... and again, recoding the list stuff (by hand or by
Pyrex) in C is not going to get any gains (it might slow things down?).

It seems to me that shallow copies (of objects built from immutable types)
should be able to be speed up by memory mapping (somehow!).  The top-level
list/rule should be the only new reference that needs to be created.

Any quick answers or most likely directions to explore, would be greatly
appreciated.

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Philippe Martin


>>It was philosophers that got us out of that Dark Ages mess, and no small
>>number of them lost their lives in doing so. And today, the philosophy
>>majors are the butts of the most jokes, because after the philosophers
>>succeeded in opening our minds, we forgot why we needed them.

Look east Xah, we're still in the "Dark Ages mess".


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


Re: It is __del__ calling twice for some instances?

2006-08-17 Thread Max Yuzhakov
Duncan Booth wrote:

 DB>  You should post a working code sample which generates your output if you 
 DB>  want a more useful answer.

Hello!

Today I have found a compact variant of a code which shows my question:
---
#!/usr/local/bin/python -d
# -*- coding: koi8-u -*-

class foo:
def __init__(self, other):
self.other = other

global ini_cnt
ini_cnt +=1

def __del__(self):
global del_cnt
del_cnt +=1

def stat():
print "-"*20
print "ini_cnt = %d" % ini_cnt
print "del_cnt = %d" % del_cnt
print "difference = %d" % (ini_cnt-del_cnt)

ini_cnt = 0
del_cnt = 0
loop_cnt = 75

a = foo(None)

for i in xrange(loop_cnt):
a = foo(a)

stat()
a = None
stat()
---

And result is:

ini_cnt = 76
del_cnt = 0
difference = 76

ini_cnt = 76
del_cnt = 77
difference = -1

Why for some instance __del__ called twice?
Such behaviour of __del__ seems to me unpredictable.

Thanks for Your attention!
-- 
GMT More Then ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hide python code !

2006-08-17 Thread Paul Boddie
danielx wrote:
>

[The suggestion that works apparently given away unconditionally become
part of common culture.]

> Extremely interesting point! This should really motivate people to
> answer the question I posed earlier: Does an author of software forfeit
> his rights to the code if he shares his program (ie, reliquishes
> _complete_ protection over the code)?

Well, although some software may be used without the user being
particularly aware of the licence, licences such as the GPL are defined
in terms of distribution. The authors of that licence perhaps realised
that grounding such an agreement in terms of the usage or performance
of a work may be susceptible to the misunderstandings which seem to
have plagued the music industry.

Listening to music over the radio is in practice an involuntary act,
whereas recording and redistributing the music is something that one
actively has to do. The apparent difference between broadcast popular
music and software is that software typically arrives with a licence
(or one is typically forced to view such a licence before downloading
it), and that redistributing software is an act where any later
argument that one was not aware of the licence would be a less credible
defence.

Of course, copyright laws may state that a work without a licence is
"strongly owned" by the author in that redistribution is prohibited,
but as I noted earlier this seems to have been perceived as
counter-intuitive, especially where the work is widely "performed" for
free.

> Let's say this happens: I want to sell some software, but I'm affraid
> people will just copy it. So I prototype it in Python (or whatever
> programming language) and never release the program. Based on that, I
> design a chip (I know this is nearly impossible, but we are doing a
> mental experiment), which does exactly the same thing.

I don't think it's an unreasonable suggestion.

> First of all, the chip can be reverse engineered (of course, with MUCH
> greater difficulty than the equivalent code). Should I still be worried
> that my invention will be copied?

It used to be said that the first people to buy the latest games
console were the competition.

> A second point to consider: The chip is patentable (I think this is the
> case legally, as well as in the court of public opinion), so what about
> the equivalent code?

This is why people are very worried about the scope of patents
gradually expanding from areas where companies have sought some kind of
incentive for investment in manufacturing, for example, to areas where
patents have actually been forbidden in the past, such as in computer
software. Sadly, there's a kind of misguided attitude amongst
law-makers (particularly certain "visionaries" in the European Union)
who think they're encouraging innovation when unquestioningly accepting
arguments that if technology A is patentable and if technology B is
like technology A, then technology B should be patentable, rather than
considering that patents on technology A should also be forbidden.

Paul

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


Re: drawingarea problem

2006-08-17 Thread Lee Harr
On 2006-08-16, Rafa³ Janas <[EMAIL PROTECTED]> wrote:
> Is somebody try to paint filled boxes in drawingarea?
> I don't know how to paint line or someting like this.
> Maybe somebody have tutorial or samples?


Your question could use a few more details (like what
you have tried, what "drawingarea" is and what exactly
is the problem), but I found this that might help:

http://www.google.com/search?q=python+drawingarea
http://www.pygtk.org/pygtk2tutorial/examples/drawingarea.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python

2006-08-17 Thread Paddy

Gallagher, Tim (NE) wrote:
> Hello all,
> I am new to python and I have a few questions.  I am an old Perl hacker
> been using Perl for many years.  I wanted to give python a try, I am
> happy with it so far.
> Question:
> 1. Is there a repository that I can go to for modules? Perl has CPAN and
> I was wondering what the Python equivalent was.
>
> I guess that I had a few more that I cannot think of right now.
>
> Thanks
>
> Tim
Welcome Tim.
The stock answer to the CPAN equivalent question is that Python comes
with a lot more included as standard. You really do need to browse the
Library Reference Docs.
  http://docs.python.org/lib/

You might also want to take a look at this page on the wiki:
  http://wiki.python.org/moin/PerlPhrasebook

Of course, this is as well as going through whatever Python tutorial
you are following.

Have fun, 

- Paddy
.

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


Re: trouble understanding inheritance...

2006-08-17 Thread enigmadude
If what you're trying to do is have more control over the type of
object that is instantiated, then you could use a function that decides
what class to use based upon the arguments supplied to the function,
where it then instantiates an object from the chosen class, then
returns the object. The __init__ method is just for initialization when
an object is created, it's not a constructor and you could even leave
it out and still be able to create objects (although that's less useful
in most cases). Changing an object's type after it's already been
created is more advanced. It's useful, but I don't think that's what
you're trying to do. I believe you're just trying to allow the program
to have more control over what type of object to create. Try doing a
Google search for "creational design patterns", "factory function", and
"factory method". Here's a simple example of what I'm talking about:

def factory(chosen):
if chosen == 'a':
obj = typeA()
elif chosen == 'b':
obj = typeB()

return obj


KraftDiner wrote:
> This is not working the way I think it should
> it would appear that fromfile and getName are calling the baseClass
> methods which are
> simple passes What have I done wrong?
>
> class baseClass:
>   def __init__(self, type):
>   if type == 'A':
>   self = typeA()
>   else:
>   self = typeB()
>   def fromfile(self):
>   pass
>   def getName(self):
>   pass
>
> class typeA(baseClass):
>   def __init__(self):
>   self.name='A'
>   print 'typeA init'
>   def fromfile(self):
>   print 'typeA fromfile'
>   def getName(self):
>   print self.name
>
> class typeB(baseClass):
>   def __init__(self):
>   self.name='B'
>   print 'typeB init'
>   def fromfile(self):
>   print 'typeB fromfile'
>   def getName(self):
>   print self.name
>
> a = baseClass('A')
> a.fromfile()
> a.getName()
>
> b = baseClass('B')
> b.fromfile()
> b.getName()
> 
> log:
> typeA init
> typeB init

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


Re: List match

2006-08-17 Thread Paddy

OriginalBrownster wrote:
> Hi there:
>
> I know this probably is a very easy thing to do in python, but i wanted
> to compare 2 lists and generate a new list that does not copy similar
> entries. An example below
>
> list= ["apple", "banana", "grape"]
> list2=["orange","banana", "pear"]
>
> now I want to compare these lits and generate a third list after
> comparison
>
> list3 would be ["apple", "banana","grape","orange", "pear"]
>
> hence the double entry would not show up?
>
> Is there a way to do this??
>
> Stephen

This solution uses sets; removes all duplicates and is order
preserving.
Remove the outer sorted wrapper if the order need not be preserved.

>>> lst= ["apple", "banana", "grape"]
>>> lst2=["orange","banana", "pear"]
>>> lst3= lst+lst2
>>> sorted([x for x in set(lst3)], key = lambda x: lst3.index(x))
['apple', 'banana', 'grape', 'orange', 'pear']
>>> 

- Paddy

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


Re: List match

2006-08-17 Thread Paddy

[EMAIL PROTECTED] wrote:
> OriginalBrownster wrote:
> > Hi there:
> >
> > I know this probably is a very easy thing to do in python, but i wanted
> > to compare 2 lists and generate a new list that does not copy similar
> > entries. An example below
> >
> > list= ["apple", "banana", "grape"]
> > list2=["orange","banana", "pear"]
> >
> > now I want to compare these lits and generate a third list after
> > comparison
> >
> > list3 would be ["apple", "banana","grape","orange", "pear"]
> >
> > hence the double entry would not show up?
> >
> > Is there a way to do this??
> >
> > Stephen
>
> How about:
>
> list3 = list1 + [item for item in list2 if item not in list1]
>
> print list3:
>
> ['apple', 'banana', 'grape', 'orange', 'pear']

It works with the data given, but if list1 contains duplicates...

- Pad

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


Newbie SQL ? in python.

2006-08-17 Thread len
I have tried both the pyodbc and mxODBC and with help from the ng been
able to do what I want using either.  My needs are pretty basic some
simple selects and inserts.

The current problem I have hit is the database I am inserting into have
a special ODBC driver that using the files natively has an
autoincrement feature.  However, through the ODBC driver the
autoincrement does not work.  (The explanation I got was the creators
did not anticapate a great need for insert.)  Anyway, I figured not a
problem I will just do a select on the table ordered by the ID field in
descending order and fetch the first record and do the autoincrementing
within the python program.  The code , using pyodbc is as follows.

c.execute("select state_sid from statecode order by state_sid DESC")
sid = c.fetchone()
newsid = sid.state_sid + 1

This code works fine and I get what I want.  My concern is that this
technique used on large files may cause problem.  I really just want to
get what is the last record in the database to get the last ID used.

Is there a better way.  I realize this may be more of an SQL question
but I figured I would try here first.

Len Sumnler

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


Re: re.sub() backreference bug?

2006-08-17 Thread Tim Chase
> s = re.sub(r'([A-Z]+)([A-Z][a-z])', "\1_\2", s)
> s = re.sub(r'([a-z\d])([A-Z])', "\1_\2", s)
> i expect to get:
> hello_world19_foo_bar
> 
> but instead i get:
> hell☺_☻orld19_fo☺_☻ar


Looks like you need to be using "raw" strings for your 
replacements as well:

s = re.sub(r'([A-Z]+)([A-Z][a-z])', r"\1_\2", s)
s = re.sub(r'([a-z\d])([A-Z])', r"\1_\2", s)

This should allow the backslashes to be parsed as backslashes, 
not as escape-sequences (which in this case are likely getting 
interpreted as octal numbers)

-tkc



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

Re: hide python code !

2006-08-17 Thread Gerhard Fiedler
On 2006-08-17 16:27:46, danielx wrote:

> A second point to consider: The chip is patentable (I think this is the
> case legally, as well as in the court of public opinion), 

No. A chip is not patentable. In your scenario, the /idea/ behind the
chip's functionality may be patentable, but for a patent it doesn't matter
whether the idea is realized as a custom chip or as software running on a
standard computer.

Differently from copyright (which is about a specific form), patents are
about ideas. They must have a realization (ie. you must be able to show
that it can work), but the patent encompasses all realizations of the
described idea. (It may of course be non-trivial to determine whether a
given modification has been described in the patent or not...)

Gerhard

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


re.sub() backreference bug?

2006-08-17 Thread jemminger
using this code:

import re
s = 'HelloWorld19-FooBar'
s = re.sub(r'([A-Z]+)([A-Z][a-z])', "\1_\2", s)
s = re.sub(r'([a-z\d])([A-Z])', "\1_\2", s)
s = re.sub('-', '_', s)
s = s.lower()
print "s: %s" % s

i expect to get:
hello_world19_foo_bar

but instead i get:
hell☺_☻orld19_fo☺_☻ar

(in case the above doesn't come across the same, it's:
hellX_Yorld19_foX_Yar, where X is a white smiley face and Y is a black
smiley face !!)

is this a bug, or am i doing something wrong?

tested on
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32

and
Python 2.4.4c0 (#2, Jul 30 2006, 15:43:58) [GCC 4.1.2 20060715
(prerelease) (Debian 4.1.1-9)] on linux2

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

Re: Curried class methods?

2006-08-17 Thread Scott Lamb
Thanks, Antoon and Carl. Just tried your solutions - both work and are
much cleaner than mine.

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


Re: Py2Exe and sys.argv : The Lost Arguments

2006-08-17 Thread Larry Bates
I entered the following simple program, compiled with py2exe (2.4)
and ran it the way you describe with two files selected and it
did what you said (e.g. only shows ays.argv[0] and sys.argv[1]):

import sys
print sys.argv
x=raw_input('Press return to continue')

Under 2.5 it didn't work at all (not sure why).

Funny thing is that if I select two .txt files and do a Open With
Notepad, Explorer only opens one of them.  So I think it is
Explorer that is throwing away the extra arguments.  Otherwise
I would expect it to open multiple notepad instances.

-Larry Bates


Thomas W wrote:
> I've created a simple script like so :
> 
> import sys
> import wx
> 
> app = wx.PySimpleApp()
> dlg = wx.MessageDialog(None, "%s" % sys.argv, 'A Message Box',
> wx.YES_NO | wx.ICON_QUESTION)
> retCode = dlg.ShowModal()
> app.MainLoop()
> 
> If I run this on the command line like
> python testcmd.py /somefile.ext /anotherfile.ext
> 
> it displays a messagebox with a stringformatted list containing
> testcmd.py, somefile.ext and anotherfile.ext.
> 
> Then I "compile" the script using py2exe, generate a file called
> testcmd.exe and select the same two files in Explorer, right click,
> "Open with ...", browse to testcmd.exe and proceed. Now the dialogbox
> only shows two items in the list; testcmd.exe and one of the files I
> selected. Why?
> 
> Is it impossible to compile a script using py2exe and pass selected
> items in Explorer to my script? It works fine when called on the
> command line so it might be something related to Explorer but I'm
> completly lost.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Interactive display of trace.py output?

2006-08-17 Thread djaquay
I've been using trace.py to get code coverage results for my unit tests, and
like it.  Now I'm trying to use it for code coverage of the GUI parts of my
wxPython-based program, and I realized how nice it would be to be able to see
what lines I'd covered and what remained to be exercised, without having to
stop the trace to get the output updated.

It occurred to me that accepting the "--trace" output from trace.py as input to
another program would allow that other program to show a source file and show
what lines remain to be tested as you're performing the tests.  It also
occurred to me that someone may have already done this.

Does such a thing exist, or do I get to write it?

Thanks,
Dave (djaquay at yahoo, dot-com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI script running not completely in HTML

2006-08-17 Thread Tim Chase
> In which case you probably need to tweak the server timeout
> setting. Nothing you can do from Python (except possibly make
> your CGI run faster).

Or have Python send a better SQL statement that would run 
faster...a little SQL mojo goes a long way.

The OP failed (as far as my thread-dabbling has noticed) to 
specify what sort of SQL is being run.  If full table results are 
being returned just to be discarded, or there are more efficient 
ways of doing things in the SQL, one would be better off doing it 
on the server and letting it return a single finely-honed 
result-set.  With some insight into the SQL statement(s), one 
might be able to find glaring bottlenecks.

-tkc



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


Re: CGI script running not completely in HTML

2006-08-17 Thread Steve Holden
Yong Wang wrote:
> Hi Steve:
>The propblem I run into is about one minute. The CGI script is not 
> completed to run and aborted.
> If I run the python script in backend solaris machine, the script needs about 
> one minute for database
> access.
> Thanks,
> 
> Yong
>  
In which case you probably need to tweak the server timeout setting. 
Nothing you can do from Python (except possibly make your CGI run faster).

regards
  Steve
> 
>>Yong Wang wrote:
>>
>>>Hi, All:
>>>I have written a python CGI script to run in html web page. When I 
>>> access to
>>>the html page, it only runs part of the script, then abort because the late 
>>>part of
>>>the script is involved in database access, it is slow. I wonder whether 
>>>there is 
>>>a way to control html running speed so that it can wait for CGI script to 
>>>complete
>>>execution, then write the results to html page ? 
>>>Thanks a lot .
>>>
>>>  Yong
>>>
>>
>>Most servers impose some sort of CPU limit on CGI processes (though 
>>typically this defaults to a value of 30 seconds or more). If you really 
>>are going past your server's default(?) limit you really need to either 
>>tweak the limit up on the server (at least for that script) or 
>>reconsider whether the application is suitable for CGI in the first place.
>>
>>What kind of "slow" are we talking about here? A minute? Ten minutes?
>>
>>regards
>>  Steve
>>-- 
>>Steve Holden   +44 150 684 7255  +1 800 494 3119
>>Holden Web LLC/Ltd  http://www.holdenweb.com
>>Skype: holdenweb   http://holdenweb.blogspot.com
>>Recent Ramblings http://del.icio.us/steve.holden
>>
>>-- 
>>http://mail.python.org/mailman/listinfo/python-list
>>
> 
> 
> 
> 
> 


-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 or mysqldb?

2006-08-17 Thread Jarek Zgoda
John Salerno napisał(a):

> I did a little experimentation with MySQL, and yesterday I was reading
> up on SQLite. Since they both use the SQL language, does this mean that
> the queries you write will be the same for both modules? I'm sure there
> are slight differences for how you connect to DBs, but since they both
> use the same DB API 2.0, and both use SQL, I was wondering how easily
> you could 'switch' them out if you needed to go from one to the other.
> 
> (I know there are slight differences between the two in terms of SQL
> commands understood, but I'm mainly referring to the most important
> things, like simply accessing and changing DB information.)
> 
> I was using mysqldb just because MySQL seems to be a pretty big
> standard, but now that sqlite3 is coming with Python 2.5, I might
> switch, since it seems to be easier to use.
> 
> (And again, I'm such an amateur programmer that really I'm using these
> things just to learn them. It's not like I control my company's entire
> employee records or anything.)   :)

To learn SQL SQLite should be enough - it has all the basics, just as
MySQL, while it doesn't require any server/client configuration
(encoding configuration in MySQL is real PITA). But if you want any
"serious SQL", go with any freely available *real SQL server*, like
Firebird or PostgreSQL. I'd consider Firebird, as it's pretty lightweight.

In theory, switching from one db backend to another should go without
problem (at least at ANSI SQL level), but usually requires much work, so
it's rather rare practice. While basics, like DML or DDL syntax, remain
similar, often particular backends require specific tweaks and
optimizations to get desired level of efficiency. You know, this part of
application is a bottleneck.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to fill a form

2006-08-17 Thread John J. Lee
Sulsa <[EMAIL PROTECTED]> writes:

> On Tue, 15 Aug 2006 03:37:02 -
> Grant Edwards <[EMAIL PROTECTED]> wrote:
> 
> > On 2006-08-15, Sulsa <[EMAIL PROTECTED]> wrote:
> > 
> > > I want to fill only one smiple form so i would like not to use
> > > any non standard libraries.
> > 
> > Then just send the HTTP "POST" request containing the fields
> > and data you want to submit.
> 
> but i don't know how to post these data if i knew there there would
> be no topic.

Something like this (UNTESTED, and I can never remember all the
details, which are fiddlier than they may look):

import urllib, urllib2
query = urllib.urlencode([
("username", "sulsa"), ("password", "sulsa"),
("redirect", ""), ("login", "Login"),
])
r = urllib2.urlopen("http://example.com/login.php";, query)
print r.read()


Note that urllib and urllib2 both, as their main job in life, open
URLs.  urllib also has miscellaneous functions related to URLs &c.  I
use urllib2 above because I know it better and because it can handle
some stuff that urllib doesn't (it's designed more for extensibility
than is urllib).


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


Re: CGI script running not completely in HTML

2006-08-17 Thread Steve Holden
Yong Wang wrote:
> Hi, All:
> I have written a python CGI script to run in html web page. When I access 
> to
> the html page, it only runs part of the script, then abort because the late 
> part of
> the script is involved in database access, it is slow. I wonder whether there 
> is 
> a way to control html running speed so that it can wait for CGI script to 
> complete
> execution, then write the results to html page ? 
> Thanks a lot .
> 
>   Yong
> 
Most servers impose some sort of CPU limit on CGI processes (though 
typically this defaults to a value of 30 seconds or more). If you really 
are going past your server's default(?) limit you really need to either 
tweak the limit up on the server (at least for that script) or 
reconsider whether the application is suitable for CGI in the first place.

What kind of "slow" are we talking about here? A minute? Ten minutes?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: CGI script running not completely in HTML

2006-08-17 Thread Tim
Yong Wang wrote:
> Hi, All:
> I have written a python CGI script to run in html web page. When I access 
> to
> the html page, it only runs part of the script, then abort because the late 
> part of
> the script is involved in database access, it is slow. I wonder whether there 
> is 
> a way to control html running speed so that it can wait for CGI script to 
> complete
> execution, then write the results to html page ? 
> Thanks a lot .
>
>   Yong
>
>   
Yong,

Are you reffering to your browser connection to web server timing out 
waiting for query to complete?

I had some long running scripts that would do that so I used a timer 
thread to print comments to the browser  IE: .  Brute 
force approach but it worked using IE with apache.  If I remember right 
you have to call sys.stdout.flush() to force the write over socket to 
happen right away. 

Tim


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


Re: New to python

2006-08-17 Thread bearophileHUGS
Tim Gallagher:
> I am new to python and I have a few questions.  I am an old Perl hacker
> been using Perl for many years.  I wanted to give python a try, I am
> happy with it so far.

In some places and jobs Perl is the only scripting language used still,
but It seems there are other people like you that are slowly
evaporating from the Perl community and trying Python and Ruby.
Welcome, and feel free to ask what you need.

Bye,
bearophile

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


Re: trouble understanding inheritance...

2006-08-17 Thread Ant
Try running the following example - it should help clear up what is
going on:

class Base:
def __init__(self):
print "Initializing base"
def shouldBeImplemented(self):
raise NotImplementedError
def hasDefaultImplementation(self):
print "Wey Hey!"

class A(Base):
def shouldBeImplemented(self):
print "Has been implemented!"

class B(Base):
def __init__(self):
Base.__init__(self)
print 'Initializing B'

class C(Base):
def __init__(self):
print "Initializing C"
def hasDefaultImplementation(self):
print "Boo Hoo!"

base = Base()
print "\n--- A "
a = A()
a.shouldBeImplemented()
print "\n--- B "
b = B()
b.hasDefaultImplementation()
print "\n--- C "
c = C()
c.hasDefaultImplementation()
c.shouldBeImplemented()

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


Re: Defining our own types?

2006-08-17 Thread tobiah
> suppose I type:
> ip = 123.45.67.89

This is probably far from what you want,
but I would do something like this:


class ip(list):

def __init__(self, ip):

bytes = ip.split('.')
for x in range(4):
self.append(bytes[x])

def __repr__(self):

return '.'.join(self)


localhost = ip('192.168.1.1')

print localhost
print localhost[2]
***
192.168.1.1
1

That way at least you can get at the value
in both of the meaningful ways, and you can
probably think of more methods, like applying
netmasks, etc...


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


Problem installing Python 2.4.3 on FreeBSD 5.3-RELEASE-p31

2006-08-17 Thread james
I have a problem installing Pyhton 2.4.3, running "./configure
--with-threads=no" completes, but gives the warning:

configure: WARNING: curses.h: present but cannot be compiled
configure: WARNING: curses.h: check for missing prerequisite
headers?
configure: WARNING: curses.h: see the Autoconf documentation
configure: WARNING: curses.h: section "Present But Cannot Be
Compiled"
configure: WARNING: curses.h: proceeding with the preprocessor's result
configure: WARNING: curses.h: in the future, the compiler will take
precedence

Running "make" then gives the error:

gcc -shared build/temp.freebsd-5.3-RELEASE-p31-i386-2.4/_cursesmodule.o
-L/usr/local/lib -lncursesw -o
build/lib.freebsd-5.3-RELEASE-p31-i386-2.4/_curses.so
Segmentation fault (core dumped)
*** Error code 139

I assume this is related to the configure warning... ?  Same error with
just a standard "./configure" and "make".

Any help would be great :)

Regards,
James

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


Re: CGI script running not completely in HTML

2006-08-17 Thread Christoph Haas
On Thursday 17 August 2006 21:50, Yong Wang wrote:
> I have written a python CGI script to run in html web page. When I
> access to the html page, it only runs part of the script, then abort
> because the late part of the script is involved in database access, it
> is slow. I wonder whether there is a way to control html running speed
> so that it can wait for CGI script to complete execution, then write the
> results to html page ?

You could use

 output = ''
 output += 'Something else to print'

instead of

 print 'Something else to print'

And finally use

 print output

Or to use that more efficiently use a list of strings and append to that 
list. That's probably faster than creating another immutable string time 
and again. And finally you just ' '.join(outputlist) and print that.

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


FrontPage COM Object Model

2006-08-17 Thread iman gowhari
I want to get frontpage web and page object models with this code.
OnPageNew works properly but when I click on the page nothing happen.

from win32com.client import DispatchWithEvents
import time, pythoncom, msvcrt

class FrontPageEvents:
def __init__(self):
print 'FrontPageEvents'
def OnPageNew(self, page):
DispatchWithEvents(f.ActiveDocument, PageEvents)

class PageEvents:
def __init__(self):
print 'PageEvents'
def onclick(self):
print 'onclick'

f=DispatchWithEvents("FrontPage.Application", FrontPageEvents)
while not msvcrt.kbhit():
pythoncom.PumpWaitingMessages()
time.sleep(.2)
msvcrt.getch()

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


CGI script running not completely in HTML

2006-08-17 Thread Yong Wang
Hi, All:
I have written a python CGI script to run in html web page. When I access to
the html page, it only runs part of the script, then abort because the late 
part of
the script is involved in database access, it is slow. I wonder whether there 
is 
a way to control html running speed so that it can wait for CGI script to 
complete
execution, then write the results to html page ? 
Thanks a lot .

  Yong

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


Re: sqlite3 or mysqldb?

2006-08-17 Thread andychambers2002
> I was using mysqldb just because MySQL seems to be a pretty big
> standard, but now that sqlite3 is coming with Python 2.5, I might
> switch, since it seems to be easier to use.

Yes and No.  Sqlite takes less to configure and manage but you have to
consider your needs for concurrent processing.  If memory/disk space is
no object then I would stick to mysql.

If its learning SQL that you want, you should try postgres.  It has a
very
interesting "RULE" system that you can play with.

Regards,
Andy

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


Re: Dynamic objects

2006-08-17 Thread Larry Bates
Mark Shewfelt wrote:
> Hello,
> 
> I have implemented a series of classes representing a Building, its
> respective Equipment, and then various Components of that equipment
> like so (as you'll be able to tell, I'm a newbie):
> 
> class Building:
>  equipment = {}
>  def AddEquipment( name, data ):
>   equipment[ name ] = Equipment( data )
> 
> class Equipment:
>  components = {}
>  def AddComponent( name, data ):
>components[ name ] = Component( data )
> 
> class Component:
>  data = ""
> 
> These classes are used like so:
> 
> test = Building()
> test.AddEquipment( "equipment 1", data )
> test.AddEquipment( "equipment 2", data )
> test.equipment["equipment 1"].AddComponent( "component 1", data )
> test.equipment["equipment 1"].AddComponent( "component 2", data )
> test.equipment["equipment 2"].AddComponent( "component 3", data )
> 
> But it appears as though the instance of "equipment 1" has ALL of the
> components in its components dictionary. I was hoping that the
> test.equipment["equipment 1"].components dictionary would only have
> those components that were assigned to "equipment 1".
> 
> I have implemented __init__  functions for all of the classes, but all
> they do is initialize some data that I haven't shown here.
> 
> I think I'm trying to use a C++ way of doing this (without the new
> operator) so if anyone would be so kind as to help with the Python way
> of doing this sort of thing I will be eternally grateful.
> 
> Cheers,
> 
> Mark Shewfelt
> 
With the way you defined Building multiple buildings would share
equipment dictionary as it is defined as a class variable and you
want an instance variable (I'm pretty sure).  You probably wanted
(not tested):

class Building:
def __init__(self):
self.equipment = {}

def AddEquipment(name, data):
equipment[name]=Equipment(data)

same for Equipment class and Component class.

class Equipment:
def __init__(self):
self.components={}

def AddComponent(name, data):
components[name]=Component(data)


class Component:
def __init__(self, data)
self.data=data


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


Py2Exe and sys.argv : The Lost Arguments

2006-08-17 Thread Thomas W
I've created a simple script like so :

import sys
import wx

app = wx.PySimpleApp()
dlg = wx.MessageDialog(None, "%s" % sys.argv, 'A Message Box',
wx.YES_NO | wx.ICON_QUESTION)
retCode = dlg.ShowModal()
app.MainLoop()

If I run this on the command line like
python testcmd.py /somefile.ext /anotherfile.ext

it displays a messagebox with a stringformatted list containing
testcmd.py, somefile.ext and anotherfile.ext.

Then I "compile" the script using py2exe, generate a file called
testcmd.exe and select the same two files in Explorer, right click,
"Open with ...", browse to testcmd.exe and proceed. Now the dialogbox
only shows two items in the list; testcmd.exe and one of the files I
selected. Why?

Is it impossible to compile a script using py2exe and pass selected
items in Explorer to my script? It works fine when called on the
command line so it might be something related to Explorer but I'm
completly lost.

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


Re: Dynamic objects

2006-08-17 Thread Mark Shewfelt
Thanks a lot Tim!

My __init__ functions didn't set the dictionaries like you did below
(e.g. self.equipment = {} ).

Newbie mistake - won't make that one again.

Thanks again,

Mark


Tim wrote:
> Mark Shewfelt wrote:
> > Hello,
> >
> > I have implemented a series of classes representing a Building, its
> > respective Equipment, and then various Components of that equipment
> > like so (as you'll be able to tell, I'm a newbie):
> >
> > class Building:
> >  equipment = {}
> >  def AddEquipment( name, data ):
> >   equipment[ name ] = Equipment( data )
> >
> > class Equipment:
> >  components = {}
> >  def AddComponent( name, data ):
> >components[ name ] = Component( data )
> >
> > class Component:
> >  data = ""
> >
> > These classes are used like so:
> >
> > test = Building()
> > test.AddEquipment( "equipment 1", data )
> > test.AddEquipment( "equipment 2", data )
> > test.equipment["equipment 1"].AddComponent( "component 1", data )
> > test.equipment["equipment 1"].AddComponent( "component 2", data )
> > test.equipment["equipment 2"].AddComponent( "component 3", data )
> >
> > But it appears as though the instance of "equipment 1" has ALL of the
> > components in its components dictionary. I was hoping that the
> > test.equipment["equipment 1"].components dictionary would only have
> > those components that were assigned to "equipment 1".
> >
> > I have implemented __init__  functions for all of the classes, but all
> > they do is initialize some data that I haven't shown here.
> >
> > I think I'm trying to use a C++ way of doing this (without the new
> > operator) so if anyone would be so kind as to help with the Python way
> > of doing this sort of thing I will be eternally grateful.
> >
> > Cheers,
> >
> > Mark Shewfelt
> >
> >
> I don't see how your examples could work, helps if you post the actual code.
> Try these classes, I think they accomplish what your trying to do.
>
> class Building:
> def __init__(self, data = ''):
> self.data = data
> self.equipment = {}
> def AddEquipment(self, name, data ):
> self.equipment[ name ] = Equipment( data )
>
> class Equipment:
> def __init__(self, data = ''):
> self.data = data
> self.components = {}
> def AddComponent(self, name, data ):
> self.components[ name ] = Component( data )
>
> class Component:
> def __init__(self, data):
> self.data = data

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


Re: hide python code !

2006-08-17 Thread danielx

Paul Boddie wrote:
> danielx wrote:
> >
> > But we have only considered the economics of such a decision. Even if
> > there is no market value to a work, a person has an understandable
> > desire to exercise the rights of ownership over a work, given the
> > amount of personal investment one makes in producing it.
>
> There are other motivations, too. An author might wish that their work
> convey a particular message and that others should not be able to make
> derived works which distort or contradict that message. However, there
> are various established principles of fair use which limit the author's
> control over such derived works.
>
> [...]
>
> > I think the above idea is frequently missed in discussions about
> > copyrights/patents in the open source world. There, the focus seems to
> > be on the marketability granted by protections (legal or physical). The
> > post I am responding to illustrates this focus. Do we believe an author
> > forfeits ownership of a work merely by sharing it? As a matter of
> > conscience, I don't believe the answer can be imposed on anyone. Every
> > person must answer this for him or herself.
>
> As we've mentioned above, one crucial issue is control over published
> works and over the potentially related works of others. With software,
> such control is mediated by the licence which is often prominent, even
> unavoidable when using proprietary software; thus, people using or
> distributing software should be aware of the licence which applies to
> the work. In contrast, works in areas such as popular music are not

While I agree with most of your post, I think the point should be made
that eula's don't hold up very well in US courts:

http://en.wikipedia.org/wiki/EULA#Enforceability

> prominently "labelled" with licensing information if you're listening
> to that music playing on the radio, television, in a public space, and
> so on. This apparent "promiscuity" with such works leads people to
> believe that they are freely exchangeable and that the author is not
> exercising control, even if that isn't really the case due to the
> framework established by the recording industry for broadcasters.
>
> So, people perceive an apparent lack of control as some kind of lack of
> ownership, that the work has, by being shared in an apparently

Extremely interesting point! This should really motivate people to
answer the question I posed earlier: Does an author of software forfeit
his rights to the code if he shares his program (ie, reliquishes
_complete_ protection over the code)?

Let's say this happens: I want to sell some software, but I'm affraid
people will just copy it. So I prototype it in Python (or whatever
programming language) and never release the program. Based on that, I
design a chip (I know this is nearly impossible, but we are doing a
mental experiment), which does exactly the same thing.

First of all, the chip can be reverse engineered (of course, with MUCH
greater difficulty than the equivalent code). Should I still be worried
that my invention will be copied?

A second point to consider: The chip is patentable (I think this is the
case legally, as well as in the court of public opinion), so what about
the equivalent code?

> unconditional way, become part of their common culture - a sentiment or
> an understanding that can presumably be traced back throughout the
> history of human culture itself. At the opposite end of the spectrum of
> control, when mechanisms of control are used to restrict the
> distribution of derived works or the production of coincidentally
> related works, is it unfair that people wish to disregard such
> apparently counter-intuitive mechanisms? An interesting example in
> popular culture was the legal argument about whether silence
> constitutes an original work
> (http://news.bbc.co.uk/1/hi/entertainment/music/2133426.stm), but
> things like patents affect the ability of others to create works in a
> fashion that can be much harder to predict.
> 
> Paul

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


Re: Dynamic objects

2006-08-17 Thread Tim


Mark Shewfelt wrote:
> Hello,
>
> I have implemented a series of classes representing a Building, its
> respective Equipment, and then various Components of that equipment
> like so (as you'll be able to tell, I'm a newbie):
>
> class Building:
>  equipment = {}
>  def AddEquipment( name, data ):
>   equipment[ name ] = Equipment( data )
>
> class Equipment:
>  components = {}
>  def AddComponent( name, data ):
>components[ name ] = Component( data )
>
> class Component:
>  data = ""
>
> These classes are used like so:
>
> test = Building()
> test.AddEquipment( "equipment 1", data )
> test.AddEquipment( "equipment 2", data )
> test.equipment["equipment 1"].AddComponent( "component 1", data )
> test.equipment["equipment 1"].AddComponent( "component 2", data )
> test.equipment["equipment 2"].AddComponent( "component 3", data )
>
> But it appears as though the instance of "equipment 1" has ALL of the
> components in its components dictionary. I was hoping that the
> test.equipment["equipment 1"].components dictionary would only have
> those components that were assigned to "equipment 1".
>
> I have implemented __init__  functions for all of the classes, but all
> they do is initialize some data that I haven't shown here.
>
> I think I'm trying to use a C++ way of doing this (without the new
> operator) so if anyone would be so kind as to help with the Python way
> of doing this sort of thing I will be eternally grateful.
>
> Cheers,
>
> Mark Shewfelt
>
>   
I don't see how your examples could work, helps if you post the actual code.
Try these classes, I think they accomplish what your trying to do.

class Building:
def __init__(self, data = ''):
self.data = data
self.equipment = {}
def AddEquipment(self, name, data ):
self.equipment[ name ] = Equipment( data )

class Equipment:
def __init__(self, data = ''):
self.data = data
self.components = {}
def AddComponent(self, name, data ):
self.components[ name ] = Component( data )

class Component:
def __init__(self, data):
self.data = data

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


Re: New to python

2006-08-17 Thread Gabe

Gallagher, Tim (NE) wrote:
> 1. Is there a repository that I can go to for modules? Perl has CPAN and
> I was wondering what the Python equivalent was.

You can try the CheeseShop.  You can locate it here:
http://cheeseshop.python.org/pypi.  Also, you might want to look into
the new .egg format for downloading modules (it's like 'gem' from ruby,
if you're familiar with that.)

Good Luck,
Gabe

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


Re: ANN: Pybots -- Python Community Buildbots

2006-08-17 Thread david_wahler
I'll be out of the office until approximately August 20th. If you have any 
questions, please email [EMAIL PROTECTED]

-- David Wahler


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


Re: RELEASED Python 2.5 (release candidate 1)

2006-08-17 Thread david_wahler
I'll be out of the office until approximately August 20th. If you have any 
questions, please email [EMAIL PROTECTED]

-- David Wahler


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


Dynamic objects

2006-08-17 Thread Mark Shewfelt
Hello,

I have implemented a series of classes representing a Building, its
respective Equipment, and then various Components of that equipment
like so (as you'll be able to tell, I'm a newbie):

class Building:
 equipment = {}
 def AddEquipment( name, data ):
  equipment[ name ] = Equipment( data )

class Equipment:
 components = {}
 def AddComponent( name, data ):
   components[ name ] = Component( data )

class Component:
 data = ""

These classes are used like so:

test = Building()
test.AddEquipment( "equipment 1", data )
test.AddEquipment( "equipment 2", data )
test.equipment["equipment 1"].AddComponent( "component 1", data )
test.equipment["equipment 1"].AddComponent( "component 2", data )
test.equipment["equipment 2"].AddComponent( "component 3", data )

But it appears as though the instance of "equipment 1" has ALL of the
components in its components dictionary. I was hoping that the
test.equipment["equipment 1"].components dictionary would only have
those components that were assigned to "equipment 1".

I have implemented __init__  functions for all of the classes, but all
they do is initialize some data that I haven't shown here.

I think I'm trying to use a C++ way of doing this (without the new
operator) so if anyone would be so kind as to help with the Python way
of doing this sort of thing I will be eternally grateful.

Cheers,

Mark Shewfelt

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


New to python

2006-08-17 Thread Gallagher, Tim (NE)
Hello all, 
I am new to python and I have a few questions.  I am an old Perl hacker
been using Perl for many years.  I wanted to give python a try, I am
happy with it so far.  
Question:
1. Is there a repository that I can go to for modules? Perl has CPAN and
I was wondering what the Python equivalent was.

I guess that I had a few more that I cannot think of right now.

Thanks

Tim


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


Re: hide python code !

2006-08-17 Thread danielx
Steven D'Aprano wrote:
> On Wed, 16 Aug 2006 13:39:10 -0700, danielx wrote:
>
> > Steven D'Aprano wrote:
> >> On Tue, 15 Aug 2006 09:00:16 -0700, Ben Sizer wrote:
> >>
> >> > Yes, in much the same way that there is no point ever locking your
> >> > doors or installing burglar alarms, as a determined thief will
> >> > eventually steal your belongings.
> >>
> >> That's an utterly pointless and foolish analogy.
> >>
> >> (1) If a thief breaks into your house and steals your TV, you no longer
> >> have a TV. If a developer sees your code, you still have your code, *even
> >> if they subsequently copy it*. You haven't lost your code, it is just no
> >> longer secret. Since secrecy is rarely valuable in and of itself, you've
> >> lost nothing.
> >
> > But haven't you lost your control over the code? If you were trying to
> > sell a program (regardless of whether this is a good way to make money
> > from it), hasn't your ability to do so been undercut? This is the loss.
>
> Maybe so. And if a competitor creates a better product than yours, hasn't
> your ability to sell your program been undercut too?

Creating a better product is a legitimate activity (that's what the
market system is trying to promot after all (not saying the market
system is right, but it is relevant since many people believe in it)).
The whole question is whether copying your code is legitimate. Drawing
an analogy from art and clearly patent-able products, it seems software
might fall into the same category of protectable products. Again, this
is the question at hand.

>
> Either scenario has NOTHING to do with thieves breaking into your house
> and locks on doors. The analogy is bogus. Undercutting your ability to
> sell a product is not theft, and compiling source code to machine code is
> not analogous to a lock on the door.
>
>
> >> Yes, I've heard all the stories about "valuable algorithms" and the like.
> >> Some of them might even be true. But for 99+% of code, spending even one
> >> cent to keep it secret is just wasting money.
> >
> > That may be true, but for someone who has determined that the hiding
> > the code would be best, it would seem to be quite a good investment.
>
> Whether it "seems" to be a good investment is quite different from whether
> it *is* a good investment.
>
> If they ask me for advice, I'll tell them that they're almost certainly
> wasting their time, that their algorithm almost certainly isn't as
> valuable as they think, and that if they disagree, well, Python supports

So it's your opinion against the author's, no? And the decision is up
to the author, and not you, no?

> .pyc files, there are tools like py2exe which will put their Python code
> inside an exe file, there is a Python obfuscator, and a few other tricks.
> If none of those things are good enough for them, then Python is not the
> language they want to be using.

That seems good, but you also seem to have something against the whole
idea of stronger protections for Python. I don't think loose
protections has to be an inherent feature of Python.

>
> As for the rest of your post, it is mostly irrelevant. However, I will
> answer one last point:
>
> [snip]
>
> > Even if we don't take the "twice" figure literally, I imagine
> > that most of us would agree that the amount that the bar can be raise
> > is considerable and not insignificant.
>
> I dispute that "most of us" agree that the bar can be raised a
> considerable amount. It is my position that in the real world, as opposed
> to the fantasies of amateur programmers, compiling code is virtually NO
> BARRIER to your competitors understanding your algorithm.

Anyone willing to take a good survey? Until then, I think we can just
disagree over that point.

>
> Perhaps you would like to consider how it is that black-hat hackers and
> virus writers can analyse Microsoft Windows for vulnerabilities and
> security holes *without access to the source code*?

Yes, but wouldn't it be much easier for those vulnerabilities to be
discovered if the code were released? Black-hats also have to advantage
that MS announces vulnerabilities for them, which they take advantage
of during the period where people are patching their windows.

>
> (And by the way: your suggestion that Microsoft has very few workers is
> wrong. Microsoft has approximately 60,000 employees, and that almost
> certainly doesn't include the many sub-contractors they hire.
> http://www.networkworld.com/news/financial/microsoft.html )

I'd say that's not a large number (I was more or less aware that ms has
ten's of thousands of emploees), but obviously you'd disagree with
that...

> 
> 
> 
> -- 
> Steven D'Aprano

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


Re: PySequence_SetItem

2006-08-17 Thread Jack Diederich
On Thu, Aug 17, 2006 at 02:35:11PM +0200, Fredrik Lundh wrote:
> John Machin wrote:
> 
> > 1. It's also documented as being the recommended way of filling up a
> > list after PyList_New.
> 
> since it doesn't work in any existing Python release, it's hardly 
> "recommended".
> 
> the Python documentation has never been formally binding; if the documentation
> doesn't match the code, it's usually the documentation that's flawed.
> 
> > 2. So you'd rather not change the code, and just let it segfault if
> > someone calls it (or PyObject_SetItem) instead of PyList_SetItem?
> 
> as I said, you're using an API that's designed for use on *properly 
> initialized*
> objects on an object that *hasn't been initialized*.  if you're going to 
> patch all
> places where that can happen, you might as well rewrite the entire 
> interpreter.
> 
> the documentation is broken, and *must* be fixed.  catching this specific case
> in the code is a lot less important; it's just one of many possible errors 
> you can
> make when writing C-level code.  there's simply no way you can catch them
> all.
> 
This was my initial reaction and I'll reluctantly go back to it.  The docs
describe a bad practice - no one ever uses an abstract API to initialize the
concrete type they just created.  For bonus points the example would have always
segfaulted (at least back to 2.2, I didn't check 1.5).

While it feels uneven that other types can't get this kind of segfault the
fact that no one else has ever run accross it makes the point moot.

Unrelated, it looks like PySequence_* doesn't have much reason to live now
that iterators are everywhere.  In the core it mainly used to do the equiv of

def listize(ob):
  if (type(ob) in (list, tuple)):
return ob
  else:
return list(iter(ob))

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


Subprocess confusion: how file-like must stdin be?

2006-08-17 Thread Cameron Laird
Question:
  import subprocess, StringIO

  input = StringIO.StringIO("abcdefgh\nabc\n")
  # I don't know of a compact, evocative, and
  # cross-platform way to exhibit this behavior.
  # For now, depend on cat(1).
  p = subprocess.Popen(["cat"], stdout = subprocess.PIPE, 
stdin = response)

Why this is a question:
A.  it tosses an AttributeError.
B.  I *expected* it to do the equivalent of
  cat << HERE 
  abcdefgh
  abc
  HERE

In http://docs.python.org/dev/lib/node530.html >, I read "Valid
values are ... an existing file object ..."  Even though StringIO is
a "file-like object", it lacks a fileno.  Is there a way to get what
I'm after?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble understanding inheritance...

2006-08-17 Thread Jason
KraftDiner wrote:
> c = [a, b]
> for c in [a,b]:
>c.getName()
>
> but when does baseClass ever get used?
> Why did i even have to define it?
>

One reason for using base classes are for logical reasons.  Oranges and
Apples are different, but they are both fruits.  Python has both
unicode strings and 8-bit ASCII strings.  Both are strings and share a
common base class: the 'basestring' class.

A second reason is for code sharing.  Let's say Python's string class
does everything you want already... except for one little thing.  You
want the split method to return a list with some extra information.
Why re-invent the wheel trying to implement the other string methods
when you can reuse everything that's already been done?

>>> class MyString(str):
...   def split(self):
... "Perform some extra work this version of split"
... wordList = str.split(self)  # Call the original method
... return ['Extra'] + wordList + ['Information']  # Do additional
work!
...
>>>

In Python, we often rely on duck typing.  "If it looks like a duck,
quacks like a duck, it's a duck."  If we can treat it like a string, we
can consider it a string.  If we can't treat it like a string, Python
will let us know by raising an exception.  We can catch this exception
and try something different, or let the exception stop the program and
let the user know something went wrong.

Duck typing allows us to re-use code very efficiently.  I'll
demonstrate it with a function and the class defined above.

>>> def GetWords(stringValue):
...   "Print the list of words in a string"
...   print 'Words are: %s' % stringValue.split()
...
>>> stringValue = str('Hello, world!')
>>> unicodeValue = unicode('These are different strings')
>>> myStringValue = MyString('good, hopefully useful')
>>>
>>> GetWords(stringValue)
Words are: ['Hello,', 'world!']
>>> GetWords(unicodeValue)
Words are: [u'These', u'are', u'different', u'strings']
>>> GetWords(myStringValue)
Words are: ['Extra', 'good,', 'hopefully', 'useful', 'Information']
>>>

As shown above, the GetWords() function works fine with my new string
class.  Any methods that I didn't redefine keep their old behavior.
For example, I didn't define the upper() method in MyString, but I can
still use it:

>>> stringValue.upper()
'HELLO, WORLD!'
>>> myStringValue.upper()
'GOOD, HOPEFULLY USEFUL'
>>>

While we rely on duck typing in Python, we occassionally want special
behavior for certain types of data.  Currently, you can pass anything
into the GetWords() function that has a method named 'split'.  It does
not have to be a string:

>>> class NotAString(object):
...   def split(self):
... return 'I am not a string!'
...
>>> otherDataValue = NotAString()
>>> GetWords(otherDataValue)
Words are: I am not a string!
>>>

Sometimes, we want some specialized behavior.  Lists, tuples, and
strings all act like sequences (meaning, you can get their length and
use them in for-loops).  Often, though, you'll want to treat strings
differently.  You can check the type directly, or you can check by
using the isinstance() built-in function.  isinstance() checks to see
if a variable is an instance of a class or any of its subclasses.

Remember the first reason given, of using a base class to logically
organize other classes?  This is it in practice.  I'll demonstrate
below:

>>> def CheckOnlyBuiltinStrings(stringValue):
...   "Tells us whether or not stringValue is a str or unicode string."
...   if type(stringValue) is str  or  type(stringValue) is unicode:
... print 'A built-in string type: %s' % stringValue
...   else:
... print 'Not a built-in string type: %s' % stringValue
...
>>> def CheckAllStrings(stringValue):
...   "Tells us whether or not stringValue is a string."
...   # The basestring class is a superclass for all string classes.
...   if isinstance(stringValue, basestring):
... print 'Is a string: %s' % stringValue
...   else:
... print 'Not a string: %s' % stringValue
...
>>> CheckOnlyBuiltinStrings(stringValue)
A built-in string type: Hello, world!
>>> CheckOnlyBuiltinStrings(unicodeValue)
A built-in string type: These are different strings
>>> CheckOnlyBuiltinStrings(myStringValue)
Not a built-in string type: good, hopefully useful
>>>
>>> CheckAllStrings(stringValue)
Is a string: Hello, world!
>>> CheckAllStrings(unicodeValue)
Is a string: These are different strings
>>> CheckAllStrings(myStringValue)
Is a string: good, hopefully useful
>>> CheckAllStrings(42)
Not a string: 42
>>>

How do you know when you should use type() checks, when you should use
isinstance(), and when you should just try to use the data?  That
depends, and there have been many lively debates on this subject in the
newsgroup.  I recommend that you should only use as much type checking
as needed, and the less is better.

A bit long, but I hope this helps you out.

--Jason

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


Re: OT: p-gal website

2006-08-17 Thread John Bokma
"ajaksu" <[EMAIL PROTECTED]> wrote:

> And to answer your question, I recommend to follow standards because
> that's how I call the mixed bag of Recommendations, some of which are
> also Specifications, allowing for the inclusion of both significant
> Standards and standards. I guess I must've been bitten by the buzzword
> bug, sorry it that offends you. But I'm not the only one (TM).

True, but if one follows a document, shouldn't one name it according to 
how it's named in the document itself? To me, the answer is yes. 
Especially if people start to claim that "ISO HTML" and HTML 4.01 are 
identical standards.

A lot of people call Python, Perl, etc. *just* scripting languages, not 
real programming languages (whatever that may be). Should we join their 
ranks or educate?

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread Robin Becker
[EMAIL PROTECTED] wrote:
> Robin> Just replaced three PyMem_DEL's with PyObject_FREE and things now
> Robin> work again.
> 
> Can you send me a patch?
> 
> Thx,
> 
> Skip
On its way
-- 
Robin Becker

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


Re: where can i get older version of python?

2006-08-17 Thread calchp

[EMAIL PROTECTED] wrote:
> does any one know where can I get older version of python for windows?
>
> I am looking for versions between 2.0 and 2.2.
>
> thanks for your help

This site might be useful http://www.oldapps.com/Python.php

http://www.oldapps.com/

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


Re: where can i get older version of python?

2006-08-17 Thread beliavsky

[EMAIL PROTECTED] wrote:
> does any one know where can I get older version of python for windows?
>
> I am looking for versions between 2.0 and 2.2.

http://www.python.org/download/releases/

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


where can i get older version of python?

2006-08-17 Thread chppatel
does any one know where can I get older version of python for windows?

I am looking for versions between 2.0 and 2.2.

thanks for your help

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


Python for arcgis

2006-08-17 Thread subramanian2003

Hello All,

  From where can I get the python tutorial for arcgis customisation?.

Bye,
Subramanian.
Sign Up for your FREE eWallet at www.wallet365.com

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


Re: py2exe and COM problem

2006-08-17 Thread Naytie
I figured it out. I can change the table column by selecting it through
the table, e.g.

column = table.Columns(1)

column.Width = 150

etc etc

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


Re: Looking For mp3 ID Tag Module

2006-08-17 Thread Tim Daneliuk
Iñigo Serna wrote:
> Hi Tim,
> 
> try mutagen. http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen
> 
> Regards,
> Iñigo

Many thanks - this looks promising...

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread skip

Robin> Just replaced three PyMem_DEL's with PyObject_FREE and things now
Robin> work again.

Can you send me a patch?

Thx,

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


Re: Curried class methods?

2006-08-17 Thread Carl Banks
Scott Lamb wrote:
> I'm trying to dynamically generate class methods which have access to
> some state passed in at creation time. (Basically as a workaround to
> twisted's trial not having a way to dynamically add stuff. Plain
> unittest seems to have TestSuite, but the trial runner doesn't know
> about it.)
>
> My first attempt might better illustrate this -
>
> class Foo:
> def generalized(self, ctx):
> print 'my ctx is %r' % ctx
>
> for i in ['a','b','c']:
> setattr(Foo, i, lambda self: self.generalized(i))
>
> foo = Foo()
> foo.a()
> foo.b()
> foo.c()
>
> but this prints "my ctx is c" three times; I'd hoped for a, b, c, of
> course.

def build(j):
   setattr(Foo, j, lambda self: self.generalized(j))
for i in ["a","b","c"]:
   build(i)

Each call of the the build function creates its own cell "j" that the
lambda references.


Carl Banks

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


Re: modify element of a list.

2006-08-17 Thread Steve Holden
KraftDiner wrote:
> Hi I have a list of Ojbects... I want to change one of the objects in
> the list for a new object
> How do I replace an existing object with a new one and maintain the
> list order..
> 
> This is what I have...
> 
> def setAttribute(self, desc, value):
>n = anObject(desc, value)
>for o in self.Objects:
>   if o.getDescription() == desc:
>  self.Objects.replace(o, n) #Replace o with n?
>  return
>self.Objects.append(n)
> 
> It's the replace in place that I don't know how to do...
> 
There are a number of ways. I suspect the simplest would be (untested):

def setAttribute(self, desc, value):
 n = anObject(desc, value)
 for i, o in enumerate(self.Objects):
 if o.getDescription() == desc:
 self.Objects[i] = n
 return
 self.Objects.append(n)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread Robin Becker
Steve Holden wrote:
> Robin Becker wrote:
...
>> Has anyone got any clue what the problem might be or a fixed version of the 
>> code?
> 
> I'm guessing this might be to do with the changes that have been made to 
> enable 64-bit readiness in the code, but I couldn't suggest specifics.
> 
> Suspect all pointers and integers first :-)
.
Indeed Steve, but it was in fact PyMem_DEL vs PyObject_NEW. Just replaced three 
PyMem_DEL's with PyObject_FREE and things now work again. The free I suspected 
wasn't involved at all.
-- 
Robin Becker

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


Re: modify element of a list.

2006-08-17 Thread Pierre Quentel
Hi,

The most simple is to use the index of the element in the list :

def setAttribute(self, desc, value):
   n = anObject(desc, value)
   for i,o in enumerate(self.Objects):
  if o.getDescription() == desc:
 self.Objects[i] = n
 return 
   self.Objects.append(n)

Pierre

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Ken Tilton


Xah Lee wrote:

> 
> • What Languages to Hate, Xah Lee, 2002
> http://xahlee.org/UnixResource_dir/writ/language_to_hate.html

Nonsense. This is technology, not religion. Technologists in fact have a 
responsibility to identify and use the best tools available.

Xah, you are getting soft in your old age. :)

hth, kenny

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread Steve Holden
Robin Becker wrote:
> I have a segfault problem in Python2.5 RC1 (win32) when using the venerable 
> extension sgmlop.c.
> 
> In case that was just because our copy was very old I downloaded a later 
> source 
> from http://pyxml.cvs.sourceforge.net, but that code (version 1.14 loewis) 
> still 
> suffers from this problem.
> 
> The problem occurs after a call to free at line so I'm guessing something has 
> changed related to allocations. Is there some magic going on which redefines 
> malloc/realloc etc etc? I'm fairly sure the object in question (-->buffer) 
> isn't 
> passed directly to python so I would have thought that malloc/realloc/free 
> were 
> appropriate. Another parser attribute does hold an array of pointers to 
> python 
> objects, but again I don't think that should be a problem.
> 
> Has anyone got any clue what the problem might be or a fixed version of the 
> code?

I'm guessing this might be to do with the changes that have been made to 
enable 64-bit readiness in the code, but I couldn't suggest specifics.

Suspect all pointers and integers first :-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread Robin Becker
Robin Becker wrote:
> I have a segfault problem in Python2.5 RC1 (win32) when using the venerable 
> extension sgmlop.c.
..
> Has anyone got any clue what the problem might be or a fixed version of the 
> code?
I think this is PyObject_NEW mixed with PyMem_DEL, I thought that had already 
come in so wasn't looking hard enough.

-- 
Robin Becker

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


Re: List match

2006-08-17 Thread Stargaming
Richie Hindle schrieb:
> [Stephen]
> 
>>[...] compare 2 lists and generate a new list that does not copy similar
>>entries. An example below
>>
>>list= ["apple", "banana", "grape"]
>>list2=["orange","banana", "pear"]
>>
>>now I want to compare these lits and generate a third list after
>>comparison
>>
>>list3 would be ["apple", "banana","grape","orange", "pear"]
> 
> 
> Use sets:
> 
> 
from sets import Set as set  # For compatibility with Python 2.3
one = ["apple", "banana", "grape"]
two = ["orange","banana", "pear"]
print list(set(one) | set(two))
> 
> ['grape', 'apple', 'orange', 'pear', 'banana']
> 

Why using Set two times, when you can do it with one call?

 >>> list(set(one + two))

According to my benchmarks, this was five times faster than calling it 
twice and use |.

There are also a few more good approaches uniquifying lists at 
http://www.peterbe.com/plog/uniqifiers-benchmark

Regards,
Stargaming

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


modify element of a list.

2006-08-17 Thread KraftDiner
Hi I have a list of Ojbects... I want to change one of the objects in
the list for a new object
How do I replace an existing object with a new one and maintain the
list order..

This is what I have...

def setAttribute(self, desc, value):
   n = anObject(desc, value)
   for o in self.Objects:
  if o.getDescription() == desc:
 self.Objects.replace(o, n) #Replace o with n?
 return
   self.Objects.append(n)

It's the replace in place that I don't know how to do...

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


Re: sqlite3 or mysqldb?

2006-08-17 Thread Paul Boddie
John Salerno wrote:
> I did a little experimentation with MySQL, and yesterday I was reading
> up on SQLite. Since they both use the SQL language, does this mean that
> the queries you write will be the same for both modules?

They should be, but database system producers tend to enjoy varying the
syntax for their own reasons.

> I'm sure there are slight differences for how you connect to DBs, but since 
> they both
> use the same DB API 2.0, and both use SQL, I was wondering how easily
> you could 'switch' them out if you needed to go from one to the other.

If you write using a conservative, standardised dialect of SQL, you
should be able to move between database systems without too many
difficulties. The first challenge, then, is to make sure you're aware
of what is standard and what the vendor has made up. Although MySQL 5.x
supports much more of the relevant standards than previous release
series, the manuals are very bad at telling you what they've made up
and what actually works on other systems. I therefore recommend that
you also consult other database system manuals, notably the PostgreSQL
manual which I have found to be more coherent.

> (I know there are slight differences between the two in terms of SQL
> commands understood, but I'm mainly referring to the most important
> things, like simply accessing and changing DB information.)

There's plenty of scope for writing non-standard SQL even in the most
common operations. Moreover, defining tables can be awkward because the
set of supported data types and the names used can vary in a seemingly
unnecessary fashion between systems.

> I was using mysqldb just because MySQL seems to be a pretty big
> standard, but now that sqlite3 is coming with Python 2.5, I might
> switch, since it seems to be easier to use.

You can consider MySQL a pseudostandard, but ignoring the actual SQL
standards will cause you difficulties if you decide you want to adopt a
different kind of database system later on. With respect to
portability, I've found sqlite3 and PostgreSQL to be surprisingly
compatible with regard to the SQL both database systems support, and I
can certainly recommend that combination wholeheartedly.

Paul

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


Python2.5 RC1 vs sgmlop.c

2006-08-17 Thread Robin Becker
I have a segfault problem in Python2.5 RC1 (win32) when using the venerable 
extension sgmlop.c.

In case that was just because our copy was very old I downloaded a later source 
from http://pyxml.cvs.sourceforge.net, but that code (version 1.14 loewis) 
still 
suffers from this problem.

The problem occurs after a call to free at line so I'm guessing something has 
changed related to allocations. Is there some magic going on which redefines 
malloc/realloc etc etc? I'm fairly sure the object in question (-->buffer) 
isn't 
passed directly to python so I would have thought that malloc/realloc/free were 
appropriate. Another parser attribute does hold an array of pointers to python 
objects, but again I don't think that should be a problem.

Has anyone got any clue what the problem might be or a fixed version of the 
code?
-- 
Robin Becker

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


sqlite3 or mysqldb?

2006-08-17 Thread John Salerno
I did a little experimentation with MySQL, and yesterday I was reading 
up on SQLite. Since they both use the SQL language, does this mean that 
the queries you write will be the same for both modules? I'm sure there 
are slight differences for how you connect to DBs, but since they both 
use the same DB API 2.0, and both use SQL, I was wondering how easily 
you could 'switch' them out if you needed to go from one to the other.

(I know there are slight differences between the two in terms of SQL 
commands understood, but I'm mainly referring to the most important 
things, like simply accessing and changing DB information.)

I was using mysqldb just because MySQL seems to be a pretty big 
standard, but now that sqlite3 is coming with Python 2.5, I might 
switch, since it seems to be easier to use.

(And again, I'm such an amateur programmer that really I'm using these 
things just to learn them. It's not like I control my company's entire 
employee records or anything.)   :)

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread J�rgen Exner
Iain King wrote:
> Xah Lee wrote:
>> Of interest:
>>
>> . The Semicolon Wars, by Brian Hayes. 2006.
>>  http://www.americanscientist.org/template/AssetDetail/assetid/51982
>>
>> in conjunction to this article, i recommend:
>>
>> . Software Needs Philosophers, by Steve Yegge, 2006
>> http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html
>>
>> . What Languages to Hate, Xah Lee, 2002
>> http://xahlee.org/UnixResource_dir/writ/language_to_hate.html
>>
>>   Xah
>>   [EMAIL PROTECTED]
>> ? http://xahlee.org/
>
> I'm confused - I thought Xah Lee loved Perl?  Now he's bashing it?

He only loves himself.
Aside of that:


 +---+ .:\:\:/:/:.
 |   PLEASE DO NOT   |:.:\:\:/:/:.:
 |  FEED THE TROLLS  |   :=.' -   - '.=:
 |   |   '=(\ 9   9 /)='
 |   Thank you,  |  (  (_)  )
 |   Management  |  /`-vvv-'\
 +---+ / \
 |  |@@@  / /|,|\ \
 |  |@@@ /_//  /^\  \\_\
   @x@@x@|  | |/ WW(  (   )  )WW
   \/|  |\|   __\,,\ /,,/__
\||/ |  | |  jgs (__Y__)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
==

jue


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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Iain King

Xah Lee wrote:
> Of interest:
>
> • The Semicolon Wars, by Brian Hayes. 2006.
>  http://www.americanscientist.org/template/AssetDetail/assetid/51982
>
> in conjunction to this article, i recommend:
>
> • Software Needs Philosophers, by Steve Yegge, 2006
> http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html
>
> • What Languages to Hate, Xah Lee, 2002
> http://xahlee.org/UnixResource_dir/writ/language_to_hate.html
>
>   Xah
>   [EMAIL PROTECTED]
> ∑ http://xahlee.org/

I'm confused - I thought Xah Lee loved Perl?  Now he's bashing it?
Huh?

Iain

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

Re: iTunes Search Algorithm/Data Structure?

2006-08-17 Thread Diez B. Roggisch
Bill Mill schrieb:
> Hello all,
> 
> What data structure would you use to implement something analogous to
> the iTunes search? I imagine that it must be a tree of some sort, but I
> can't figure out an easy structure for it.
> 
> Requirements (in case you haven't used it):
> 
> You are given 4 rows in a list view:
> [["alpha, "beta"], ["delta", "gamma"], ["foo", "bar"], ["etc", "etc"]]
> 
> and a search text box.
> 
> Typing "a" in the list box leaves rows 0, 1 and 2 in the list box,
> because some element in each of those rows has an "a" in it. Typing
> "am" leaves only row 1, since "gamma" has the substring "am" in it.
> 
> The key here is that this works instantaneously as you type, even with
> very large lists with many elements per row. I'd like the employee list
> in my current application to be similarly filtered, but I don't quite
> see how.
> 
> Thoughts?


Use an index. You can create one for each character, tuples of 
characters and so on that are contained in a word. That makes finding 
the entries a dict lookup + throwing the results together, filtering 
doubles.

I guess you can stop using indices at 3 or 4 characters, and then 
linearily search through the rest of the possibilities linearily.

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


1. Re: hide python code ! (enigmadude)

2006-08-17 Thread Ronny Abraham
Actually the reason you want to have one layer of encryption isn't to
prevent someone from understanding what you wrote, it's so that if some
company decides to "acquire" your code, they can't claim that you had
it in the public domain.

I think even the most pathetic encryption can serve this purpose.

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

Re: List match

2006-08-17 Thread Richard Brodie

"OriginalBrownster" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I know this probably is a very easy thing to do in python, but i wanted
> to compare 2 lists and generate a new list that does not copy similar
> entries. An example below
>
> list= ["apple", "banana", "grape"]
> list2=["orange","banana", "pear"]

Other people have already posted solutions but I'll add a couple of
comments:

1. Avoid calling lists 'list', you will break the list built-in function.

2. You don't specify whether the lists are ordered. If there is no
significance to the order of the items, it may be more appropriate
to use sets throughout. Then the answer is just: set3 = set1 | set2. 


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


Re: How to delete a directory tree in FTP

2006-08-17 Thread T

That looks useful.  Thanks!

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread jmckitrick
What's more of a waste of time:

1.  The 30 minutes he took to write his vacuous essay.
2.  The 15 seconds it took to skim it and see nothing worth reading.
3.  The 30 seconds it took to write this post.

Tough call.

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


  1   2   >