Re: Class Methods Vs Any Other Callable

2008-05-15 Thread George Sakkis
On May 14, 4:38 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 14 mai, 16:30, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > On May 14, 10:19 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
> > > > An instance method works on the instance
> > > > A Static method is basically a function nested within a class object
> > > > A class method is overkill?
>
> > > If anything, a static method is overkill. See it this way: *if* you for 
> > > some
> > > reason put a method into an enclosing context - isn't it worth having a
> > > reference to that?
>
> > My feeling exactly; these days I almost always use class methods
> > instead of static. I vaguely remember seeing somewhere an example
> > where a static method was the only (elegant) solution; neither a class
> > method nor a plain function would do. I'll post it if I find it unless
> > someone beats me to it.
>
> No concrete example here but I surely remember having used
> staticmethods in one case where I needed class-based polymorphic
> dispatch and eventually implementation inheritance (to get a default
> implementation)  for something that didn't required access to the
> class object.

Yes, that's common, but a class method could be used just as well
here. I couldn't find the original example but IIRC it was related to
monkeypatching. Say that you have a package P1 that has some useful
classes:

class A(object): pass
class B(A): pass
class C(A): pass

You also have an unrelated package P2 with some useful functions:

def f1(): return 0
def f2(): return 1

Naturally you want to combine these two. One common pattern when doing
so turns out to be like:

# e.g. x = random.choice([A(), B(), C()])
...
assert isinstance(x, A)
if type(x) in (A,B):
print f1()
elif type(x) is C:
print f2()

With a less trivial hierarchy and number of functions, it becomes
clear that it would help a lot if you could refactor it somehow so you
can just say "print x.f()" and it would do the right thing.
Monkeypatching it as a normal method ("A.f = f1; C.f = f2") doesn't
work because it expects self as the first argument, and similarly for
class methods and the cls argument. OTOH static methods do the trick:

A.f = staticmethod(f1)
C.f = staticmethod(f2)
print x.f()

Admittedly it's not a common scenario but it's good to know it's there
if you need it.

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


Re: [x for x in <> while <>]?

2008-05-15 Thread Terry Reedy

"urikaluzhny" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| It seems that I rather frequently need a list or iterator of the form
| [x for x in <> while <>]

I can think of two ways to interpret that.

| And there is no one like this.
| May be there is another short way to write it (not as a loop). Is
| there?

Using loops to write an example of what you mean would make the above 
clearer.

tjr



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


Re: Install Python MySQL db module?

2008-05-15 Thread martin . laloux
search, search, it is a recurrent question
for example

http://groups.google.be/group/comp.lang.python/browse_thread/thread/7bef767753fe40f1/a3fd7c2dd7a50bef?hl=fr&lnk=gst&q=mysqldb+mac#a3fd7c2dd7a50bef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Nasty gotcha/bug in heapq.nlargest/nsmallest

2008-05-15 Thread Peter Otten
George Sakkis wrote:

> I spent several hours debugging some bogus data results that turned
> out to be caused by the fact that heapq.nlargest doesn't respect rich
> comparisons:
> 
> import heapq
> import random
> 
> class X(object):
> def __init__(self, x): self.x=x
> def __repr__(self): return 'X(%s)' % self.x
> if True:
> # this succeeds
> def __cmp__(self, other): return cmp(self.x , other.x)
> else:
> # this fails
> def __lt__(self, other): return self.x < other.x
> 
> s = [X(i) for i in range(10)]
> random.shuffle(s)
> 
> s1 = heapq.nlargest(5, s)
> s2 = sorted(s, reverse=True)[:5]
> assert s1 == s2, (s,s1,s2)
> 
> s1 = heapq.nsmallest(5, s)
> s2 = sorted(s)[:5]
> assert s1 == s2, (s,s1,s2)
> 
> 
> According to the docs, nlargest is equivalent to: "sorted(iterable,
> key=key, reverse=True)[:n]" and similarly for nsmallest. So that must
> be at least a documentation bug, if not an implementation one.

Implementing a subset of the rich comparisons is always dangerous. According
to my ad hoc test you need <, <=, and == for nlargest()/nsmallest() to
work:

import heapq
import random

used_rich = set()

class X(object):
def __init__(self, x): self.x=x
def __repr__(self): return 'X(%s)' % self.x
def __lt__(self, other):
used_rich.add("lt")
return self.x < other.x
def __eq__(self, other): 
used_rich.add("eq")
return self.x == other.x
def __gt__(self, other):
used_rich.add("gt")
return self.x > other.x
def __ge__(self, other):
used_rich.add("ge")
return self.x >= other.x
def __ne__(self, other):
used_rich.add("ne")
return self.x != other.x
def __le__(self, other):
used_rich.add("le")
return self.x <= other.x

s = [X(8), X(0), X(3), X(4), X(5), X(2), X(1), X(6), X(7), X(9)]

smallest = sorted(s)[:5]
largest = sorted(s, reverse=True)[:5]

print "used by sorted:", used_rich
used_rich = set()

for i in range(1):

s1 = heapq.nlargest(5, s)
assert s1 == largest, (s, s1, largest)

s1 = heapq.nsmallest(5, s)
assert s1 == smallest, (s, s1, smallest)

random.shuffle(s)

print "used by nlargest/nsmallest:", used_rich

Output:
used by sorted: set(['lt'])
used by nlargest/nsmallest: set(['lt', 'le', 'eq'])

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


Re: Class Methods Vs Any Other Callable

2008-05-15 Thread Bruno Desthuilliers

vbgunz a écrit :

I remember learning closures in Python and thought it was the dumbest
idea ever. Why use a closure when Python is fully object oriented? I
didn't grasp the power/reason for them until I started learning
JavaScript and then BAM, I understood them.

Just a little while ago, I had a fear of decorators because I really
couldn't find a definitive source to learn them (how to with with @).
How important are they? They must be important otherwise why have'em
in the language? I had to learn'em and then suddenly, BAM. I
understand them.

My main issue with closures and decorators was hidden in the fact of
how *dead simple* they were. All I needed were reasons to use them
over doing it X style. So what is my point? How dead simple are class
methods? 


Way dumber than closures and HOFs (which is what 'decorators' are when 
you take back the @syntactic sugar).


A classmethod is simply a method that works on the class itself - it 
takes the class as first argument, instead of taking the instance.



I must be missing there point so I am convinced they must be
dead simple.

classes, functions, instance and static methods are easy. So easy in
fact, I could shoot myself in the foots without looking (preferably
without aiming). So, why am I stuck on the *idea* of a class method?


Could it be because you don't see the implication of classes being 
objects too ?



An instance method works on the instance
A Static method is basically a function nested within a class object
A class method is overkill?


Nope. It's sometimes pretty usefull.


I can call a static or class method through either the class OR any
instance of it. I've never designed a method that took advantage of
the class name except in cases where I needed to extend a super class
*but* even in this case, I didn't use the enclosing class name...


s/name//g

What you have is the class *object*, not the class name.


Whats the deal with class methods, why use them over anything else?
What does a class method accomplish in at least one line shorter than
anything else? Does it help reduce duplication or typing? I am at a
lost for words that can shed at least *one* good reason to use them.

> What is the one greatest reason to use them?

Factory methods (alternate constructors...) is probably the most obvious 
use case. You need to get at the class to instanciate it, don't you ? An 
example of this pattern is dict.fromkeys().


You'll find a more elaborate example here too:
http://groups.google.fr/group/comp.lang.python/browse_frm/thread/65868e8a12bcf375/a31bb0e13bf09316#a31bb0e13bf09316

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


Re: Class Methods Vs Any Other Callable

2008-05-15 Thread Bruno Desthuilliers

vbgunz a écrit :

Instance methods make the most sense. A static method makes sense too
*but* I can see how a class method not only does what a static method
does but how a class method *also* gets the cls reference for free.

I don't understand the last part - but I certainly agree on the "instance
methods make the most sense". But *if* you want a hierarchy
of "sensefulness",
method > classmethod > staticmethod


Sorry I quoted this earlier and meant to respond to it. What I meant
was, might as well use a class method over a static method AND in
doing so, cls is free.


cf Georges Sakkis point about this. 'cls is free' ? Well, not 
necessarily. Your function must take the class as first argument, and so 
you just can't use just any plain function as a classmethod.


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


Re: [x for x in <> while <>]?

2008-05-15 Thread Bruno Desthuilliers

urikaluzhny a écrit :

It seems that I rather frequently need a list or iterator of the form
[x for x in <> while <>]
And there is no one like this.
May be there is another short way to write it (not as a loop). Is
there?


The answer is very probably in the itertools module.

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


Re: named tuple mutability

2008-05-15 Thread Bruno Desthuilliers

Ben Finney a écrit :

"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:


On 14 mai, 18:20, [EMAIL PROTECTED] wrote:

I'm concerned over the future of Python.  Should tuples be named?

Obviously not, unless they should.


Clearly they should, unless not.


May we agree to disagree here - unless we don't ?
--
http://mail.python.org/mailman/listinfo/python-list

Re: Custom Classes?

2008-05-15 Thread Gabriel Genellina
En Tue, 13 May 2008 15:10:21 -0300, Victor Subervi  
<[EMAIL PROTECTED]> escribió:



I remember why I had the number with the getpic. It is because I display
several of these images on a single page, and apparently I cannot call  
the

same script and get more than one image from an HTML page.


That's not true. If you still have the example I posted a few weeks ago,  
you can use this script to show a full listing of all uploaded pictures.  
It's a small variation of album.py.
I think you were saving the pictures on disk - DON'T do that. It's  
unnecesary, wastes time and disk space, and if not done properly one  
request interferes with the other.


--
Gabriel Genellina#!/usr/bin/python

"Full listing (all pictures)"

import cgi
import sqlite3

conn = sqlite3.connect("demo.db")
cursor = conn.cursor()
sql = "select id, title, description from album order by id"
cursor.execute(sql)
lines = []
for row in cursor.fetchall():
id, title, description = row
lines.append("%s"
 "%s"
 "  "
 "" % (cgi.escape(title), 
  cgi.escape(description), 
  id))
conn.close()

print "Content-Type: text/html"
print "Pragma: no-cache" 
print "Cache-Control: no-cache"
print
print "Picture album (full)"
print ""
print "Picture album"
if lines:
print "\n".join(lines)
else:
print "No pictures yet."
print "You can upload a new picture."
print ""
--
http://mail.python.org/mailman/listinfo/python-list

Re: Recommended way to POST with cookies?

2008-05-15 Thread Laszlo Nagy

Gilles Ganault wrote:

Hello

According to Google, there seems to be several tools available,
possibly deprecated, to download data from web pages by POSTing forms
and save cookies to maintain state.

I need to write a script under Windows with ActivePython 2.5.1.1  that
would do this:
1. Connect through a local proxy, so I can see the whole dialog
between the Python script and the web server
2. POST form variables
3. Save cookies sent by the server (session cookie to keep state)
4. Save received data into an SQLite file

Which tools would you recommend for this type of script?
  
Within a day this is the second request for a browser emulator. Looks 
like many pepole want this.


I just posted a recipe that you can try:

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


Best,

Laszlo

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


Re: [x for x in <> while <>]?

2008-05-15 Thread Paul Rubin
urikaluzhny <[EMAIL PROTECTED]> writes:
> It seems that I rather frequently need a list or iterator of the form
> [x for x in <> while <>]
> And there is no one like this.
> May be there is another short way to write it (not as a loop). Is there?

itertools.takewhile(condition, seq)
--
http://mail.python.org/mailman/listinfo/python-list


Re: ?

2008-05-15 Thread urikaluzhny
On May 15, 10:06 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "urikaluzhny" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | It seems that I rather frequently need a list or iterator of the form
> | [x for x in <> while <>]
>
> I can think of two ways to interpret that.
I mean like [x for x in  if ], only that it breaks the loop when
the expression  is false.
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython dialog - do something after ShowModal()?

2008-05-15 Thread Iain King
On May 14, 9:37 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>  Iain King <[EMAIL PROTECTED]> wrote:
>
> > Hi.  I have a modal dialog whcih has a "Browse..." button which pops
> > up a file selector.  This all works fine, but the first thing the user
> > has to do when they open the dialog is select a file, so I would like
> > the dialog to automatically call the onBrowse function as soon as the
> > dialog opens.  However, I don't know how to do this.
>
> > dlg.ShowModal()
> > onBrowse()
>
> > obviously doesn't work, and neither does the reverse.  I was hoping
> > that the dialog would throw some kind of "I have been shown" event,
> > but it doesn't (as far as I can tell).  How do I make the dialog do
> > something as soon as it's been shown?
>
> It's too bad that you found an answer. You _shouldn't_ have your
> dialog pop up a file-selection box as soon as it's shown! That's
> not the way dialogs usually work, so you're going to confuse
> people.
>
> Instead, first pop up the file-selection box, and then pop up
> the dialog (without the Browse button) to do whatever else it
> does after you've got the filename.
>

