Re: Time for : comp.lang.python.newbies ??

2004-12-06 Thread Tim Roberts
gmduncan <[EMAIL PROTECTED]> wrote:

>
>Am I correct in detecting a greater presence of Newbies in
>this  "Pierian Spring" aka c.l.p. ??
>
>Seems there's more than the usual bunch of pleas for help
>esp. from the Newbie Windoze fraternity.
>
>And it seems the Uber-Gurus (You Know Who You ARE) have retreated
>a bit - most are in the NH so it can't be that they are holidaying
>in the Bahamas, Greece, and Corfu and the like, in their winter
>"of discontent" no doubt.
>
>Maybe a time for a new discussion group along that suggested
>by the Subject line ?

Unfortunately, what you propose is doomed to failure.  This has been shown
many times before in Usenet.

Let's say you're a newbie, and you have a question.  You are presented with
two newsgroups:
comp.lang.python.newbies
comp.lang.python.experts
Where do you think you will be getting the most productive answers to your
questions?  If there are no experts in the newbie group, there aren't going
to be very many useful answers there.

>I've got nothing against Newbies - I was one once - but there
>is a limit.

No, there isn't, really.  I don't think the percentage of true newbie
questions has really gone up.  However, as you grow more knowledgeable, the
percentage of questions that SEEM like newbie questions goes up.

comp.lang.python has always been a bastion of kindness and tolerance in the
comp.lang hierarchy.  I hope that remains true.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python in debug version?

2004-12-06 Thread "Martin v. Löwis"
mep wrote:
I view my python 2.3.4 from python.org by VC6's dependency walker tool.
What suprise me is that python.exe and python32.dll are built into *DEBUG*
version.
What precisely did the tool report? To my knowledge, the DLLs are not in
the debug version.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Win32 Libs for 2.4

2004-12-06 Thread "Martin v. Löwis"
Robin Becker wrote:
I thought that static .libs didn't make reference to the dll's they 
need; isn't that done at load time?
Unfortunately, thanks to Microsoft's infinite wisdom, static libs
*do* reference DLLs. The C lib headers contain things like
#pragma lib("msvcrt.lib") // or some such
The compiler translates this into a reference to the DLL in the
object file, which the linker will then translate into a reference
to the DLL when linking, even if the DLL was not giving on the linker
command line.
However, I am uncertain how this works with multiple VC versions -
whether the DLL reference is CRT version independent or not.
You should view the resulting extension module in depends.exe,
and check whether it refers to multiplce CRT dlls (which would be
bad).
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: RPC with Python - Comparison?

2004-12-06 Thread Jeremy Bowers
On Mon, 06 Dec 2004 21:38:16 -0800, johng2001 wrote:
> Anyone has any insights on REST Vs SOAP/XML-RPC? I have seen these debates
> else where on the web. Just want to know what the view point here is.

I've seen people argue this point a bajillion times, and honestly, I think
the best insight is that there *is* no insight. Each of those three things
(XML-RPC is not the same as SOAP, it is *way* simpler with the associated
costs and benefits) are exactly what they look like, three entries on a
pretty typical cost/benefit scale, with the primary tradeoffs being
between ease of use and cross-platform/language. There's a time and a
place for each, they don't really overlap much, and people trying to fit
the world into the One True RPC, in my experience, generally only have
experience in one of the RPC domains and mistake their experience for
global truth.


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


Forums based on python

2004-12-06 Thread Florian Lindner
Hello,
which free forums, based on mod_python and MySQL are around there? 
Something like phpBB...

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


Python in debug version?

2004-12-06 Thread mep
Hi, all
I view my python 2.3.4 from python.org by VC6's dependency walker tool.
What suprise me is that python.exe and python32.dll are built into *DEBUG*
version.
Is it intend to do so?Is a release version faster?

-- 
Best Regards,
Wang Kebo

http://www.huihoo.org/~mep


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


python programming help

2004-12-06 Thread Alfred Canoy



Hello,
Thanks for the input:-) I made a mean, median & 
mode program. I'm trying to figure how can I store this program in another file 
and opens the file to display. Any idea what to add in my source code. 
Thanks!
 
 
# compute the Mean, Median & Mode of a list of 
numbers:
 
sum = 0.0
 
print 'This program will take several numbers then 
average them'count = input(' How many numbers would you like to sum: 
')current_count = 0
 
