Re: difference between class methods and instance methods

2005-02-18 Thread Antoon Pardon
Op 2005-02-17, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
> John wrote:
>> ... hmm... bound methods get created each time you make
>> a call to an instance method via an instance of the given class?
>
> No, they get created when you create an actual instance of an object.

I'm not so sure about that. Take the following code:

>>> class A:
...   def m():
... pass
... 
>>> a = A()
>>> u = a.m
>>> u is a.m
False

If bound methods were created at instance creation one would expect
a True result here instead of False.

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


Hello File.py

2005-02-18 Thread Lith

Here's a simple script, where I want to use a GUI to select a file.
(And eventually do something interesting with it.) Some problems
appear.

(1) Why does it call MenuOpen automatically?

(2) Why won't it open when I choose the menu item?

(3) Python Cookbook gave me the sys.exit call, if I run it from IDLE it
gives me a traceback. Should I be using something else?

(4) Does tkFileDialog have any useful official documentation? The main
google results for it don't even give the possible parameters for the
function calls, or sample code showing how to use.

(5) Is the 'parent = parent,' line just plain wrong?

Feel free to note any horrors you see.


..

import sys
from Tkinter import *
import tkFileDialog

def MenuOpen(parent):
tkFileDialog.askopenfilename(
defaultextension= '.ctb',
filetypes   = [
('AutoCAD Color-Dependent Style Table Files', '*.ctb'),
('AutoCAD Named Style Table Files', '*.stb'),
('All Files', '*.*')
  ],
initialdir  = 'Desktop',
initialfile = '',
parent  = parent,
title   = 'Open Plot Style File...'
)


def DoInterface():
root= Tk()

menubar = Menu(root)
root.config(menu = menubar)

menuFile= Menu(menubar)
menuFile.add_command(   label='Open',
command=MenuOpen(parent=root))
menuFile.add_separator()
menuFile.add_command(   label='Exit', command=sys.exit)

menubar.add_cascade(label='File', menu=menuFile);

root.mainloop()

#

DoInterface()

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


Re: how can i randomly choose keys in dictionary

2005-02-18 Thread Thomas Guettler
Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:

> Hi,there. How can I choose a key in dictionary randomly?
> 
> Say, random.choice() in lists,
> 
> or in lists:
> lists = [1,2,3,4]
> position = random.range(len(lists))
> word = lists[position]

Hi, try this:

import random

mydict={1: "one", 2: "two"}
print mydict[random.choice(mydict.keys())]


-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES

2005-02-18 Thread Peter Maas
Terry Reedy schrieb:
"Peter Maas" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

http://nobelprize.org/medicine/educational/pavlov/
and then do something useful :)

Thanks.  I showed this to my daughter, who enjoyed the game, and explained 
your point re Pavlov posting, and about Pavlov advertising, etc. 
Fine that at least one person benefitted from my post :) I came across
this when I browsed through the Lazaridis thread which was - if for
nothing else - good for some laughs.
But at the same time I felt uncomfortable to see how many bright
Pythoneers cared to give well thought, helpful and friendly answers
to somebody who was acting unpolite and kind of stupid, even mechanical.
This newsgroup is used to be helpful to newbies and Lazaridis was
ringing the newbie bell.
Perhaps we will soon see a triumphant publication with the title
"Ilias Lazaridis - the ELIZA of the 21st century. A milestone towards
the perfect Turing test" ;)
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


wxPython and thread memory problems?

2005-02-18 Thread plumpy321
Hi,

   I took an example from wxPython with the IE web browser and
created a refresh button to automatically refresh a web page in 5
second intervals.  But I notice that the memory utilization in Python
keeps increasing over time.  Can anyone tell me why this is happening?
Here is my code:



import wx, re
import time, thread
from urlparse import *

if wx.Platform == '__WXMSW__':
import  wx.lib.iewinas  iewin

refresh = 0

#--

class TestPanel(wx.Panel):
def __init__(self, parent, frame=None):
wx.Panel.__init__(
self, parent, -1,
style = wx.TAB_TRAVERSAL |
wx.CLIP_CHILDREN |
wx.NO_FULL_REPAINT_ON_RESIZE
)

self.current = "http://www.google.com";
self.frame = frame

if frame:
self.titleBase = frame.GetTitle()

sizer = wx.BoxSizer(wx.VERTICAL)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)

self.ie = iewin.IEHtmlWindow(self, -1, style =
wx.NO_FULL_REPAINT_ON_RESIZE)

btn = wx.Button(self, -1, "Open", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "Home", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnHomeButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "<--", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "-->", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "Stop", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "Search", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnSearchPageButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "Refresh", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

btn = wx.Button(self, -1, "AutoRefresh", style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON, self.OnAutoRefreshPageButton, btn)
btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

txt = wx.StaticText(self, -1, "Location:")
btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)

self.location = wx.TextCtrl(self, -1, "",
style=wx.TE_PROCESS_ENTER)

self.location.Bind(wx.EVT_CHAR, self.OnLocationReturn)
btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)

sizer.Add(btnSizer, 0, wx.EXPAND)
sizer.Add(self.ie, 1, wx.EXPAND)

self.ie.LoadUrl(self.current)

self.SetSizer(sizer)
# Since this is a wxWindow we have to call Layout ourselves
self.Bind(wx.EVT_SIZE, self.OnSize)

# Hook up the event handlers for the IE window
self.Bind(iewin.EVT_DocumentComplete, self.OnDocumentComplete,
self.ie)

thread.start_new_thread(self.refresh_url, (5,))

def OnSize(self, evt):
self.Layout()

def OnLocationReturn(self, evt):
if evt.KeyCode() == wx.WXK_RETURN:
self.ie.Navigate(self.location.GetValue(),
 iewin.NAV_NoReadFromCache | iewin.NAV_NoWriteToCache)
else:
evt.Skip()

def OnOpenButton(self, event):
dlg = wx.TextEntryDialog(self, "Open Location",
"Enter a full URL or local path",
self.current, wx.OK|wx.CANCEL)
dlg.CentreOnParent()

if dlg.ShowModal() == wx.ID_OK:
self.current = dlg.GetValue()
self.ie.Navigate(self.current,
 iewin.NAV_NoReadFromCache | iewin.NAV_NoWriteToCache)

dlg.Destroy()

def OnHomeButton(self, event):
self.ie.GoHome()## ET Phone Home!

def OnPrevPageButton(self, event):
self.ie.GoBack()

def OnNextPageButton(self, event):
self.ie.GoForward()

def OnStopButton(self, evt):
self.ie.Stop()

def OnSearchPageButton(self, evt):
self.ie.GoSearch()

def OnRefreshPageButton(self, evt):
self.ie.RefreshPage(iewin.REFRESH_COMPLETELY)

def OnAutoRefreshPageButton(self, evt):
global refresh
refresh = not refresh

def refresh_url(self, delay):
global refresh
while (1):
time.sleep(delay)
if refresh:
self.ie.Navigate(self.ie._get_LocationURL(),
iewin.NAV_NoReadFromCache |
iewin.NAV_NoWriteToCache)

def OnDocumentComplete(self, evt):
self.current = evt.URL
self.

Re: Hello File.py

2005-02-18 Thread Eric Brunel
On 18 Feb 2005 00:17:01 -0800, Lith <[EMAIL PROTECTED]> wrote:
Here's a simple script, where I want to use a GUI to select a file.
(And eventually do something interesting with it.) Some problems
appear.
(1) Why does it call MenuOpen automatically?
Because this code:
menuFile.add_command(label='Open', command=MenuOpen(parent=root))
*calls* your MenuOpen function and assign its *returned value* to the 
command option in your menu. You need to pass the function itself, not call it. 
In fact, you did it correctly in:
menuFile.add_command(   label='Exit', command=sys.exit)
Here, you pass the sys.exit function. What you did above is as if you wrote:
menuFile.add_command(label='Exit', command=sys.exit())
With this line, sys.exit gets called and your application will terminate 
immediatly.
As for the line above, the general solution is to do:
menuFile.add_command(label='Open', command=lambda root=root: MenuOpen(root))
The 'lambda' stuff creates an anonymous function that will call your MenuOpen 
function when the menu is selected. For more details, please refer to the 
Python tutorial - 
http://docs.python.org/tut/node6.html#SECTION00675
But here, you don't even need that, since the root window is the default parent 
for all Tkinter dialogs, so doing:
menuFile.add_command(label='Open', command=MenuOpen)
is enough.
(2) Why won't it open when I choose the menu item?
Since you assigned the value returned by MenuOpen to the command option, 
and since MenuOpen doesn't return anything, there is no command associated to 
your menu and it does nothing at all.
(3) Python Cookbook gave me the sys.exit call, if I run it from IDLE it
gives me a traceback. Should I be using something else?
No you shouldn't; I don't know exactly how IDLE handles this, but the way 
sys.exit() terminates your program is actually by raising an exception. In 
regular usage, i.e. if you run your Python script from the command line, you'll 
never see this exception. Maybe IDLE treats it like any other one; any 
experience on this topic, anyone?
(4) Does tkFileDialog have any useful official documentation? The main
google results for it don't even give the possible parameters for the
function calls, or sample code showing how to use.
The best documentation you'll ever find is the tcl/tk one, e.g. here: 
http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
The corresponding functions are tk_getOpenFile & tk_getSaveFile; you'll just 
have to convert the '-option value' syntax to 'option=value' to be able to use it 
via Tkinter.
(5) Is the 'parent = parent,' line just plain wrong?
It may look so, but it isn't: the parent at the left is the name for a 
keyword parameter for the function and the one at the right is the name of a 
variable. There is no possible confusion here, and this form is actually quite 
frequent.
Feel free to note any horrors you see.
Just one little thing: if you declare:
def MenuOpen(parent): ...
you'd better call it via:
MenuOpen(root)
and not:
MenuOpen(parent=root)
The 'parent=' stuff is unnecessary and may be confusing, since this syntax is 
often used only when you declare a function with keyword parameters like:
def f(arg, **kwdParams): ...
HTH
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES

2005-02-18 Thread David Fraser
Stephen Kellett wrote:
In message <[EMAIL PROTECTED]>, Ilias Lazaridis 
<[EMAIL PROTECTED]> writes

This thread proofs simply the inability of this community [1] to focus 
on a simple essence.

Incorrect analysis. This thread proves that you have no concept of how 
to interact with the community. If you had done what many people asked 
you to do, which is do some work yourself, then ask questions about the 
few answers you didn't discover yourself, you would have got lots of 
helpful answers. You were told this many times by many people. Also on 
the odd occasion someone did proffer some on-topic advice, sometimes in 
long articles that must have taken some time to produce you'd dismiss 
the article with "It is not on topic, I have not read it". How could you 
know if it is not on topic if you don't read it? Apart from the gross 
rudeness in such an attitude it demonstrates your arrogance, selfishness 
and utter contempt for those replying to you.

And then you have the gall to blame your failure on others...
Next you'll be telling me the world is flat and held up by an infinite 
array of tortoises.
Actually I suspect Ilias is trying to carry out his own sort of 'survey' 
on how various communities respond to questions asked in the kind of way 
he asked them ... See his web site.

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


Re: Access to formatting controls from within __repr__ or __str__?

2005-02-18 Thread Serge Orlov
Dan Sommers wrote:

> So my question is:  Is there a way to pass options "through" a format
> string to the __str__ and __repr__ functions?  For example, can I
> define  my own alternate form for use with the '#' formatting
> character, so that '%#s' generates output according to SI guidelines?

You can create your own class FmtTemplate like string.Template was done
in python 2.4: http://docs.python.org/lib/node105.html