That's actually what happens - the dialog throws EVT_INIT_DIALOG
before it displays itself.  Not that I really agree with you.  I don't
think that a "do such-and-such dialog" appearing with a "Select file
for such-and-such" file selector on top of it, the file selector being
in focus, is confusing for the user.  Actually, I think it'd be
friendlier - the user can see where the data from the file is going,
so has an immediate reminder of what the (generic) file selector is
for.
--
http://mail.python.org/mailman/listinfo/python-list


Re: cgitb performance issue

2008-05-15 Thread Gabriel Genellina
En Wed, 14 May 2008 13:51:40 -0300, Ethan Furman <[EMAIL PROTECTED]>  
escribió:

Gabriel Genellina wrote:
En Mon, 05 May 2008 15:56:26 -0300, Ethan Furman  
<[EMAIL PROTECTED]> escribió:



I tried adding a form to our website for uploading large files.
Personally, I dislike the forms that tell you you did something wrong
and make you re-enter *all* your data again, so this one cycles and
remembers your answers, and only prompts for the file once the rest of
the entered data is good.  However, the first time the form loads it  
can

take up to 30 seconds... any ideas why?


Hard to tell without looking at the code... And what has cgitb to do  
with this?



H... excellent question, and the answer is -- Nothing.  My
apologies.  I'm importing cgi (cgitb was while I was debugging it), as
well as a bunch of others.

Here's the source, with a bunch of the actual html stripped out.  The -u
as well as the last two lines were an attempt to eliminate the 30-second
pause while it loads, as it seems to get all data transferred, then just
waits for a while.  Any ideas appreciated.  My apologies for the ugly  
code.


*When* do you see the 30-secs delay? After uploading the files? I see  
they're transferred using SMTP, but I think you're not talking about the  
time it takes to send the mail.
I'd use the old-fashioned "print" statement to see *what* gets executed  
and how long it takes each step.


--
Gabriel Genellina

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


Making Variable Text Output More Pythonic?

2008-05-15 Thread Casey McGinty
Hi,

I have some classes that print variable outputs depending on their internal
state, like so:

def __str__(self):
out = []
if self.opt1: out += ['option 1 is %s' % self.opt1']
if self.opt2: out += ['option 2 is %s' % self.opt2']

return '\n'.join(out)

Is there any way to make this cleaner?
--
http://mail.python.org/mailman/listinfo/python-list

Re: sys.excepthack...

2008-05-15 Thread Nick Craig-Wood
David C. Ullrich <[EMAIL PROTECTED]> wrote:
>  Becoming a fan of wxPython, but I can't stand
>  what it does with error messsages 
[snip]
>  So I want to pop up a modal dialog on error.
[snip]
>  Came up with a ridiculous hack involving both sys.stderr
>  and sys.excepthook. Works exactly the way I want.
>  Seems ridiculous - what's the right way to do this?
> 
>  Ridiculous_hack.py:
> 
>  import sys
>  import wx
> 
>  def hook(*args):
>try:
>  sys.__excepthook__(*args)
>finally:
>  printer.Show()
> 
>  class ErrorDisplay:
>def __init__(self):
>  self.buffer = ''
>def write(self, text):
>  self.buffer = self.buffer + text
> 
>def Show(self): 
>wx.MessageDialog(None, str(self.buffer), 
>'Error:',wx.OK).ShowModal()
>self.buffer = ''
> 
>  printer = ErrorDisplay()
>  sys.stderr = printer
>  sys.excepthook = hook

Here is how I've done it in the past.  It is a complete runnable
example :-


#!/usr/bin/python

import wx
import sys
from traceback import format_exception

class TestApp(wx.Frame):
"""Test error handling"""

def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, -1, title, size=(200,200))
sys.excepthook = self.OnException
button = wx.Button(self, wx.NewId(), "Produce Error")
self.Bind(wx.EVT_BUTTON, self.OnClick)
self.Show(True)

def OnException(self, type, value, traceback):
"""
Called on OnException
"""
error_text = "".join(format_exception(type, value, traceback))
wx.MessageDialog(None, error_text, 'Custom Error:', wx.OK).ShowModal()

def OnClick(self, evt):
"Click with a deliberate mistake"
adsfsfsdf

if __name__ == "__main__":
app = wx.PySimpleApp()
frame = TestApp(None, -1, "Test")
app.MainLoop()


-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rename field in Access DB

2008-05-15 Thread Iain King
On May 14, 4:29 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> Iain King wrote:
> > I'm manipulating an MS Access db via ADODB with win32com.client.  I
> > want to rename a field within a table, but I don't know how to.  I
> > assume there is a line of SQL which will do it, but nothing I've tried
> > (from searching) has worked.
> > Basic code:
>
> > import win32com.client
> > connection = win32com.client.Dispatch(r'ADODB.Connection')
> > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;'
> > connection.Open(DSN)
> > connection.Execute("ALTER TABLE tablename CHANGE from to")   #this sql
> > doesn't work
> > connection.Close()
>
> 
> import os, sys
> from win32com.client.gencache import EnsureDispatch as Dispatch
>
> DATABASE_FILEPATH = r"c:\temp\test.mdb"
> CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0; data Source=%s" % \
>   DATABASE_FILEPATH
>
> if os.path.exists (DATABASE_FILEPATH):
>os.remove (DATABASE_FILEPATH)
>
> adox = Dispatch ("ADOX.Catalog")
> adox.Create (CONNECTION_STRING)
> adox = None
>
> db = Dispatch ('ADODB.Connection')
> db.Open (CONNECTION_STRING)
> try:
>   db.Execute ('CREATE TABLE dtest (id INT, data INT)')
>   db.Execute ('INSERT INTO dtest (id, data) VALUES (1, 2)')
>
>   try:
> db.Execute ('SELECT id, newdata FROM dtest')
>   except:
> print "FAILED as expected"
>   else:
> print "SUCCEEDED unexpectedly"
>
>   try:
> db.Execute ('SELECT id, data FROM dtest')
>   except:
> print "FAILED unexpectedly"
>   else:
> print "SUCCEEDED as expected"
>
>   adox = Dispatch ("ADOX.Catalog")
>   adox.ActiveConnection = db
>   adox.Tables ("dtest").Columns ("data").Name = "newdata"
>   adox.Tables.Refresh ()
> finally:
>   db.Close ()
>
> db = Dispatch ('ADODB.Connection')
> db.Open (CONNECTION_STRING)
> try:
>
>   try:
> db.Execute ('SELECT id, data FROM dtest')
>   except:
> print "FAILED as expected"
>   else:
> print "SUCCEEDED unexpectedly"
>
>   try:
> db.Execute ('SELECT id, newdata FROM dtest')
>   except:
> print "FAILED unexpectedly"
>   else:
> print "SUCCEEDED as expected"
>
> finally:
>db.Close ()
>
> 
>
> TJG


Excellent, many thanks.

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


Re: Sanitised Newsgroup Feeds?

2008-05-15 Thread Casey McGinty
On Wed, May 14, 2008 at 7:47 PM, Paddy <[EMAIL PROTECTED]> wrote:

> Hi,
> Does anyone do a sanitised newsgroup feed? Something like what mail
> filters do for email?
>  
>

Hi, I used to read the summary emails and had the same problem. I think the
best method is to subscribe to the list using an e-mail program that can do
spam filtering. Gmail gets rid of about 98% of the spam for me right now and
I mark any spam that gets by. Also, I would put a filter on the python
emails so they don't show up directly in your Inbox. Good luck.

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

Re: create window on panel

2008-05-15 Thread Laszlo Nagy

Jimmy wrote:

Hi, all

I have been trying to use wxPython to design a GUI that will be
displayed on the panel on the top of desktop. that is when the
program starts, it will dwell on the panel to display some dynamic
information.

can anyone tell me in wxPython how to do this? thanks!
  
AFAIK it cannot be done in pure wxPython. The reason is that your 
"panel" is part of the window manager. What kind of "panel" are you 
talking about anyway? Under Microsoft Windows it is called "the tray". 
In Gnome it is "panel" indeed. In KDE it might also be panel, there is 
OS X etc. They are quite different. For example, under MS Windows you 
cannot embed an application into the tray (other than an icon).


They are all different window managers, based on different client libs 
(MS gui, GTK, Qt etc.). wxPython is designed to be platform independent, 
and  it does not support special, platform dependent features. (Well it 
does a few...)


You need to tell us what kind of system are you using? Then we can tell 
you where to start. For example, there are extension modules for writing 
Gnome panel applications. (Well, it is not wxPython but GTK.)


BTW the idea is good: we could have "panel" support in wxPython, but 
since the interface of these panels (and how they should be programmed) 
is very different on different platforms, it would not be easy to implement.


  Laszlo

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


Re: [off-topic] Usenet

2008-05-15 Thread Ben Finney
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> "John Salerno" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> | On Wed, 14 May 2008 12:58:12 -0400
> | "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> |
> | > gmane.comp.python.general
> |
> | So that's the same as c.l.p.?
> 
> It is the same as python-list, which happens to be the same as c.l.p..

Which, to be clear, is a special case: the fact that the mailing list
'python-list' and the newsgroup 'comp.lang.python' interchange
messages, and are effectively the same forum, has nothing to do with
Gmane. That situation predates, and is unaffected by, the introduction
of Gmane.

-- 
 \“Good morning, Pooh Bear,” said Eeyore gloomily. “If it is a |
  `\  good morning,” he said. “Which I doubt,” said he. —A. A. |
_o__) Milne, _Winnie-the-Pooh_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Sanitised Newsgroup Feeds?

2008-05-15 Thread Ben Finney
Paddy <[EMAIL PROTECTED]> writes:

> Does anyone do a sanitised newsgroup feed? Something like what mail
> filters do for email?

The feature you're looking for is called a "kill list" or "kill file":
add patterns to the kill file, and matching messages will be omitted
from your view of the newsgroup.

Whether your NNTP client supports such a feature is for you to
determine. (I'm pretty sure Google Groups, among its litany of
failings as an NNTP client, is lacking in this aspect too. So, don't
use Google Groups.)

> It is getting tedious wading through the ads for 'cracks' & watches;
> as well as the Xah cross-posted self-promotions, the wx-'its easier to
> post than read the tutorial' annoyances and the castiro (human/Eliza?)
> weirdnesses.

Yes, those authors are among the patterns in my GNUS kill file.

> I guess that many would want to add the same things to their kill
> file, but it takes me three clicks to add anyone/any thread to it
> and the c.l.p signal-to-noise is getting lower.

Huh? How often do you have to add patterns to the file? I do it once
every couple of weeks, if that.

-- 
 \ "Are you pondering what I'm pondering?" "I think so, Brain, but |
  `\pants with horizontal stripes make me look chubby."  -- _Pinky |
_o__)   and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: named tuple mutability

2008-05-15 Thread Ben Finney
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

> May we agree to disagree here - unless we don't ?

Absolutely not, except where not applicable.