while current_count < 
count:    current_count = 
current_count + 1num_list = []    
while len (num_list) < 
count:    number = input ('Enter a 
number: ')    
num_list.append(number)    print 
"Number", current_count,":",number    
sum = sum + number
 
print num_list
 
def median(alist):    
list_of_numbers = alist[:]    
list_of_numbers.sort()    listLen = 
len(list_of_numbers)    middleIndex = (listLen - 
1)/2    if listLen % 2 == 
1:    # odd number of elements. 
return middle element    return 
list_of_numbers[middleIndex]    
else:    # even number of element. 
return average of middle 2 
elements    return 
(list_of_numbers[middleIndex] + list_of_numbers[middleIndex + 1]) / 2.0if 
__name__ == '__main__':      
def mode(alist):    start = 1    current = 
0    new = 0    for i in 
alist:    if alist.count(i) 
>  
start:    
current = 
alist.count(i)    
start = 
current    
new = i    if new > 
1:    return 
new    else:    
return "All members of [%s] are modes." %alistprint 'mean:', 
sum/countprint 'median:',median (num_list)print 'mode:',mode 
(num_list)
    

Al _ __ _Alfred CanoyAgana, 
GuamPacific time[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Chicago Python Users Group Meeting, Thurs Dec 9

2004-12-06 Thread Ian Bicking
The Chicago Python User Group, ChiPy, will have its next meeting
on Thursday, December 9th, starting at 7pm.  For more information on 
ChiPy see http://chipy.org

Topic
-
This month's topic is testing and profiling strategies in Python.  Chris 
McAvoy will talk about doctest.  Brian Ray will talk about the hotspot 
profiler.  Ian Bicking will be talking about py.test, a unittest 
alternative.  Maybe John Roth will be able to talk about Fitnesse, a 
Wiki-based acceptance test system.

There will also be time to chat, and many opportunities to ask
questions.  We encourage people at all levels to attend.
We also want to hold a post-meeting chat to talk about Python advocacy 
in the Chicago area, and ChiPy promotion.

Location

This month we will be meeting at Imaginary Landscape:
  5121 N. Ravenswood Ave, Chicago
It's close to the Ravenswood stop on the North Shore Metra line, and a 
modest hike from the CTA brown line (Damen stop) and red line (Argyle 
stop).  Parking is available out front.  See the website for a map. 
Buzz to come up.

We're looking to do a meeting in the suburbs in February.  If you have a 
venue we could use (in the suburbs or elsewhere, February or another 
month), please email the mailing list.  We want to move the meeting 
around to make it possible for the people from the entire Chicagoland 
area to participate.

About ChiPy
---
Each month we try to pick a general topic, and people who can do 
presentations around that topic.  The tentative topic for January is 
Jython.  Presentations can be short, and need not be authoritative; have 
you done something in Jython you'd like to share?  Tell us a little 
about it on the mailing list.

This will be ChiPy's 7th meeting, give or take a few.  We meet once a
month, on the second Thursday of the month.  If you can't come
this month, please join our mailing list:
http://lonelylion.com/mailman/listinfo/chipy
--
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python and interpreter threads

2004-12-06 Thread Charlie DeTar
Quick correction, sorry - the command should read like this (I had 
omitted the "log" before 'CaptureStdout' and 'CaptureStderr').  Same 
problems exist.

 PyRun_SimpleString(
 "import log\n"
 "import sys\n"
 "class StdoutCatcher:\n"
 "\tdef write(self, str):\n"
 "\t\tlog.CaptureStdout(str)\n"
 "class StderrCatcher:\n"
 "\tdef write(self, str):\n"
 "\t\tlog.CaptureStderr(str)\n"
 "sys.stdout = StdoutCatcher()\n"
 "sys.stderr = StderrCatcher()\n");
=Charlie
Charlie DeTar wrote:
So, I have an amazing, functioning foobar class that embeds python. Only 
trouble is, I want to be able to have multiple foobar objects at once, 
each with their own interpreters, stdouts, and stderrs.

My initialization of the python interpreter in the class "x" is as follows:
[snip]
if (!Py_IsInitialized()) {
PyEval_InitThreads();
Py_Initialize();
}   

// Start and switch to a new interpreter thread.
x->thread = Py_NewInterpreter();

// initialize the module 'logMethods', defined elsewhere,
// which contains my stdout and stderr definitions
Py_InitModule("log", logMethods);

// overwrite Python's stdout and stderr
PyRun_SimpleString(
"import log\n"
"import sys\n"
"class StdoutCatcher:\n"
"\tdef write(self, str):\n"
"\t\t.CaptureStdout(str)\n"
"class StderrCatcher:\n"
"\tdef write(self, str):\n"
"\t\t.CaptureStderr(str)\n"
"sys.stdout = StdoutCatcher()\n"
"sys.stderr = StderrCatcher()\n");
--
http://mail.python.org/mailman/listinfo/python-list


embedded python and interpreter threads

2004-12-06 Thread Charlie DeTar
So, I have an amazing, functioning foobar class that embeds python. 
Only trouble is, I want to be able to have multiple foobar objects at 
once, each with their own interpreters, stdouts, and stderrs.

My initialization of the python interpreter in the class "x" is as follows:
[snip]
if (!Py_IsInitialized()) {
PyEval_InitThreads();
Py_Initialize();
}   

// Start and switch to a new interpreter thread.
x->thread = Py_NewInterpreter();
// initialize the module 'logMethods', defined elsewhere,
// which contains my stdout and stderr definitions
Py_InitModule("log", logMethods);

// overwrite Python's stdout and stderr
PyRun_SimpleString(
"import log\n"
"import sys\n"
"class StdoutCatcher:\n"
"\tdef write(self, str):\n"
"\t\t.CaptureStdout(str)\n"
"class StderrCatcher:\n"
"\tdef write(self, str):\n"
"\t\t.CaptureStderr(str)\n"
"sys.stdout = StdoutCatcher()\n"
"sys.stderr = StderrCatcher()\n");

PyEval_ReleaseThread(x->thread);
[snip]
Everything seems to work as expected - each object seems to have its own 
interpreter (if I evaluate "tree = 'a larch'" in one of them, 'tree' is 
not thusly defined in the others).  Since I store the threadstate as a 
property of the object, I can easily juggle the interpreter lock between 
objects when evaluating python code.  However, the last foobar object to 
be instantiated collects the stdout and stderr of all the other objects 
(as though the stdout and stderr definitions were shared over all the 
objects).  This seems strange, as the docs say that if I start a 
"Py_NewInterpreter()" I get new copies of all the modules, particuarly 
'sys', and explicitly 'stdout' and 'stderr'.

I thought of the possibility that the 'logMethods' structure which 
includes my versions of stdout and stderr might be behaving statically. 
 But I didn't define it as static...  I am new to C, so there might be 
something basic I am missing.  Any suggestions or ideas?

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


ANN: Wing IDE 2.0.1 released

2004-12-06 Thread Stephan Deibel
Hi,

I'm happy to announce version 2.0.1 Wing IDE, an advanced integrated
development environment for Python.  This is a free upgrade for Wing IDE
2.0 users.  It can be downloaded from:

http://wingware.com/downloads

Highlights of this release include:

* Support for Python 2.4
* Optimized debugger
* Searchable documentation
* Expanded auto-completion preferences
* Easier to customize key bindings
* Remembers window layout even when no project is open
* Zope instance directory support
* Various bug fixes

New features in Wing IDE 2.0 since the last 1.1 release include a
redesigned customizable user interface, call tips, syntax error
indicators, editor tabs and splits, multi-file wildcard and regular
expression searching, integrated documentation and tutorial, German
localization, and Unicode support.

This release is available for Windows, Linux, and Mac OS X, and can be
compiled from sources on FreeBSD, Solaris, and other Posix operating
systems.

A complete list of changes is available here:

http://wingware.com/pub/wingide/2.0.1/CHANGELOG.txt

For more information see:

Product Info:   http://wingware.com/products
Sales:  http://wingware.com/store/purchase
Upgrades:   http://wingware.com/store/upgrade

Sincerely,

Stephan Deibel

--
Wingware
Wing IDE for Python
Advancing Software Development

www.wingware.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RPC with Python - Comparison?

2004-12-06 Thread johng2001
> Candidates could be:
>
> - Pyro
> - Twisted.spread
> - OSE (XML-RPC)
> - ICE
> - ...others?

Anyone has any insights on REST Vs SOAP/XML-RPC? I have seen these
debates else where on the web. Just want to know what the view point
here is.

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


Re: Deadlock detection

2004-12-06 Thread Paul Du Bois
(warning: pedantic and off-topic response) NP-Complete does not mean
"equivalent to the halting problem." It means "poly-time equivalent to
any other NP-Complete problem".

NP-Complete problems are "only" exponential-time. The halting problem
is much harder! And of course, just the fact that a problem is
NP-complete doesn't mean that you can't construct algorithms that do a
pretty good job a pretty good fraction of the time.

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


ANN: GallerPy 0.5.0

2004-12-06 Thread Freddie
GallerPy is a fairly basic dynamic web gallery written in Python and
uses the Python Imaging Library. It is licensed under the terms of the
BSD License.
Features include:
  * Fluid CSS layout
  * SCGI support
  * Other exciting stuff
GallerPy is available for download from the MadCowDisease web site:
http://www.madcowdisease.org/index.py/GallerPy
--
http://mail.python.org/mailman/listinfo/python-list


Weekly Python Patch/Bug Summary

2004-12-06 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  259 open ( +1) /  2705 closed ( +4) /  2964 total ( +5)
Bugs:  800 open (-12) /  4662 closed (+20) /  5462 total ( +8)
RFE :  160 open ( +0) /   137 closed ( +1) /   297 total ( +1)

New / Reopened Patches
__

add key  (2004-12-01)
CLOSED http://python.org/sf/1077353  opened by  Steven Bethard

Simple webbrowser fix for netscape -remote  (2004-12-02)
   http://python.org/sf/1077979  opened by  Josh Cherry

readline does not need termcap  (2004-12-01)
   http://python.org/sf/1076826  reopened by  nijel

Make cgi.py use logging module  (2004-12-05)
   http://python.org/sf/1079729  opened by  Josh Hoyt

Make cgi.py use email instead of rfc822 or mimetools  (2004-12-05)
   http://python.org/sf/1079734  opened by  Josh Hoyt

list sort is not "in place"  (2004-12-06)
   http://python.org/sf/1080078  reopened by  rhettinger

list sort is not "in place"  (2004-12-06)
CLOSED http://python.org/sf/1080078  opened by  Heikki Orsila

Patches Closed
__

add key  (2004-12-02)
   http://python.org/sf/1077353  closed by  rhettinger

readline does not need termcap  (2004-12-01)
   http://python.org/sf/1076826  closed by  loewis

raise error for common mistake with subprocess  (2004-11-23)
   http://python.org/sf/1071755  closed by  astrand

list sort is not "in place"  (2004-12-06)
   http://python.org/sf/1080078  closed by  rhettinger

list sort is not "in place"  (2004-12-06)
   http://python.org/sf/1080078  closed by  tim_one

AUTH PLAIN in smtplib  (2004-11-30)
   http://python.org/sf/1075928  closed by  jlgijsbers

New / Reopened Bugs
___

problem with make test on OS/X  (2004-12-02)
CLOSED http://python.org/sf/1077302  opened by  Ian Holsman

threads: segfault or Py_FatalError at exit  (2004-11-08)
   http://python.org/sf/1061968  reopened by  mhammond

assert fail to threw exception when run python with '-O'  (2004-12-02)
CLOSED http://python.org/sf/1077862  opened by  tj128

Python2.4: building '_socket' extension fails with `INET_ADD  (2004-12-03)
   http://python.org/sf/1078245  opened by  Michael Ströder

Docs for run() methods are misleading  (2004-12-04)
CLOSED http://python.org/sf/1078905  opened by  Kent Johnson

Email.Header encodes non-ASCII content incorrectly  (2004-12-04)
   http://python.org/sf/1078919  opened by  Tessa Lau

Incorrect error message (somewhat)  (2004-12-04)
   http://python.org/sf/1079011  opened by  Gerrit Holl

datetime changes missing from "Porting from 2.3 to 2.4"  (2004-12-04)
   http://python.org/sf/1079134  opened by  Sadruddin Rejeb

python-2.4.msi install error  (2004-12-05)
   http://python.org/sf/1079545  opened by  maharal

IDLE and old color themes  (2004-12-06)
   http://python.org/sf/1080387  opened by  projecktzero

Bugs Closed
___

threads: segfault or Py_FatalError at exit  (2004-11-07)
   http://python.org/sf/1061968  closed by  arigo

Tutorial corrections  (2004-12-01)
   http://python.org/sf/1076955  closed by  rhettinger

test_shutil fails on x86-64 // Suse 9.1  (2004-12-01)
   http://python.org/sf/1076467  closed by  jlgijsbers

test test_unicodedata failed   (2004-12-01)
   http://python.org/sf/1076795  closed by  lemburg

Problem testing python 2.4  (2004-12-01)
   http://python.org/sf/1077103  closed by  lemburg

re module segfaulting in large regular expression  (2004-11-24)
   http://python.org/sf/1072259  closed by  niemeyer

Memory fault pyexpat.so on SGI  (2004-11-30)
   http://python.org/sf/1075990  closed by  akuchling

assert fail to threw exception when run python with '-O'  (2004-12-02)
   http://python.org/sf/1077862  closed by  tim_one

Errors and omissions in logging module documentation  (2004-11-28)
   http://python.org/sf/1074693  closed by  vsajip

xml.dom.minidom produces errors with certain unicode chars  (2004-11-27)
   http://python.org/sf/1074200  closed by  effbot

test test_re produced unexpected output  (2004-12-01)
   http://python.org/sf/1076791  closed by  nijel

^Z doesn't exit interpreter - 2.4c1 & Win2K  (2004-11-26)
   http://python.org/sf/1073736  closed by  facundobatista

test_macostools failure on OS X  (2004-12-01)
   http://python.org/sf/1077302  closed by  bcannon

PyGILState_Ensure() deadlocks (ver 2.4)  (2004-11-29)
   http://python.org/sf/1075703  closed by  andivajda

calendar.weekheader() undocumented  (2004-05-04)
   http://python.org/sf/947894  closed by  doerwalter

Docs for unittest run() methods are misleading  (2004-12-04)
   http://python.org/sf/1078905  closed by  rhettinger

Another message that croaks email.FeedParser  (2004-11-30)
   http://python.org/sf/1076485  closed by  bwarsaw

Windows msi doesn't install site-packages directory  (2004-11-23)
   http://python.org/sf/1071594  closed by  loewis

win32con missing codes VK_VOLUME_MUTE, VK_BROWSER_BACK,

Re: GUI Frames and classmethod

2004-12-06 Thread Jeremy Bowers
On Mon, 06 Dec 2004 14:11:04 -0800, Scott David Daniels wrote:
> Second, I was referring to code like:
> 
>   try:
>   inner = table[state]
>   except KeyError:
>   table[state] = inner = {}
>   inner[action] = whatever
> 
> vs. code like this:
> 
>   table[state, action] = whatever
> 
> That is, dynamic table modification code for a table of pairs is clearer.

But it isn't quite as tradeoff free as you say; you do lose the ability to
say table[state] and get just the information relevant to your state (you
might take the .keys() of that or something).

In this case, it may not be a big deal; depends on what the program does
and how the programmer thinks. In other cases, dicts of dicts can make
perfect sense. For instance, I have a Registry type that uses
dicts-in-dicts the obvious way to store things like
"table1.table2.table3.value", and that way there is a coherent way to pass
"table1.table2.table3" around. Yeah, you could work out a string or tuple
subclass that could still work, but that's a lot more work :-) and you'd
still have a hard time getting all keys from a table without searching the
whole thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why python is slower than java?

2004-12-06 Thread Jeremy Bowers
On Mon, 06 Dec 2004 13:01:47 -0800, fuzzylollipop wrote:

> yeah, but a lie unanswered by the truth becomes the truth.

You know, it's bad enough that somebody starts this thread anew about
every two months anyhow, do you really have to try to resurrect dead ones?

Be patient and I'm sure you'll have many more opportunities to post this
general thought in a more timely fashion in the all-too-near future.

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


httpconnection class handle 302 redirect?

2004-12-06 Thread Joe Wong



Hi , it looks like that HTTPConnection class is not 
capable to handle 302 redirect response. Is there any sample implementation that 
tackle this problem? I am using python 2.3.3 on Windows platform.
 
best regards,
 
- Joe
 
 
---Outgoing mail is certified Virus 
Free.Checked by AVG anti-virus system (http://www.grisoft.com).Version: 6.0.806 / 
Virus Database: 548 - Release Date: 2004/12/5
-- 
http://mail.python.org/mailman/listinfo/python-list

Python Boost, help

2004-12-06 Thread To Forum
Hi,

My problem is the following

1/ I install Python 2.4 at D:\Programs\Python24 using the binary file from
www.python.org

2/ following the document from the boost.org I type the command

>bjam "-sTOOLS=vc-7_1 --with-python-root=D:\Programs\Python24" stage

But I receive the following error

> --with-python-root=D:\Programs\Python24-tools.jam: Invalid argument



I think I do something wrong here. If I use the simple command

>bjam "-sTOOLS=vc-7_1 " stage

I get the message:

>skipping Boost.Python .



Can someone show me how can I install Boost.Python correctly?

TF






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


Re: regex syntax

2004-12-06 Thread and-google
Andreas Volz <[EMAIL PROTECTED]> schrieb:

> Ich hab mir schon überlegt einfach die letzten viel Stellen des
> strings "per Hand" auf die Zeichenfolge zu vergleichen und so
> regex zu umgehen. Aber ich muss es irgendwann ja doch mal nutzen

"Muss"? stimme nicht zu! Regexps sind ja fuer begrenzte Zwecke eine
gute Loesung, aber kein Basisteil der Programmierung. Bei diesem
Beispiel waere:

>>> filename.endswith('.jpg')

viel besser als das vergleichbare Regexp:

>>> re.match('.*\.jpg$', filename)
-- 
Andrew Clover
mailto:[EMAIL PROTECTED]
http://www.doxdesk.com/

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


Re: better regular expression?

2004-12-06 Thread Steve Holden
Vivek wrote:
[third request ...]
Any suggestions?
Thanx.
Well, you could try asking just once and then waiting a bit :-)
regards
 Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


RE: better regular expression?

2004-12-06 Thread Robert Brewer
Vivek wrote:
> I am trying to construct a regular expression using the re module that
> matches for
> 1. my hostname
> 2. absolute from the root URLs including just "/"
> 3. relative URLs.
> 
> Basically I want the attern to not match for URLs that are not on my
> host.

Far easier would be grabbing the URL's and then using
urlparse.urlparse() on them. Relative paths should be combined with the
base scheme://location/path. When you want to see if they are on your
host, just use .startswith(). If you're worried about ../, make the
paths concrete (os paths) and call os.path.normpath before comparing
them.


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


better regular expression?

2004-12-06 Thread Vivek
Hi,

I am trying to construct a regular expression using the re module that
matches for
1. my hostname
2. absolute from the root URLs including just "/"
3. relative URLs.

Basically I want the attern to not match for URLs that are not on my
host.

The following statement satisfies numbers 1 and 2, but not 3:

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/)([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

An improvement that also partially satisfies number 3 is

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/|[^h][^t][^t][^p][^:][^/][^/])([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

This is not complete because if the relative url is less than seven
characters, than it will not match.

Any suggestions?

Thanx.

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


Re: better regular expression?

2004-12-06 Thread Roy Smith
"Vivek" <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I am trying to construct a regular expression using the re module that
> matches for
> 1. my hostname
> 2. absolute from the root URLs including just "/"
> 3. relative URLs.

Is your goal to learn more about regexes, or to parse URLs?  If the 
latter, my suggestion would be to look at the urlparse module; the hard 
work has already been done for you.
-- 
http://mail.python.org/mailman/listinfo/python-list


better regular expression?

2004-12-06 Thread Vivek
Hi,

I am trying to construct a regular expression using the re module that
matches for
1. my hostname
2. absolute from the root URLs including just "/"
3. relative URLs.

Basically I want the attern to not match for URLs that are not on my
host.

The following statement satisfies numbers 1 and 2, but not 3:

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/)([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

An improvement that also partially satisfies number 3 is

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/|[^h][^t][^t][^p][^:][^/][^/])([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

This is not complete because if the relative url is less than seven
characters, than it will not match.

Any suggestions?

Thanx.

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


Re: better regular expression?

2004-12-06 Thread Andy Gross
Check out the 'urlparse' module, in the standard library, unless for  
some reason you *have* to use regular expressions.

/arg
On Dec 6, 2004, at 7:46 PM, Vivek wrote:
Hi,
I am trying to construct a regular expression using the re module that
matches for
1. my hostname
2. absolute from the root URLs including just "/"
3. relative URLs.
Basically I want the attern to not match for URLs that are not on my
host.
The following statement satisfies numbers 1 and 2, but not 3:
line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]? 
|/)([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

An improvement that also partially satisfies number 3 is
line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/ 
|[^h][^t][^t][^p][^:][^/][^/])([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

This is not complete because if the relative url is less than seven
characters, than it will not match.
Any suggestions?
Thanx.
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


better regular expression?

2004-12-06 Thread Vivek
Hi,

I am trying to construct a regular expression using the re module that
matches for
1. my hostname
2. absolute from the root URLs including just "/"
3. relative URLs.

Basically I want the attern to not match for URLs that are not on my
host.

The following statement satisfies numbers 1 and 2, but not 3:

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/)([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

An improvement that also partially satisfies number 3 is

line =
re.sub(r'(href=")(http[s]?://'+hostname+'[/]?|/|[^h][^t][^t][^p][^:][^/][^/])([^"]*?)(")',r'\1\2\3'+sInfo+r'\4',line)

This is not complete because if the relative url is less than seven
characters, than it will not match.

Any suggestions?

Thanx.

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


Re: cut strings and parse for images

2004-12-06 Thread Paul McGuire
"Andreas Volz" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Am Mon, 06 Dec 2004 20:36:36 GMT schrieb Paul McGuire:
>
> > Check out the urlparse module (in std distribution).  For images, you
> > can provide a default addressing scheme, so you can expand
> > "images/marine.jpg" relative to the current location.
>
> Ok, this looks good. But I'm a really newbie to python and not able to
> create a minimum example. Could you please give me a very small example
> how to use urlparse? Or point me to an example in the web?
>
> regards
> Andreas

No problem.  Googling for 'python urlparse' gets us immediately to:
http://www.python.org/doc/current/lib/module-urlparse.html.  This online doc
has some examples built into it.

But as a newbie, it would also be good to get comfortable with dir() and
help() and trying simple commands at the >>> Python prompt.  If I type the
following at the Python prompt:
>>> import urlparse
>>> help(urlparse)
I get almost the same output straight from the Python source.

dir(urlparse) gives me just a list of the global symbol names from the
module, but sometimes that's enough of a clue without reading the whole doc.

Now is where the intrepid Pythonista-to-be uses the Python interactive
prompt and the tried-and-true Python methodology known as "Just Trying Stuff
Out".

>>> url = "http://www.example.com/dir/example.html";# from your
example
>>> urlparse(url)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'module' object is not callable
(Damn! forgot to prefix with urlparse.)
>>> urlparse.urlparse(url)
('http', 'www.example.com', '/dir/example.html', '', '', '')
>>> img = "images/marine.jpeg"   # also from your example
>>> urlparse.urlparse(img)
('', '', 'images/marine.jpeg', '', '', '')

Now you can start to predict what kind of tuples you'll get back from
urlparse, you can visualize how you might merge the data from the img
fragment and the url fragment.  Wait, I didn't read all of the doc - let's
try urljoin!
>>> urljoin(url,img)
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'urljoin' is not defined
(Damn! forgot to prefix with urlparse AGAIN!)
>>> urlparse.urljoin(url,img)
'http://www.example.com/dir/images/marine.jpeg'

Is this in the ballpark of where you are trying to go?

-- Paul
Give a man a fish and you feed him for a day; give a man a fish every day
and you feed him for the rest of his life.


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


Re: [Python-Help] Programming help

2004-12-06 Thread Bob Gailer
At 07:07 PM 12/5/2004, Alfred Canoy wrote:
Please help me out:(.. I've been trying to figure this out for 2 days now..
I don't know what to use to print  all the list of numbers. I hve know 
idea how should I do this. I tried a lot of trial & error for the the def, 
dict, .list( ). have no luck.
I just need to find this out then I'm good to go for the whole thing. I 
have save the other test source code for this problem. I just need to 
combine it after I figure this out.
Thank you all!

Source code:
# compute the Mean, Median & Mode of a list of numbers:
sum = 0.0
print 'This program will take several numbers then average them'
count = input(' How many numbers would you like to sum: ')
current_count = 0
freq = {}
freq [current_count] = number
while current_count < count:
   current_count = current_count + 1
   number = input ('Enter a number: ')
   print "Number", current_count,":",number
   sum = sum + number
print " [x,...,x] ?"
It's hard to respond since there is so much amiss in your code. Inside the 
while loop you need to append each user entry to a list. Then you can print 
the list. Have you studied list operations in a tutorial?

Also it is unclear what you intend by freq [current_count] = number. There 
is no variable named "number" at that point in the program, so the program 
should crash at that statement. I think you want that statement inside the 
loop also, although it is not doing anything useful. If you want to capture 
frequencies you need to use the number as a dictionary key, and increment 
the value under that key.

Clean things up as best you can then come back for the next round.
Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

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


regex syntax

2004-12-06 Thread Andreas Volz
Hi,

ich kann nicht gut regex, aber für das nötigste reicht es eigentlich.
Irgendwie komm ich aber mit der Syntax der re.* Befehle in Python nicht
klar Vielleicht kann mir das an diesem Beispiel jemand zeigen:

string = "bild.jpg"

ich möchte jetzt einfach wissen ob in dem string ein ".jpg" vorkommt
oder nicht und dann eine Entscheidung treffen. Ich hab mir schon
überlegt einfach die letzten viel Stellen des strings "per Hand" auf die
Zeichenfolge zu vergleichen und so regex zu umgehen. Aber ich muss es
irgendwann ja doch mal nutzen ;-)

Gruß
Andreas
--
http://mail.python.org/mailman/listinfo/python-list


Re: why no python setup.py uninstall?

2004-12-06 Thread alia_khouri

Peter Hansen wrote:

> On your specific reason for asking: I would suggest
> just not worrying about "being extra clean about it".
> Python's generally pretty good about not messing up
> when you install a new version of something without
> uninstalling the previous version.

Granted. However, the reason I did bring this up to begin with was the
odd 'exceptional' case when doing the python setup.py install
incantation over an older installation did cause problems.

I think a little database (maybe in xml?) of installed files/modules
and their locations would be useful, perhaps even for a future
automatic download/installation/dependency-tracking thingmabob that
still regretably still doesn't exist as parth of the stdlib in
Pythonia.

AK

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


Re: RPC with Python - Comparison?

2004-12-06 Thread has
Wolfgang Keller wrote:

> > MacPython also supports Apple events
>
> I know, but I was thinking of OS-independent RPC protocols. :-)
Pity, you're missing some good stuff... :/

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


Re: pre-PEP generic objects

2004-12-06 Thread Carlos Ribeiro
On 06 Dec 2004 10:09:25 +0100, Jacek Generowicz
<[EMAIL PROTECTED]> wrote:
[great explanation about function descriptors]

Thanks. Now I know more about function descriptors than I ever wanted
to :-) With a little polish, this post would make a great addition to
the descriptors documentation, don't you think?

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: [EMAIL PROTECTED]
mail: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


SOAP failure

2004-12-06 Thread savio
Hi 

I am trying to run the following code snip - it works on my machine at
home - does not work in the office - is it a firewall thing?  Can
anyone help?


from SOAPpy import WSDL
wsdlFile = 'http://www.xmethods.net/sd/2001/TemperatureService.wsdl'
server = WSDL.Proxy(wsdlFile)
server.soapproxy.config.dumpSOAPOut = 1
server.soapproxy.config.dumpSOAPIn = 1
x = server.getTemp('90210')
print x 



Traceback (most recent call last):
  File "D:\mypython\soapviawsdl.py", line 3, in ?
server = WSDL.Proxy(wsdlFile)
  File "C:\Python23\lib\site-packages\SOAPpy\WSDL.py", line 67, in
__init__
self.wsdl = reader.loadFromString(str(wsdlsource))
  File "C:\Python23\lib\site-packages\SOAPpy\wstools\WSDLTools.py",
line 49, in loadFromString
return self.loadFromStream(StringIO(data))
  File "C:\Python23\lib\site-packages\SOAPpy\wstools\WSDLTools.py",
line 28, in loadFromStream
document = DOM.loadDocument(stream)
  File "C:\Python23\lib\site-packages\SOAPpy\wstools\Utility.py", line
572, in loadDocument
x = xml.dom.minidom.parse(data)
  File "C:\Python23\Lib\site-packages\_xmlplus\dom\minidom.py", line
1908, in parse
return expatbuilder.parse(file)
  File "C:\Python23\lib\site-packages\_xmlplus\dom\expatbuilder.py",
line 933, in parse
result = builder.parseFile(file)
  File "C:\Python23\lib\site-packages\_xmlplus\dom\expatbuilder.py",
line 210, in parseFile
parser.Parse(buffer, 0)
ExpatError: not well-formed (invalid token): line 1, column 5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why no python setup.py uninstall?

2004-12-06 Thread alia_khouri
Peter Hansen wrote:

> On your specific reason for asking: I would suggest
> just not worrying about "being extra clean about it".
> Python's generally pretty good about not messing up
> when you install a new version of something without
> uninstalling the previous version.

Granted. However, the reason I did bring this up to begin with was the
odd 'exceptional' case when doing the python setup.py install
incantation over an older installation did cause problems.

I think a little database (maybe in xml?) of installed files/modules
and their locations would be useful, perhaps even for a future
automatic download/installation/dependency-tracking thingmabob that
still regretably still doesn't exist as parth of the stdlib in
Pythonia.

AK

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


Re: Win32 Libs for 2.4

2004-12-06 Thread Daniel Dittmar
Robin Becker wrote:
I guess that it won't work if something malloc'ed from the MSC 6 
runtime is free'd by the MSC 7.1 runtime.
I thought that static .libs didn't make reference to the dll's they 
need; isn't that done at load time?
You're right, DLL-phobia made my thinking less than precise.
The other things I could think of might not apply in this case:
- Routines accessing the elements of FILE* directly. I though library 
designers had learned not to export this, but stdio.h still shows it and 
some macros from that header file might use it (a problem only if the 
definitions in MSC 6 and MSC 7.1 differ)
- calling conventions: in the past, that was a problem mostly with 
functions returning structs. (Meaning caller and callee would implement 
it differently if they were compiled by different compilers)

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


Re: cut strings and parse for images

2004-12-06 Thread Andreas Volz
Am Mon, 06 Dec 2004 20:36:36 GMT schrieb Paul McGuire:

> Check out the urlparse module (in std distribution).  For images, you
> can provide a default addressing scheme, so you can expand
> "images/marine.jpg" relative to the current location.

Ok, this looks good. But I'm a really newbie to python and not able to
create a minimum example. Could you please give me a very small example
how to use urlparse? Or point me to an example in the web?

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


Re: Help with super()

2004-12-06 Thread Steven Bethard
Christopher J. Bottaro wrote:
Why don't this code work?
import PRI
class Poscdnld_PYIO(PRI.BasicBatch):
   
   def __init__(self, *argv):
  super(Poscdnld_PYIO, self).__init__(*argv)

x = Poscdnld_PYIO()
I get this exception:
File "poscdnld_pyio.py", line 52, in __init__
super(Poscdnld_PYIO, self).__init__(*argv)
TypeError: super() argument 1 must be type, not classobj
What am I doing wrong?  Thanks.
I don't know what PRI is, but I suspect that PRI.BasicBatch is a classic 
class, not a new-style class.  The super function only works for 
new-style classes:

>>> class C:
... def __init__(self):
... super(C, self).__init__()
...
>>> c = C()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in __init__
TypeError: super() argument 1 must be type, not classobj
>>> class C(object):
... def __init__(self):
... super(C, self).__init__()
...
>>> c = C()
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mean, median, and mode

2004-12-06 Thread Steven Bethard
Paul Rubin wrote:
median = x.sorted()[len(x)//2]
In Python 2.4:
>>> [10, 8, 6, 4, 2, 1].sorted()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'list' object has no attribute 'sorted'
Perhaps you meant "sorted(x)"?
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with super()

2004-12-06 Thread Peter Otten
Christopher J. Bottaro wrote:

> Why don't this code work?
> 
> import PRI
> 
> class Poscdnld_PYIO(PRI.BasicBatch):
>
>def __init__(self, *argv):
>   super(Poscdnld_PYIO, self).__init__(*argv)
> 
> x = Poscdnld_PYIO()
> 
> I get this exception:
> File "poscdnld_pyio.py", line 52, in __init__
> super(Poscdnld_PYIO, self).__init__(*argv)
> TypeError: super() argument 1 must be type, not classobj
> 
> What am I doing wrong?  Thanks.

super() does not work with classic classes:

>>> class Classic: pass
...
>>> class A(Classic):
... def __init__(self):
... super(A, self).__init__()
...
>>> A()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in __init__
TypeError: super() argument 1 must be type, not classobj

whereas:

>>> class A(object):
... def __init__(self):
... super(A, self).__init__()
...
>>> A()
<__main__.A object at 0x402ac02c>

Invoking

def __init__(self, *argv):
PRI.BasicBatch.__init__(self, *argv)

explicitly instead works as well unless you need cooperative methods which
are only possible with newstyle classes.

Peter



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


[Plone] Form Controller

2004-12-06 Thread Ro
Help!

Using the CMFController actions, how do I POST the results of the
validated form to another site? I am trying to integrate my plone site
with salesforce.com so that leads automatically get created when users
fill out the contact me form.

This works - but no validation obviously:
http://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
method="post">

This validates the form, but I am stumped on how to pass this on to
sales force as an success action (traversal_to the above absolute url
fails):


Thanks
Ro

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


RE: byte code generated under linux ==> bad magic number under windows

2004-12-06 Thread Delaney, Timothy C (Timothy)
Philippe C. Martin wrote:

> I understand from my reading that a .pyc generated by python anywhere
> should run anywhere else - is that true ?
> 
> If I generate 'compile.all' a pyc with python 2.3.3 under Linux, I
^
> get a 'bad magic number' trying to execute it under windows (2.4).
   ^^^
> are the pyc plateform dependant ? and if so must I generate one
> version for each version of Linux, windows .. ?

.pyc files are not platform dependent, but they are *version* dependent
- specifically, major version (i.e. 2.3, 2.4).

Between major versions, the bytecode can change. There were in fact some
significant changes between 2.3 and 2.4.

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


Re: GUI Frames and classmethod

2004-12-06 Thread Scott David Daniels
Zak Arntson wrote:
On Mon, 06 Dec 2004 13:08:15 -0800, Scott David Daniels
<[EMAIL PROTECTED]> wrote:
Zak Arntson wrote:
On Fri, 03 Dec 2004 14:48:30 -0800, Scott David Daniels wrote:
...The real advantage is clarity: the inner dictionaries in a dict-of-dict
implementation have no real "meaning."  The extra overhead (in the mind
of the program reader) involved in creating inner dictionaries at
appropriate times makes the code harder to understand.
... If I see:
{("None", "Enter"): enter_state_None,
 ("None", "During"): during_state_None,
 ("None", "Leave"): leave_state_None,
 ("LWait", "Enter"): enter_state_LWait,
 ("LWait", "During"): during_state_LWait,
 ("LWait", "Leave"): leave_state_LWait}
I want to split it up. This is more intuitive for me because it shows
an obvious one-many relationship between the outer keys and the inner
keys.
{"None": {"Enter": enter_state_None, "During": during_state_None,
"Leave": leave_state_None},
 "LWait": {"Enter": enter_state_LWait, "During": during_state_Lwait,
"Leave": leave_state_LWait}}
First, I'd probably write the above as some variation of the following:
{"None": {"Enter": enter_state_None,
  "During": during_state_None,
  "Leave": leave_state_None},
 "LWait": {"Enter": enter_state_LWait,
   "During": during_state_Lwait,
   "Leave": leave_state_LWait}
}
to show the two-layer structure.  I'd also prefer function names
describing what is done, rather than why the code was called, but
the names may only be in the current form because we are talking
about coding, and have no real application here.
Second, I was referring to code like:
 try:
 inner = table[state]
 except KeyError:
 table[state] = inner = {}
 inner[action] = whatever
vs. code like this:
 table[state, action] = whatever
That is, dynamic table modification code for a table of pairs is
clearer.  If you are simply creating the table from a simple source,
I might make a different choice.  I am not particularly big on
names like enter_state_none, nor one of prescribing a structure
that makes the creation of lots of no-ops necessary.  I'd rather
see code using the system look like:
try:
action = table[state, stimulus]
except KeyError:
pass
else:
action(arglist)
or even:
def noop(*args, **kwargs):
pass
...
table.get((state, stimulus), noop)(arglist)
If each state is an instance with a dictionary, you might even want
to go with:
class State(object): pass # or whatever
...
NullState = State()
NullState.enter = whatever
NullState.during = whenever
NullState.leave = forever
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mean, median, and mode

2004-12-06 Thread Fredrik Lundh
Paul Rubin wrote:

> > > median = lambda x: x.sort() or x[len(x)//2]
>
> Yucch!!
>
> median = x.sorted()[len(x)//2]

that doesn't do the same thing, and doesn't work on pre-2.4 releases.

try again.

(learning how "or" and "and" works in Python doesn't hurt, either;
"value or value" is a very common idiom in Python code)

 



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


Help with super()

2004-12-06 Thread Christopher J. Bottaro
Why don't this code work?

import PRI

class Poscdnld_PYIO(PRI.BasicBatch):
   
   def __init__(self, *argv):
  super(Poscdnld_PYIO, self).__init__(*argv)

x = Poscdnld_PYIO()

I get this exception:
File "poscdnld_pyio.py", line 52, in __init__
super(Poscdnld_PYIO, self).__init__(*argv)
TypeError: super() argument 1 must be type, not classobj

What am I doing wrong?  Thanks.

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


Re: Mean, median, and mode

2004-12-06 Thread Paul Rubin
Josiah Carlson <[EMAIL PROTECTED]> writes:
> > > median = lambda x: x.sort() or x[len(x)//2]
> > 
> > That...is a really sneaky use of null return values. I like. :)
> 
> Thank you, I'm just using a paradigm (exploiting lambdas) that I picked
> up while going through various functional programming modules.

Yucch!!

median = x.sorted()[len(x)//2]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUI Frames and classmethod

2004-12-06 Thread Zak Arntson
On Mon, 06 Dec 2004 13:08:15 -0800, Scott David Daniels
<[EMAIL PROTECTED]> wrote:
> Zak Arntson wrote:
> > On Fri, 03 Dec 2004 14:48:30 -0800, Scott David Daniels
> Most likely so.  Possibly an equal amount of has work -- hash of a pair
> is a function of hashes of the lelements, but fewer trips in and out of
> the interpretter.  So, one less lookup, less refcount fiddling, and
> fewer dispatches through the interpretter.
> 
> The real advantage is clarity: the inner dictionaries in a dict-of-dict
> implementation have no real "meaning."  The extra overhead (in the mind
> of the program reader) involved in creating inner dictionaries at
> appropriate times makes the code harder to understand.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

I feel differently (though I'd accept being in the minority on this
one). If you have a dictionary of tuples where the first member is an
often-repeated value, then it makes more sense (again, to me) to split
it up.

So if I see:
{("None", "Enter"): enter_state_None,
 ("None", "During"): during_state_None,
 ("None", "Leave"): leave_state_None,
 ("LWait", "Enter"): enter_state_LWait,
 ("LWait", "During"): during_state_LWait,
 ("LWait", "Leave"): leave_state_LWait}

I want to split it up. This is more intuitive for me because it shows
an obvious one-many relationship between the outer keys and the inner
keys.
{"None": {"Enter": enter_state_None, "During": during_state_None,
"Leave": leave_state_None},
 "LWait": {"Enter": enter_state_LWait, "During": during_state_Lwait,
"Leave": leave_state_LWait}}


I have to confess to not knowing whether one way is more "Pythonic"
than the other. The first method is mostly easier to code with, but
doesn't explicitly state a one-many relationship. The second give
lengthier code for most operations.

-- 
Zak Arntson
http://www.harlekin-maus.com - Games - Lots of 'em
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mean, median, and mode

2004-12-06 Thread Scott David Daniels
How about:
def median(lst):
lst = sorted(lst)
inner = lst[(len(lst) - 1) // 2 : (len(lst) + 2) // 2]
if len(inner) > 1:
return sum(inner) / 2.
else:
return inner[0]
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: How is Python designed?

2004-12-06 Thread Limin Fu
Hi,

> So I guess you don't use classic parser techniques
> then?

You are right. The Yuan interpreter scans the tokens
resulted from lexical analysis and matches them to the
syntax patterns. There are 3 basic patterns defined in
Yuan: arithmetic "a*b+c", chain (as I called it)
"objs[i]->func()" and regular expression "/\d*[abc]/",
each of which is represented by a class. And the other
patterns are a combination of these 3 basic pattern,
e.g. array enumeration "a=[1,a+1,func()]" etc. There
are functions responsible to parse the token patterns
to phrase objects. After all phrase objects are
generated, logical and loop controls are checked, so
that each phrase object "knows" if it should "step to"
the next phrase object or "jump to" another one when
it is executed. In this technique, indeed, checking
patterns is a little complicated. In Yuan this part is
not optimally implemented, somethings have to be
improved or changed. 

> I'm still not sure what you mean by "recursive" - to
> me, recursion is the
> act of a function calling itself until some
> condition is met that markes
> the end (or actually begin I think) of the
> recursion, like this:
> 
> def fac(n):
> if n == 1:
> return 1
> return n * fac(n-1)
> 
> Thats recursion.

I supposed you would have done like:
class node{
...
char oper;
node *left,*right;
void compute();
};
void node::compute()
{
   if(left) left->compute();
   if(right) right->compute();
   if(oper=='+'){
  
   }else if(...){
  
   }
}
This is a kind of recursive evaluation of arithmetic
tree. Now I believe that's not what you have used.

> If you mean by recursion that the top-node is called
> for evaluation which
> then delegates the evaluation to its children -

Ah, yes. That's exactly what I mean.

> well, that's unavoidable -

That's avoidable, using depth first seach.

> but also in both cases. As I mentioned before, the
> only difference I see is
> the order of evaluation  - but that is invariant, as
> long as for all
> expression's their respective sub-expressions are
> evaluated beforehand.

It seemed to me that it made much difference in
efficiency so that I reimplemented it by depth-first
search. Maybe because I didn't implement the recursive
evaluation properly :), I will check.

> 
> I'm not upset - I feared you were :) And I perceive

Ok, since non of us is upseted, let's forget it :)

Best,

Limin





__ 
Do you Yahoo!? 
Yahoo! Mail - Helps protect you from nasty viruses. 
http://promotions.yahoo.com/new_mail
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Mean, median, and mode - third time's the charm!!!

2004-12-06 Thread Frohnhofer, James
> 
> median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)])) or
> (sum(x[((len(x)>>1)-1):(len(x)>>1)+1])/2.0)
> 
> >>> median( [2,3,4,5,6,7])
> 4.5
> >>> median( [2,3,4,5,6])
> 4

How about

>>> median = lambda x: x.sort() or (x[(len(x)-1)/2] + x[len(x)/2])/2.0
>>> median([2,3,4,5,6,7])
4.5
>>> median( [2,3,4,5,6])
4.0
>>> 


==
This message is for the sole use of the intended recipient. If you received
this message in error please delete it and notify us. If this message was
misdirected, CSFB does not waive any confidentiality or privilege. CSFB
retains and monitors electronic communications sent through its network.
Instructions transmitted over this system are not binding on CSFB until they
are confirmed by us. Message transmission is not guaranteed to be secure.
==

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


Re: GUI Frames and classmethod

2004-12-06 Thread Scott David Daniels
Zak Arntson wrote:
On Fri, 03 Dec 2004 14:48:30 -0800, Scott David Daniels
<> wrote:
 question: A dictionary of dictionaries is slower than a
dictionary of tuples, right? Because when Python accesses a
dictionary, it produces a hash from the key and finds that in its hash
table. Producing a hash from a tuple is much faster than producting
two hashes and doing two lookups. At least that's what I'm assuming.
Most likely so.  Possibly an equal amount of has work -- hash of a pair
is a function of hashes of the lelements, but fewer trips in and out of
the interpretter.  So, one less lookup, less refcount fiddling, and
fewer dispatches through the interpretter.
The real advantage is clarity: the inner dictionaries in a dict-of-dict
implementation have no real "meaning."  The extra overhead (in the mind
of the program reader) involved in creating inner dictionaries at
appropriate times makes the code harder to understand.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Seeking Python + Subversion hosting.

2004-12-06 Thread remi
> Anyone know of a good hosting company that offers both server-side
> Python and a subversion repository?
>
> I know of one: www.textdrive.com - they're a bit pricey, but I s'pose
> you gets what you pays for - they look good.
>
> Just FYI - right now I'm with sapphiresoft.co.uk. They're cheap and
in
> my brief experience have been pretty good at responding to support
> issues. They gave me a big 'no' to subversion though. (tip: if you
use
> these guys, be sure to tell them you want the server with the latest
> Python goodies *before* you sign up!)

Python-Hosting.com supports Subversion hosting as well.
You can also get Trac hosting there if you need it.
This is available as part of all the plans and you'll get all the other
features included (backups, monitoring, DNS hosting, e-mail hosting,
web hosting, DB hosting, ...)

This is where http://www.cherrypy.org is hosted for instance.
Regards,

Remi.

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


Re: why python is slower than java?

2004-12-06 Thread fuzzylollipop
yeah, but a lie unanswered by the truth becomes the truth.

you state opinon as fact and someone comes along reads your statement
that Python is so much slower and believes it is true because there is
no disententing voice to say, wait just a sec, this guy is clueless and
has no idea what he is talking about and here is why.

learn how to ask questions instead of stateing opinions as fact and you
might get a better response.

if you had said, is Python really as slow vs Java as these 3 year old
benchmarks seem to suggest, and then post what your own findings were
and that might prove DISCUSSION instead of posting in a Trolling sort
of way.

No matter how many times you say you are not trolling and continue to
post trolling style posts will make it true.

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


Re: cut strings and parse for images

2004-12-06 Thread Steve Holden
Andreas Volz wrote:
Hi,
I used SGMLParser to parse all href's in a html file. Now I need to cut
some strings. For example:
http://www.example.com/dir/example.html
Now I like to cut the string, so that only domain and directory is
left over. Expected result: 

http://www.example.com/dir/
I know how to do this in bash programming, but not in python. How could
this be done?
The next problem is not only to extract href's, but also images. A href
is easy:
Install
But a image is a little harder:

This is my current example code:
from sgmllib import SGMLParser
leach_url = "http://stargus.sourceforge.net/";
class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.urls = []
def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)
if __name__ == "__main__":
	import urllib
	usock = urllib.urlopen(leach_url)
	parser = URLLister()
	parser.feed(usock.read())
	parser.close()
	usock.close()
	for url in parser.urls: 
		print url

Perhaps you've some tips how to solve this problems?
from sgmllib import SGMLParser
leach_url = "http://stargus.sourceforge.net/";
class URLLister(SGMLParser):

def reset(self):
SGMLParser.reset(self)
self.urls = []
self.images = []
def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)
def do_img(self, attrs):
"We assume each image *has* a src attribute."
for k, v in attrs:
if k == 'src':
self.images.append(v)
break


if __name__ == "__main__":
import urllib
usock = urllib.urlopen(leach_url)
parser = URLLister()
parser.feed(usock.read())
parser.close()
usock.close()
print "URLs:"
for url in parser.urls:
print url
print "IMGs:"
for img in parser.images:
print img
$ python sgml1.py
URLs:
about.php
install.php
features.php
http://www.stratagus.org/
http://www.stratagus.org/
http://www.blizzard.com/
http://sourceforge.net/projects/stargus/
IMGs:
images/stargus_banner.jpg
images/marine.jpg
http://sourceforge.net/sflogo.php?group_id=119561&type=1
regards
 Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


PyAr - Python Argentina 4th Meeting, Thursday, December 9th

2004-12-06 Thread Batista, Facundo
Title: PyAr - Python Argentina 4th Meeting, Thursday, December 9th





The Argentinian Python User Group, PyAr, will have its next
meeting this Thursday, December 9th at 8.30pm. Please see 
http://pyar.decode.com.ar/Members/pziliani/event.diciembre for
details (in Spanish.)



Agenda
--


Despite our agenda tends to be rather open, this time we would
like to cover these topics:


- Website organization & content
- Means of promoting the group's activities, in order to increase
  our member base.
- Planning of our first sprint.



Where
-


We're meeting at Hip Hop Bar, Hipólito Yirigoyen 640, Ciudad de Buenos
Aires, starting at 8.30pm. We use to get together early, but this month 
the starting time has been postponed for reasons beyond our control.



About PyAr
--


For more information on PyAr see http://pyar.decode.com.ar (in Spanish), 
or join our mailing list (Also in Spanish. For instructions see 
http://pyar.decode.com.ar/Members/ltorre/listademail)


We meet on the second Thursday of every month.


.   Facundo



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

Re: byte code generated under linux ==> bad magic number under windows

2004-12-06 Thread Jarek Zgoda
Fredrik Lundh wrote:
AFAIK, they *are* platform dependent. You can not share pyc files between ASCII and EBCDIC 
machine.
however, that could be seen as be a flaw in the EBCDIC ports.
We'll see if this could be fixed. I try to foster some "movement" in 
Python/400 (I love this name, please, dont call it iSeries Python!) 
community in the hope to put more life in this port. We have more bugs 
than anyone else to fight, at last. ;)

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


Re: Python installation breaks Outlook Express

2004-12-06 Thread Mike
I have the same problem.  It isn't a problem with Outlook.  It is with
Python.  I loose my wired AND wireless connections.  Removing Python
bringst them back to operational.
Mike

M. Laymon wrote:
> I just installed Python 2.3.3 under Windows XP professional.   After
I
> did, my wife tried to access her email using Outlook Express and got
> the error messages:
>
> Your server has unexpectedly terminated the connection. Possible
> causes for
> this include server problems, network problems, or a long period of
> inactivity.
> Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net',
> Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F
>
> Your server has unexpectedly terminated the connection. Possible
> causes for this
> include server problems, network problems, or a long period of
> inactivity.
> Account: 'incoming.verizon.net', Server: 'incoming.verizon.net',
> Protocol: POP3,
> Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F
>
>  (No comments about Outlook, please.I have tried to get her to use a
> different email program, but she likes Outlook.)   I checked the
> settings, then recreated her account in Outlook, but nothing worked.
> My Mozilla Thunderbird email client worked fine.
>
> Since the only thing I had done recently was to install Python.  I
> used system restore to go back to the point before installing Python.
> After I did, Outlook started working again.  Has anyone else seen
this
> behavior ?
> 
> Thanks.
> 
> M. Laymon

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


Re: Mean, median, and mode

2004-12-06 Thread Josiah Carlson

[EMAIL PROTECTED] (Michael Fuhr) wrote:
> 
> Josiah Carlson <[EMAIL PROTECTED]> writes:
> 
> 
> > "Robert Brewer" <[EMAIL PROTECTED]> wrote:
> > > 
> > > Josiah Carlson wrote:
> > > > 
> > > > median = lambda x: x.sort() or x[len(x)//2]
> > > 
> > > That...is a really sneaky use of null return values. I like. :)
> >
> > Thank you, I'm just using a paradigm (exploiting lambdas) that I picked
> > up while going through various functional programming modules.
> 
> print median([1, 2, 3, 4, 5, 6])
> 4
> 
> Shouldn't the median be 3.5?

The wikipedia entry (as mentioned by Peter Hanson in another post) is
incomplete. There are 3 valid medians for even-lengthed sequences:
sorted(seq)[len(seq)//2]
sorted(seq)[len(seq)//2-1]
sum(sorted(seq)[len(seq)//2-1:len(seq)//2+2])/2.0

All are correct, what is /desired/ is generally application specific. If
you want the statistical median, 3.5 is the answer.  If you want a
computer science median (for quicksort, etc.), 3 or 4 is sufficient.  I
chose the shortest implementation (using the author's style, without
sorted, because I forgot about the new builtin), which gives the greater
(or equal) of the two possible computer science median values.


 - Josiah

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


Re: cut strings and parse for images

2004-12-06 Thread Paul McGuire
"Andreas Volz" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I used SGMLParser to parse all href's in a html file. Now I need to cut
> some strings. For example:
>
> http://www.example.com/dir/example.html
>
> Now I like to cut the string, so that only domain and directory is
> left over. Expected result:
>
> http://www.example.com/dir/
>
> I know how to do this in bash programming, but not in python. How could
> this be done?
>
> The next problem is not only to extract href's, but also images. A href
> is easy:
>
> Install
>
> But a image is a little harder:
>
> 
>

Check out the urlparse module (in std distribution).  For images, you can
provide a default addressing scheme, so you can expand "images/marine.jpg"
relative to the current location.

-- Paul


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


Re: file descriptors & fdopen

2004-12-06 Thread Scott Frankel
foo = open('foo.txt', 'w')
duh.
Thanks -
Scott
On Dec 6, 2004, at 11:27 AM, Scott Frankel wrote:
Why does os.fdopen('foo.txt', 'w') require an integer?
Ultimately, I want to create a new file on disk.
Funny, I can't seem to suss-out how to create a new file without 
resorting
to os.system('touch foo.txt').  ... Or maybe not so funny ...

>>> foo = os.fdopen('foo.txt', 'w')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: an integer is required
Thanks in advance!
Scott

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


Re: Mean, median, and mode - third time's the charm!!!

2004-12-06 Thread Paul McGuire
"Paul McGuire" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> "Paul McGuire" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > This median expression is incorrect.  median is *not* the midpoint
between
> > max and min values.  It is the middle value when all values are sorted
> (for
> > an odd number of values), or the average of the two middle values when
all
> > values are sorted (for an even number of values).
> >
> > In Python 2.4 (needed to use sorted() built-in), this can be one-lined
as:
> > median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
> > (sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))
> >
> > (not yet tested, as I've not installed v2.4 yet)
> > With boolean short-circuiting, this should only sort the list once.
> >
> > -- Paul
> >
> >
> Damned off-by-one errors!
>
> Try this instead:
>
> median = lambda x: ((len(x) % 2) and (sorted(x)[(len(x)>>1)-1]) or
> (sum(sorted(x)[((len(x)>>1)-1):(len(x)>>1)])/2))
>
>
> Or using the sneaky None returned by sort(), for pre-2.4 utility:
>
> median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)-1]) or
> (sum(x[((len(x)>>1)-1):(len(x)>>1)])/2))
>
>
> -- Paul
>
>

median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)])) or
(sum(x[((len(x)>>1)-1):(len(x)>>1)+1])/2.0)

>>> median( [2,3,4,5,6,7])
4.5
>>> median( [2,3,4,5,6])
4



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


Re: byte code generated under linux ==> bad magic number under windows

2004-12-06 Thread Fredrik Lundh
Jarek Zgoda wrote:

> AFAIK, they *are* platform dependent. You can not share pyc files between 
> ASCII and EBCDIC 
> machine.

however, that could be seen as be a flaw in the EBCDIC ports.

 



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


Re: python-mode question

2004-12-06 Thread Skip Montanaro

Thomas> I assume you meant the python-mode project?

Whoops.  Yeah.  Thanks.

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


Re: file descriptors & fdopen

2004-12-06 Thread Jeremy Jones
Scott Frankel wrote:
Why does os.fdopen('foo.txt', 'w') require an integer?
Ultimately, I want to create a new file on disk.
Funny, I can't seem to suss-out how to create a new file without 
resorting
to os.system('touch foo.txt').  ... Or maybe not so funny ...

>>> foo = os.fdopen('foo.txt', 'w')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: an integer is required
Thanks in advance!
Scott

If you just want to create a file for writing to, you probably want:
foo = open('foo.txt', 'w')
Jeremy Jones
--
http://mail.python.org/mailman/listinfo/python-list


Re: Seeking Python + Subversion hosting.

2004-12-06 Thread remi
> Anyone know of a good hosting company that offers both server-side
> Python and a subversion repository?
>
> I know of one: www.textdrive.com - they're a bit pricey, but I s'pose
> you gets what you pays for - they look good.
>
> Just FYI - right now I'm with sapphiresoft.co.uk. They're cheap and
in
> my brief experience have been pretty good at responding to support
> issues. They gave me a big 'no' to subversion though. (tip: if you
use
> these guys, be sure to tell them you want the server with the latest
> Python goodies *before* you sign up!)

Python-Hosting.com supports Subversion hosting as well.
You can also get Trac hosting there if you need it.
This is available as part of all the plans and you'll get all the other
features included (backups, monitoring, DNS hosting, e-mail hosting,
web hosting, DB hosting, ...)

This is where http://www.cherrypy.org is hosted for instance.
Regards,

Remi.

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


Re: [Python-Help] Programming help

2004-12-06 Thread Danny Yoo


On Mon, 6 Dec 2004, Alfred Canoy wrote:

> Please help me out:(.. I've been trying to figure this out for 2 days
> now.. I don't know what to use to print all the list of numbers. I hve
> know idea how should I do this. I tried a lot of trial & error for the
> the def, dict, .list( ). have no luck.


Hi Alfred.

When you are reading numbers from the user, you should be careful to store
those numbers somewhere.  That is, you need to "collect" each new number
in some kind of container.


Take a look at:

http://www.freenetpages.co.uk/hp/alan.gauld/tutdata.htm

The "Collections" section of that page has tutorial material on how to
collect a bunch of numbers in a single container.


Good luck to you!

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


Re: byte code generated under linux ==> bad magic number under windows

2004-12-06 Thread Jarek Zgoda
Aaron Bingham wrote:
.pyc files are platform-independant but are incompatible between major 
Python versions.  You can not use a .pyc file generated with Python 2.3 
with Python 2.4 or vice versa.
AFAIK, they *are* platform dependent. You can not share pyc files 
between ASCII and EBCDIC machine.

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


Re: Mean, median, and mode

2004-12-06 Thread Peter Hansen
Michael Fuhr wrote:
Josiah Carlson <[EMAIL PROTECTED]> writes:

"Robert Brewer" <[EMAIL PROTECTED]> wrote:
Josiah Carlson wrote:
median = lambda x: x.sort() or x[len(x)//2]
That...is a really sneaky use of null return values. I like. :)
Thank you, I'm just using a paradigm (exploiting lambdas) that I picked
up while going through various functional programming modules.

print median([1, 2, 3, 4, 5, 6])
4
Shouldn't the median be 3.5?
According to http://en.wikipedia.org/wiki/Median you are correct.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any affordable Python-based CRM & ERP solutions?

2004-12-06 Thread EuGeNe
Will wrote:
Hi all,
Please excuse the longish post. I'm new to Python (and programming),
but love what I see and believe it to be an important language.
I have (at least) one retail client (with single outlet at present)
that requires a total business solution for their operation,
preferably open source. They need:
- an ecommerce website providing sales, customer service, order
tracking and an opt-in newsletter
- system for tracking inventory
- full accounting system, tied-into the ecommerce website-- so full
front-end and back-end system integration
- possibly even point of sale tied-into the above.
They've been using Windows up until now, but are happy to consider
Linux, BSD, Mac, etc, as long as there's not a huge learning curve
(they merely want a solution that works and is cost-effective). Other
than standard accounting reporting requirements, they need the ability
to add tax to local transactions.
I have Googled with not a lot of contenders (Compiere--
http://www.compiere.org/index.html -- not Python and an Oracle license
is required to run it; and I've just started reading about Bizar
Shop-- http://www.bizarshop.com.au/). Anything else I've seen is
either really expensive, doesn't fit the bill, or are not Python-based
(which I'd ultimately like to promote).
Because of the above requirements I was thinking something quite
modular (that could be added to in future) would be the way to go. I
like what I have seen with Plone and Zope but am unsure at present
(given limited experience with these products) how one would integrate
something into those solutions (if package didn't come from one
'vendor'), so that at least on the surface, everything appeared pretty
seamless.
Is this wishful thinking in Python at present? If so, have you
encountered any other open source solutions that cover part of the
above with Python handling the rest (and being easily integrated)?
I look forward to any feedback. Thanks very much in advance.
Cheers,
Will :)
Maybe http://www.erp5.org/ is what you are looking for!
--
http://mail.python.org/mailman/listinfo/python-list


cut strings and parse for images

2004-12-06 Thread Andreas Volz
Hi,

I used SGMLParser to parse all href's in a html file. Now I need to cut
some strings. For example:

http://www.example.com/dir/example.html

Now I like to cut the string, so that only domain and directory is
left over. Expected result: 

http://www.example.com/dir/

I know how to do this in bash programming, but not in python. How could
this be done?

The next problem is not only to extract href's, but also images. A href
is easy:

Install

But a image is a little harder:



This is my current example code:

from sgmllib import SGMLParser

leach_url = "http://stargus.sourceforge.net/";

class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.urls = []

def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)

if __name__ == "__main__":
import urllib
usock = urllib.urlopen(leach_url)
parser = URLLister()
parser.feed(usock.read())
parser.close()
usock.close()
for url in parser.urls: 
print url


Perhaps you've some tips how to solve this problems?

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


Re: Trying to understand a little python

2004-12-06 Thread Jeremy Jones




McCarty, Greg wrote:

  
  
  
  
  Ok, I'm new to python,
and I'm trying to come to grips with
a few things.  Got
  lots of years of
experience with Java and asp/aspx,
etc.  Trying to relate
  Python's behavior to what
I already know.
   
  Here's the python code
(line #'s added for my question) -
   
  01 class Tester:
  02 def __init__
(self):
  03 print
"I'm initializing Tester"
  04
  05 def test(klass=Tester):
  06 klass.stuff =
"setting
stuff"
  07 print "I'm in
test: " +
klass.stuff
  08
  09
test()  # results 1: I'm
in test: setting stuff
  10 a=Tester()  #
results 2: I'm
initializing Tester
  11 a.stuff #
results 3: 'setting stuff'
  12 b=Tester()  #
results 4: I'm
initializing Tester
  13 b.stuff #
results 5: 'setting stuff'
  14 a.stuff="changed!"
  15 b.stuff #
results 6: 'setting stuff'
  16 a.stuff #
results 7:'changed!'
   
  And here's my questions -
   
  Line 09 - I expected the
default argument assignment of line
05 to 
  create an object of type
Tester and assign it to the var
klass.  Thus I
  expected Tester.__init__
to fire, which it didn't. 
What does 'klass=Tester' 
  actually do on line 05?
   
  

klass=Tester sets the default value of the variable klass to the
*class* Tester.  This isn't creating an instance of Tester.  Only
pointing klass to the class itself.

  
  Line 10 - Seems that the
syntax 'Tester()' actually causes
the __init__ method to 
  fire.  Is this the only
case?
  

Mostly.  You can use getattr if you like.  And probably eval or exec. 
But I would try to stick with the Tester() syntax.

  
  
   
  Line 12 - At this point,
I was thinking of Tester.stuff as a
static variable
  of the Tester class.
  

When you set a.stuff to "changed", you are setting an instance
attribute on "a" to "changed".  "b" is still pointing to the "static
variable" on Tester.  Look at this:

In [12]: a = Tester()
I'm initializing Tester

In [13]: b = Tester()
I'm initializing Tester

In [14]: Tester.stuff
Out[14]: 'setting stuff'

In [15]: Tester.stuff = "FOOBAR"

In [16]: a.stuff
Out[16]: 'FOOBAR'

In [17]: b.stuff
Out[17]: 'FOOBAR'

In [18]: a.stuff = "A.STUFF"

In [19]: a.stuff
Out[19]: 'A.STUFF'

In [20]: b.stuff
Out[20]: 'FOOBAR'

I re-set Tester.stuff to "FOOBAR".  "a" and "b" attributes "stuff" were
pointing to that for a second.  Then I pointed the attribute "stuff" on
"a" to "FOOBAR".

  
  
   
  Line 15 - We'll, I guess
stuff isn't a static variable! 
What is the
  explanation here?
   
  Thanks for any help.
   
  Greg McCarty
  Senior Technical Advisor / ManTech
IST
  ph:  410-480-9000 x2804
or
703-674-2804    fx: 410-480-0916
   
  

HTH.

Jeremy


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

Re: Mean, median, and mode

2004-12-06 Thread Paul McGuire

"Paul McGuire" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> This median expression is incorrect.  median is *not* the midpoint between
> max and min values.  It is the middle value when all values are sorted
(for
> an odd number of values), or the average of the two middle values when all
> values are sorted (for an even number of values).
>
> In Python 2.4 (needed to use sorted() built-in), this can be one-lined as:
> median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
> (sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))
>
> (not yet tested, as I've not installed v2.4 yet)
> With boolean short-circuiting, this should only sort the list once.
>
> -- Paul
>
>
Damned off-by-one errors!

Try this instead:

median = lambda x: ((len(x) % 2) and (sorted(x)[(len(x)>>1)-1]) or
(sum(sorted(x)[((len(x)>>1)-1):(len(x)>>1)])/2))


Or using the sneaky None returned by sort(), for pre-2.4 utility:

median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)-1]) or
(sum(x[((len(x)>>1)-1):(len(x)>>1)])/2))


-- Paul


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


Re: GUI Frames and classmethod

2004-12-06 Thread Zak Arntson
On Fri, 03 Dec 2004 14:48:30 -0800, Scott David Daniels
<[EMAIL PROTECTED]> wrote:
> Zak Arntson wrote:
>  > My current approach is that in the Frame class, I have a method to
>  > call _after_ initialization that creates a bunch of dummy methods so
>  > the user doesn't have to implement EVERY state change method in a
> 
> Really, I think the above is a bad idea.  Don't implement empty
> methods.  Make a dictionary of state transitions, and store code in it.
> Note: you don't need a dictionary of dictionaries; you could use a
> dictionary of pairs.  Do something on each attempted transition like the
> following:

A dictionary of methods! Thanks. Boy, do I feel silly now. So I have a
more general question: A dictionary of dictionaries is slower than a
dictionary of tuples, right? Because when Python accesses a
dictionary, it produces a hash from the key and finds that in its hash
table. Producing a hash from a tuple is much faster than producting
two hashes and doing two lookups. At least that's what I'm assuming.

-- 
Zak Arntson
http://www.harlekin-maus.com - Games - Lots of 'em
-- 
http://mail.python.org/mailman/listinfo/python-list


file descriptors & fdopen

2004-12-06 Thread Scott Frankel
Why does os.fdopen('foo.txt', 'w') require an integer?
Ultimately, I want to create a new file on disk.
Funny, I can't seem to suss-out how to create a new file without 
resorting
to os.system('touch foo.txt').  ... Or maybe not so funny ...

>>> foo = os.fdopen('foo.txt', 'w')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: an integer is required
Thanks in advance!
Scott

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


Trying to understand a little python

2004-12-06 Thread McCarty, Greg








Ok, I'm new to python, and I'm trying to come to grips with
a few things.  Got

lots of years of experience with Java and asp/aspx,
etc.  Trying to relate

Python's behavior to what I already know.

 

Here's the python code (line #'s added for my question) -

 

01 class Tester:

02 def __init__ (self):

03 print
"I'm initializing Tester"

04

05 def test(klass=Tester):

06 klass.stuff = "setting
stuff"

07 print "I'm in test: " +
klass.stuff

08

09
test()  # results 1: I'm
in test: setting stuff

10 a=Tester()  # results 2: I'm
initializing Tester

11 a.stuff #
results 3: 'setting stuff'

12 b=Tester()  # results 4: I'm
initializing Tester

13 b.stuff #
results 5: 'setting stuff'

14 a.stuff="changed!"

15 b.stuff #
results 6: 'setting stuff'

16 a.stuff #
results 7:'changed!'

 

And here's my questions -

 

Line 09 - I expected the default argument assignment of line
05 to 

create an object of type Tester and assign it to the var
klass.  Thus I

expected Tester.__init__ to fire, which it didn't. 
What does 'klass=Tester' 

actually do on line 05?

 

Line 10 - Seems that the syntax 'Tester()' actually causes
the __init__ method to 

fire.  Is this the only case?

 

Line 12 - At this point, I was thinking of Tester.stuff as a
static variable

of the Tester class.

 

Line 15 - We'll, I guess stuff isn't a static variable! 
What is the

explanation here?

 

Thanks for any help.

 

Greg McCarty

Senior Technical Advisor / ManTech
IST

ph:  410-480-9000 x2804 or
703-674-2804    fx: 410-480-0916

 






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

Re: Mean, median, and mode

2004-12-06 Thread Michael Fuhr
Josiah Carlson <[EMAIL PROTECTED]> writes:


> "Robert Brewer" <[EMAIL PROTECTED]> wrote:
> > 
> > Josiah Carlson wrote:
> > > 
> > > median = lambda x: x.sort() or x[len(x)//2]
> > 
> > That...is a really sneaky use of null return values. I like. :)
>
> Thank you, I'm just using a paradigm (exploiting lambdas) that I picked
> up while going through various functional programming modules.

print median([1, 2, 3, 4, 5, 6])
4

Shouldn't the median be 3.5?

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using cmd.exe as a telnet client

2004-12-06 Thread Donnal Walter
I wrote:
I've been wanting to get acquainted with Twisted for awhile
now, ... BTW, do you know if Twisted's option negotiation
uses a callback function? I might download it to take a look, ...
Sorry I did not do this earlier, before I posted. It is obvious (now 
that I have downloaded it) that Twisted's Telnet implementation is based 
on its own Protocol base class (nice design). The only documentation I 
have been able to find, however, is in the protocols/telnet module 
itself. It is still not immediately obvious (to me) how to use the iac* 
methods to negotiate these options. Any help is much appreciated.

(I've not given up on writing my own funtion for Python's telnetlib, but 
I'm trying to keep all my options open. Besides, I will probably have 
other uses for Twisted later.)

Donnal Walter
Arkansas Children's Hospital


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


ANN: eGenix mx Experimental Package 0.9.0 (mxNumber, mxTidy, mxURL, etc.)

2004-12-06 Thread M.-A. Lemburg

ANNOUNCING
 eGenix.com mx Experimental Extension Package
Version 0.9.0
 Experimental Python extensions providing important and useful
services for Python programmers.

ABOUT
The eGenix.com mx Experimental Extensions for Python are a collection
of beta quality software tools for Python which will be integrated
into the other mx Extension Packages after they have matured to
professional quality tools.
* About Python:
Python is an object-oriented Open Source programming language which
runs on all modern platforms (http://www.python.org/). By integrating
ease-of-use, clarity in coding, enterprise application connectivity
and rapid application design, Python establishes an ideal programming
platform for todays IT challenges.
* About eGenix:
eGenix is a consulting and software product company focused on
providing professional quality services and products to Python
users and developers (http://www.egenix.com/).

NEWS
The new version includes patches needed to compile the package
for Python 2.4. It now supports all Python versions 1.5.2 - 2.4.
As always we are providing pre-compiled versions of the package for
Windows and Linux as well as sources which allow you to install the
package on all other supported platforms.

EGENIX MX EXPERIMENTAL PACKAGE OVERVIEW
mxNumber - Python Interface to GNU MP Number Types
 mxNumber provides direct access to the high performance numeric
 types available in the GNU Multi-Precision Lib (GMP).  This
 library is licensed under the LGPL and runs on practically all
 Unix platforms. eGenix.com has ported the GMP lib to Windows, to
 also provide our Windows users with the added benefit of being
 able to do arbitrary precision calculations and to easily port
 applications based on mxNumber from Unix to Windows or vice-versa.
 The package currently provide theses numerical types:
 1. Integer(value)  -- arbitrary precision integers much like
   Python longs only faster
 2. Rational(nom,denom) -- rational numbers with Integers as
   numerator and denominator
 3. Float(value[,prec]) -- floating point number with at least
   prec bits precision
 4. FareyRational(value, maxden)
-- calculate the best rational
   representation n/d of value
   such that d < maxden
mxTidy - Interface to HTML Tidy (HTML/XML cleanup tool)
 mxTidy provides a Python interface to a thread-safe, library
 version of the HTML Tidy. command line tool.
 HTML Tidy helps you to cleanup coding errors in HTML and XML
 files and produce well-formed HTML, XHTML or XML as output. This
 allows you to pre-process web-page for inclusion in XML
 repositories, prepare broken XML files for validation and also
 makes it possible to write converters from well-known word
 processing applications such as MS Word to other structured data
 representations by using XML as intermediate format.
mxURL - A fast URL Data-Type
 mxURL provides a new data-type for storing and manipulating URL
 values as well as a few helpers related to URL building, encoding
 and decoding.
 The main intention of the package is to provide an easy to use,
 fast and lightweight data-type for Universal Resource Locators
 (note the W3C now calls these URIs).
mxUID - A fast UID Data-Type
 mxUID provides a fast mechanism for generating universal
 identification strings (UIDs). The intent is to make these UIDs
 unique with high probability in order to serve as object or data
 set identifiers.
 A typical use lies in generating session IDs. Other areas where
 unique IDs play an important role are RPC-implementations,
 ORBs, etc.

DOWNLOADS
The download archives and instructions for installing the packages can
be found at:
 http://www.egenix.com/
Note that in order to use the eGenix mx Experimental package you
will first need to install the eGenix mx Base package which can
be downloaded from the same location.

LICENSES & COSTS
The mx-Experimental packages uses different licenses in its sub-packages.
Please refer to the sub-package documentation for details. Some of them
may be integrated into the eGenix mx Base package, others will be
integrated into the eGenix mx Commercial package.
The package comes with full source code

ANN: eGenix mxODBC Python Database Interface Version 2.0.7

2004-12-06 Thread M.-A. Lemburg

ANNOUNCING
   eGenix.com mxODBC Database Interface
  Version 2.0.7
 Full Source Python extension providing ODBC database connectivity
 to Python applications on Windows and Unix platforms

ABOUT
The mxODBC Database Interface allows users to easily connect
Python applications to just about any database on the market
today - on both Windows and Unix platforms in a highly portable
and convenient way.  This makes mxODBC the ideal basis for writing
cross-platform database programs and utilities in Python.
mxODBC is included in the eGenix.com mx Commercial Extension Package
for Python, the commercial part of the eGenix.com mx Extension Series,
a collection of professional quality software tools which enhance
Python's usability in many important areas such as ODBC database
connectivity, fast text processing, date/time processing and
web site programming.
The package has proven its stability and usefulness in many mission
critical applications and various commercial settings all around
the world.
* About Python:
Python is an object-oriented Open Source programming language which
runs on all modern platforms (http://www.python.org/). By integrating
ease-of-use, clarity in coding, enterprise application connectivity
and rapid application design, Python establishes an ideal programming
platform for todays IT challenges.
* About eGenix:
eGenix is a consulting and software product company focused on
providing professional quality services and products to Python
users and developers (http://www.egenix.com/).

NEWS
The new version includes patches needed to compile the package
for Python 2.4. It now supports all Python versions 1.5.2 - 2.4.
As always we are providing pre-compiled versions of the package for
Windows and Linux as well as sources which allow you to install the
package on all other supported platforms.

EGENIX MX COMMERCIAL PACKAGE OVERVIEW
mxODBC - High-Performance ODBC 3.5 Interface for Python
 mxODBC is an extension package that provides a Python Database
 API compliant interface to ODBC capable database drivers and
 managers.
 In addition to the capabilities provided through the standard DB
 API it also gives access to a rich set of catalog methods which
 allow you to scan the database for tables, procedures,
 etc. Furthermore, it uses the mxDateTime package for date/time
 value interfacing eliminating most of the problems these types
 normally introduce (other in/output formats are available too).
 mxODBC allows you to interface to more than one database from one
 process, making inter-database interfacing very flexible and
 reliable.
 The source version includes a variety of pre-configured setups for
 many commonly used databases such as MySQL, Oracle, Informix,
 Solid, SAP DB, Sybase ASA and ASE, DBMaker and many more. The
 pre-compiled versions for Windows and Linux include the interfaces
 to the standard ODBC manager on these platforms to allow for a
 more easily configurable setup.
 More details are available at:
  http://www.egenix.com/files/python/mxODBC.html

DOWNLOADS
The download archives and instructions for installing the package can
be found at:
http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Packages
IMPORTANT:
In order to use the eGenix mx Commercial package you will first
need to install the eGenix mx Base package which can be downloaded
from the same location.

LICENSES & COSTS
mxODBC is distributed under the terms and conditions of the
eGenix.com Commercial License. mxODBC is free for use in non-commercial
environments.
Commercial users may evaluate the product for 30 days following the
initial installation. For continued use, commercial users can purchase
installation licenses for mxODBC through our secure online shop.
We also provide special licensing setups for commercial product
developers that want to integrate mxODBC into their products.
For full details, please see
http://www.egenix.com/files/python/eGenix-mx-Extensions.html#BuyLicenses
or write to [EMAIL PROTECTED]
The package comes with full source code

SUPPORT
Commercial quality support for these packages is available from
eGenix.com. Please see
http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Support
for details about our support offerings.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source  (#1, Dec 06 2004)
Python/Zope Consulting and Support ...

ANN: eGenix mx Base Package 2.0.6 (mxDateTime, mxTextTools, etc.)

2004-12-06 Thread M.-A. Lemburg

ANNOUNCING
eGenix.com mx Base Extension Package
Version 2.0.6
  Open Source Python extensions providing important and useful
  services for Python programmers.

ABOUT
The eGenix.com mx Base Extensions for Python are a collection of
professional quality software tools which enhance Python's usability
in many important areas such as fast text searching, date/time
processing and high speed data types.
The tools have a proven record of being portable across many Unix and
Windows platforms. You can write applications which use the tools on
Windows and then run them on Unix platforms without change due to the
consistent platform independent interfaces.
All available packages have proven their stability and usefulness in
many mission critical applications and various commercial settings all
around the world.
* About Python:
Python is an object-oriented Open Source programming language which
runs on all modern platforms (http://www.python.org/). By integrating
ease-of-use, clarity in coding, enterprise application connectivity
and rapid application design, Python establishes an ideal programming
platform for todays IT challenges.
* About eGenix:
eGenix is a consulting and software product company focused on
providing professional quality services and products to Python
users and developers (http://www.egenix.com/).

NEWS
The new version includes patches needed to compile the package
for Python 2.4. It now supports all Python versions 1.5.2 - 2.4.
As always we are providing pre-compiled versions of the package for
Windows and Linux as well as sources which allow you to install the
package on all other supported platforms.

EGENIX MX BASE PACKAGE OVERVIEW
mxDateTime - Generic Date/Time Types
 mxDateTime is an extension package that provides three new object
 types, DateTime, DateTimeDelta and RelativeDateTime, which let
 you store and handle date/time values in a very convenient way.
 You can add, subtract and even multiply instances, pickle and
 copy them and convert the results to strings, COM dates, ticks
 and some other more esoteric values. In addition, there are
 several convenient constructors and formatters at hand to greatly
 simplify dealing with dates and times in real-world applications.
 In addition to providing an easy-to-use Python interface the
 package also exports a comfortable C API interface for other
 extensions to build upon. This is especially interesting for
 database applications which often have to deal with date/time
 values (the mxODBC package is one example of an extension using
 this interface).
mxTextTools - Fast Text Processing Tools
 mxTextTools is an extension package for Python that provides
 several useful functions and types that implement
 high-performance text manipulation and searching algorithms in
 addition to a very flexible and extendable state machine, the
 Tagging Engine, that allows scanning and processing text based on
 low-level byte-code "programs" written using Python tuples. It
 gives you access to the speed of C without the need to do any
 compile and link steps every time you change the parsing
 description.
 Applications include parsing structured text, finding and
 extracting text (either exact or using translation tables) and
 recombining strings to form new text.
mxStack - Fast and Memory-Efficient Stack Type
 mxStack is an extension package that provides a new object type
 called Stack. It works much like what you would expect from such
 a type, having .push() and .pop() methods and focuses on
 obtaining maximum speed at low memory costs.
mxTools - Collection of Additional Built-Ins
 mxTools is an extension package that includes a collection of
 handy functions and objects giving additional functionality in
 form of new built-ins to the Python programmer.
 The package auto-installs the new functions and objects as
 built-ins upon first import. This means that they become
 instantly available to all other modules without any further
 action on your part. Add the line import NewBuiltins to your
 site.py script and they will be available to all users at your
 site as if they were installed in the Python interpreter itself.
mxProxy - Generic Proxy Wrapper Type
 mxProxy is an extension package that provides a new type that is
 suitable to implement Bastion like features without the need to
 use restricted execution environments.
 The type's main features are secure data encapsulation (the
 hidden objects are not accessible from Python since the

Re: RPC with Python - Comparison?

2004-12-06 Thread Wolfgang Keller
>> Candidates could be:
>>
>> - Pyro

I forgot to mention Corba here:

- Omniorb
- Orbit
- Fnorb

BTW: It seems to me that none of these provides an AMI implementation...?

>> - Twisted.spread
>> - OSE (XML-RPC)
>> - ICE
>> - ...others?

> MacPython also supports Apple events (high-level bridge:
> )

I know, but I was thinking of OS-independent RPC protocols. :-)

Best regards,

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


Re: Recursive list comprehension

2004-12-06 Thread Peter Hansen
Timothy Babytch wrote:
Serhiy Storchaka wrote:
 >>>sum([['N', 'F'], ['E'], ['D']], [])
['N', 'F', 'E', 'D']
THE BEST!
Hmmm.  Maybe, unless readability as in "self-documenting code"
is important to you...
Preceding the above with "flatten = sum" would perhaps be
an adequate improvement.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: using cmd.exe as a telnet client

2004-12-06 Thread Grant Edwards
On 2004-12-06, Donnal Walter <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
> > You don't have to start from scratch. The telnet module has
> > hooks built-into it1 so that you can have it call your routines
> > to handle option negotiation.  I did it once to impliment some
> > extra Telnet protocol features, and it wasn't difficult.
>
> Ok, you've inspired me to give it a try. First, I am assuming
> that you mean writing a custom callback function to send to 
> Telnet.set_option_negotiation_callback(callback).

Yes.

> Or did you mean writing a subclass of Telnet?

That depends.  If you need to _impliment_ a feature in addition
to doing the negotiation, then you may want to define a
subclass -- though it may easier to just grab the source for
telnetlib and add the feature.

> Can someone provide an example of a callback function that I
> might use as a template for writing mine?

I've got a negotiation function at home I'll try to remember to
post.

> This is unfamiliar territory for me, but as near as I can tell, the 
> options in question are:
> 0, binary transmission
> 1, echo
> 3, suppress go ahead
> 23, send location
>
> And it may be that not all of these are critical, but if so, I
> don't know how to tell which is which.

That's the tricky part. :)

I guess I'd "enable" negotiation of each of the features one at
a time, and see what happens.

-- 
Grant Edwards   grante Yow!  Hey, I LIKE that
  at   POINT!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using cmd.exe as a telnet client

2004-12-06 Thread Donnal Walter
Grant Edwards wrote:
> You don't have to start from scratch. The telnet module has
> hooks built-into it1 so that you can have it call your routines
> to handle option negotiation.  I did it once to impliment some
> extra Telnet protocol features, and it wasn't difficult.
Ok, you've inspired me to give it a try. First, I am assuming that you 
mean writing a custom callback function to send to 
Telnet.set_option_negotiation_callback(callback). Or did you mean 
writing a subclass of Telnet? Can someone provide an example of a 
callback function that I might use as a template for writing mine?

This is unfamiliar territory for me, but as I can tell, the options in 
question are:
0, binary transmission
1, echo
3, suppress go ahead
23, send location

And it may be that not all of these are critical, but if so, I don't 
know how to tell which is which.

Eyal Lotem wrote:
> I think I have a much simpler solution for you guys..
> Assuming you can run arbitrary code on the proprietary
> server.
Actually I cannot. The server runs a second-party information system, 
the primary access to which is third-party terminal emulator software 
that uses telnet connections. What I am trying to do is emulate this 
emulator. :-)

Jp Calderone wrote:
>   cmd.exe is not a command line program.  It's a terminal (emulator).
> You might be able to use the telnet program, though.
Yes, I see that now. Thanks.
>  Before doing this,
> I'd recommend looking at Twisted's telnet support (both
> the version in 1.3 and the version that will be in 2.0),
> which actually supports option negotiation in a
> reasonable way.
I've been wanting to get acquainted with Twisted for awhile now, so this 
might be a good time to do so. I think I will give Grant's idea a whirl, 
but if I get bogged down there, I will definitely look at Twisted's 
telnet support. BTW, do you know if Twisted's option negotiation uses a 
callback function? I might download it just to take a look, even if I 
don't use it directly.

Thanks,
Donnal Walter
Arkansas Children's Hospital
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mean, median, and mode

2004-12-06 Thread Josiah Carlson

"Robert Brewer" <[EMAIL PROTECTED]> wrote:
> 
> Josiah Carlson wrote:
> > [EMAIL PROTECTED] (Sean McIlroy) wrote:
> > > 
> > > >>> median = lambda x: (max(x)-min(x))/2
> > 
> > That is /not/ the median in the general case.
> > 
> > median = lambda x: x.sort() or x[len(x)//2]
> 
> That...is a really sneaky use of null return values. I like. :)

Thank you, I'm just using a paradigm (exploiting lambdas) that I picked
up while going through various functional programming modules.

If you're really good, you can do crazy stuff with list comprehensions.
I'll leave that exercise up to the reader, as many of my examples are
in for-pay code.


 - Josiah

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


Re: xmlrpclib or twisted?

2004-12-06 Thread Andy Gross
If you're not concerned about interoperability with other languages and 
are already using Twisted, I'd go with PB.  Especially if you are using 
complicated datatypes that have to be serialized and sent over the wire 
- PB has a nice Cacheable type that doesn't serialize the whole object. 
 XMLRPC on the other hand is a little simpler and will work with 
third-party stuff.

/arg
On Dec 6, 2004, at 5:11 AM, flupke wrote:
Hi,
previously i made an application that used sockets to
do some network based processing.
My next app is again going to be a client/server app
and i wanted to see if i can't find an easier way to
make the networking going.
I bumped into xmlrpclib and also twisted (pb).
I'm not sure which on of these would suit my needs better.
I am planning to build a web GUI for the client so if i
use twisted, i would already have the components in there
to do so, so this could be a plus for twisted.
The client will connect to the server to receive data.
The data is the result of one of several queries and these raw
results would then be displayed in the client via a webgui or
wxPython. (leaning towards webgui)
Any other ideas?
Thanks
Benedict
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: asynchat and threading

2004-12-06 Thread Fredrik Lundh
Anthony Baxter wrote:

> > AFAICT, the main complaint is that it is tied to the TCP transport,
> > the sockets API, and the select/poll API. IOW, it cannot easily:
> > - integrate TLS on top of TCP (because TLS might involve no-data
> >communications, e.g. when TLS negotation happens in the middle
> >of a TLS session),
> > - integrate other transports, such as serial ports on Windows,
> > - integrate other multi-endpoint wait APIs, such as IO completion
> >ports on Windows NT+, or kqueue on BSD.
>
> - work with other event loops, such as GUI toolkits

sure can.

but sure, if you don't want it to work, nothing stops you from writing
crappy code.  we've been using asyncore/medusa on high-performance
servers for nearly 10 years; I think we'd noticed by now if the library
was seriously broken.

 



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


Re: Mean, median, and mode

2004-12-06 Thread Paul McGuire
This median expression is incorrect.  median is *not* the midpoint between
max and min values.  It is the middle value when all values are sorted (for
an odd number of values), or the average of the two middle values when all
values are sorted (for an even number of values).

In Python 2.4 (needed to use sorted() built-in), this can be one-lined as:
median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
(sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))

(not yet tested, as I've not installed v2.4 yet)
With boolean short-circuiting, this should only sort the list once.

-- Paul


"Sean McIlroy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> >>> mean = lambda x: sum(x)/len(x)
> >>> median = lambda x: (max(x)-min(x))/2
> >>> mode = lambda x: max([(x.count(y),y) for y in x])[1]
>
> "Robert Brewer" <[EMAIL PROTECTED]> wrote in message
news:<[EMAIL PROTECTED]>...
> > (now that we have a meaningful subject line)
> >
> > Alfred Canoy wrote:
> > > >>  I'm just new to programming and would like to ask for help..
> > > >>
> > > >> Build a module that contains three functions that do the following:
> > > >>
> > > >>   a.. Compute the average of a list of numbers
> > > >>   b.. Finds the statistical median value of a list of numbers
> > > >>   c.. Finds the mode of a list of numbers
> > > >>
> > > >> Can you please give me clue how I should start solving the
> > > >> following problem
> > > >> below? Here's the source code that I did so far:
> > > >>
> > > >> # compute the average of a list of numbers:
> > > >> # Keeps asking for numbers until 0 is entered
> > > >> # Prints the average value
> > > >>
> > > >> count = 0
> > > >> sum = 0
> > > >> number = 1
> > > >>
> > > >> print 'Enter 0 to exit the loop'
> > > >> while number != 0:
> > > >> number = input ('Enter a number: ')
> > > >> count = count + 1
> > > >> sum = sum + number
> > > >> count = count -1
> > > >> print ' The average is:', sum/count
> >
> > For the mode, you might build a dictionary:
> >
> > freq = {}
> > while number != 0:
> > number = input ('Enter a number: ')
> > count = count + 1
> > sum = sum + number
> > try:
> > freq[number] += 1
> > except KeyError:
> > freq[number] = 1
> >
> > ...then you can check for the largest value in that dictionary:
> >
> > max = 0
> > mode = None
> > for k, v in freq.iteritems():
> > if v > max:
> > max = v
> > mode = k
> >
> > I leave the rest in your capable hands... ;) Including the case where
> > two numbers occur in equal frequencies. ;;)
> >
> >
> > Robert Brewer
> > MIS
> > Amor Ministries
> > [EMAIL PROTECTED]


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


Re: using cmd.exe as a telnet client

2004-12-06 Thread Donnal Walter
Grant Edwards wrote:
> You don't have to start from scratch. The telnet module has
> hooks built-into it1 so that you can have it call your routines
> to handle option negotiation.  I did it once to impliment some
> extra Telnet protocol features, and it wasn't difficult.
Ok, you've inspired me to give it a try. First, I am assuming that you 
mean writing a custom callback function to send to 
Telnet.set_option_negotiation_callback(callback). Or did you mean 
writing a subclass of Telnet? Can someone provide an example of a 
callback function that I might use as a template for writing mine?

This is unfamiliar territory for me, but as near as I can tell, the 
options in question are:
0, binary transmission
1, echo
3, suppress go ahead
23, send location

And it may be that not all of these are critical, but if so, I don't 
know how to tell which is which.

Eyal Lotem wrote:
> I think I have a much simpler solution for you guys..
> Assuming you can run arbitrary code on the proprietary
> server.
Actually I cannot. The server runs a second-party information system, 
the primary access to which is third-party terminal emulator software 
that uses telnet connections. What I am trying to do is emulate this 
emulator. :-)

Jp Calderone wrote:
>   cmd.exe is not a command line program.  It's a terminal (emulator).
> You might be able to use the telnet program, though.
Yes, I see that now. Thanks.
>  Before doing this,
> I'd recommend looking at Twisted's telnet support (both
> the version in 1.3 and the version that will be in 2.0),
> which actually supports option negotiation in a
> reasonable way.
I've been wanting to get acquainted with Twisted for awhile now, so this 
might be a good time to do so. I think I will give Grant's idea a whirl, 
but if I get bogged down there, I will definitely look at Twisted's 
telnet support. BTW, do you know if Twisted's option negotiation uses a 
callback function? I might download it just to take a look, even if I 
don't use it directly.

Thanks,
Donnal Walter
Arkansas Children's Hospital
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL and antialiasing problem

2004-12-06 Thread Fredrik Lundh
Laszlo Zsolt Nagy wrote:

> Statement: Sometimes PIL is better than Adobe Photoshop. :-)
>
> I also found these with the aid of the wonderful dir() function:
>
> MinFilter, MaxFilter, MedianFilter, ModeFilter, RankFilter, BuiltInFilter
>
> They do not have a docstring and they are not documented in the
> handbook. I'm curious what they do exactly. The others (like BLUR, EMBOSS,
> CONTOUR etc.) are documented very well. I wonder why is that.

they were experimental (and some of them were slightly broken, iirc)
in 1.1.4.  they're all officially supported in 1.1.5:

http://www.pythonware.com/library/pil/handbook/imagefilter.htm






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


Re: help using sockets, and OOP?

2004-12-06 Thread Andy Gross
On Dec 6, 2004, at 12:04 PM, Dfenestr8 wrote:
Ok, so are there other types of sockets that aren't "blocking" ?
Yes, sockets can be either blocking or non-blocking.  An I/O operation 
on a 'blocking' socket will not return until the operation is complete. 
 If you try to read more bytes than are currently available, the call 
will block, possibly forever.  Operations on non-blocking sockets 
return "immediately", but are not guaranteed to have completed.  For 
example, a write() of 1024 bytes may only succeed in writing 10 bytes.  
It's up to your application to keep track of this state.  Google around 
for socket programming tutorials for complete information.

WRT Python, you'll quickly find that asynchronous programming becomes 
tedious without a framework.  As JP suggested, check out 
http://www.twistedmatrix.com.  Twisted does a good job of abstracting 
away a lot of the low-level details and allows you to focus on 
implementing the functionality of your program.

Good luck,
/arg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deadlock detection

2004-12-06 Thread Josiah Carlson

Duncan Grisby <[EMAIL PROTECTED]> wrote:
> 
> Hi,
> 
> Does anyone know of a deadlock detector for Python?  I don't think it
> would be too hard to hook into the threading module and instrument
> mutexes so they can be tested for deadlocks. I've googled around but I
> haven't found anything.

I'm not aware of a deadlock dector for any language.  I propose that a
completely working deadlock detector is NP-Complete, as it would, I
believe, necessitate solving the halting problem.


 - Josiah

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


Re: using cmd.exe as a telnet client

2004-12-06 Thread Donnal Walter
Grant Edwards wrote:
You don't have to start from scratch. The telnet module has
hooks built-into it1 so that you can have it call your routines
to handle option negotiation.  I did it once to impliment some
extra Telnet protocol features, and it wasn't difficult.
Ok, you've inspired me to give it a try. First, I am assuming that you 
mean writing a custom callback function to send to 
Telnet.set_option_negotiation_callback(callback). Or did you mean 
writing a subclass of Telnet? Can someone provide an example of a 
callback function that I might use as a template for writing mine?

This is unfamiliar territory for me, but I tried to snoop a bit using 
ethereal (also new to me) and as near as I can tell, the options in 
question are:
0, binary transmission
1, echo
3, suppress go ahead
23, send location

And it may be that not all of these are critical, but if so, I don't 
know how to tell which is which.

Eyal Lotem wrote:
I think I have a much simpler solution for you guys..
Assuming you can run arbitrary code on the proprietary
server.
Actually I cannot. The server runs a second-party information system, 
the primary access to which is third-party terminal emulator software 
that uses telnet connections. What I am trying to do is emulate this 
emulator. :-)

  cmd.exe is not a command line program.  It's a terminal (emulator).  
You might be able to use the telnet program, though.
Yes, I see that now. Thanks.
 Before doing this, 
I'd recommend looking at Twisted's telnet support (both
the version in 1.3 and the version that will be in 2.0),
which actually supports option negotiation in a
reasonable way.
I've been wanting to get acquainted with Twisted for awhile now, so this 
might be a good time to do so. I think I will give Grant's idea a whirl, 
but if I get bogged down there, I will definitely look at Twisted's 
telnet support. BTW, do you know if Twisted's option negotiation uses a 
callback function? I might download it just to take a look, even if I 
don't use it directly.

Thanks,
Donnal Walter
Arkansas Children's Hospital
--
http://mail.python.org/mailman/listinfo/python-list


RE: Mean, median, and mode

2004-12-06 Thread Robert Brewer
Josiah Carlson wrote:
> [EMAIL PROTECTED] (Sean McIlroy) wrote:
> > 
> > >>> median = lambda x: (max(x)-min(x))/2
> 
> That is /not/ the median in the general case.
> 
> median = lambda x: x.sort() or x[len(x)//2]

That...is a really sneaky use of null return values. I like. :)


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


Re: Mean, median, and mode

2004-12-06 Thread Josiah Carlson

[EMAIL PROTECTED] (Sean McIlroy) wrote:
> 
> >>> median = lambda x: (max(x)-min(x))/2

That is /not/ the median in the general case.

median = lambda x: x.sort() or x[len(x)//2]

 - Josiah

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


Re: help using sockets, and OOP?

2004-12-06 Thread Diez B. Roggisch
> Ok, so are there other types of sockets that aren't "blocking" ?

You don' want other types of sockets (they are pretty good the way the are)
but other ways of using them. The topics you might need to delve into are
threading, the select module and twisted.  Which at least in part Jp
already suggested...

With threading you can have one thread blocked while others still run. With
select (which is made use of in twisted) you can wait for file-descriptors
(sockets _are_ filedescriptors) to actually have data, so that a call to
them won't block. That allows for scenarios such as yours.



-- 
Regards,

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


Re: help using sockets, and OOP?

2004-12-06 Thread Grant Edwards
On 2004-12-06, Dfenestr8 <[EMAIL PROTECTED]> wrote:

>>> Ok, so what if I remove the while loop from the Botling class, and
>>> include it in the __main__ ? Might this work as a solution then?
>> 
>>   No.
>
> Ok, so are there other types of sockets that aren't "blocking" ?

Yes, non-blocking ones.

-- 
Grant Edwards   grante Yow!  My ELBOW is a remote
  at   FRENCH OUTPOST!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python2.4 IDLE can't be lanuched.

2004-12-06 Thread Jean Brouwers

This is a known problem.  More details at




/Jean Brouwers


In article <[EMAIL PROTECTED]>,
AnkyHe <[EMAIL PROTECTED]> wrote:

>   I downloaded the python 2.4 final from the offical website and installed it
> on the WindowsXP+SP2 (Chinese version).
> There was not any problem in this process, but the IDLE can't be lanuched
> without any warnning.  Is there anybody else 
> encount this problem and how to resolve it?  Thanks!  
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python2.4 IDLE can't be lanuched.

2004-12-06 Thread Brian Beck
Abe Mathews wrote:
I'm not running SP 2 on any machines, so I can't test it for you, but
it may be that the personal firewall being activated on SP 2 is
blocking IDLE from starting up.  You might try turning that off and
seeing if that helps.  IIRC, part of SP 2 was port disabling.
I do remember seeing that message but thought "no way" since the Windows 
firewall is pretty forgiving in my experience.  But after a bit of 
tweaking and even disabling the firewall completely, the problem persists.

--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Win32 Libs for 2.4

2004-12-06 Thread Robin Becker
Daniel Dittmar wrote:
Robin Becker wrote:
actually I want to build the PIL extension for 2.4 as pyd and include 
various libraries eg zlib and jpeg. To avoid the missing dlls issue we 
have done this in the past by incorporating the zlib/jpeg code using 
static libraries for both zlib and jpeg.

It seems I can use the static lib built with MSC 6 with the extension 
code compiled with MSC 7.1. At least the extnsion build doesn't 
complain. Whether this is really allowed is another matter.

I guess that it won't work if something malloc'ed from the MSC 6 runtime 
is free'd by the MSC 7.1 runtime.
..
I thought that static .libs didn't make reference to the dll's they need; isn't 
that done at load time?

As for rebuilding that's easy; the hard part is having all the versions 
available at once. I prefer to keep common code in one place so would prefer to 
have only one static lib for these non version dependant things.


Daniel

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


  1   2   >