and have it call obj.__str__("#s") when you use ${obj:#s} format. I'm
not sure why you want to pass format to repr (as far as I understand
repr is mostly for debug purposes) but you can call from template as
${obj:r} --> obj.__repr__()
${obj:#r} --> obj.__repr__("#r")

fmt = FmtTemplate("quantity1: ${q1:#s}, quantity2: ${q2:#s}")
q1=MyQuantity(...)
q2=MyQuantity(...)
print fmt.substitute(q1=q1,q2=q2)

  Serge.

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


Re: PythonCard and Py2Exe

2005-02-18 Thread PipedreamerGrey
I am using the command prompt.  What I realized after reading your
entry, Peter, is that if I use "setup.py py2exe" instead of "start
setup.py py2exe"  I can see the error in the same window without it
closing.

I went into the script and double spaced everything in case Notebook
smashed the lines together while I was tweaking the code.  After that,
the code resumed packing.  Now, however, it seems I'm back where I
started.  Running the .Exe returned this error:


Traceback (most recent call last):
  File "custdb.py", line 202, in ?
app = model.Application(CustDbStack)
  File "PythonCard\model.pyc", line 337, in __init__
  File "PythonCard\resource.pyc", line 48, in getResource
  File "PythonCard\resource.pyc", line 86, in __init__
  File "PythonCard\resource.pyc", line 91, in __init__
  File "PythonCard\resource.pyc", line 91, in __init__
  File "PythonCard\resource.pyc", line 96, in __init__
  File "PythonCard\resource.pyc", line 139, in enforceSpec
  File "PythonCard\resource.pyc", line 30, in loadComponentModule
ImportError: cannot import module 'radiogroup


Cannot import module 'radiogroup' was the initial problem I was having.
 This is just a more detailed error message.

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


Re: difference between class methods and instance methods

2005-02-18 Thread Duncan Booth
John wrote:

>>inst = C()
>>f1 = inst.foo
>>f2 = inst.foo
>>f1, f2
>> 
>> (>, > method C.foo of <__main__.C instance at 0x00B03F58>>)
>> 
> 
> I just wanted to interject, although those two hex
> numbers in the above line are the same, calling
> id() on f1 and f2 produces two *different* numbers,
> which agrees with the point you made.

Yes, note that the numbers are in the repr of C() and are actually 
id(inst).

A common mistake seems to be for people to do:

>>> inst = C()
>>> id(inst.foo), id(inst.foo)
(11803664, 11803664)

and conclude that the bound methods are the same. They aren't, but if you 
just take the id of an object and throw it away then the next object of 
similar size can [and with the current implementation probably will] be 
allocated at the same location.
-- 
http://mail.python.org/mailman/listinfo/python-list


combining several lambda equations

2005-02-18 Thread Paddy McCarthy
Hi,
I am trying to use eval as little as possible but solve this problem.

#If given:two or more lambda equations
x=lambda : A < B
y=lambda : C+6 >= 7
...

How do I create another lambda expression Z equivalent to 

Z=lambda : (A=7)

# i.e. the anding together of the originals, but without referencing 
# globals x and y as they are artificial in that I will start of with 
# probably a list of lambda equations.

Your help would be appreciated.
Thanks, Paddy.
-- 
http://mail.python.org/mailman/listinfo/python-list


COM+metaclass+property issue

2005-02-18 Thread Thomas Lilley
I'm trying to manufacture a class that provides attributes which mimic the HTML collections offered by the Internet Explorer COM object.  My platform is Win32 (Windows XP) and ActiveState's latest Python 2.3.  The problem is, my attributes are based on properties, which work fine except for when I have a win32com collection returned, they don't appear to have any information in them.  Part of my code:
 
from win32com.client import Dispatch
class metaie(type):    def __init__(cls, name, bases, dict):    super(metaie, cls).__init__(name, bases, dict)    for tag in cls.tags:    setattr(cls, tag, property(lambda self: self.ie.Document.getElementsByTagName(tag)))
 
class ie(object):    __metaclass__ = metaie    tags = ["a", "area", "body", "button", "fieldset", "form", "frame", "head",    "html", "img", "li", "link", "ol", "table", "td", "tr", "ul"]    def __init__(self):    self.ie = Dispatch("InternetExplorer.Application")
An example of the problem:
 
>>>myie = ie()
>>>myie.ie.Document.Navigate(http://www.google.com/)
>>>myie.table.length
0
>>>myie.ie.getElementsByTagName("table").length
2
 
A quick note: ie is my wrapper class, while ie.ie is the win32com Dispatch object representing Internet Explorer.
 
My code should be creating a property attribute for each tag in the tags list and binding it to getElementsByTagName() with the tag pre-loaded by the lambda _expression_.  This means that reading the attribute myie.table should be equivalent to a call to ie.ie.Document.getElementsByTagName("table").  But for some reason, it's not working.  Other property assignments in the metaclass that don't refer to getElementsByTagName work fine (for example, I make ie.url an attribute that navigates to whatever location you assign to it).  Is there any guru who understands these tools out there who can help?
 
In case you're wondering, the reason I brought metaclasses into the picture is that you can't iterate through a list of attribute assignments within the class definition using setattr or __dict__ because the former requires a class name (doesn't exist until the class statement completes) and the latter doesn't seem to exist for classes, at least, I couldn't find a class __dict__.
		Do you Yahoo!? 
Meet the all-new My Yahoo! – Try it today! -- 
http://mail.python.org/mailman/listinfo/python-list

Re: combining several lambda equations

2005-02-18 Thread Fredrik Lundh
Paddy McCarthy wrote:

> #If given:two or more lambda equations
> x=lambda : A < B
> y=lambda : C+6 >= 7
>
> How do I create another lambda expression Z equivalent to
>
> Z=lambda : (A=7)
>
> # i.e. the anding together of the originals, but without referencing
> # globals x and y as they are artificial in that I will start of with
> # probably a list of lambda equations.

x=lambda : A < B
y=lambda : C+6 >= 7
Z=lambda x=x, y=y: x() and y()
del x, y

 



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


Re: low-end persistence strategies?

2005-02-18 Thread Paul Rubin
Pierre Quentel <[EMAIL PROTECTED]> writes:
> Even if the 12 requests occur in the same 5 minutes, the time needed
> for a read or write operation on a small base of any kind (flat file,
> dbm, shelve, etc) is so small that the probability of concurrence is
> very close to zero

I prefer "equal to zero" over "close to zero".  Also, there are times
when the server is heavily loaded, and any file operation can take a
long time.

> If you still want to avoid it, you'll have to pay some price. The most
> simple and portable is a client/server mode, as suggested for
> KirbyBase for instance. Yes, you have to run the server 24 hours a
> day, but you're already running the web server 24/7 anyway

If I have to run a db server 24/7, that's not simple or portable.
There's lots of hosting environments where that's plain not permitted.
Using file locks is much simpler and more portable.  The penalty is
that I can only handle one request at a time, but as mentioned, this
is for a low-usage app, so that serialization is ok.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: low-end persistence strategies?

2005-02-18 Thread Nick Craig-Wood
Michele Simionato <[EMAIL PROTECTED]> wrote:
>  Ok, I have yet another question: what is the difference
>  between fcntl.lockf  and fcntl.flock? The man page of
>  my Linux system says that flock is implemented independently
>  of fcntl, however it does not say if I should use it in preference
>  over fcntl or not.

flock() and lockf() are two different library calls.

With lockf() you can lock parts of a file.  I've always used flock().

>From man lockf() "On Linux, this call [lockf] is just an interface for
fcntl(2). (In general, the relation between lockf and fcntl is
unspecified.)"

see man lockf and man flock

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


Re: Help needed for to build a CGI shell interface.

2005-02-18 Thread Fuzzyman

Tim Roberts wrote:
> Slalomsk8er <[EMAIL PROTECTED]> wrote:
> >
> >What do I want to do? I am building an admintool (deamon and client)
and
> >for this I need to script a interface to the shell, with the console

> >ansi escape sequences, whitch is fully transparent for the user.
>
> Do you honestly plan to expose a command shell via CGI?  Can you
think of a
> better way to allow hackers to wreak havoc on your system?

CGI is not a very good way of doing this - although I did implement a
*very* basic version that is on the Python Cookbook. The python
interpreter closes after executing a CGI... You could setup a long
running process on teh server that communicates with the CGI every time
it opens. I don't use Lunix systems myself... so I don't know how to
tell the client shell to communicate via the CGI

Regards,


Fuzzy

> --
> - Tim Roberts, [EMAIL PROTECTED]
>   Providenza & Boekelheide, Inc.

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


Re: combining several lambda equations

2005-02-18 Thread paddy3118
Fredrik Lundh wrote:
> Paddy McCarthy wrote:
>
> > #If given:two or more lambda equations
> > x=lambda : A < B
> > y=lambda : C+6 >= 7
> >
> > How do I create another lambda expression Z equivalent to
> >
> > Z=lambda : (A=7)
> >
> > # i.e. the anding together of the originals, but without
referencing
> > # globals x and y as they are artificial in that I will start of
with
> > # probably a list of lambda equations.
>
> x=lambda : A < B
> y=lambda : C+6 >= 7
> Z=lambda x=x, y=y: x() and y()
> del x, y
>
> 

Thanks Frederik.

I actually have a set of lambdas so my use will be more like:


>>> s = set([lambda : A < B, lambda : C+6 >= 7])
>>> x=s.pop(); y=s.pop()
>>> Z=lambda x=x, y=y: x() and y()
>>> del x,y
>>> A,B,C = [2,3,1]
>>> Z()
True
>>> A,B,C = [2,3,0]
>>> Z()
False
>>> A,B,C = [3,3,1]
>>> Z()
False
>>> 

- Gosh, isn't life fun!

- Pad.

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


Re: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES

2005-02-18 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, David Fraser 
<[EMAIL PROTECTED]> writes
Actually I suspect Ilias is trying to carry out his own sort of 
'survey' on how various communities respond to questions asked in the 
kind of way he asked them ... See his web site.
Its as unreadable as his network news postings. One of the first things 
I did was check out his website. I didn't gain a lot as it is written in 
his typical automaton style. It actively discourages you from engaging. 
Thats quite an achievement for a static piece of text.

Stephen
--
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk
RSI Information:http://www.objmedia.demon.co.uk/rsi.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES

2005-02-18 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, Peter Maas 
<[EMAIL PROTECTED]> writes
Perhaps we will soon see a triumphant publication with the title
"Ilias Lazaridis - the ELIZA of the 21st century. A milestone towards
the perfect Turing test" ;)
I've got to admit that for a large proportion of the time interacting 
(if that is the word) with him I thought I was the butt of a clever AI 
joke. I've finally come to the conclusion that there is a real, if 
seriously dysfunctional, person behind the communications.

If I knew more about the AI subject arena AND had more time on my hands 
I'd try to write an IlliasBot to see how far I got before I was found 
out. But I'm way too busy, so someone else will have to do it. I just 
hope they do it in Python or Ruby so that these languages get more 
publicity.

Stephen
--
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk
RSI Information:http://www.objmedia.demon.co.uk/rsi.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python, Matlab and AI question

2005-02-18 Thread Robert Kern
dataangel wrote:
I'm a student who's considering doing a project for a Machine Learning 
class on pathing (bots learning to run through a maze). The language 
primarily used by the class has been Matlab. I would prefer to do the 
bulk of the project in python because I'm familiar with pygame (for the 
visuals) but I already have a lot of AI code written in Matlab.

I'd like to be able to call Matlab code from within python. I'm not sure 
this is possible. My code runs in Octave just fine.
There have been some bridges between Matlab and Python, but most of them 
are old, I believe.

  http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html
If you're on Windows, this may help:
  http://www.geocities.com/ptmcg/python/using_matlab_from_python.html
I've heard about 
numerical python and scipy, but I'm not sure what tool is going to mean 
the least amount of recoding for me. At the very least I need to find a 
really fast package for matrix operations.
That would be Numeric and scipy. You'll probably need Numeric anyways 
for pygame. scipy has a set of functions that try to mimic Matlab 
functionality with the same names, so that may help in translating the code.

Anyone have any input on what the best tool for the job would be? I've 
googled, but I figure it's best to ask experience ;)
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I make my program start fullscreen ?

2005-02-18 Thread dimitri pater
If you're using Tkinter, the next url might help:
http://effbot.org/zone/tkinter-toplevel-fullscreen.htm


On Tue, 15 Feb 2005 23:35:05 +0100, BOOGIEMAN <[EMAIL PROTECTED]> wrote:
> os = windows xp
> How do I make "myprogram.py" start fullscreen at windows command prompt ?
> Also I made it as "myprogram.exe" with py2exe,but how to start fullscreen ?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
Please visit dimitri's website: www.serpia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combining several lambda equations

2005-02-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I actually have a set of lambdas so my use will be more like:

A set of lambdas gains you nothing.

>>> (lambda: a > 0) in set([lambda: a > 0])
False

is probably not what you expected. So you might want to go back to strings
containing expressions. Anyway, here is a way to "and" an arbitrary number
of functions (they all must take the same arguments):

>>> def make_and(*functions):
... def all_true(*args, **kw):
... for f in functions:
... if not f(*args, **kw):
... return False
... return True
... return all_true
...
>>> abc = make_and(lambda: a > 0, lambda: b < 0, lambda: c == 0)
>>> a, b, c = 1, -1, 0
>>> abc()
True
>>> c = 1
>>> abc()
False

For a set/list of lambdas/functions, you would call make_and() with a
preceding star:

and_all = make_and(*some_set_of_functions)

> - Gosh, isn't life fun!

I seem to remember that the manual clearly states otherwise :-)

Peter


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


Re: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos?

2005-02-18 Thread Diez B. Roggisch
Thomas Heller wrote:

> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> 
>> Maybe somehow the pygame sdl wrapper can be used for gui-stuff. SDL has
>> had a DOS mode. But it is discontinued.
> 
> What exactly is discontinued?  pygame? SDL?

The dos mode of sdl.
-- 
Regards,

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


Re: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES

2005-02-18 Thread Neil Hodgson
Peter Maas:

> Perhaps we will soon see a triumphant publication with the title
> "Ilias Lazaridis - the ELIZA of the 21st century. A milestone towards
> the perfect Turing test" ;)

   as laridis

   Neil


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


Re: [OT]: Re: Why doesn't join() call str() on its arguments?

2005-02-18 Thread Nick Vargish
"news.sydney.pipenetworks.com" <[EMAIL PROTECTED]> writes:

> I'm sure theres got to be a few copy cats in those 12 though.

Those that don't come up with original answers alter the existing
ones a bit and call it their own.

> Does that mean you just haven't had time to finish ? or you have been
> studying philosophy for 15 years ?

Sort of an extended break, really. Every year I plan to finish up, but
then can't find the time and/or money to do it.

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between class methods and instance methods

2005-02-18 Thread Diez B. Roggisch
> This is badly wrong. John was correct.
> 
> Bound methods get created whenever you reference a method of an instance.
> If you are calling the method then the bound method is destroyed as soon
> as the call returns. You can have as many different bound methods created
> from the same unbound method and the same instance as you want:

That did escape me so far - interesting. Why is it that way? I'd expect that
creating a bound method from the class and then storing it in the objects
dictionary is what happens. 

-- 
Regards,

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


Solution for architecure dependence in Numeric ?

2005-02-18 Thread Johannes Nix|Johannes.Nix

Hi,

I have a tricky problem with Numeric. Some time ago, I have generated
a huge and complex data structure, and stored it using the cPickle
module. Now I want to evaluate it quickly again on a workstation
cluster with 64-Bit Opteron CPUs - I have no more than three days to
do this. Compiling Python and running Numeric has been no problem at
all. However, I get an error message when accessing the data pickled
before. (I can load it regularly on 32 bit computers, but it is a
quite complex data object, so I really don't want to store every
element as ASCII data).  The problem seems to be with 64 Bit integers
(with 32-bit-floats, no problem was observed).

This looks like that (from the Unix command shell):


[EMAIL PROTECTED]:~> python ~/python/test_npickle.py  -dump test.pck
[EMAIL PROTECTED]:~> python ~/python/test_npickle.py  test.pck
[0 1 2 3 4 5 6 7 8 9]
[EMAIL PROTECTED]:~> ssh 64bithost python ~/python/test_npickle.py  test.pck
Traceback (most recent call last):
  File "/home/jnix/python/test_npickle.py", line 16, in ?
a = cPickle.load(file(filename))
  File "/home/jnix/lib/python2.4/SuSE-9.0/x86_64/Numeric/Numeric.py", line 520, 
in array_constructor
x.shape = shape
ValueError: ('total size of new array must be unchanged', , ((10,), 'l', 
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00',
 1))


also I get:
[EMAIL PROTECTED]:~> python -c "import Numeric; print 
Numeric.arange(0).itemsize()"
4
[EMAIL PROTECTED]:~>  python -c "import Numeric; print 
Numeric.arange(0).itemsize()"
8


The script used to produce the example above is:

-
#/usr/bin/python
# -*- coding: latin1 -*-

import Numeric
import cPickle
import sys

if len(sys.argv) > 1 and sys.argv[1] == '-dump':
filename = sys.argv[2]
binary=1
a = Numeric.arange(10) 
cPickle.dump(a, file(filename,'w',binary))

else:
filename = sys.argv[1]
a = cPickle.load(file(filename))
print a


-


So what would you suggest ? Can I hack Numeric to assume non-native
32 bit integer numbers ?

Many thanks for any help,

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


Re: Py2exe and extension issues

2005-02-18 Thread kdahlhaus
John,

Thanks, for some reason, I just saw your response.  I'll be getting
back to that app in about 2 week and the first item is to look into the
issue.

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


Re: Solution for architecure dependence in Numeric ?

2005-02-18 Thread Michael Spencer
"Johannes Nix|Johannes.Nix"@uni-oldenburg.de wrote:
Hi,
I have a tricky problem with Numeric. Some time ago, I have generated
a huge and complex data structure, and stored it using the cPickle
module. Now I want to evaluate it quickly again on a workstation
cluster with 64-Bit Opteron CPUs - I have no more than three days to
do this. Compiling Python and running Numeric has been no problem at
all. However, I get an error message when accessing the data pickled
before. (I can load it regularly on 32 bit computers, but it is a
quite complex data object, so I really don't want to store every
element as ASCII data).  The problem seems to be with 64 Bit integers
(with 32-bit-floats, no problem was observed).
This looks like that (from the Unix command shell):
[EMAIL PROTECTED]:~> python ~/python/test_npickle.py  -dump test.pck
[EMAIL PROTECTED]:~> python ~/python/test_npickle.py  test.pck
[0 1 2 3 4 5 6 7 8 9]
[EMAIL PROTECTED]:~> ssh 64bithost python ~/python/test_npickle.py  test.pck
Traceback (most recent call last):
  File "/home/jnix/python/test_npickle.py", line 16, in ?
a = cPickle.load(file(filename))
  File "/home/jnix/lib/python2.4/SuSE-9.0/x86_64/Numeric/Numeric.py", line 520, 
in array_constructor
x.shape = shape
ValueError: ('total size of new array must be unchanged', , ((10,), 'l', 
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00',
 1))
also I get:
[EMAIL PROTECTED]:~> python -c "import Numeric; print 
Numeric.arange(0).itemsize()"
4
[EMAIL PROTECTED]:~>  python -c "import Numeric; print 
Numeric.arange(0).itemsize()"
8
The script used to produce the example above is:
-
#/usr/bin/python
# -*- coding: latin1 -*-
import Numeric
import cPickle
import sys
if len(sys.argv) > 1 and sys.argv[1] == '-dump':
filename = sys.argv[2]
binary=1
a = Numeric.arange(10) 
cPickle.dump(a, file(filename,'w',binary))

else:
filename = sys.argv[1]
a = cPickle.load(file(filename))
print a


-
So what would you suggest ? Can I hack Numeric to assume non-native
32 bit integer numbers ?
Many thanks for any help,
Johannes
It might be worth posting to the Numeric mailing list, mirrored at 
http://news.gmane.org/gmane.comp.python.numeric.general

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


Re: Solution for architecure dependence in Numeric ?

2005-02-18 Thread Paul Rubin
Johannes Nix |[EMAIL PROTECTED]> writes:
> So what would you suggest ? Can I hack Numeric to assume non-native
> 32 bit integer numbers ?

I think it would be better to fix the pickle/cPickle module to
correctly unpack the 32-bit ints on your 64 bit machine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Annoying Socket Problem

2005-02-18 Thread John Abel
I'm hoping this is something simple, and someone can point me in the 
right direction here.  I have a class based on SocketServer 
(ThreadingTCPServer), and I've used makefile on the socket so I use the 
"for in " routine.  My client sends it a small amount of data.  However, 
both programs appear to hang once the data has been sent, obviously 
something to do with flushing.

I'd appreciate any pointers.
Regards
J
Server Class:
class _DBSocketHandler( SocketServer.BaseRequestHandler ):
  
   xmlStart = re.compile( "XML-START" )
   xmlEnd = re.compile( "XML-END" )
  
   def handle( self ):
   print "Accepted Connection From", self.client_address
   socketIn = self.request.makefile( 'r' )
   socketOut = self.request.makefile( 'wb' )
   remoteDoc = None
   for dataIn in socketIn:
   if self.xmlEnd.match( dataIn ):
   remoteDoc.close()
   break
   if self.xmlStart.match( dataIn ):
   print "Receiving XML"
   remoteDoc = StringIO()
   continue
  
   if remoteDoc is not None:
   remoteDoc.write( dataIn )
  
   socketOut.write( "Got Yer XML File, Thanks" )

Client Code:
   def connect( self ):
   self.socketCon.connect( ( self.dbServer, self.dbPort ) )
   testFile = StringIO.StringIO( testXML )
   self.socketCon.send( "XML-START" )
   for xmlSQL in testFile:
   self.socketCon.send( xmlSQL )
   testFile.close()
   self.socketCon.send( "XML-END" )
   self.socketCon.send( "" )
   time.sleep(10)
   while True:
   dataRec = self.socketCon.recv( 8192 )
   if not dataRec: break
   self.socketCon.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: low-end persistence strategies?

2005-02-18 Thread John Lenton
On Thu, Feb 17, 2005 at 10:20:58PM -0800, Michele Simionato wrote:
> Ok, I have yet another question: what is the difference
> between fcntl.lockf  and fcntl.flock? The man page of
> my Linux system says that flock is implemented independently
> of fcntl, however it does not say if I should use it in preference
> over fcntl or not.

it depends on what you want to do: as the manpages say, flock is
present on most Unices, but lockf is POSIX; flock is BSD, lockf is
SYSV (although its in XPG4.2, so you have it on newer Unices of any
flavor); on Linux, lockf works over NFS (if the server supports it),
and gives you access to mandatory locking if you want it. You can't
mix lockf and flock (by this I mean: you can get a LOCK_EX via flock
and via lockf on the same file at the same time).

So: use whichever you feel more comfortable with, although if you are
pretty confident your program will run mostly on Linux there is a bias
towards lockf given its extra capabilities there.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
¡¡  QQuuiittaa  eell  LLooccaall  EEcchhoo,,  MMaannoolloo  !!


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how can i randomly choose keys in dictionary

2005-02-18 Thread John Lenton
On Fri, Feb 18, 2005 at 09:35:30AM +0100, Thomas Guettler wrote:
> Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:
> 
> > Hi,there. How can I choose a key in dictionary randomly?
> > 
> > Say, random.choice() in lists,
> > 
> > or in lists:
> > lists = [1,2,3,4]
> > position = random.range(len(lists))
> > word = lists[position]
> 
> Hi, try this:
> 
> import random
> 
> mydict={1: "one", 2: "two"}
> print mydict[random.choice(mydict.keys())]

if you're going to do that, why don't you do

  print random.choice(mydict.values())

?

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Quien da parte de sus cohechos, de sus tuertos hace derechos. 


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Annoying Socket Problem

2005-02-18 Thread Irmen de Jong
John Abel wrote:
I'm hoping this is something simple, and someone can point me in the 
right direction here.  I have a class based on SocketServer 
(ThreadingTCPServer), and I've used makefile on the socket so I use the 
"for in " routine.  My client sends it a small amount of data.  However, 
both programs appear to hang once the data has been sent, obviously 
something to do with flushing.
http://www.amk.ca/python/howto/sockets/sockets.html#SECTION00040
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: difference between class methods and instance methods

2005-02-18 Thread Duncan Booth
Diez B. Roggisch wrote:

>> This is badly wrong. John was correct.
>> 
>> Bound methods get created whenever you reference a method of an
>> instance. If you are calling the method then the bound method is
>> destroyed as soon as the call returns. You can have as many different
>> bound methods created from the same unbound method and the same
>> instance as you want: 
> 
> That did escape me so far - interesting. Why is it that way? I'd
> expect that creating a bound method from the class and then storing it
> in the objects dictionary is what happens. 
> 
If you had a class with 50,000 methods it could take quite a while to 
create instances, consider Zope as an example where every object acquires 
large numbers of methods most of which are completely irrelevant. Even 
outside Zope most objects never have all their methods called: dict, for 
example, has 38 methods but most of them get little or no use.

Creating a bound method is a comparatively cheap operation, its a small 
object which just has to hold references to the instance and the function.
The memory allocation is fast, because Python keeps lists of appropriately 
sized buckets for small objects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] exercise: partition a list by equivalence

2005-02-18 Thread anton muhin
Xah Lee wrote:
here's another interesting algorithmic exercise, again from part of a
larger program in the previous series.
Here's the original Perl documentation:
=pod
merge($pairings) takes a list of pairs, each pair indicates the
sameness
of the two indexes. Returns a partitioned list of same indexes.
For example, if the input is
merge( [ [1,2], [2,4], [5,6] ] );
that means 1 and 2 are the same. 2 and 4 are the same. Therefore
1==2==4. The result returned is
[[4,2,1],[6,5]];
(ordering of the returned list and sublists are not specified.)
=cut
Almost a joke:
from numarray import *
def merge(*pairs):
  flattened = reduce(tuple.__add__, pairs, tuple())
  m, M = min(flattened), max(flattened)
  d = M - m + 1
  matrix = zeros((d, d), type = Bool)
  for x, y in pairs:
X, Y = x - m, y - m
matrix[X, X] = 1
matrix[X, Y] = 1
matrix[Y, X] = 1
matrix[Y, Y] = 1
  while True:
next = greater(dot(matrix, matrix), 0)
if alltrue(ravel(next == matrix)):
  break
matrix = next
  results = []
  for i in range(d):
eqls, = nonzero(matrix[i])
if eqls.size():
  if i == eqls[0]:
results.append(tuple(x + m for x in eqls))
  return results
Disclaimer: I'm not an expert in numarray and suppose the something can 
be dramatically imporved.
--
http://mail.python.org/mailman/listinfo/python-list


Re: difference between class methods and instance methods

2005-02-18 Thread Antoon Pardon
Op 2005-02-18, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>> This is badly wrong. John was correct.
>> 
>> Bound methods get created whenever you reference a method of an instance.
>> If you are calling the method then the bound method is destroyed as soon
>> as the call returns. You can have as many different bound methods created
>> from the same unbound method and the same instance as you want:
>
> That did escape me so far - interesting. Why is it that way? I'd expect that
> creating a bound method from the class and then storing it in the objects
> dictionary is what happens. 
>

No. What happens is that functions are descriptors. So if you
assign a function to a class attribute any access to this
attribute will call the __get__ method which will create a
bound method if the access was through an instance or an
unbound method if the access was through the class.

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


How to save an image created from multiple images?

2005-02-18 Thread Antti Isomursu
Ok, this is my problem:

I have succesfully created an image by pasting smaller images into
area, created with canvas method:
>>> canvas = Canvas(win, width=canvasX, height=canvasY,
background='white')
""" Then I add images to picture using line below """
>>> canvas.create_image(ax, yy, anchor='nw', image=testi)

So, I got the image i wanted. How can I now save that picture as an
jpeg?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: having troubleing finding package for Twisted 1.3 for Mac OS X 10.3.x

2005-02-18 Thread John
fuzzylollipop wrote:
just got a Powerbook and need to do twisted development on it, but I
can't find a simple straight foward instructions on installing Twisted
1.3 on it.
Also the package manager at undefined.org has 1.1.0 and it doesn't work
with 10.3.x ( pre-installed Python )
any help is welcome
I'm pretty sure the package manager at undefined.org had
lapsed into disrepair. IIRC, the author has not updated
it in a long time and doesn't plan to.
Have you tried building from source? It should just be
a simple './configure', 'make', and 'sudo make install',
no?
---J
--
--- remove zees if replying via email ---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying Socket Problem

2005-02-18 Thread John Abel
Read/tried that before posting.  Even with a flush, everything hangs 
until I kill the client.

Irmen de Jong wrote:
John Abel wrote:
I'm hoping this is something simple, and someone can point me in the 
right direction here.  I have a class based on SocketServer 
(ThreadingTCPServer), and I've used makefile on the socket so I use 
the "for in " routine.  My client sends it a small amount of data.  
However, both programs appear to hang once the data has been sent, 
obviously something to do with flushing.

http://www.amk.ca/python/howto/sockets/sockets.html#SECTION00040 

--Irmen

--
*John Abel
Senior Unix Administrator*
PA News Limited
www.pa.press.net 
E-Mail address: [EMAIL PROTECTED] 
Telephone Number : 01430 43
Fax Number : 0870 1240192
Mobile Number : 07971 611356
The Bishop's Manor, Market Place, Howden, DN14 7BL
PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered 
in England No. 3891053.
--
http://mail.python.org/mailman/listinfo/python-list


Chart Director?

2005-02-18 Thread kdahlhaus
Does anyone here have experience with Chart Director
(http://www.advsofteng.com/index.html)?   I'm thinking about purchasing
it and looking for any feedback from the Python community.  Thanks

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


Platform independent adduser script?

2005-02-18 Thread morphex
Hi there,

does anyone here know of a script that enables adding of users on UNIX
platforms via python?

Thanks,

Morten

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


Re: Platform independent adduser script?

2005-02-18 Thread Grant Edwards
On 2005-02-18, morphex <[EMAIL PROTECTED]> wrote:
> Hi there,
>
> does anyone here know of a script that enables adding of users on UNIX
> platforms via python?

os.system("adduser ... ") ?

The way that users are added on "UNIX platforms" varies.  Most
(Linux, BSD, Solaris) seem to have an "adduser" command.  I
don't know how consistent the format of the adduser arguements
are.

-- 
Grant Edwards   grante Yow!  Didn't I buy a 1951
  at   Packard from you last March
   visi.comin Cairo?
-- 
http://mail.python.org/mailman/listinfo/python-list


interface like behavior for mudules

2005-02-18 Thread paolo_veronelli
Hello  pyple,
I have two modules :remote.py  and local.py which have some classes with 
the same names specifically one we can call Model.So it exist 
remote.Model class and local.Model class

A third module called uri.py  derives some of its classes from a not 
better specified repository.Model

at the beginning of uri.py I can write 'import local as repository' or 
'import remote as repository'. In either cases the module uri is ready 
to be imported from a fourth module

Now I have two applications ,say applocal.py and appremote.py. Both 
import uri as a module ,but the first wants uri to have imported local 
as repository and the second wants uri to have imported remote as 
repository.

In pseudo language applocal.py would have 'import uri with local as 
repository'  at the beginning and appremote.py would have 'import uri 
with remote as repository'

I wonder if there is a way to keep uri unique,because as it is now I 
have to keep two modules,say urilocal and uriremote which differs only 
for a line at the top.

I suppose __import__ is there to help me, but I have no idea on how.
Hope I have been clear,thanks for considerations and help
Yours Paolino
--
http://mail.python.org/mailman/listinfo/python-list


3d graphics

2005-02-18 Thread Eric Hanson
Hi,

I'm interested in doing some work with 3d graphics
visualizations of XML/RDF data in Python.  I know Python is
strong on the XML front but what about 3d graphics?  Is there a
graphics library out there with graphics library with a fairly
gradual learning curve?  Do people actually use Python for games
programming and the likes?

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


Re: low-end persistence strategies?

2005-02-18 Thread Michele Simionato
Uhm ... I reading /usr/src/linux-2.4.27/Documentation/mandatory.txt
The last section says:

"""
6. Warning!
---

Not even root can override a mandatory lock, so runaway processes can
wreak
havoc if they lock crucial files. The way around it is to change the
file
permissions (remove the setgid bit) before trying to read or write to
it.
Of course, that might be a bit tricky if the system is hung :-(
"""

so lockf locks do not look completely harmless ...

  Michele Simionato

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


Re: msnp, friends list

2005-02-18 Thread jr
Mark,
Thank you so much for that information. Been struggling with this issue
for quite some time now. A simle line comment on line 647 of session.py
solves all problems :)
this line sets your status to online and does not get time (usually) to
get friends list correctly.

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


Re: [perl-python] exercise: partition a list by equivalence

2005-02-18 Thread John Lenton
On Thu, Feb 17, 2005 at 03:46:20PM -0800, Xah Lee wrote:
> here's another interesting algorithmic exercise, again from part of a
> larger program in the previous series.
> 
> Here's the original Perl documentation:
> 
> =pod
> 
> merge($pairings) takes a list of pairs, each pair indicates the
> sameness
> of the two indexes. Returns a partitioned list of same indexes.
> 
> For example, if the input is
> merge( [ [1,2], [2,4], [5,6] ] );
> 
> that means 1 and 2 are the same. 2 and 4 are the same. Therefore
> 1==2==4. The result returned is
> 
> [[4,2,1],[6,5]];
> 
> (ordering of the returned list and sublists are not specified.)
> 
> =cut

in Python:

def merge(pairings):
rev = {}
res = []
for pairing in pairings:
first, second = pairing
has_first = first in rev
has_second = second in rev
if has_first and has_second:
rev[first].extend(rev[second])
rev[second][:] = []
rev[second] = rev[first]
elif has_first:
rev[first].append(second)
rev[second] = rev[first]
elif has_second:
rev[second].append(first)
rev[first] = rev[second]
else:
copy = [first, second]
res.append(copy)
rev[first] = rev[second] = copy
return filter(None, res)

and in Perl:

sub merge($)
{
my %rev = ();
my @res = ();
my ($pairing, $first, $second, $has_first, $has_second);
foreach $pairing (@{$_[0]})
{
($first, $second) = @$pairing;
$has_first = exists $rev{$first};
$has_second = exists $rev{$second};
if ($has_first and $has_second)
{
push @{$rev{$first}}, @{$rev{$second}};
@{$rev{$second}} = ();
$rev{$second} = $rev{$first};
}
elsif (exists $rev{$first})
{
push @{$rev{$first}}, $second;
$rev{$second} = $rev{$first};
}
elsif (exists $rev{$second})
{
push @{$rev{$second}}, $first;
$rev{$first} = $rev{$second};
}
else
{
my @copy = ($first, $second);
push @res, [EMAIL PROTECTED];
$rev{$first} = $rev{$second} = [EMAIL PROTECTED];
}
}
return [grep @$_, @res];
}

although in Perl you wouldn't define it to take a reference to a list
(as you did), but rather a list, and you wouldn't define it to return
a reference to a list, but rather a list in list context (and possibly
a reference in scalar context).

Both versions are (IMHO) pretty clear (when the docstring/pod is
included), and O(n) because dict/hash lookup and list
appending/pushing is O(1) in both languages. Both versions can
probably be tweaked for speed quite a bit, but I don't *think* there's
a better-than-O(n) algorithm for this.

Note that the Python version assumes that the pairs' elements are
hashable; your example used numbers, so I thought it was pretty safe
assumption. The Perl version has no such restriction.


-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Noble cosa es, aún para un anciano, el aprender.
-- Sófocles. (497-406 a.C.) Filósofo griego. 


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: low-end persistence strategies?

2005-02-18 Thread John Lenton
On Fri, Feb 18, 2005 at 07:57:21AM -0800, Michele Simionato wrote:
> Uhm ... I reading /usr/src/linux-2.4.27/Documentation/mandatory.txt
> The last section says:
> 
> """
> 6. Warning!
> ---
> 
> Not even root can override a mandatory lock, so runaway processes
> can wreak havoc if they lock crucial files. The way around it is to
> change the file permissions (remove the setgid bit) before trying to
> read or write to it.  Of course, that might be a bit tricky if the
> system is hung :-(
> """
> 
> so lockf locks do not look completely harmless ...

if you read the whole file, you will have read that turning on
mandatory locks is not trivial. I never said it was harmless, and in
fact (as that section explains) it's a bad idea for most cases; there
are some (very few) situations where you need it, however, and so you
can get at that functionality. Having to mount your filesystem with
special options and twiddling the permission bits is a pretty strong
hint that the implementors didn't think it was a good idea for most
cases, too.

Hmm, just read that file, and it doesn't mention the "have to mount
with special options" bit. But if you look in mount(8), you see an
entry under the options list,

   mand   Allow mandatory locks on this filesystem. See fcntl(2)

and if you look in fcntl(2), you see that

   Mandatory locking
   (NonâPOSIX.)  The above record locks may be either adviâ
   sory or mandatory, and are advisory by default.  To make
   use  of  mandatory  locks,  mandatory  locking  must  be
   enabled (using the "âo mand" option to mount(8)) for the
   file system containing the file to be locked and enabled
   on the file itself (by disabling group  execute  permisâ
   sion  on  the  file  and enabling the setâGID permission
   bit).

   Advisory locks are not  enforced  and  are  useful  only
   between   cooperating  processes.  Mandatory  locks  are
   enforced for all processes.

if I have come across as recommending mandatory locks in this thread,
I apologize, as it was never my intention. It is a cool feature for
the .001% of the time when you need it (and the case in discussion in
this thread is not one of those), but other than that it's a very,
very bad idea. In the same league of badness as SysV IPC; I'd still
mention SysV IPC to someone who asked about IPC on Linux, however,
because there are places where it is useful even though most times
it's a stupid way to do things (yes, Oracle, *especially* you).

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
A pencil with no point needs no eraser.


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Help with research

2005-02-18 Thread Jack Diederich
On Thu, Feb 17, 2005 at 07:09:44PM -0500, Jeremy Bowers wrote:
> On Thu, 17 Feb 2005 15:51:47 -0800, elena wrote:
> > I can go to my friends, however it occurred to me that it might be
> > better to post in a newsgroup and get a larger, more diverse, and
> > random sample. 
> 
> Larger, yes, more diverse, yes, more random, probably not in the
> statistical/scientific sense. Caveat emptor.

Bigtime, I see you have a occupation box for "Software Developer" and
"Other."  The data for software people (and lawyers) may be noisy becuase
they take the questions literally.  Because the answers are True/False
folks might parse them narrowly for their truth value (and all in an 
effort to help!).  for instance,

"I find that it is possible to be too organized when performing certain  
 kinds of tasks."

False, I don't find this is possible because I'm not organized.  

This reminds me of a story, for Psychology 101 all freshman had to
participate in three experiments by grad students.  One I did involved
riding on an excercise bike for ten minutes wearing a heart monitor.
After that you could leave as soon as you felt your heartrate was back
to normal.  The study concluded that people are bad at knowing when
their heart rate is elevated.  I concluded that undergrads will only
do the minimum to pass a course, and are willing to lie about their
heartrate if it gets them out the door five minutes sooner.

Be careful with data!

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


Re: 3d graphics

2005-02-18 Thread Mike C. Fletcher
Eric Hanson wrote:
Hi,
I'm interested in doing some work with 3d graphics
visualizations of XML/RDF data in Python.  I know Python is
strong on the XML front but what about 3d graphics?  Is there a
graphics library out there with graphics library with a fairly
gradual learning curve?  Do people actually use Python for games
programming and the likes?
 

Python's got a few 3D libraries:
   http://www.vrplumber.com/py3d.py
You'll probably be most interested in a scenegraph/retained-mode 
renderer, listed here:

   http://www.vrplumber.com/py3d.py?category=retained
depending on your background, VPython (or VTK/MayaVi if you're more from 
a science background) might be a good starting point.  Soya or Panda 
seem more involved, but probably take you a little further toward 
game-like engines.  Pivy or OpenGLContext (both being Inventor-style 
scenegraphs) are more toolkits for developers to build applications, 
they generally let you load and work with objects readily, but they 
aren't trying to provide "jumping, shooting and exploding" features 
out-of-the-box.  Then there are the full (normally C++) game engines 
with Python wrappers, likely a steeper learning curve, but once you get 
up and running they should give you fairly easy going for writing a game.

Most (commercial) games that use Python follow that last model, a C++ 
engine that uses Python for scripting and extensions.  AFAIK there 
hasn't been a (commercial) 3D game (graphics engine) written with Python 
as the primary implementation language (for the graphics engine).  Of 
the retained-mode renderers on that page, only a handful are primarily 
Python code; it takes a lot of work to get a decently performing 
scenegraph engine written in Python.

HTH,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
 PyCon is coming...
--
http://mail.python.org/mailman/listinfo/python-list


WebServices/SOAP/Zolera Arghhhhhhhhh!!!!!!...not so much

2005-02-18 Thread Tom Willis
I am not a SOAP/Web Services expert!!

But I had to interface with some webservice code here at work. I was
reading on the net the complextypes didn't work or were finnicky
etc

Well I managed to get it to work on Zolera 1.7. First the code
generated from the wsdl didn't work without some editing due to types
being declared later in the file but referenced earlier, and being in
different namespaces.

The next hurdle was getting the request to serialize properly. My
request consisted of some strings and a complextype which was nothing
but strings accept for a date.

The date serialization was throwing an error. There was an article on
ibm dev works where they claimed to not be able to get it to work. So
I tried some things

def parsedatestring(datestr):
#SQLServer Date Format delimited by space 1st part date (/) 2nd
part time (:)
dt = datestr.strip("'").split(" ")
month,day,year = dt[0].split("/")
hour,minute,second = dt[1].split(":")

#this one works
return 
datetime(int(year),int(month),int(day),int(hour),int(minute),int(second)).utctimetuple()

#throws "Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError int argument
required"
#return "%s-%s-%s" % (year,month,day)

#throws error " Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError int argument
required"
#return "%s-%s-%sT%s:%s:%s" % (year,month,day,hour,minute,second)

#throws "Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError not all
arguments converted during string formatting"
#return 
tuple((int(year),int(month),int(day),int(hour),int(minute),int(second)))

#throws "Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError not all
arguments converted during string formatting"
#return tuple((year,month,day,hour,minute,second))

#throws "Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError not all
arguments converted during string formatting"
#return 
tuple((float(year),float(month),float(day),float(hour),float(minute),float(second)))

#throws "Exception Serializing demo
xmlns="http://DefaultNamespace"._birthDate, TypeError iteration over
non-sequence"
#return 
datetime(int(year),int(month),int(day),int(hour),int(minute),int(second))


Call me stupid, but I could not find out anywhere in the ZLI docs, the
web, code or anything that specified I pass a utctimetuple. As a
client of the API, I would assume it would be converted for me if I
pass a python object.


Anyway, I'm not bitching so much about the api as I am making an
effort to get this out there on the web just in case someone else is
hitting a brick wall on webservice interaction with python.

I'm not convinced that Simple Object Access Protocol is actually
simple. I guess if you compare to raw sockets yeah. Easier than COM+ ?
Hardly.

-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


DB Schema

2005-02-18 Thread Gabriel B.
I started to use dbschema.com but it has some big flaws (mainly
regarding keys and mysql) and besides it's being in java (wich i don't
like to code at all) it's closed source.