-- 
 \   "I always wanted to be somebody. I see now that I should have |
  `\  been more specific."  -- Lily Tomlin |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: "indexed properties"...

2008-05-15 Thread Gabriel Genellina
En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich  
<[EMAIL PROTECTED]> escribió:



Having a hard time phrasing this in the form
of a question...

The other day I saw a thread where someone asked
about overrideable properties and nobody offered
the advice that properties are Bad. So maybe we've
got over that. I suppose properties could have
Bad consequences if a user doesn't know they exist
and think that a certain property of an object is
just an ordinary attribute. But that applies to
almost any aspect of any language.

If a person comes from, say, Object Pascal (Delphi)
then properties are hard to live without. The
other day I decided I wanted what OP calls an
"indexed property" or "array property". Couldn't
figure out how to make a _property_ behave that way.
So I read a little bit about descriptors, and a
few minutes later I had an indexedproperty thing
that works just like property, except it gives
an indexed property! This is just too cool.

Why? For example, a Matrix should have a row[n]
property allowing things like

m.row[0] = m.row[1] + m.row[2]

Ok, you could do _that_ by just making row
an ordinary list of Row objects. But then
you'd have to say

m.row[0] = Row([1,2,3])

where I want to be able to say

m.row[0] = [1,2,3]

and have the Row created automatically.

_Also_ with these indexed properties my Matrix
can have m.row[j] and m.col[k] that look exactly
the same to a client - we don't want to store a
list of rows internally and also store the same
data in a list of columns. Too cool.

Hmm, none of that's a valid excuse for a post here.
Um, right, here we go: Anyone see problems or
possible improvements with the implementation
of indexedproperty below?

"""indexed.py: "indexedproperty" works more or less
like "property" except it gives what in Object Pascal
would be an "indexed property". See the
__name__="__main__" section below for a demo

"""

class WriteOnlyIP(Exception):
  def __str__(self):
return """

indexed property is write-only

"""

class ReadOnlyIP(Exception):
  def __str__(self):
return """

indexed property is read-only

"""

class indexedproperty(object):
  def __init__(self, getitem=None, setitem=None):
self.getitem = getitem
self.setitem = setitem

  def __get__(self, obj, owner):
self.obj = obj
return self

  def __getitem__(self, index):
if self.getitem:
  return self.getitem(self.obj, index)
else:
  raise WriteOnlyIP

  def __setitem__(self, index, value):
if self.setitem:
  self.setitem(self.obj, index, value)
else:
  raise ReadOnlyIP


if __name__ == "__main__":

  class AClass(object):
def __init__(self):
  self.cells = [[0,0], [0,0]]

def SetCell(self, (row, col), value):
  self.cells[row][col] = value

def GetCell(self, (row, col)):
  return self.cells[row][col]

cell = indexedproperty(GetCell, SetCell)

  C = AClass()
  for row in range(2):
for col in range(2):
  C.cell[row, col] = "row: %s, col: %s" % (row, col)

  for row in range(2):
for col in range(2):
  print C.cell[row, col]

  C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0]

  print "After  C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0]:"

  for row in range(2):
for col in range(2):
  print C.cell[row, col]





--
Gabriel Genellina

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


Re: python newbie: some surprises

2008-05-15 Thread Kees Bakker
Gabriel Genellina wrote:

> En Fri, 09 May 2008 10:37:30 -0300, v4vijayakumar <[EMAIL PROTECTED]> 
> escribió:
> 
>> On May 9, 1:48 pm, Bruno Desthuilliers > [EMAIL PROTECTED]> wrote:
>>> v4vijayakumar a écrit :
>>>
>>> > When I started coding in python, these two things surprised me.
>>>
>>> > 1. my code is inconsistently indented with the combination of tabs and
>>> > spaces. Even lines looked intended, but it is not.
>>>
>>> Then you have a problem with your code editor - not with Python.
>>>
>>
>> Editors can not be wrong. :)
>>
>> I think there should be some way to say python compiler, to consider
>> tab and two blank spaces equal, when tab space = 2.
> 
> It already considers tab = 8 spaces, and when invoked with -tt it rejects 
> mixed tabs+spaces. (I would like Python rejected *any* tab used for 
> indenting...)
> There is a tool 'reindent.py' -somewhere on your Python install-, and an 
> indentation checker 'tabnanny.py' (this one in the standard library).
> 

That's one of the reasons why I like Python :-)

Still too many people don't know that you must set a TAB to 8 in
your editor. Anything other than 8 for a TAB will, at some point,
confuse somebody.

Don't confuse indentation with TAB setting.

Many editors are not helpfull either. Pydev, for example, has a setting
for TAB, but it is used for indentation. It is just luck (I think) that
pydev has an option to say that you only want spaces. (Take a look at
the main preferences of Pydev.)

So far, I have seen only one editor that understands the difference between
TABs and indentation, and that is Emacs.
-- 
Kees

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


Re: create window on panel

2008-05-15 Thread Jimmy
On May 15, 5:54 pm, Laszlo Nagy <[EMAIL PROTECTED]> wrote:
> Jimmy wrote:
> > Hi, all
>
> > I have been trying to use wxPython to design a GUI that will be
> > displayed on the panel on the top of desktop. that is when the
> > program starts, it will dwell on the panel to display some dynamic
> > information.
>
> > can anyone tell me in wxPython how to do this? thanks!
>
> AFAIK it cannot be done in pure wxPython. The reason is that your
> "panel" is part of the window manager. What kind of "panel" are you
> talking about anyway? Under Microsoft Windows it is called "the tray".
> In Gnome it is "panel" indeed. In KDE it might also be panel, there is
> OS X etc. They are quite different. For example, under MS Windows you
> cannot embed an application into the tray (other than an icon).
>
> They are all different window managers, based on different client libs
> (MS gui, GTK, Qt etc.). wxPython is designed to be platform independent,
> and  it does not support special, platform dependent features. (Well it
> does a few...)
>
> You need to tell us what kind of system are you using? Then we can tell
> you where to start. For example, there are extension modules for writing
> Gnome panel applications. (Well, it is not wxPython but GTK.)
>
> BTW the idea is good: we could have "panel" support in wxPython, but
> since the interface of these panels (and how they should be programmed)
> is very different on different platforms, it would not be easy to implement.
>
>Laszlo

Thanks for your reply!

I am using Linux+gnome. Actually, what I want is simply a text-region
on the panel
and display some dynamic information on it. Is it hard to do it ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: List behaviour

2008-05-15 Thread A.T.Hofkamp
On 2008-05-15, Gabriel <[EMAIL PROTECTED]> wrote:
> Hi all
>
> Just wondering if someone could clarify this behaviour for me, please?
>
 tasks = [[]]*6
 tasks
> [[], [], [], [], [], []]
 tasks[0].append(1)
 tasks
> [[1], [1], [1], [1], [1], [1]]
>
> Well what I was expecting to end up with was something like:
> ?>>> tasks
> [[1], [], [], [], [], []]
>
>
> I got this example from page 38 of Beginning Python.

This is a more complicated case of

a = []
b = a

a.append(1)
print b  # Will print "[1]"

This is the case, because both a and b refer to the same list data-value.


In your case, basically what you are doing is

a = []  # a is an empty list (introduced for easier explanation)
tasks = [a] # tasks is a list with 1 'a'
tasks = tasks*6 # you create 5 additional references to 'a' in 'tasks

ie tasks is now the equivalent of [a, a, a, a, a, a]. It refers to the same 'a'
list 6 times. When you print 'tasks', you actually print the same 'a' value 6
times.


in particular, tasks is **NOT**

a,b,c,d,e,f = [], [], [], [], [], []  # create 6 different empty list values
tasks2 = [a, b, c, d, e, f]

although when you print both tasks, you won't see the difference.


Next, 'tasks[0]' refers to the first list element, that is, value 'a'. To that
list you append an element. In other words, you do "a.append(1)".

However, since tasks has 6 references to the same list 'a', all its members
appear to be changed (but you are really displaying the same value 6 times).


You can query this equality with 'is':

print tasks[0] is tasks[1]  # will print 'True'
print tasks2[0] is tasks2[1]  # Will print 'False'


Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: python newbie: some surprises

2008-05-15 Thread Marco Mariani

Kees Bakker wrote:



So far, I have seen only one editor that understands the difference between
TABs and indentation, and that is Emacs.


Oh, well... in .vimrc:

autocmd FileType python set tabstop=8
autocmd FileType python set softtabstop=4
autocmd FileType python set expandtab

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


Re: List behaviour

2008-05-15 Thread Gabriel
Bruno Desthuilliers  websiteburo.invalid> writes:


> The problem here is that your first statement
> 
> #>>> tasks = [[]]*6
> 
> creates a list (task) containing 6 references to the *same* (empty) list 
> object. You can check this easily using the identity test operator 'is':
> 

> If you want 6 different list objects in tasks, you can use a list 
> comprehension instead:
> 
> #>>> tasks = [[] for i in range(6)]
> #>>> tasks
> [[], [], [], [], [], []]
> #>>> tasks[0].append(1)
> #>>> tasks
> [[1], [], [], [], [], []]
> 
> HTH
> --
> http://mail.python.org/mailman/listinfo/python-list

Hi Bruno

Thanks for clearing that up. Your example certainly works well, I will study
list comprehension a little more.

Many thanks

Gabriel




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


Re: named tuple mutability

2008-05-15 Thread Bruno Desthuilliers

Ben Finney a écrit :

Bruno Desthuilliers <[EMAIL PROTECTED]> writes:


May we agree to disagree here - unless we don't ?


Absolutely not, except where not applicable.



and vice versa.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python newbie: some surprises

2008-05-15 Thread tinnews
Kees Bakker <[EMAIL PROTECTED]> wrote:
> 
> So far, I have seen only one editor that understands the difference between
> TABs and indentation, and that is Emacs.

Most vi clones (and the original vi) do too!  :-)

E.g. in the clone I use (vile) there are independent settings for
tabstop and shiftwidth.  In addition you can tell the editor to change
tabs to spaces (or not) as you wish.

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


Re: List behaviour

2008-05-15 Thread Bruno Desthuilliers

Gabriel a écrit :

Hi all

Just wondering if someone could clarify this behaviour for me, please?


tasks = [[]]*6
tasks

[[], [], [], [], [], []]

tasks[0].append(1)
tasks

[[1], [1], [1], [1], [1], [1]]

Well what I was expecting to end up with was something like:
>>> tasks
[[1], [], [], [], [], []]


The problem here is that your first statement

#>>> tasks = [[]]*6

creates a list (task) containing 6 references to the *same* (empty) list 
object. You can check this easily using the identity test operator 'is':


#>>> tasks[0] is tasks[1]
True


In fact, it's exactly as if you had written:

#>>> task = []
#>>> tasks = []
#>>> for i in range(6):
#... tasks.append(task)
#...

If you want 6 different list objects in tasks, you can use a list 
comprehension instead:


#>>> tasks = [[] for i in range(6)]
#>>> tasks
[[], [], [], [], [], []]
#>>> tasks[0].append(1)
#>>> tasks
[[1], [], [], [], [], []]

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

Re: How to subclass file

2008-05-15 Thread Gabriel Genellina
En Wed, 14 May 2008 21:23:26 -0300, Yves Dorfsman <[EMAIL PROTECTED]>  
escribió:


I want to create a subclass of 'file' but need to open the file with  
os.open
(because I want to open it in exclusive mode), and need an additional  
method.


Because I need an additional method, I truly need a object of my sublass.
If I do something like

class myFile(file):

  def __new__(cls, filename):
import os
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
   return os.fdoen(fd, 'w')

  def myMethod(self):
do_something


then x = myFile('somefilename') is of type file, not myFile, and  
therefore

does not have myMethod as a valid method.


Use delegation instead of inheritance.

from __future__ import with_statement
import os

class myFile(object):
__slots__ = ['_file']

def __init__(self, filename):
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
f = os.fdopen(fd, 'w')
object.__setattr__(self, '_file', f)

def __getattr__(self, name):
return getattr(self._file, name)

def __setattr__(self, name, value):
setattr(self._file, name, value)

def mymethod(self):
print "anything"



py> regular_file = open(r"c:\\temp\\regular.txt", "wt")
py> special_file = myFile(r"c:\\temp\\special.txt")
py> print regular_file

py> print special_file
<__main__.myFile object at 0x00A3D1D0>
py> print dir(regular_file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__',  
'__getattribute
__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__',  
'__reduce_ex__
', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding',  
'fileno'
, 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read',  
'readinto', 're
adline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write',  
'writeli

nes', 'xreadlines']
py> print dir(special_file)
['__class__', '__delattr__', '__doc__', '__getattr__', '__getattribute__',  
'__ha
sh__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',  
'__re

pr__', '__setattr__', '__slots__', '__str__', '_file', 'mymethod']
py> with special_file:
...   special_file.write("hello\n")
...   special_file.mymethod()
...
anything
py> print "closed?", special_file.closed
closed? True


(note that __enter__/__exit__ -used by the with statement- work fine, even  
if not listed by dir(); also the "closed" attribute exists and is set  
correctly)


Note also that myFile is *not* a subclass of file:

py> isinstance(special_file, file)
False

but it has all methods and attributes of file objects, even if  
dir(special_files) doesn't list them. Duck typing in action - typical  
Python code should work fine with this myFile object instead of a true  
file object, but if you actually need a file subclass, I think you'll have  
to write a C extension.


--
Gabriel Genellina

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


Re: List behaviour

2008-05-15 Thread bockman
On 15 Mag, 12:08, Gabriel <[EMAIL PROTECTED]> wrote:
> Hi all
>
> Just wondering if someone could clarify this behaviour for me, please?
>
> >>> tasks = [[]]*6
> >>> tasks
>
> [[], [], [], [], [], []]>>> tasks[0].append(1)
> >>> tasks
>
> [[1], [1], [1], [1], [1], [1]]
>
> Well what I was expecting to end up with was something like:
> >>> tasks
> [[1], [], [], [], [], []]
>
> I got this example from page 38 of Beginning Python.
>
> Regards
>
> Gabriel

The reason is that
tasks = [[]]*6
creates a list with six elements pointing to *the same* list, so when
you change one,
it shows six times.

In other words, your code is equivalent to this:
>>> a = []
>>> tasks = [a,a,a,a,a,a]
>>> a.append(1)
>>> tasks
[[1], [1], [1], [1], [1], [1]]


Insead, to create a list of lists, use the list comprehension:

>>> tasks = [ [] for x in xrange(6) ]
>>> tasks[0].append(1)
>>> tasks
[[1], [], [], [], [], []]
>>>

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

Re: List behaviour

2008-05-15 Thread Gabriel
Diez B. Roggisch  nospam.web.de> writes:

> So instead of creating a list of list by the *-operator that only multiplies
> the references (which is fine immutable objects like strings or numbers),
> you need to explicitly create new lists, e.g. with a list-comprehension:
> 
> tasks = [[] for _ in xrange(6)]
> 
> Try this and everything will work as expected.
> 

Thanks, Diez.

Thanks to all who replied to help me with this :)

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


Re: List behaviour

2008-05-15 Thread Gabriel
  virgilio.it> writes:

> >>> tasks = [ [] for x in xrange(6) ]
> >>> tasks[0].append(1)
> >>> tasks
> [[1], [], [], [], [], []]
> >>>
> 

Thanks, Bockman


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


List behaviour

2008-05-15 Thread Gabriel
Hi all

Just wondering if someone could clarify this behaviour for me, please?

>>> tasks = [[]]*6
>>> tasks
[[], [], [], [], [], []]
>>> tasks[0].append(1)
>>> tasks
[[1], [1], [1], [1], [1], [1]]

Well what I was expecting to end up with was something like:
>>> tasks
[[1], [], [], [], [], []]


I got this example from page 38 of Beginning Python.

Regards

Gabriel



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

Re: List behaviour

2008-05-15 Thread Diez B. Roggisch
Gabriel wrote:

> Hi all
> 
> Just wondering if someone could clarify this behaviour for me, please?
> 
 tasks = [[]]*6
 tasks
> [[], [], [], [], [], []]
 tasks[0].append(1)
 tasks
> [[1], [1], [1], [1], [1], [1]]
> 
> Well what I was expecting to end up with was something like:
> >>> tasks
> [[1], [], [], [], [], []]
> 
> 
> I got this example from page 38 of Beginning Python.

The "problem" is that all the lists inside the outer list are the same
list - you can check that with 

id(tasks[0]) == id(tasks[1])

So instead of creating a list of list by the *-operator that only multiplies
the references (which is fine immutable objects like strings or numbers),
you need to explicitly create new lists, e.g. with a list-comprehension:

tasks = [[] for _ in xrange(6)]

Try this and everything will work as expected.

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

Re: Class Methods Vs Any Other Callable

2008-05-15 Thread Arnaud Delobelle


[EMAIL PROTECTED] wrote:
> On 14 mai, 22:44, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > > On 14 mai, 19:45, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> > >> __new__ is a static method!
> >
> > > __new__ is a special-cased staticmethod that  1/ must not be declared
> > > as such and 2/ takes the class object as first args. As far as I'm
> > > concerned, it's semantically a classmethod.
> >
> > It's a static method!
>

OK then let me reply pedantically:

> Sorry Arnaud, I probably didn't made it clear enough : I do know it is
> a staticmethod object. What I say is that
> 1/ it's special-cased since you don't *explicitely* declare it as a
> staticmethod

In some cases you have to:

class Foo(object): pass

# Later on I want to redefine Foo.__new__

@staticmethod
def Foo__new__(cls):
print "new Foo!"
return object.__new__(cls)

Foo.__new__ = Foo__new__

>>> Foo()
New Foo!
>>> # Without the @staticmethod we would get a TypeError

> 2/ it behaves just like a classmethod, since it takes the class as
> first argument.

When you invoke it implicitely maybe, but not when you do so
explicitely! Look at my example below:  to create my Foo object, I
have to write

object.__new__(Foo)

> IOW, I'm talking about semantic, not implementation.

I understand what you mean, and from that point of view you can argue
against my example above (after all, my example is code, not pure
concept) but for me it is simpler to think of __new__ as a
staticmethod (which it is!), plain and simple.

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


Re: Running an interactive interpreter inside a python

2008-05-15 Thread R. Bernstein
"Alan J. Salmoni" <[EMAIL PROTECTED]> writes:
> I'm not sure if this is exactly what you're after, but try looking
> into the 'code' module.
>
> It's fairly easy to make an interactive interpreter that runs within
> your program. If you import your programs variables into
> __main__.__dict__, you can have access to them which can be funky. You
> can even override the showtraceback method to catch various exceptions
> and do daft things like adding new methods to strings. I guess it
> would even be possible to have the commands compared to a list of
> commands and keywords to build a restricted interpreter, though how
> secure this would be against a determined attack is another matter.
>
> Alan

I think this (largely) does the trick. Thanks!

I'm not sure about how to deal with globals yet which should come from
a stackframe f_globals. It might be possible to save and restore
__main__.__dict__ before and after the call to interact(). Probably
would have been cooler to design interact() to take a globals
parameter, same as eval does.


>
> On May 15, 11:31 am, [EMAIL PROTECTED] (R. Bernstein) wrote:
>> The next release of pydb will have the ability to go into ipython from
>> inside the debugger. Sort of like how in ruby-debug you can go into
>> irb :-)
>>
>> For ipython, this can be done pretty simply; there is an IPShellEmbed
>> method which returns something you can call. But how could one do the
>> same for the stock python interactive shell?
>>
>> To take this out of the realm of debugging. What you want to do is to
>> write a python program that goes into the python interactive shell -
>> without having to write your own a read/eval loop and deal with
>> readline, continuation lines, etc.
>>
>> The solution should also allow
>>  - variables/methods in the calling PYthon program to be visible
>>in the shell
>>  - variables set in the interactive (sub) shell should persist after the 
>> shell
>>terminates, although this is a weaker requirement. POSIX subshells
>>for example *don't* work this way.
>>
>> There has been much written about how to embed Python from C, so I
>> suppose this may offer one way. And at worst, I could write
>> a C extension which follows how C Python does this for itself.
>>
>> But is there a simpler way?
>>
>> Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: create window on panel

2008-05-15 Thread Laszlo Nagy



Thanks for your reply!

I am using Linux+gnome. Actually, what I want is simply a text-region
on the panel
and display some dynamic information on it. Is it hard to do it ?
  
Google is your friend! I searched for "gnome python panel" and the first 
hit was:



http://www.onlamp.com/pub/a/python/2000/07/25/gnome_applet.html

:-)

Of course it is out of date but you can see that there is something 
called "/PyGNOME".

/
The package names on my Linux:

python-gnome2 python-gnome2-desktop python-gnome2-extras python-gnomecanvas

Description:

Python bindings for the GNOME desktop environment
This archive contains modules that allow you to write GNOME programs
in Python. This package contains the bindings for the new version 2.0
of that desktop environment.

URL: http://www.daa.com.au/~james/software/pygtk/
/
/It should be easy to read the docs, view the demo programs and create 
your own program.


L

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


Greetings

2008-05-15 Thread castironpi
Hail, Earthlings,

I have an easy request to take over the newsgroup ("Taking Over the
Newsgroup", "TOTN").  May I?

Pros:
  Lifetime benefits
  Google product
  Talking
Cons:
  World domination
  No crossing
  Social aspect*

Read the fine print:

*Social: Subscribers to TOTN may come talking, telling jokes, and
laughing loudly.  Neighbors subject to smiling.  Vikings prone to
capitalize.

Settings include autovoltic, board, and charm.  Dimensions include 4.
Restrictions apply.  States may vary.  Void where prohibited.  People
include the living.  Times include eternity.  Toys include Legos.

Assume screen is two-dimensions and audio stereo; what are building
Legos?  Assume digital.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Nasty gotcha/bug in heapq.nlargest/nsmallest

2008-05-15 Thread George Sakkis
On May 15, 3:06 am, Peter Otten <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
> > I spent several hours debugging some bogus data results that turned
> > out to be caused by the fact that heapq.nlargest doesn't respect rich
> > comparisons:
>
> > import heapq
> > import random
>
> > class X(object):
> > def __init__(self, x): self.x=x
> > def __repr__(self): return 'X(%s)' % self.x
> > if True:
> > # this succeeds
> > def __cmp__(self, other): return cmp(self.x , other.x)
> > else:
> > # this fails
> > def __lt__(self, other): return self.x < other.x
>
> > s = [X(i) for i in range(10)]
> > random.shuffle(s)
>
> > s1 = heapq.nlargest(5, s)
> > s2 = sorted(s, reverse=True)[:5]
> > assert s1 == s2, (s,s1,s2)
>
> > s1 = heapq.nsmallest(5, s)
> > s2 = sorted(s)[:5]
> > assert s1 == s2, (s,s1,s2)
>
> > According to the docs, nlargest is equivalent to: "sorted(iterable,
> > key=key, reverse=True)[:n]" and similarly for nsmallest. So that must
> > be at least a documentation bug, if not an implementation one.
>
> Implementing a subset of the rich comparisons is always dangerous. According
> to my ad hoc test you need <, <=, and == for nlargest()/nsmallest() to
> work:
>
> import heapq
> import random
>
> used_rich = set()
>
> class X(object):
> def __init__(self, x): self.x=x
> def __repr__(self): return 'X(%s)' % self.x
> def __lt__(self, other):
> used_rich.add("lt")
> return self.x < other.x
> def __eq__(self, other):
> used_rich.add("eq")
> return self.x == other.x
> def __gt__(self, other):
> used_rich.add("gt")
> return self.x > other.x
> def __ge__(self, other):
> used_rich.add("ge")
> return self.x >= other.x
> def __ne__(self, other):
> used_rich.add("ne")
> return self.x != other.x
> def __le__(self, other):
> used_rich.add("le")
> return self.x <= other.x
>
> s = [X(8), X(0), X(3), X(4), X(5), X(2), X(1), X(6), X(7), X(9)]
>
> smallest = sorted(s)[:5]
> largest = sorted(s, reverse=True)[:5]
>
> print "used by sorted:", used_rich
> used_rich = set()
>
> for i in range(1):
>
> s1 = heapq.nlargest(5, s)
> assert s1 == largest, (s, s1, largest)
>
> s1 = heapq.nsmallest(5, s)
> assert s1 == smallest, (s, s1, smallest)
>
> random.shuffle(s)
>
> print "used by nlargest/nsmallest:", used_rich
>
> Output:
> used by sorted: set(['lt'])
> used by nlargest/nsmallest: set(['lt', 'le', 'eq'])

Interesting, I don't get 'eq' on one box ("2.5 (r25:51908, Sep 19
2006, 09:52:17) [MSC v.1310 32 bit (Intel)]") but I get it on another
("2.5.1 (r251:54863, May  9 2007, 15:27:54) [GCC 3.3.5 (Debian
1:3.3.5-13)]").

A more interesting question is how many (and which) of the rich
comparisons can you omit while maintaining correctness (see script
below). The results on my v2.5 on Windows are:

1. Use ('lt', 'le') if both present
2. If only 'lt' is missing use ('le', 'gt')
3. If only 'le' is missing use ('lt', 'ge')
4. If both ('lt', 'le') are missing use  ('gt', 'ge')
5. If 3 or more of ('lt', 'le', 'gt', 'ge') are missing use the
remaining one (if any) plus 'cmp'
6. If (5) holds and there is no 'cmp', nlargest/nsmaller are WRONG

The results on the v2.5.1 debian box are the same, with the addition
of 'eq' in all steps; if 'eq' is not present, 'cmp' is called, and if
neither 'cmp' is present, the results are still correct (provided any
of the cases 1-4 above hold of course). IOW, it does some extra
equality checks if it can, but these are optional since it can be
correct without them.

For sorted(), the results are identical on both boxes:
  - Use only 'lt' if present else
  - Use only 'gt' if present else
  - Use only 'cmp' if present else
  - WRONG RESULTS
IOW, no attempt to use 'le','ge','eq','ne' is made.

I wonder how stable is this behavior across different versions and
implementations (Jython, IronPython, etc).

George


 testing script ==

import heapq
from random import shuffle

used = set(); add = used.add

class X(object):
def __init__(self, x): self.x=x
def __repr__(self): return 'X(%s)' % self.x

# try to remove one or more of these included in a used set
# and see what happens
def __gt__(self, other): add('gt'); return self.x > other.x
def __ge__(self, other): add('ge'); return self.x >= other.x
def __lt__(self, other): add('lt'); return self.x < other.x
def __le__(self, other): add('le'); return self.x <= other.x
def __eq__(self, other): add('eq'); return self.x == other.x
def __ne__(self, other): add('ne'); return self.x != other.x
def __cmp__(self, other): add('cmp'); return cmp(self.x, other.x)


if __name__ == '__main__':
check_heapq = True
n = 1000
s = [X(8), X(0), X(3), X(4), X(5), X(2), X(1), X(6), X(7), X(9)]
used.clear()
if check_he

Re: ?

2008-05-15 Thread Geoffrey Clements
"urikaluzhny" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On May 15, 10:06 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "urikaluzhny" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | It seems that I rather frequently need a list or iterator of the form
> | [x for x in <> while <>]
>
> I can think of two ways to interpret that.
>> I mean like [x for x in  if ], only that it breaks the loop when
>> the expression  is false.

def gen(a):
for x in a:
if B: break
yield x

a_gen = gen(A)

# now iterate over a_gen

-- 
Geoff 


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


datamining .txt-files, library?

2008-05-15 Thread globalrev
i have a big collection of .txt files that i want to open and parse to
extract information.

is there a library for this or maybe even built in?
--
http://mail.python.org/mailman/listinfo/python-list


Re: datamining .txt-files, library?

2008-05-15 Thread Chris
On May 15, 2:27 pm, globalrev <[EMAIL PROTECTED]> wrote:
> i have a big collection of .txt files that i want to open and parse to
> extract information.
>
> is there a library for this or maybe even built in?

os.open to open the files and iterate through it and built in string
functions to parse it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: datamining .txt-files, library?

2008-05-15 Thread George Sakkis
On May 15, 8:27 am, globalrev <[EMAIL PROTECTED]> wrote:
> i have a big collection of .txt files that i want to open and parse to
> extract information.
>
> is there a library for this or maybe even built in?

This has a lot to do with how well-structured are your files and what
kind of information you hope to extract (shallow or deep). NLTK might
be a good starting point: http://nltk.sourceforge.net/

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


how to send files via bluetoot

2008-05-15 Thread sayang-87

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


basic comparing files

2008-05-15 Thread Beema shafreen
hi all,

I have a very basic doubt

I am comparing two files A and B
which has three columns a1, b1 of A and a2, b2
say for example if need to compare a1 with a2 and if there are common i have
display a1, b1, b2
or else i have to display a1 , b1 or a1, b2

is the set function going to be the best option or is there any other way



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

Re: datamining .txt-files, library?

2008-05-15 Thread globalrev
On 15 Maj, 14:40, George Sakkis <[EMAIL PROTECTED]> wrote:
> On May 15, 8:27 am, globalrev <[EMAIL PROTECTED]> wrote:
>
> > i have a big collection of .txt files that i want to open and parse to
> > extract information.
>
> > is there a library for this or maybe even built in?
>
> This has a lot to do with how well-structured are your files and what
> kind of information you hope to extract (shallow or deep). NLTK might
> be a good starting point:http://nltk.sourceforge.net/
>
> George

superstructured, 10K+files, all look the same.
--
http://mail.python.org/mailman/listinfo/python-list


no inputstream?

2008-05-15 Thread max
hey folks,

coming from java, new to python.  i'm trying to port a java app to
python that writes an inputstream to a buffer, then parses the buffer
(specifically, i'm getting ID3 tags from mp3s online).  i understand
that this java approach to the task may not apply to python, but i'm
having trouble finding a working approach in python.

i currently have locations of the mp3s in question as strings, which
works for parsing local files, but gives me a "No such file or
directory" error when it tries to process URLs.  it seems terribly
inefficient to download each mp3 just to get at that small tag data,
and i assume there's a way to do this with file() or open() or
something, i just can't get it to work.

anyone know how i can fix this?  thanks in advance for any help!

best,
max



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


Re: create window on panel

2008-05-15 Thread Jimmy
On May 15, 7:45 pm, Laszlo Nagy <[EMAIL PROTECTED]> wrote:
> > Thanks for your reply!
>
> > I am using Linux+gnome. Actually, what I want is simply a text-region
> > on the panel
> > and display some dynamic information on it. Is it hard to do it ?
>
> Google is your friend! I searched for "gnome python panel" and the first
> hit was:
>
> http://www.onlamp.com/pub/a/python/2000/07/25/gnome_applet.html
>
> :-)
>
> Of course it is out of date but you can see that there is something
> called "/PyGNOME".
> /
> The package names on my Linux:
>
> python-gnome2 python-gnome2-desktop python-gnome2-extras python-gnomecanvas
>
> Description:
>
> Python bindings for the GNOME desktop environment
> This archive contains modules that allow you to write GNOME programs
> in Python. This package contains the bindings for the new version 2.0
> of that desktop environment.
>
> URL:http://www.daa.com.au/~james/software/pygtk/
> /
> /It should be easy to read the docs, view the demo programs and create
> your own program.
>
> L

thanks~ it seems attractive, however, I did not find much useful
information :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: datamining .txt-files, library?

2008-05-15 Thread Ville M. Vainio
Chris <[EMAIL PROTECTED]> writes:

> On May 15, 2:27 pm, globalrev <[EMAIL PROTECTED]> wrote:

>> i have a big collection of .txt files that i want to open and parse to
>> extract information.
>>
>> is there a library for this or maybe even built in?
>
> os.open to open the files and iterate through it and built in string
> functions to parse it.

Or more probably, regular expression library "re".
--
http://mail.python.org/mailman/listinfo/python-list


send yield

2008-05-15 Thread castironpi
Why can't I write this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread Marc 'BlackJack' Rintsch
On Thu, 15 May 2008 06:08:35 -0700, max wrote:

> i currently have locations of the mp3s in question as strings, which
> works for parsing local files, but gives me a "No such file or
> directory" error when it tries to process URLs.  it seems terribly
> inefficient to download each mp3 just to get at that small tag data,
> and i assume there's a way to do this with file() or open() or
> something, i just can't get it to work.

You can use `urllib2.urlopen()` to open URLs as files.  But if you deal
with ID3 V1 tags you'll have to download the file anyway because those are
in the last 128 bytes of an MP3 file.

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


Re: no inputstream?

2008-05-15 Thread castironpi
On May 15, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 15 May 2008 06:08:35 -0700, max wrote:
> > i currently have locations of the mp3s in question as strings, which
> > works for parsing local files, but gives me a "No such file or
> > directory" error when it tries to process URLs.  it seems terribly
> > inefficient to download each mp3 just to get at that small tag data,
> > and i assume there's a way to do this with file() or open() or
> > something, i just can't get it to work.
>
> You can use `urllib2.urlopen()` to open URLs as files.  But if you deal
> with ID3 V1 tags you'll have to download the file anyway because those are
> in the last 128 bytes of an MP3 file.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Just don't import time.  What would you do with an autolocking timer,
such as time.sleep( ) on a thread?  I am tongue tied in the presence
of a lady.
--
http://mail.python.org/mailman/listinfo/python-list


Re: create window on panel

2008-05-15 Thread Laszlo Nagy



URL:http://www.daa.com.au/~james/software/pygtk/
/
/It should be easy to read the docs, view the demo programs and create
your own program.

L



thanks~ it seems attractive, however, I did not find much useful
information :(
  

http://www.pygtk.org/ -- full docs
http://packages.ubuntu.com/dapper/doc/python-gtk2-tutorial -- This seems 
to be a tutorial for python-gnome2.


Let me know if it doesn't help.

L


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


Re: "indexed properties"...

2008-05-15 Thread Gabriel Genellina
En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich <[EMAIL PROTECTED]> 
escribió:

> Having a hard time phrasing this in the form
> of a question...
>
> The other day I saw a thread where someone asked
> about overrideable properties and nobody offered
> the advice that properties are Bad. So maybe we've
> got over that. I suppose properties could have
> Bad consequences if a user doesn't know they exist
> and think that a certain property of an object is
> just an ordinary attribute. But that applies to
> almost any aspect of any language.

Which "bad consequences" are you thinking of? Apart from the user not being 
aware of the complexity of certain operations, or a getter/setter very 
time-consuming (in that case I'd use public getXXX/setXXX functions instead, to 
emphasize that "something" is happening, not just an attribute lookup)

> If a person comes from, say, Object Pascal (Delphi)
> then properties are hard to live without. The

You should read the article "Python is not Java" if you haven't done it yet.
http://dirtsimple.org/2004/12/python-is-not-java.html

> other day I decided I wanted what OP calls an
> "indexed property" or "array property". Couldn't
> figure out how to make a _property_ behave that way.
> So I read a little bit about descriptors, and a
> few minutes later I had an indexedproperty thing
> that works just like property, except it gives
> an indexed property! This is just too cool.
>
> Why? For example, a Matrix should have a row[n]
> property allowing things like
>
> m.row[0] = m.row[1] + m.row[2]
>
> Ok, you could do _that_ by just making row
> an ordinary list of Row objects. But then
> you'd have to say
>
> m.row[0] = Row([1,2,3])
>
> where I want to be able to say
>
> m.row[0] = [1,2,3]
>
> and have the Row created automatically.

One could make *row* an object with a custom __getitem__/__setitem__ in this 
case. But I prefer to have as little magic as possible on my objects: if it 
says m.row[0] = [1,2,3] I expect m.row[0] to actually *be* that list (whenever 
possible), and not any other object initialized from the [1,2,3] arguments. 
(Maybe this is some overreaction against C++ "magic" constructors and such 
horrible things...)

> _Also_ with these indexed properties my Matrix
> can have m.row[j] and m.col[k] that look exactly
> the same to a client - we don't want to store a
> list of rows internally and also store the same
> data in a list of columns. Too cool.

The same can be achieved having m.row and m.col be custom objects like I said 
above.

> Hmm, none of that's a valid excuse for a post here.
> Um, right, here we go: Anyone see problems or
> possible improvements with the implementation
> of indexedproperty below?

Note that the property object (or your indexedproperty) is a *class* attribute. 
That is, shared among all instances.

> class indexedproperty(object):
>   def __init__(self, getitem=None, setitem=None):
> self.getitem = getitem
> self.setitem = setitem
>
>   def __get__(self, obj, owner):
> self.obj = obj
> return self

Here is the problem. You can't store "obj" in "self" because it is shared among 
all instances. Your examples don't show any problem because all property 
accesses are immediately followed by a getitem access using the same object. 
Try this:

x = AClass()
y = AClass()
x.cell[0,0] = 1
print x.cell[1,1]   # output: 0
y.cell[x.cell[0,0], x.cell[0,0]] = 2
print y.cell[1,1]   # should be 2, still 0
print x.cell[1,1]   # should still be 0, but changed, now 2

A workaround would be to return another object in __get__ instead of self, 
which remembers the "obj" instance, or a closure, or...
But I don't really see the point, it's a lot easier to use another object for 
.cell (it's more clear, doesn't break encapsulation, divides 
responsabilities...)

class Matrix2x2(object):
   def __init__(self):
 self.cells = [[0,0], [0,0]]

   def __setitem__(self, (row, col), value):
 self.cells[row][col] = value

   def __getitem__(self, (row, col)):
 return self.cells[row][col]

class AClass(object):
   def __init__(self):
 self.cell = Matrix2x2()


-- 
Gabriel Genellina

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


Re: send yield

2008-05-15 Thread Max Erickson
castironpi <[EMAIL PROTECTED]> wrote:

> Why can't I write this?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Because you don't know how?



max

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


Re: send yield

2008-05-15 Thread castironpi
On May 15, 8:32 am, castironpi <[EMAIL PROTECTED]> wrote:
> Why can't I write this?

It is twice one.  Now: Where's My Volume?
--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread max
On May 15, 9:51 am, castironpi <[EMAIL PROTECTED]> wrote:
> On May 15, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > On Thu, 15 May 2008 06:08:35 -0700, max wrote:
> > > i currently have locations of the mp3s in question as strings, which
> > > works for parsing local files, but gives me a "No such file or
> > > directory" error when it tries to process URLs.  it seems terribly
> > > inefficient to download each mp3 just to get at that small tag data,
> > > and i assume there's a way to do this with file() or open() or
> > > something, i just can't get it to work.
>
> > You can use `urllib2.urlopen()` to open URLs as files.  But if you deal
> > with ID3 V1 tags you'll have to download the file anyway because those are
> > in the last 128 bytes of an MP3 file.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> Just don't import time.  What would you do with an autolocking timer,
> such as time.sleep( ) on a thread?  I am tongue tied in the presence
> of a lady.

thanks guys.  i guess i just figured there'd be a way to get at those
id3 bytes at the end without downloading the whole file.  if java can
do this, seems like i should just stick with that implementation, no?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class Methods Vs Any Other Callable

2008-05-15 Thread Bruno Desthuilliers

Arnaud Delobelle a écrit :


[EMAIL PROTECTED] wrote:

On 14 mai, 22:44, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:

"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

On 14 mai, 19:45, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:

__new__ is a static method!

__new__ is a special-cased staticmethod that  1/ must not be declared
as such and 2/ takes the class object as first args. As far as I'm
concerned, it's semantically a classmethod.

It's a static method!


OK then let me reply pedantically:


Sorry Arnaud, I probably didn't made it clear enough : I do know it is
a staticmethod object. What I say is that
1/ it's special-cased since you don't *explicitely* declare it as a
staticmethod


In some cases you have to:

class Foo(object): pass

# Later on I want to redefine Foo.__new__

@staticmethod
def Foo__new__(cls):
print "new Foo!"
return object.__new__(cls)

Foo.__new__ = Foo__new__


Foo()

New Foo!

# Without the @staticmethod we would get a TypeError


Point taken. But you'll admit that monkeypatching the __new__ method is 
somewhat uncommon !-)


2/ it behaves 



Poor word choice here I'm afraid - of course a staticmethod doesn't 
"behave" like a classmethod object. But you of course __knew__ what I 
meant !-)




just like a classmethod, since it takes the class as
first argument.


When you invoke it implicitely maybe, but not when you do so
explicitely!


I'm not talking about how you invoke it (FWIW, direct invocation of 
__new__ is pretty rare, parent call excepted - and then, well, it mostly 
mirrors a direct parent call within an overridden instance method). It's 
about having __new__ taking the class as first argument.


FWIW, I wonder why the BDFL choosed to implement __new__ as a 
staticmethod - there are probably some pretty good reasons, but not 
knowing them, it looks like __new__ would have been a perfect candidate 
for a classmethod.


So far, the only reason I can think of is that making it a classmethod 
would have required the use of super(Parent, cls) to call the parent's 
class __new__, which may (or may not - never had the case) be 
problematic (any guru on this ?)



IOW, I'm talking about semantic, not implementation.


I understand what you mean, and from that point of view you can argue
against my example above 


It's somehow difficult to argue against something that's just the plain 
and naked truth. My one and only argument is about __new__ being 
semantically close enough to a classmethod to wonder why it isn't one.



(after all, my example is code, not pure
concept) but for me it is simpler to think of __new__ as a
staticmethod (which it is!), plain and simple.


I could by no mean hold it against you !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: send yield

2008-05-15 Thread Bruno Desthuilliers

castironpi a écrit :

Why can't I write this?


Because one or more of the "t", "h", "i", "s" keys are missing from your 
keyboard ?

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


Re: Running an interactive interpreter inside a python

2008-05-15 Thread castironpi
On May 15, 6:26 am, [EMAIL PROTECTED] (R. Bernstein) wrote:
> "Alan J. Salmoni" <[EMAIL PROTECTED]> writes:
>
> > I'm not sure if this is exactly what you're after, but try looking
> > into the 'code' module.
>
> > It's fairly easy to make an interactive interpreter that runs within
> > your program. If you import your programs variables into
> > __main__.__dict__, you can have access to them which can be funky. You
> > can even override the showtraceback method to catch various exceptions
> > and do daft things like adding new methods to strings. I guess it
> > would even be possible to have the commands compared to a list of
> > commands and keywords to build a restricted interpreter, though how
> > secure this would be against a determined attack is another matter.
>
> > Alan
>
> I think this (largely) does the trick. Thanks!
>
> I'm not sure about how to deal with globals yet which should come from
> a stackframe f_globals. It might be possible to save and restore
> __main__.__dict__ before and after the call to interact(). Probably
> would have been cooler to design interact() to take a globals
> parameter, same as eval does.
>
>
>
>
>
> > On May 15, 11:31 am, [EMAIL PROTECTED] (R. Bernstein) wrote:
> >> The next release of pydb will have the ability to go into ipython from
> >> inside the debugger. Sort of like how in ruby-debug you can go into
> >> irb :-)
>
> >> For ipython, this can be done pretty simply; there is an IPShellEmbed
> >> method which returns something you can call. But how could one do the
> >> same for the stock python interactive shell?
>
> >> To take this out of the realm of debugging. What you want to do is to
> >> write a python program that goes into the python interactive shell -
> >> without having to write your own a read/eval loop and deal with
> >> readline, continuation lines, etc.
>
> >> The solution should also allow
> >>  - variables/methods in the calling PYthon program to be visible
> >>    in the shell
> >>  - variables set in the interactive (sub) shell should persist after the 
> >> shell
> >>    terminates, although this is a weaker requirement. POSIX subshells
> >>    for example *don't* work this way.
>
> >> There has been much written about how to embed Python from C, so I
> >> suppose this may offer one way. And at worst, I could write
> >> a C extension which follows how C Python does this for itself.
>
> >> But is there a simpler way?
>
> >> Thanks.- Hide quoted text -
>
> - Show quoted text -

One threat is malicious code; sorry for this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread castironpi
On May 15, 9:02 am, max <[EMAIL PROTECTED]> wrote:
> On May 15, 9:51 am, castironpi <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On May 15, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > > On Thu, 15 May 2008 06:08:35 -0700, max wrote:
> > > > i currently have locations of the mp3s in question as strings, which
> > > > works for parsing local files, but gives me a "No such file or
> > > > directory" error when it tries to process URLs.  it seems terribly
> > > > inefficient to download each mp3 just to get at that small tag data,
> > > > and i assume there's a way to do this with file() or open() or
> > > > something, i just can't get it to work.
>
> > > You can use `urllib2.urlopen()` to open URLs as files.  But if you deal
> > > with ID3 V1 tags you'll have to download the file anyway because those are
> > > in the last 128 bytes of an MP3 file.
>
> > > Ciao,
> > >         Marc 'BlackJack' Rintsch
>
> > Just don't import time.  What would you do with an autolocking timer,
> > such as time.sleep( ) on a thread?  I am tongue tied in the presence
> > of a lady.
>
> thanks guys.  i guess i just figured there'd be a way to get at those
> id3 bytes at the end without downloading the whole file.  if java can
> do this, seems like i should just stick with that implementation, no?- Hide 
> quoted text -
>
> - Show quoted text -

I can post life1 to this: lifeOne, lifeone, lifea perhaps.
--
http://mail.python.org/mailman/listinfo/python-list


Re: send yield

2008-05-15 Thread castironpi
On May 15, 9:04 am, Bruno Desthuilliers  wrote:
> castironpi a écrit :
>
> > Why can't I write this?
>
> Because one or more of the "t", "h", "i", "s" keys are missing from your
> keyboard ?

No; they're all here.
--
http://mail.python.org/mailman/listinfo/python-list


ANN: Pyrex 0.9.8

2008-05-15 Thread greg

Pyrex 0.9.8 is now available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

This version has a number of new features:

* In-place operators (+= etc.) are now supported.

* The Pyrex compiler now has built-in facilities for
  automatically tracking down and compiling all the
  modules a given module depends on, and for only
  compiling modules whose source has changed.

* Some restrictions on nogil functions have been relaxed.
  In particular, it's now possible to declare a C method
  as nogil.

* A feature has been added that makes it easier to manage
  circular imports between .pxd files. It's now possible
  to declare two extension types in different .pxd files
  that refer to each other.

What is Pyrex?
--

Pyrex is a language for writing Python extension modules.
It lets you freely mix operations on Python and C data, with
all Python reference counting and error checking handled
automatically.
--
http://mail.python.org/mailman/listinfo/python-list


Re: send yield

2008-05-15 Thread castironpi
On May 15, 9:07 am, castironpi <[EMAIL PROTECTED]> wrote:
> On May 15, 9:04 am, Bruno Desthuilliers 
> [EMAIL PROTECTED]> wrote:
> > castironpi a écrit :
>
> > > Why can't I write this?
>
> > Because one or more of the "t", "h", "i", "s" keys are missing from your
> > keyboard ?
>
> No; they're all here.

I have

life1= Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 )
--
http://mail.python.org/mailman/listinfo/python-list


Dbase / foxpro files

2008-05-15 Thread Johny
Is there a module for reading/modifing db files from Python?
Thanks for help
B.
--
http://mail.python.org/mailman/listinfo/python-list


Re: send yield

2008-05-15 Thread Dan Upton
On Thu, May 15, 2008 at 9:32 AM, castironpi <[EMAIL PROTECTED]> wrote:
> Why can't I write this?
> --

Because your antecedent is undefined?
--
http://mail.python.org/mailman/listinfo/python-list


Re: datamining .txt-files, library?

2008-05-15 Thread Bruno Desthuilliers

Chris a écrit :

On May 15, 2:27 pm, globalrev <[EMAIL PROTECTED]> wrote:

i have a big collection of .txt files that i want to open and parse to
extract information.

is there a library for this or maybe even built in?


os.open to open the files


What's wrong with (builtin) open ?

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


Re: Dbase / foxpro files

2008-05-15 Thread Peter Otten
Johny wrote:

> Is there a module for reading/modifing db files from Python?

There is a recipe by Raymond Hettinger:

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

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


Re: send yield

2008-05-15 Thread castironpi
On May 15, 9:26 am, "Dan Upton" <[EMAIL PROTECTED]> wrote:
> On Thu, May 15, 2008 at 9:32 AM, castironpi <[EMAIL PROTECTED]> wrote:
> > Why can't I write this?
> > --
>
> Because your antecedent is undefined?

Of the two ways to play, just to say #define this per se would be a
bad move, but that's one that comes from the wrong group.  #define is
a big scary macro, that python hasn't been using; it's the one-line
typo.  Instance:

#define life1 Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 )

Use it to render planes in solids.

Back about 'this', I honestly hadn't remembered 'til this time, when I
got a chance to reread the subject.  Plus I keep ditching my radio.

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


Re: Custom Classes?

2008-05-15 Thread Victor Subervi
Well, you are right. It looks like one of those instances where I fixed
something and did not check to see if it influenced the problem now at hand.
Thanks again.
Victor


On 5/15/08, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>
> En Tue, 13 May 2008 15:10:21 -0300, Victor Subervi <
> [EMAIL PROTECTED]> escribió:
>
> I remember why I had the number with the getpic. It is because I display
>> several of these images on a single page, and apparently I cannot call the
>> same script and get more than one image from an HTML page.
>>
>
> That's not true. If you still have the example I posted a few weeks ago,
> you can use this script to show a full listing of all uploaded pictures.
> It's a small variation of album.py.
> I think you were saving the pictures on disk - DON'T do that. It's
> unnecesary, wastes time and disk space, and if not done properly one request
> interferes with the other.
>
> --
> Gabriel Genellina
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list

pyserial and file open conflict?

2008-05-15 Thread p . wallstedt
Hi all!

I have a small but rather annoying problem with pyserial. I want to
open a file on disk for reading and then open a com-port, write lines
from the file to the port and then read something back and compare it
to the next line in the file. Should be simple. And it is, apart from
the fact that the file seems to be doubled ...? Or it loops through
the file twice.

If I exclude the "import serial" it works.

Any ideas?

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


RE: no inputstream?

2008-05-15 Thread John Krukoff
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of max
> Sent: Thursday, May 15, 2008 8:02 AM
> To: python-list@python.org
> Subject: Re: no inputstream?
> 
> On May 15, 9:51 am, castironpi <[EMAIL PROTECTED]> wrote:
> > On May 15, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> >
> > > On Thu, 15 May 2008 06:08:35 -0700, max wrote:
> > > > i currently have locations of the mp3s in question as strings, which
> > > > works for parsing local files, but gives me a "No such file or
> > > > directory" error when it tries to process URLs.  it seems terribly
> > > > inefficient to download each mp3 just to get at that small tag data,
> > > > and i assume there's a way to do this with file() or open() or
> > > > something, i just can't get it to work.
> >
> > > You can use `urllib2.urlopen()` to open URLs as files.  But if you
> deal
> > > with ID3 V1 tags you'll have to download the file anyway because those
> are
> > > in the last 128 bytes of an MP3 file.
> >
> > > Ciao,
> > >         Marc 'BlackJack' Rintsch
> >
> > Just don't import time.  What would you do with an autolocking timer,
> > such as time.sleep( ) on a thread?  I am tongue tied in the presence
> > of a lady.
> 
> thanks guys.  i guess i just figured there'd be a way to get at those
> id3 bytes at the end without downloading the whole file.  if java can
> do this, seems like i should just stick with that implementation, no?
> --
> http://mail.python.org/mailman/listinfo/python-list

First off, ignore castironpi, it's a turing test failure.

Second, I'm curious as to how Java manages this. I'd think their streams
would have to be pretty magic to pull this off after the HTTP connection has
already been built.

Anyway, as I see it, this is more of a HTTP protocol question. I think what
you need to do is set the HTTP Range header to bytes=-128, see the urllib2
documentation for how. It's not that hard. Only down side is that not all
HTTP servers support the Range header, and it's an optional part of the HTTP
spec anyway. As far as I know it's the only way to get partial transfers,
though.

Also, are you sure you're dealing with v1 tags and not v2? Since v2 tags are
stored at the beginning (or sometimes end with v2.4) of the file. You might
be better off just opening the file with urllib2 and handing it off to
whatever id3 tag reading library you're using. As long as it's reasonably
smart, it should only download the part of the file it needs (which if the
tag happens to be v1, will be the whole file).

I'd love to know how Java handles all that automatically through a generic
stream interface, though.
--
John Krukoff
[EMAIL PROTECTED]

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


Building python 2.5 fails on linux 64

2008-05-15 Thread Marc-André Belzile
Hi,
 
I have the following error when building python 2.5 (revision 63261)
 
./Parser/asdl_c.py -c ./Python ./Parser/Python.asdl
'import site' failed; use -v for traceback
Traceback (most recent call last):
  File "./Parser/asdl_c.py", line 7, in ?
import os, sys, traceback
ImportError: No module named os
make: *** [Python/Python-ast.c] Error 1
 
I'm using gcc version 4.1.1 on Red Hat Enterprise Linux WS release 4 (Nahant 
Update 4)
 
What could be the problem ?
 
Thanks for helping.
 
-mab

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

Problem creating a shorcut

2008-05-15 Thread Mike Driscoll
Hi,

I've had this niggling issue from time to time. I want to create a
shortcut on the user's desktop to a website that specifically loads
Firefox even if Firefox is not the default browser.

I usually use COM as it allows very specific settings of the shortcut,
such as the Working Directory and the Target Path. However, the
following will not work for some reason:



import win32com.client
import winshell

shell = win32com.client.Dispatch('WScript.Shell')
userDesktop = winshell.desktop()

shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk')
shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe"
https:\www.myCompanyWebsite.com\auth\preauth.php'
shortcut.WorkingDirectory = r'C:\Program Files\Mozilla
Firefox'
shortcut.save()



This creates the following target path (which doesn't work):

"C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https:
\www.myCompanyWebsite.com\auth\preauth.php"

If I leave the website off, it works. If I leave the path to Firefox
out, it works too. Is there another method I can use other than
creating the shortcut by hand and using the shutil module?

Thank you for any ideas.

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


Re: Dbase / foxpro files

2008-05-15 Thread John Machin

Johny wrote:

Is there a module for reading/modifing db files from Python?
Thanks for help
B.


I have a module -- which I'm going to get around to releasing one of 
these days :-) -- which allows to read dBase III, dBase IV and Foxpro 
files (sequentially only, not randomly) and to write dBaseIII files 
sequentially. Index files if any are ignored.


Field types supported for reading:
C character
D date
F float
I integer (32 bits)
L logical
M memo (stored in a .DBT (dBase) or .FPT (FoxPro) file)
N number
T time

Writing supports only dBaseIII with C, D, L and N fields, but could be 
extended easily enough (I've never had the need). No index files are 
written.


E-mail me if you are interested.

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


Re: Dbase / foxpro files

2008-05-15 Thread Johny
On May 15, 5:21 pm, John Machin <[EMAIL PROTECTED]> wrote:
> Johny wrote:
> > Is there a module for reading/modifing db files from Python?
> > Thanks for help
> > B.
>
> I have a module -- which I'm going to get around to releasing one of
> these days :-) -- which allows to read dBase III, dBase IV and Foxpro
> files (sequentially only, not randomly) and to write dBaseIII files
> sequentially. Index files if any are ignored.
>
> Field types supported for reading:
> C character
> D date
> F float
> I integer (32 bits)
> L logical
> M memo (stored in a .DBT (dBase) or .FPT (FoxPro) file)
> N number
> T time
>
> Writing supports only dBaseIII with C, D, L and N fields, but could be
> extended easily enough (I've never had the need). No index files are
> written.
>
> E-mail me if you are interested.
>
> Cheers,
> John

Hello John,
Yes, I am interested. Is it possible to download the module?
Thanks
Lad
--
http://mail.python.org/mailman/listinfo/python-list


Re: List behaviour

2008-05-15 Thread Lie
On May 15, 5:08 pm, Gabriel <[EMAIL PROTECTED]> wrote:
> Hi all
>
> Just wondering if someone could clarify this behaviour for me, please?
>
> >>> tasks = [[]]*6
> >>> tasks
>
> [[], [], [], [], [], []]>>> tasks[0].append(1)
> >>> tasks
>
> [[1], [1], [1], [1], [1], [1]]
>
> Well what I was expecting to end up with was something like:
> >>> tasks
> [[1], [], [], [], [], []]
>
> I got this example from page 38 of Beginning Python.
>
> Regards
>
> Gabriel

As a complementary note, if you want to copy a list (probably a filled
one instead of blank ones like here) and wanted to copy a list so that
the new copy is a completely separate instance from the old copy, you
may use deepcopy (from copy import deepcopy).
--
http://mail.python.org/mailman/listinfo/python-list

Re: Class Methods Vs Any Other Callable

2008-05-15 Thread Arnaud Delobelle
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

> FWIW, I wonder why the BDFL choosed to implement __new__ as a
> staticmethod - there are probably some pretty good reasons, but not
> knowing them, it looks like __new__ would have been a perfect
> candidate for a classmethod.
>
> So far, the only reason I can think of is that making it a classmethod
> would have required the use of super(Parent, cls) to call the parent's
> class __new__, which may (or may not - never had the case) be
> problematic (any guru on this ?)

Don't know but I remember something about this in 'Unifying types and
classes'.  There it is:

Factoid: __new__ is a static method, not a class method. I
initially thought it would have to be a class method, and that's
why I added the classmethod primitive. Unfortunately, with class
methods, upcalls don't work right in this case, so I had to make
it a static method with an explicit class as its first
argument. Ironically, there are now no known uses for class
methods in the Python distribution (other than in the test
suite). I might even get rid of classmethod in a future release if
no good use for it can be found!

(http://www.python.org/download/releases/2.2/descrintro/)

I don't have the time to try to figure it out :(

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


How do I use the unpack function?

2008-05-15 Thread Marlin Rowley

All:

I've got a script that runs really slow because I'm reading from a stream a 
byte at a time:

// TERRIBLE
for y in range( height ):
for color in range(4):
for x in range( width ):
pixelComponent = fileIO.read(4)
   
buffer = unpack("!f",pixelComponent)  << unpacks ONE
float, but we now can do something with that pixel component.


I can speed this up dramatically if I did this:

// MUCH FASTER
for y in range( height ):
for color in range(4):
   
   pixelComponent = fileIO.read(4*width)
<  GET a LOT more data from the
stream into memory FIRST!!
for x in range( width ):
   buffer = unpack( ?? )  how do I get each float from the 
pixelComponent???


-M
_
With Windows Live for mobile, your contacts travel with you.
http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008--
http://mail.python.org/mailman/listinfo/python-list

exists=false, but no complaint when i open it!?

2008-05-15 Thread globalrev
print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
\trainingsetunzipped\training_set\mv_001.txt')

d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of-
sweden.gif')
d.close()

exists returns false but when i open it doesnt complain. how come?

another file that exists returned false for complained when i tried to
open it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: HASH TABLES IN PYTHON

2008-05-15 Thread Michael Torrie
Blubaugh, David A. wrote:
> I was wondering if anyone has ever worked with hash tables within the
> Python Programming language?  I will need to utilize this ability for
> quick numerical calculations.  

Dictionaries are, by definition, hash tables with a very optimized
algorithm to minimize collisions.

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


Re: exists=false, but no complaint when i open it!?

2008-05-15 Thread Tim Golden

globalrev wrote:

print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
\trainingsetunzipped\training_set\mv_001.txt')

d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of-
sweden.gif')
d.close()


Ummm. These are not the same files (unless you've got some bizarre
NTFS linking going on).


exists returns false but when i open it doesnt complain. how come?


Also, in general, you're prone to race conditions if you do this
kind of thing, altho' on a local C: drive that's less likely. But
still possible. Probably better to wrap the open in a try-except
and handle an IOError.

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


Re: How do I use the unpack function?

2008-05-15 Thread Gary Herron

Marlin Rowley wrote:

All:

I've got a script that runs really slow because I'm reading from a 
stream a byte at a time:


// TERRIBLE
for y in range( height ):
for color in range(4):
for x in range( width ):
pixelComponent = fileIO.read(4)
buffer = unpack("!f",pixelComponent)  << unpacks ONE 
float, but we now can do something with that pixel component.



I can speed this up dramatically if I did this:

// MUCH FASTER
for y in range( height ):
for color in range(4):
   pixelComponent = fileIO.read(4*width) <  GET a LOT more 
data from the stream into memory FIRST!!

   for x in range( width ):
   buffer = unpack( ?? )  how do I get each float from 
the pixelComponent???


Just carve of the first four bytes of pixelComponent on each pass 
through the loop, and unpack that.


for x in range(width):
 fourbytes = pixelComponent[:4]   # first 4 bytes
 pixelComponent = pixelComponent[4:]  # All but first four bytes
 buffer = unpack("!f", fourbytes)


There are probably better ways overall, but this directly answers your 
question.


Gary Herron





-M

With Windows Live for mobile, your contacts travel with you. Connect 
on the go. 
 




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


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


Re: exists=false, but no complaint when i open it!?

2008-05-15 Thread John Machin
On May 16, 2:03 am, globalrev <[EMAIL PROTECTED]> wrote:
> print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
> \trainingsetunzipped\training_set\mv_001.txt')
>
> d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of-
> sweden.gif')
> d.close()
>
> exists returns false but when i open it doesnt complain. how come?
>
> another file that exists returned false for complained when i tried to
> open it.

Ummm ... you are testing one path with os.path.exists and then opening
a *DIFFERENT* path. If you think you still have a problem, show us a
short piece of code that you actually executed and that demonstrates
the problem.
--
http://mail.python.org/mailman/listinfo/python-list


RE: exists=false, but no complaint when i open it!?

2008-05-15 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Reedick, Andrew
> Sent: Thursday, May 15, 2008 12:11 PM
> To: globalrev; python-list@python.org
> Subject: RE: exists=false, but no complaint when i open it!?
> 
> >
> > print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
> > \trainingsetunzipped\training_set\mv_001.txt')
> >
> 
> 
> You're falling victim to string interpolation because of the
> backslashes.  (\n == newline, \N == N).
> 
> Try using a raw string r'filename', instead of 'filename':
>   print
>
os.path.exists(r'C:\Users\saftarn\Desktop\NetFlixDataSet\trainingsetunz
> i
> pped\training_set\mv_001.txt')
> 
> 

Specificially, the \t in '\trainingsetunzipped' and in '\training_set'
were being treated as tab characters.  Ignore my comment about '\N ==
N'.
--
http://mail.python.org/mailman/listinfo/python-list


RE: exists=false, but no complaint when i open it!?

2008-05-15 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of globalrev
> Sent: Thursday, May 15, 2008 12:04 PM
> To: python-list@python.org
> Subject: exists=false, but no complaint when i open it!?
> 
> print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
> \trainingsetunzipped\training_set\mv_001.txt')
> 
> d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of-
> sweden.gif')
> d.close()
> 
> exists returns false but when i open it doesnt complain. how come?
> 
> another file that exists returned false for complained when i tried to
> open it.
> --


You're falling victim to string interpolation because of the
backslashes.  (\n == newline, \N == N).

Try using a raw string r'filename', instead of 'filename':
print
os.path.exists(r'C:\Users\saftarn\Desktop\NetFlixDataSet\trainingsetunzi
pped\training_set\mv_001.txt')


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


file open/read/name etc, not working

2008-05-15 Thread globalrev
import os

print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
d.readline()

returns true in the shell but prints no text even though the document
contains text.

d.name returns nothing, d.name() raises an error.
--
http://mail.python.org/mailman/listinfo/python-list


Re: file open/read/name etc, not working

2008-05-15 Thread globalrev
On 15 Maj, 18:12, globalrev <[EMAIL PROTECTED]> wrote:
> import os
>
> print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
> d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
> d.readline()
>
> returns true in the shell but prints no text even though the document
> contains text.
>
> d.name returns nothing, d.name() raises an error.

wow im an idiot. print...
--
http://mail.python.org/mailman/listinfo/python-list


Re: cgitb performance issue

2008-05-15 Thread Ethan Furman


Gabriel Genellina wrote:

En Wed, 14 May 2008 13:51:40 -0300, Ethan Furman 
<[EMAIL PROTECTED]>  escribió:



Gabriel Genellina wrote:

En Mon, 05 May 2008 15:56:26 -0300, Ethan Furman  
<[EMAIL PROTECTED]> escribió:



I tried adding a form to our website for uploading large files.
Personally, I dislike the forms that tell you you did something wrong
and make you re-enter *all* your data again, so this one cycles and
remembers your answers, and only prompts for the file once the rest of
the entered data is good.  However, the first time the form loads 
it  can

take up to 30 seconds... any ideas why?



Hard to tell without looking at the code... And what has cgitb to 
do  with this?



H... excellent question, and the answer is -- Nothing.  My
apologies.  I'm importing cgi (cgitb was while I was debugging it), as
well as a bunch of others.

Here's the source, with a bunch of the actual html stripped out.  The -u
as well as the last two lines were an attempt to eliminate the 30-second
pause while it loads, as it seems to get all data transferred, then just
waits for a while.  Any ideas appreciated.  My apologies for the 
ugly  code.



*When* do you see the 30-secs delay? After uploading the files? I see  
they're transferred using SMTP, but I think you're not talking about 
the  time it takes to send the mail.
I'd use the old-fashioned "print" statement to see *what* gets 
executed  and how long it takes each step.


The initial load of the page in question is a static html page (done as 
a crutch so there's *something* on screen while the rest of the thing 
loads).  After five seconds the static html page redirects to the python 
cgi script -- and that's where the delay occurs.  I just double checked, 
and it also occurs everytime it has to reload the script.  I'll try the 
print statements and see if I can narrow down where the bottleneck is 
located.  The sending of the file via smtp happens on our server after 
the file has been uploaded, the delays are happening long before that.  
Thanks for your help!

--
Ethan

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


Re: file open/read/name etc, not working

2008-05-15 Thread John Machin
On May 16, 2:12 am, globalrev <[EMAIL PROTECTED]> wrote:
> import os
>
> print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
> d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')

Two different paths again.

> d.readline()

This reads one line and then does absolutely nothing with it. The
Python interactive shell prints the result of each expression, which
is a Good Thing. For Python to do the same when running a script would
be a Bad Thing.

readline and readlines are old hat; instead, iterate over the file
object, like this:

for line in d:
print line,

>
> returns true in the shell but prints no text even though the document
> contains text.
>
> d.name returns nothing, d.name() raises an error.

d.name should return the name of the file; I suspect that you again
have done nothing with it. d.name() would raise an exception because
d.name is not a method, so you can't call it.

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


Re: pyserial and file open conflict?

2008-05-15 Thread Henrique Dante de Almeida
Em Thu, 15 May 2008 08:03:40 -0700, p.wallstedt escreveu:

> Hi all!
> 
> I have a small but rather annoying problem with pyserial. I want to open
> a file on disk for reading and then open a com-port, write lines from
> the file to the port and then read something back and compare it to the
> next line in the file. Should be simple. And it is, apart from the fact
> that the file seems to be doubled ...? Or it loops through the file
> twice.
> 
> If I exclude the "import serial" it works.
> 
> Any ideas?
> 
> thanks
> Peter

 Are you sure you need to reinvent the wheel ? For example, pppd has the 
"chat" application:

 http://www.hmug.org/man/8/chat.php

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


RE: How do I use the unpack function?

2008-05-15 Thread Marlin Rowley
Thanks for the advice!
 
However, I assumed that:
 
fourbytes = pixelComponent[:4]
 
would shave that byte off the array in pixelComponent.  So that the array is 
smaller by one on the next iteration.  Is this not the case?
 
I'm getting weird results now..
 
-M



> Date: Thu, 15 May 2008 09:11:23 -0700> From: [EMAIL PROTECTED]> To: [EMAIL 
> PROTECTED]> CC: python-list@python.org> Subject: Re: How do I use the unpack 
> function?> > Marlin Rowley wrote:> > All:> >> > I've got a script that runs 
> really slow because I'm reading from a > > stream a byte at a time:> >> > // 
> TERRIBLE> > for y in range( height ):> > for color in range(4):> > for x in 
> range( width ):> > pixelComponent = fileIO.read(4)> > buffer = 
> unpack("!f",pixelComponent) << unpacks ONE > > float, but we now can do 
> something with that pixel component.> >> >> > I can speed this up 
> dramatically if I did this:> >> > // MUCH FASTER> > for y in range( height 
> ):> > for color in range(4):> > pixelComponent = fileIO.read(4*width) 
> < GET a LOT more > > data from the stream into memory FIRST!!> > for 
> x in range( width ):> > buffer = unpack( ?? )  how do I get each 
> float from > > the pixelComponent???> > Just carve of the first four bytes of 
> pixelComponent on each pass > through the loop, and unpack that.> > for x in 
> range(width):> fourbytes = pixelComponent[:4] # first 4 bytes> pixelComponent 
> = pixelComponent[4:] # All but first four bytes> buffer = unpack("!f", 
> fourbytes)> > > There are probably better ways overall, but this directly 
> answers your > question.> > Gary Herron> > > >> >> > -M> > 
> > > 
> With Windows Live for mobile, your contacts travel with you. Connect > > on 
> the go. > > 
> 
>  > >> > 
> > >> 
> > --> > http://mail.python.org/mailman/listinfo/python-list> 
_
Get Free (PRODUCT) RED™  Emoticons, Winks and Display Pics.
http://joinred.spaces.live.com?ocid=TXT_HMTG_prodredemoticons_052008--
http://mail.python.org/mailman/listinfo/python-list

Re: How do I use the unpack function?

2008-05-15 Thread John Machin
On May 16, 2:11 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Marlin Rowley wrote:
> > All:
>
> > I've got a script that runs really slow because I'm reading from a
> > stream a byte at a time:
>
> > // TERRIBLE
> > for y in range( height ):
> > for color in range(4):
> > for x in range( width ):
> > pixelComponent = fileIO.read(4)
> > buffer = unpack("!f",pixelComponent)  << unpacks ONE

[snip]
Perhaps the OP might be able to use the Python Imaging Library (PIL)
instead of reinventing an image-file handler.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I use the unpack function?

2008-05-15 Thread Gary Herron

Marlin Rowley wrote:

Thanks for the advice!
 
However, I assumed that:
 
fourbytes = pixelComponent[:4]
 
would shave that byte off the array in pixelComponent.  So that the 
array is smaller by one on the next iteration.  Is this not the case?

You don't need the newsgroup to answer this kind of question.  Just try it!

>>> a = 'abcdefghi'
>>> b = a[:4]
>>> print a,b
abcdefghi abcd

Notice that the [:4] index does not change the original array.

Gary Herron



 
I'm getting weird results now..
 
-M







> Date: Thu, 15 May 2008 09:11:23 -0700
> From: [EMAIL PROTECTED]
> To: [EMAIL PROTECTED]
> CC: python-list@python.org
> Subject: Re: How do I use the unpack function?
>
> Marlin Rowley wrote:
> > All:
> >
> > I've got a script that runs really slow because I'm reading from a
> > stream a byte at a time:
> >
> > // TERRIBLE
> > for y in range( height ):
> > for color in range(4):
> > for x in range( width ):
> > pixelComponent = fileIO.read(4)
> > buffer = unpack("!f",pixelComponent) << unpacks ONE
> > float, but we now can do something with that pixel component.
> >
> >
> > I can speed this up dramatically if I did this:
> >
> > // MUCH FASTER
> > for y in range( height ):
> > for color in range(4):
> > pixelComponent = fileIO.read(4*width) < GET a LOT more
> > data from the stream into memory FIRST!!
> > for x in range( width ):
> > buffer = unpack( ?? )  how do I get each float from
> > the pixelComponent???
>
> Just carve of the first four bytes of pixelComponent on each pass
> through the loop, and unpack that.
>
> for x in range(width):
> fourbytes = pixelComponent[:4] # first 4 bytes
> pixelComponent = pixelComponent[4:] # All but first four bytes
> buffer = unpack("!f", fourbytes)
>
>
> There are probably better ways overall, but this directly answers your
> question.
>
> Gary Herron
>
>
> >
> >
> > -M
> > 


> > With Windows Live for mobile, your contacts travel with you. Connect
> > on the go.
> > 
 


> >
> > 


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



Get Free (PRODUCT) RED™ Emoticons, Winks and Display Pics. Check it 
out! 




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


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


RE: file open/read/name etc, not working

2008-05-15 Thread Andreas Tawn
>import os
>
>print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
>d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
>d.readline()
>
>returns true in the shell but prints no text even though the document
>contains text.
>
>d.name returns nothing, d.name() raises an error.
>--
>http://mail.python.org/mailman/listinfo/python-list

Try...

import os

print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
for line in d:
print line


And I'm guessing that's a typo in flim.txt?

Cheers,

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


RE: How do I use the unpack function?

2008-05-15 Thread Marlin Rowley
Sorry Gary,
 
I found out that I wasn't reassigning the array back once I got the first 4 
bytes.  I don't mean to appear lazy..:(
 
Thanks for the help!
 
-M



> Date: Thu, 15 May 2008 09:51:22 -0700> From: [EMAIL PROTECTED]> To: [EMAIL 
> PROTECTED]> CC: python-list@python.org> Subject: Re: How do I use the unpack 
> function?> > Marlin Rowley wrote:> > Thanks for the advice!> > > > However, I 
> assumed that:> > > > fourbytes = pixelComponent[:4]> > > > would shave that 
> byte off the array in pixelComponent. So that the > > array is smaller by one 
> on the next iteration. Is this not the case?> You don't need the newsgroup to 
> answer this kind of question. Just try it!> > >>> a = 'abcdefghi'> >>> b = 
> a[:4]> >>> print a,b> abcdefghi abcd> > Notice that the [:4] index does not 
> change the original array.> > Gary Herron> > > > > > > I'm getting weird 
> results now..> > > > -M> >> >> >> >> > 
> > >> 
> > > Date: Thu, 15 May 2008 09:11:23 -0700> > > From: [EMAIL PROTECTED]> > > 
> To: [EMAIL PROTECTED]> > > CC: python-list@python.org> > > Subject: Re: How 
> do I use the unpack function?> > >> > > Marlin Rowley wrote:> > > > All:> > > 
> >> > > > I've got a script that runs really slow because I'm reading from a> 
> > > > stream a byte at a time:> > > >> > > > // TERRIBLE> > > > for y in 
> range( height ):> > > > for color in range(4):> > > > for x in range( width 
> ):> > > > pixelComponent = fileIO.read(4)> > > > buffer = 
> unpack("!f",pixelComponent) << unpacks ONE> > > > float, but we now can do 
> something with that pixel component.> > > >> > > >> > > > I can speed this up 
> dramatically if I did this:> > > >> > > > // MUCH FASTER> > > > for y in 
> range( height ):> > > > for color in range(4):> > > > pixelComponent = 
> fileIO.read(4*width) < GET a LOT more> > > > data from the stream 
> into memory FIRST!!> > > > for x in range( width ):> > > > buffer = unpack( 
> ?? )  how do I get each float from> > > > the pixelComponent???> > >> 
> > > Just carve of the first four bytes of pixelComponent on each pass> > > 
> through the loop, and unpack that.> > >> > > for x in range(width):> > > 
> fourbytes = pixelComponent[:4] # first 4 bytes> > > pixelComponent = 
> pixelComponent[4:] # All but first four bytes> > > buffer = unpack("!f", 
> fourbytes)> > >> > >> > > There are probably better ways overall, but this 
> directly answers your> > > question.> > >> > > Gary Herron> > >> > >> > > >> 
> > > >> > > > -M> > > > > > 
> > > > 
> > With Windows Live for mobile, your contacts travel with you. Connect> > > > 
> on the go.> > > > > > 
> 
>  > >> > > >> > > > > > 
> > > > 
> >> > > > --> > > > http://mail.python.org/mailman/listinfo/python-list> > >> 
> >> >> > 
> > > 
> Get Free (PRODUCT) RED™ Emoticons, Winks and Display Pics. Check it > > out! 
> > > > > 
> > >> 
> > --> > http://mail.python.org/mailman/listinfo/python-list> 
_
With Windows Live for mobile, your contacts travel with you.
http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008--
http://mail.python.org/mailman/listinfo/python-list

Re: Dbase / foxpro files

2008-05-15 Thread Claudio Driussi

Johny ha scritto:

Is there a module for reading/modifing db files from Python?
Thanks for help
B.


If your target is Windows, you can try mediator components

http://www.otc.pl/download/

which are COM objects based on xHarbour and which give you
full access to DBF and index.

You need PythonWin too.

I did some tests, if you like i can send you something,
call me in my private mail.

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


  1   2   >