I'm considering starting a new GPL one in python, so, i ask if you
people already know a project like that.

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


Newbie CGI problem

2005-02-18 Thread Rory Campbell-Lange
#!/usr/bin/python
import cgi
print "Content-type: text/html\n\n"
print "hi"

Gives me the following in my browser:

'''
hi
Content-type: text/html


hi
'''

Why are there two 'hi's?

Thanks,
Rory
-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


unicode encoding usablilty problem

2005-02-18 Thread aurora
I have long find the Python default encoding of strict ASCII frustrating.  
For one thing I prefer to get garbage character than an exception. But the  
biggest issue is Unicode exception often pop up in unexpected places and  
only when a non-ASCII or unicode character first found its way into the  
system.

Below is an example. The program may runs fine at the beginning. But as  
soon as an unicode character u'b' is introduced, the program boom out  
unexpectedly.

sys.getdefaultencoding()
'ascii'
a='\xe5'
# can print, you think you're ok
... print a
å
b=u'b'
a==b
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0:  
ordinal not in range(128)


One may suggest the correct way to do it is to use decode, such as
  a.decode('latin-1') == b
This brings up another issue. Most references and books focus exclusive on  
entering unicode literal and using the encode/decode methods. The fallacy  
is that string is such a basic data type use throughout the program, you  
really don't want to make a individual decision everytime when you use  
string (and take a penalty for any negligence). The Java has a much more  
usable model with unicode used internally and encoding/decoding decision  
only need twice when dealing with input and output.

I am sure these errors are a nuisance to those who are half conscious to  
unicode. Even for those who choose to use unicode, it is almost impossible  
to ensure their program work correctly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-18 Thread aurora
Not sure about the repeated hi. But you are supposed to use \r\n\r\n, not  
just \n\n according to the HTTP specification.

#!/usr/bin/python
import cgi
print "Content-type: text/html\n\n"
print "hi"
Gives me the following in my browser:
'''
hi
Content-type: text/html
hi
'''
Why are there two 'hi's?
Thanks,
Rory
--
http://mail.python.org/mailman/listinfo/python-list


Re: difference between class methods and instance methods

2005-02-18 Thread Steven Bethard
Duncan Booth wrote:
Diez B. Roggisch wrote:
Duncan Booth wrote:
Bound methods get created whenever you reference a method of an
instance.
That did escape me so far - interesting. Why is it that way? I'd
expect that creating a bound method from the class and then storing it
in the objects dictionary is what happens. 
If you had a class with 50,000 methods it could take quite a while to 
create instances, consider Zope as an example where every object acquires 
large numbers of methods most of which are completely irrelevant. Even 
outside Zope most objects never have all their methods called: dict, for 
example, has 38 methods but most of them get little or no use.
So why couldn't bound methods be created like lazy properties:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602
So that they're not created at instance creation time, but they're only 
created once, when first accessed?

Not that I've ever had any problems with the speed or memory usage of 
bound methods -- I'm just curious about the design decision.

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


Re: combining several lambda equations

2005-02-18 Thread Steven Bethard
Paddy McCarthy wrote:
x=lambda : A < B
y=lambda : C+6 >= 7
[snip]
Z=lambda : (A=7)
See "Inappropriate use of Lambda" in
http://www.python.org/moin/DubiousPython
Perhaps your real example is different, but notice that
 = lambda : 
is equivalent to
def ():
return 
except that the latter will give your function a useful name.  No reason 
to use the *anonymous* function construct to create a *named* function.

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


Re: Newbie CGI problem

2005-02-18 Thread Peter Otten
Rory Campbell-Lange wrote:

> #!/usr/bin/python
> import cgi
> print "Content-type: text/html\n\n"
> print "hi"
> 
> Gives me the following in my browser:
> 
> '''
> hi
> Content-type: text/html
> 
> 
> hi
> '''
> 
> Why are there two 'hi's?

You have chosen a bad name for your script: cgi.py.
It is now self-importing. Rename it to something that doesn't clash with the
standard library, and all should be OK.

Peter


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


Re: low-end persistence strategies?

2005-02-18 Thread pyguy2
You do not need to use a  24/7 process for low end persistance, if you
rely on the fact that only one thing can ever succeed in making a
directory. If haven't seen a filesystem where this isn't the case. This
type of locking works cross-thread/process whatever.

An example of that type of locking can be found at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252495

The only problem with this locking is if a process dies w/out cleaning
up the lock, how do you know when to remove them?
If you have the assumption that the write to the database is quick
(ok for low end), just have the locks time out after a minute. And if
you need to keep the lock longer, unpeel  appropriately and reassert
them.

With 2 lock directories, 2 files and 1 temporary file, you end up with
a hard to break system. The cost is disk space, which for low end
should be fine.

Basically, the interesting question is, how far can one,
cross-platform, actually go in building a persistence system with long
term process business.

john

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


Re: Newbie CGI problem

2005-02-18 Thread m
m wrote:
gives just one hi for me.
"
Content-type: text/html
hi
"
I get this
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-18 Thread m
Rory Campbell-Lange wrote:
#!/usr/bin/python
import cgi
print "Content-type: text/html\n\n"
print "hi"
Gives me the following in my browser:
'''
hi
Content-type: text/html
hi
'''
Why are there two 'hi's?
Thanks,
Rory
gives just one hi for me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Mike C. Fletcher
[Samantha: your email has been bouncing, might want to clear your inbox]
Samantha wrote:
Thanks Mike. I must have not installed the ttfquery and font tools 
correctly. I get an error. This error:
 

...
ImportError: No module named fontTools
Like I said I think I am way in over my short head.
S
 

Does look as though you missed getting FontTools installed.  You realise
it's a separate package from TTFQuery, right?
   http://sourceforge.net/projects/fonttools/
You'll have to do the standard:
   python setup.py install
to get it installed on your system.
HTH,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
 PyCon is coming...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-18 Thread aurora
On Fri, 18 Feb 2005 18:36:10 +0100, Peter Otten <[EMAIL PROTECTED]> wrote:
Rory Campbell-Lange wrote:
#!/usr/bin/python
import cgi
print "Content-type: text/html\n\n"
print "hi"
Gives me the following in my browser:
'''
hi
Content-type: text/html
hi
'''
Why are there two 'hi's?
You have chosen a bad name for your script: cgi.py.
It is now self-importing. Rename it to something that doesn't clash with  
the
standard library, and all should be OK.

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


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Samantha
Mike,
Not sure why that email bounced.
I downloaded these files:
WinTTX2.0b1.exe
TTFQuery-1.0.0.win32.exe
numarray-1.1.1.win32-py2.4.exe

They all seemed to install. Is WinTTX2.0b1.exe not the fontTools file?
S

"Mike C. Fletcher" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> [Samantha: your email has been bouncing, might want to clear your inbox]
>
> Samantha wrote:
>
>>Thanks Mike. I must have not installed the ttfquery and font tools 
>>correctly. I get an error. This error:
>>
> ...
>
>>ImportError: No module named fontTools
>>
>>Like I said I think I am way in over my short head.
>>S
>>
> Does look as though you missed getting FontTools installed.  You realise
> it's a separate package from TTFQuery, right?
>
>http://sourceforge.net/projects/fonttools/
>
> You'll have to do the standard:
>
>python setup.py install
>
> to get it installed on your system.
>
> HTH,
> Mike
>
> 
>  Mike C. Fletcher
>  Designer, VR Plumber, Coder
>  http://www.vrplumber.com
>  http://blog.vrplumber.com
>  PyCon is coming...
>
> 


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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-18 Thread Ilias Lazaridis
[this is a summary of a private conversation that I had with the 
developer of the phMinGW. It contains just my comments. I've send 
additionally a CC via email (private-to-public switch notification)]

-
A.B., Khalid wrote:
[...]
Khalid,
first of all I like to thank you for the efforts you have taken to
provide pyMinGW to the python community.
I would like to assist you with your efforts, see below.
If passing all the regression tests of the official Windows Python 
distribution is an indication of the quality of patch-- and pyMinGW 
patched and MinGW built Python does pass all of them-- then one is 
inclined to say that pyMinGW is a good patch.

=> {pyMinGW is a good patch}
The reason why it is, on the other hand, not included in the official
 distribution is threefold.
1. Contrary to what many might imagine, I don't think enough people
use MinGW to frankly justify any extra effort beyond pyMinGW.

The defined "extra effort" is the effort to provide the patches for the
main source-code base?
If you can send me an email of how to do this, I would take this effort.
of course I must first know, that the python-team would accept those
patches (technical applicability provided).
Thus this can wait, until an official response.
2. Given number 1 above, this patch, I believe, and I could be 
mistaken, must not rush to be included in Python's core;

Of course you are right.
people like your esteemed person should test it (note that it is
designed not to interfere with your trusted and working official
Python, if any);

=> {trusted and working official python}
: it is
only when enough people do such testing that there will be a case for
 it to be included in Python's core.

I agree with you.
If you are willing to extend your project, thus the intrested community
members can collaborate, I would like to assist you to do so.
I would try to take away all setup efforts from you.
3. Finally. there is nothing wrong with third-party patches if they
get the job done, which I believe is the case with pyMinGW.

You have stated above: "trusted and working official python"
The main goal would be, to get a "trusted and working official python"
based on MinGW, _within_ the official source-code-base.
The secondary goal would be, to get a "trusted and working official
python" based on MinGW, _with_ a very close to the official
source-code-base (possibly with just one #define).
-
Please contact me vial email if you are intrested.
Regards, Khalid

Best Regards,
ILIAS LAZARIDIS
-
-
-
After some comments, [which did not show to me an intrested of making 
the above happen (which is fully in the developers rights)], I've 
simplified my suggestions in the following message:

"
thank you for your comments.
I will express my suggestion more practically
  * as a first step, I would setup a pyMinGW mailinglist
* intrested people can come together an communicate
  * as a second step, I would setup an SVN
* intrested projects could get your patch via SVN
  * as a third step, I would find intrested contributors
* which would help testing
* which would help you with coding
All this could happen without (or with very low) efforts for you.
"
-
-
-
I got no answer.
-
-
-
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


re.compile and very specific searches

2005-02-18 Thread rbt
Is it possible to use re.compile to exclude certain numbers? For 
example, this will find IP addresses:

ip = re.compile('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}')
But it will also find 999.999.999.999 (something which could not 
possibly be an IPv4 address). Can re.compile be configured to filter 
results like this out?
--
http://mail.python.org/mailman/listinfo/python-list


wxPython demo /Process does not open new demo

2005-02-18 Thread Andy Leszczynski
Try to run wxPython 2.5 (for python 2.3) demo. Then Open Process and 
Events/Process. Type in "python -u demo.py" and wait. There is a splash 
screen but nothing more. Why?

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


Re: wxPython demo /Process does not open new demo

2005-02-18 Thread Andy Leszczynski
Andy Leszczynski wrote:
Try to run wxPython 2.5 (for python 2.3) demo. Then Open Process and 
Events/Process. Type in "python -u demo.py" and wait. There is a splash 
screen but nothing more. Why?

Regards,A.
Forgot to add that it happnes on Win2K.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-18 Thread Fredrik Lundh
anonymous coward <[EMAIL PROTECTED]> wrote:

> This brings up another issue. Most references and books focus exclusive on  
> entering unicode 
> literal and using the encode/decode methods. The fallacy  is that string is 
> such a basic data type 
> use throughout the program, you  really don't want to make a individual 
> decision everytime when 
> you use  string (and take a penalty for any negligence). The Java has a much 
> more  usable model 
> with unicode used internally and encoding/decoding decision  only need twice 
> when dealing with 
> input and output.

that's how you should do things in Python too, of course.  a unicode string
uses unicode internally. decode on the way in, encode on the way out, and
things just work.

the fact that you can mess things up by mixing unicode strings with binary
strings doesn't mean that you have to mix unicode strings with binary strings
in your program.

> Even for those who choose to use unicode, it is almost impossible  to ensure 
> their program work 
> correctly.

well, if you use unicode the way it was intended to, it just works.

 



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


Re: having troubleing finding package for Twisted 1.3 for Mac OS X 10.3.x

2005-02-18 Thread fuzzylollipop
nope I was hoping there was a more "mac" way of doing that :-)

I will research that and see what I can get to work, I am born-again
Mac user ( last machine was a 7200 ) just got a PowerBook so I am in
re-learn mode again ( am familiar with Unix that is why I wanted the
PowerBook as a change of pace )

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


Re: "Best" way to SIGHUP spamd from web page?

2005-02-18 Thread stephen
Webmin (webmin.com) has a command shell module (cgi over https?). Isn't
this an example of a secure way to run commands via the internet?

Stephen

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


Re: re.compile and very specific searches

2005-02-18 Thread Diez B. Roggisch
rbt wrote:

> Is it possible to use re.compile to exclude certain numbers? For
> example, this will find IP addresses:
> 
> ip = re.compile('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}')
> 
> But it will also find 999.999.999.999 (something which could not
> possibly be an IPv4 address). Can re.compile be configured to filter
> results like this out?

You could use another regular expressin, e.g. like this:

import re

rex = re.compile(r"^((\d)|(1\d{1,2})|(2[0-5]\d))$") 

for i in xrange(1000):
m = rex.match(str(i))
if m:
print m.groups(), i


This is of course only for one number. Extend it accordingly to the ip4
address format.

However, you won't be able to suppress the matching of e.g. 259 by that
regular expression. So I'd suggest you dump re and do it like this:

address = "192.168.1.1"

def validate_ip4(address):
digits = address.split(".")
if len(digits) == 4:
for d in digits:
if int(d) < 0 or int(d) > 255:
  return False
return True

-- 
Regards,

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


Re: move bugs from Zope BITS into Bugzilla?

2005-02-18 Thread lmhaskins
Does it import from BITS?

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


Re: unicode encoding usablilty problem

2005-02-18 Thread aurora
On Fri, 18 Feb 2005 19:24:10 +0100, Fredrik Lundh <[EMAIL PROTECTED]>  
wrote:

that's how you should do things in Python too, of course.  a unicode  
string
uses unicode internally. decode on the way in, encode on the way out, and
things just work.

the fact that you can mess things up by mixing unicode strings with  
binary
strings doesn't mean that you have to mix unicode strings with binary  
strings
in your program.
I don't want to mix them. But how could I find them? How do I know this  
statement can be potential problem

  if a==b:
where a and b can be instantiated individually far away from this line of  
code that put them together?

In Java they are distinct data type and the compiler would catch all  
incorrect usage. In Python, the interpreter seems to 'help' us to promote  
binary string to unicode. Things works fine, unit tests pass, all until  
the first non-ASCII characters come in and then the program breaks.

Is there a scheme for Python developer to use so that they are safe from  
incorrect mixing?
--
http://mail.python.org/mailman/listinfo/python-list


duplicate docstrings

2005-02-18 Thread Steven Bethard
I have two classes that implement the same interface, e.g. something like:
class C(object):
def foo(self):
"""Foo things"""
...
def bar(self):
"""Bar things"""
...
def baz(self):
"""Baz things in a C manner"""
...
class D(object):
def foo(self):
"""Foo things"""
...
def bar(self):
"""Bar things"""
...
def baz(self):
"""Baz things in a D manner"""
...
It bothers me that I'm basically writing the same docstrings multiple 
times.  I guess what I really want to do is just write the docstrings 
for the interface I'm describing, and only supply docstrings in the 
classes when they need to differ from the interface docstrings.

Is there a good way to do this?  If it's necessary, I can have C and D 
inherit from another class...

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


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Fredrik Lundh
"Samantha" <[EMAIL PROTECTED]> wrote:

>I am attempting to extract the Font Names from the installed windows fonts. I 
>am having a heck of a 
>time getting these rather than the file names. Examples can be seen by going 
>to Control Panel > 
>Fonts

here's one way to do it (using Tkinter):

>>> import Tkinter, tkFont
>>> tk = Tkinter.Tk()
>>> tkFont.families()
('System', 'Terminal', 'Fixedsys', 'Roman', 'Script', 'Modern', 'Small Fonts', 
'MS Serif', ...)

here's another way (using PIL):

import os
from PIL import ImageFont

fontdir = os.path.join(os.environ["windir"], "fonts")

for fontfile in os.listdir(fontdir):
  try:
font = ImageFont.truetype(os.path.join(fontdir, fontfile), 1)
  except IOError:
pass
  else:
print font.font.family, font.font.style

(this prints a list of family/style combinations).  You can get PIL from

http://www.pythonware.com/products/pil/ (1.1.4)
http://effbot.org/downloads/#pil (1.1.5 betas)

 



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


unicode and socket

2005-02-18 Thread zyqnews
hello all,
 I am new in Python. And I have got a problem about unicode.
I have got a unicode string, when I was going to send it out throuth a
socket by send(), I got an exception. How can I send the unicode string
to the remote end of the socket as it is without any conversion of
encode, so the remote end of the socket will receive unicode string?

Thanks

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


Re: unicode encoding usablilty problem

2005-02-18 Thread Walter Dörwald
aurora wrote:
> [...]
In Java they are distinct data type and the compiler would catch all  
incorrect usage. In Python, the interpreter seems to 'help' us to 
promote  binary string to unicode. Things works fine, unit tests pass, 
all until  the first non-ASCII characters come in and then the program 
breaks.

Is there a scheme for Python developer to use so that they are safe 
from  incorrect mixing?
Put the following:
import sys
sys.setdefaultencoding("undefined")
in a file named sitecustomize.py somewhere in your Python path and
Python will complain whenever there's an implicit conversion between
str and unicode.
HTH,
   Walter Dörwald
--
http://mail.python.org/mailman/listinfo/python-list


RE: "Best" way to SIGHUP spamd from web page?

2005-02-18 Thread Robert Brewer
[EMAIL PROTECTED] wrote:
> Webmin (webmin.com) has a command shell module (cgi over 
> https?). Isn't this an example of a secure way to run
> commands via the internet?

Yes, if I wanted to write my app in Perl 5. ;) But as far as I can tell,
that relies heavily on Perl's taint-checking, which isn't available in
Python.

I ended up writing a daemon (running as root) which simply listens on a
local socket; when it receives any message, it HUPs spamd. Ugly but
effective.


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-18 Thread Josef Meile
It looks like here the only worth words are yours. Didn't
you close this thread?
I will refresh your mind with your own unpolite way:
"""
Ilias Lazaridis wrote:
[...]
closing thread
http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1
"""
Anyway, I will add some comments:
The defined "extra effort" is the effort to provide the patches for the
main source-code base?
If you can send me an email of how to do this, I would take this effort.
Good for you.
of course I must first know, that the python-team would accept those
patches (technical applicability provided).
There is no guaranty. Did you forget the reply from Tim Peters:
> [...] A problem is that a
> patch won't get reviewed unless a volunteer does a review, and we've
> got an increasing backlog of unreviewed patches because of that.  The
> most effective way for a person P to get their patch reviewed now is
> for P to volunteer to review 5 other patches first.  There are a few
> Python developers who have promised, in return, to review P's patch
> then.
So, you will have to review some patches first.
>Ilias> Now, can you please tell me the process I have to follow to
>Ilias> suggest the following (to the PSF or to the programmers or to
>Ilias> the decision takers),possibly to get at least a vote on it:
>Tim> No such thing will happen -- forget that.  For MinGW to be
>Tim> supported forever, it's necessary and sufficient that a specific
>Tim> person volunteer to support MinGW forever.  If that person goes
>Tim> away, so does the support they provided; it's the same story for
>Tim> Cygwin, and even for Linux and native Windows.
So, it is not just making the patch. You will have to compromise to
support it and not just go away.
Regards,
Josef
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode and socket

2005-02-18 Thread aurora
You could not. Unicode is an abstract data type. It must be encoded into  
octets in order to send via socket. And the other end must decode the  
octets to retrieve the unicode string. Needless to say the encoding scheme  
must be consistent and understood by both ends.

On 18 Feb 2005 11:03:46 -0800, <[EMAIL PROTECTED]> wrote:
hello all,
 I am new in Python. And I have got a problem about unicode.
I have got a unicode string, when I was going to send it out throuth a
socket by send(), I got an exception. How can I send the unicode string
to the remote end of the socket as it is without any conversion of
encode, so the remote end of the socket will receive unicode string?
Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Mike C. Fletcher
Samantha wrote:
Mike,
Not sure why that email bounced.
 

That last one bounced too, btw.
I downloaded these files:
WinTTX2.0b1.exe
TTFQuery-1.0.0.win32.exe
numarray-1.1.1.win32-py2.4.exe
They all seemed to install. Is WinTTX2.0b1.exe not the fontTools file?
 

I believe WinTTX is a font-editing program from which fontTools was 
split out into a separate project.

As well, though I don't *know* that this will cause problems, I'd 
thought fontTools required Numeric (Numpy) rather than Numarray.  Would 
try the fontTools package first with the Numarray you've installed, and 
if you then find problems with it not being able to find Numeric, 
install the Numpy release.

HTH,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
 PyCon is coming...
--
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-18 Thread Ilias Lazaridis
Josef Meile wrote:
It looks like here the only worth words are yours. Didn't
you close this thread?
yes, but when reviewing again I found this lack [created by myself due 
to private conversation].

I will refresh your mind with your own unpolite way:
I find this very polite [to notify conversation partners instead of 
letting them wait for an answer].

"""
Ilias Lazaridis wrote:
[...]
closing thread
http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1
"""
Anyway, I will add some comments:
[...]
The first step is to make a pyMinGW project.
If one is intrested, he has possibly more luck [than I had] to convince 
the author of pyMinGW.

Good luck.
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-18 Thread Alec Wysoker
I need to be able to access mySQL 4.0 and 4.1 databases from python.  I
was hoping to find mysql-python 1.2.0 already built for Sparc, but no
such luck.  I've been struggling trying to get it build.  First, I had
to hack setup.py because mysql_config --cflags was returning -m64,
which wasn't right because this is on a 32-bit processor.  Then I got a
warning:

ld: warning: file /usr/local/mysql/lib/libmysqlclient_r.a(libmysql.o):
wrong ELF class: ELFCLASS64

No idea if this is causing my current problem.

Finally, I seemed to get the thing built and installed, but why I try
to import MySQLdb, I get the following:

  File "/usr/local/lib/python2.3/site-packages/MySQLdb/__init__.py",
line 27, in ?
import _mysql
ImportError: ld.so.1: /usr/local/bin/python: fatal: relocation error:
file /usr/local/lib/python2.3/site-packages/_mysql.so: symbol
mysql_errno: referenced symbol not found

Any advice would be greatly appreciated.

Thanks, 

Alec Wysoker

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


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Pierre Quentel
"Samantha" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> I am attempting to extract the Font Names from the installed windows fonts. 
> I am having a heck of a time getting these rather than the file names. 
> Examples can be seen by going to Control Panel > Fonts
> 
> Any help or direction is appreciated.
> S

Try this :

Python 2.3.2 (#49, Oct  2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from Tkinter import Tk
>>> import tkFont
>>> root=Tk()
>>> print tkFont.families(root)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to get Font Names

2005-02-18 Thread Samantha
Thanks Fredrik,
The Tkinter method didn't give any results but using PIL did. I'll have to 
play with it a little.
Thanks again,
S
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Samantha" <[EMAIL PROTECTED]> wrote:
>


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


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Samantha
Mike,
Strange Hotmail.
I'll start over with the installs and you are correct on it being Numpy. I 
got the wrong file.
I'll give it a go and let you know.
Thanks
S
"Mike C. Fletcher" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Samantha wrote:
>


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


selecting dictionaries to maximize counts

2005-02-18 Thread Steven Bethard
I have a list of dictionaries.  Each dictionary holds counts of various 
'words', e.g.:

py> countdicts = [
... dict(a=9, b=9, c=9),
... dict(a=8, b=7),
... dict(a=4, b=5, c=12)]
I need to select dicts with the constraint that the number of each 
'word' totalled over all selected dicts doesn't exceed a given 
MAX_VALUE.  Right now, I do this by:

py> def select(dicts, n):
... result = []
... counts = {}
... def doadd(d):
... for label, count in d.iteritems():
... if counts.get(label, 0) + count > n:
... return False
... return True
... for d in dicts:
... if doadd(d):
... result.append(d)
... for label, count in d.iteritems():
... counts[label] = counts.get(label, 0) + count
... return result
...
Basically, I use a greedy approach -- adding a dict each time if I can. 
 This leads to some suboptimal solutions given that, while the total 
counts must not exceed MAX_VALUE, I'd like them to be as close to 
MAX_VALUE as possible.  An example of data on which my select function 
produces such a suboptimal solution:

py> countdicts = [
... dict(a=9, b=9, c=9),
... dict(a=8, b=7),
... dict(a=4, b=5, c=12)]
py> select(countdicts, 12)
[{'a': 9, 'c': 9, 'b': 9}]
The better solution would have been to select the second two dicts -- 
then all 'words' would have count 12.

I don't need an optimal solution; in fact, the solution I have right now 
is tolerable.  But if anyone knows a simple way to improve my 
performance, I'd appreciate it.  Thanks!

STeVe
P.S.  No, I'm not just making these problems up!  I'm sick, but not that 
sick. ;)  It has to do with resampling a set of data...  If you're 
really interested, I can provide the full details, but they'll only make 
the problem even _more_ complicated. =)
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-18 Thread Jarek Zgoda
Fredrik Lundh napisał(a):
This brings up another issue. Most references and books focus exclusive on  entering unicode 
literal and using the encode/decode methods. The fallacy  is that string is such a basic data type 
use throughout the program, you  really don't want to make a individual decision everytime when 
you use  string (and take a penalty for any negligence). The Java has a much more  usable model 
with unicode used internally and encoding/decoding decision  only need twice when dealing with 
input and output.
that's how you should do things in Python too, of course.  a unicode string
uses unicode internally. decode on the way in, encode on the way out, and
things just work.
There are implementations of Python where it isn't so easy, Python for 
iSeries (http://www.iseriespython.com/) is one of them. The code written 
for "normal" platform doesn't work on AS/400, even if all strings used 
internally are unicode objects, also unicode literals don't work as 
expected.

Of course, this is implementation fault but this makes a headache if you 
need to write portable code.

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


Re: unicode encoding usablilty problem

2005-02-18 Thread Thomas Heller
=?ISO-8859-15?Q?Walter_D=F6rwald?= <[EMAIL PROTECTED]> writes:

> aurora wrote:
>
>  > [...]
>> In Java they are distinct data type and the compiler would catch all
>> incorrect usage. In Python, the interpreter seems to 'help' us to
>> promote  binary string to unicode. Things works fine, unit tests
>> pass, all until  the first non-ASCII characters come in and then the
>> program breaks.
>> Is there a scheme for Python developer to use so that they are safe
>> from  incorrect mixing?
>
> Put the following:
>
> import sys
> sys.setdefaultencoding("undefined")
>
> in a file named sitecustomize.py somewhere in your Python path and
> Python will complain whenever there's an implicit conversion between
> str and unicode.

Sounds cool, so I did it.
And started a program I was currently working on.
The first function in it is this:

if sys.platform == "win32":

def _locate_gccxml():
import _winreg
for subkey in (r"Software\gccxml", r"Software\Kitware\GCC_XML"):
for root in (_winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE):
try:
hkey = _winreg.OpenKey(root, subkey, 0, _winreg.KEY_READ)
except WindowsError, detail:
if detail.errno != 2:
raise
else:
return _winreg.QueryValueEx(hkey, "loc")[0] + r"\bin"

loc = _locate_gccxml()
if loc:
os.environ["PATH"] = loc

All strings in that snippet are text strings, so the first approach was
to convert them to unicode literals.  Doesn't work.  Here is the final,
working version (changes are marked):

if sys.platform == "win32":

def _locate_gccxml():
import _winreg
for subkey in (r"Software\gccxml", r"Software\Kitware\GCC_XML"):
for root in (_winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE):
try:
hkey = _winreg.OpenKey(root, subkey, 0, _winreg.KEY_READ)
except WindowsError, detail:
if detail.errno != 2:
raise
else:
return _winreg.QueryValueEx(hkey, "loc")[0] + ur"\bin"
#-^
loc = _locate_gccxml()
if loc:
os.environ["PATH"] = loc.encode("mbcs")
#^

So, it appears that:

- the _winreg.QueryValue function is strange: it takes ascii strings,
  but returns a unicode string.
- _winreg.OpenKey takes ascii strings
- the os.environ["PATH"] accepts an ascii string.

And I won't guess what happens when there are registry entries with
unlauts (ok, they could be handled by 'mbcs' encoding), and with chinese
or japanese characters (no way to represent them in ascii strings with a
western locale and mbcs encoding, afaik).


I suggest that 'sys.setdefaultencoding("undefined")' be the standard
setting for the core developers ;-)

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


Re: unicode encoding usablilty problem

2005-02-18 Thread "Martin v. Löwis"
aurora wrote:
The Java 
has a much more  usable model with unicode used internally and 
encoding/decoding decision  only need twice when dealing with input and 
output.
In addition to Fredrik's comment (that you should use the same model
in Python) and Walter's comment (that you can enforce it by setting
the default encoding to "undefined"), I'd like to point out the
historical reason: Python predates Unicode, so the byte string type
has many convenience operations that you would only expect of
a character string.
We have come up with a transition strategy, allowing existing
libraries to widen their support from byte strings to character
strings. This isn't a simple task, so many libraries still expect
and return byte strings, when they should process character strings.
Instead of breaking the libraries right away, we have defined
a transitional mechanism, which allows to add Unicode support
to libraries as the need arises. This transition is still in
progress.
Eventually, the primary string type should be the Unicode
string. If you are curious how far we are still off that goal,
just try running your program with the -U option.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


help for xml parsing error

2005-02-18 Thread Michael Zhang
Hi,

I got a strange error of my python program.  The
program is trying to load some data from server (also
built in Python).  the data is in xml format.  After
calling xml parser, I got the following error:

 File "ShowAll.py", line 156, in ?
main(sys.argv)
  File "ShowAll.py", line 129, in main
win = MainWindow()
  File "ShowAll.py", line 63, in __init__
videoInfo =
CaMLDocumentParser.getVideoInfo(GenericParser.parse(StringIO(result)))
  File
"/home/vraid1/mzhang/CaMLServer3/lib/GenericParser.py",
line 39, in parse
xml.sax.parse (file, g)
  File
"/usr/lib/python2.2/site-packages/_xmlplus/sax/__init__.py",
line 31, in parse
parser.parse(filename_or_stream)
  File
"/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py",
line 109, in parse
xmlreader.IncrementalParser.parse(self, source)
  File
"/usr/lib/python2.2/site-packages/_xmlplus/sax/xmlreader.py",
line 123, in parse
self.feed(buffer)
  File
"/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py",
line 220, in feed
self._err_handler.fatalError(exc)
  File
"/usr/lib/python2.2/site-packages/_xmlplus/sax/handler.py",
line 38, in fatalError
raise exception
xml.sax._exceptions.SAXParseException: :1:0:
not well-formed (invalid token)

PS. I have tried to view the content which should be
some text, but it prints some chars that not read to
human at all.

Thank you in advance,

Michael

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


extracting HTML fragments and counting words

2005-02-18 Thread Ksenia Marasanova
Hi,

I want to show preview  of several HTML formatted newsitems on one
page, preserving markup (and images) intact, but showing not more
thatn X first _readable_ words of every page. Is anyone aware of some
Python library that makes programming this easy? I already started to
program it with Beautiful Soup, but maybe there is a more easy way...

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


Re: unicode encoding usablilty problem

2005-02-18 Thread Jarek Zgoda
Walter Dörwald napisał(a):
Is there a scheme for Python developer to use so that they are safe 
from  incorrect mixing?

Put the following:
import sys
sys.setdefaultencoding("undefined")
in a file named sitecustomize.py somewhere in your Python path and
Python will complain whenever there's an implicit conversion between
str and unicode.
This will help in your code, but there is big pile of modules in stdlib 
that are not unicode-friendly. From my daily practice come shlex 
(tokenizer works only with encoded strings) and logging (you cann't 
specify encoding for FileHandler).

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


Re: Access to formatting controls from within __repr__ or __str__?

2005-02-18 Thread Dan Sommers
On 18 Feb 2005 01:25:06 -0800,
"Serge Orlov" <[EMAIL PROTECTED]> wrote:

> Dan Sommers wrote:

>> So my question is:  Is there a way to pass options "through" a format
>> string to the __str__ and __repr__ functions?  For example, can I
>> define my own alternate form for use with the '#' formatting
>> character, so that '%#s' generates output according to SI guidelines?

> You can create your own class FmtTemplate like string.Template was done
> in python 2.4: http://docs.python.org/lib/node105.html

That looks interesting.  Perhaps that will push me into upgrading to 2.4
sooner rather than later (I'm *not* looking forward to rebuilding all my
extensions...).

Thanks you,
Dan

-- 
Dan Sommers

Never play leapfrog with a unicorn.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-18 Thread Thomas Heller
=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= <[EMAIL PROTECTED]> writes:

> We have come up with a transition strategy, allowing existing
> libraries to widen their support from byte strings to character
> strings. This isn't a simple task, so many libraries still expect
> and return byte strings, when they should process character strings.
> Instead of breaking the libraries right away, we have defined
> a transitional mechanism, which allows to add Unicode support
> to libraries as the need arises. This transition is still in
> progress.
>
> Eventually, the primary string type should be the Unicode
> string. If you are curious how far we are still off that goal,
> just try running your program with the -U option.

Is it possible to specify a byte string literal when running with the -U option?

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


Re: Python, Matlab and AI question

2005-02-18 Thread Alexander Schmolck
Robert Kern <[EMAIL PROTECTED]> writes:

> dataangel wrote:
>> I'm a student who's considering doing a project for a Machine Learning class
>> on pathing (bots learning to run through a maze). The language primarily
>> used by the class has been Matlab. I would prefer to do the bulk of the
>> project in python because I'm familiar with pygame (for the visuals) but I
>> already have a lot of AI code written in Matlab.
>> I'd like to be able to call Matlab code from within python. I'm not sure
>> this is possible. My code runs in Octave just fine.
>
> There have been some bridges between Matlab and Python, but most of them are
> old, I believe.
>
>http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html

Actually, I've written a highlevel matlab-python bridge (based on bugfixed and
slightly extended version of the original pymat) which is quite up-to-date; by
and large it makes using matlab from python as easy as if matlab were just
some python library:

>>> from mlabwrap import mlab; mlab.plot([1,2,3],'-o')

>>> mlab.sin([4,5,6])
array([[-0.7568025 ],
   [-0.95892427],
   [-0.2794155 ]])

As you can see from the last example there a certain minor idiosyncrasies
stemming from unbridgable semantic differences between matlab and python
(matlab doesn't have "real" vectors, which means that Numeric vectors are
translated to Nx1 matrices), also the call to matlab of course incurs a
significant overhead compared to Numeric.sin.

All in all I it works quite well for me, though (I've been using it
productively for years now and a couple of other people have also used it) --
so I guess I should finally announce it (there were a few minor things I
wanted to add first, but since people periodically ask for something like it
on c.l.py so now would seem like a good time).

You can find it on sourceforge:

 

I'd appreciate feedback.

'as

p.s. never mind the project activity meter at 0% -- as you can see the latest
version was uploaded mid january this year.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.compile and very specific searches

2005-02-18 Thread John Machin
Diez B. Roggisch wrote:


> So I'd suggest you dump re and do it like this:
>
> address = "192.168.1.1"
>
> def validate_ip4(address):
> digits = address.split(".")
> if len(digits) == 4:
> for d in digits:
> if int(d) < 0 or int(d) > 255:
>   return False
> return True
>

The OP wanted to "find" IP addresses -- unclear whether re.search or
re.match is required. Your solution doesn't address the search case.
For the match case, it needs some augmentation. It will fall apart if
presented with something like "..." or "comp.lang.python.announce". AND
while I'm at it ... in the event of a valid string of digits, it will
evaluate int(d) twice, rather unnecessarily & uglily.

So: match case:

! for s in strings_possibly_containing_digits:
! #   if not(s.isdigit() and 0 <= int(s) <= 255): # prettier, but test
on zero is now redundant
! if not s.isdigit() or int(s) > 255:

and the search case: DON'T dump re; it can find highly probable
candidates (using a regexp like the OP's original or yours) a damn
sight faster than anything else this side of C or Pyrex. Then you
validate the result, with a cut-down validator that relies on the fact
that there are 4 segments and they contain only digits:

! # no need to test length == 4
! for s in address.split('.'):
! if int(s) > 255:

HTH,
John

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


Re: unicode encoding usablilty problem

2005-02-18 Thread Thomas Heller
=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= <[EMAIL PROTECTED]> writes:

> Eventually, the primary string type should be the Unicode
> string. If you are curious how far we are still off that goal,
> just try running your program with the -U option.

Not very far - can't even call functions ;-)

c:\>py -U
Python 2.5a0 (#60, Dec 29 2004, 11:27:13) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(**kw):
...   pass
...
>>> f(**{"a": 0})
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: f() keywords must be strings
>>>

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


  1   2   >