dynamically generating temporary files through python/cgi

2005-04-27 Thread poisondart
Is there a way to dynamically generate temporary files (such as an
html, xml or text file) in Python?

I'm not sure if I'm explaining myself clearly as I've no clue how to
describe this mechanism. I've seen it on certain websites that will
generate a file under certain parameters (through forms) that will
dissapear (i.e. delete itself) after a specified amount of time. These
files usually have some phony string for their filenames...like it's
been md5 hashed or something.

Is there a group of library functions that allow this? I imagine that
if i manually go and allocate a bunch of timers to monitor files, it
would be really expensive in load. Or perhaps is this a client-side
mechanism?

Thanks,
- poisondart

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


Re: Which IDE is recommended?

2005-04-27 Thread Ville Vainio
> "pydev" == Brian Beck <[EMAIL PROTECTED]> writes:

pydev> * PyDev isn't yet mature enough to make it practical for me

What version? PyDev has increased in maturity quite a bit lately.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyqt and Eric 3

2005-04-27 Thread Phil Thompson
On Thursday 28 April 2005 3:46 am, ChrisH wrote:
> In article <[EMAIL PROTECTED]>,
> [EMAIL PROTECTED] says...
>
> > Are there any Eric 3 users out there?
> >
> > I've been thinking about trying it.
> >
> > Also, if I write scripts for internal use only at my company, do I have
> > to purchase a Qt or pyqt license?
> >
> > Thanks for the info!
> > Chris
>
> Oops.. I forgot to say I'm writing code for Windows.

Until the GPL versions of Qt4 and PyQt4 are available for Windows (and eric 
has been ported to it) you will need Qt and PyQt licenses.

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


Re: creating very small types

2005-04-27 Thread Michael Spencer
andrea wrote:
No it's not for homework but for learning purposes...
Bengt wrote:
I think I prefer little-endian bit streams though, 
good point: should lead to easier decoding via right-shifts
e.g. (just hacked, not tested beyond
what you see 
Yep, yours looks better.  Pretty soon there isn't going to be much learning left 
in this for Andrea ;-)

and not recommended as efficient either way, esp the decode,
I expect that decoding by walking the coding tree is cleaner (not sure about 
faster).

but it might
be illustrative of something for Andrea  ;-) 
Michael

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


Re: Question about python code distribution...

2005-04-27 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> Hi,
>
> I am sure that this question might have come up repeatedly. Companies
> may not want to distribute their python code in source form. Even
> though pyc files are one option, it gets inconvenient to distribute
> bunch of them . If there is some way to bundle pyc files (akin to
> .jar), it would be really nice. I understand that pyc files are not
> hard to decompile (from my reading of previous posts) and module
> startup times may be longer if they have to be read from an archive.
> Neverthless, an option to distribute in the form of an archive is
> attractive. Has this ever been considered for Python? If one were to
> consider it, what would be pros and cons of such approach?
>
> Any comments are appreciated.
>
> Thanks,
> Raghu.


As of version 2.3 of python zip files are supported:
http://www.python.org/doc/2.3.5/whatsnew/node5.html

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


Re: regex over files

2005-04-27 Thread Bengt Richter
On Wed, 27 Apr 2005 21:39:45 -0500, Skip Montanaro <[EMAIL PROTECTED]> wrote:

>
>Robin> I implemented a simple scanning algorithm in two ways. First 
> buffered scan 
>Robin> tscan0.py; second mmapped scan tscan1.py.
>
>...
>
>Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan0.py dingo.dat
>Robin> len=139583265 w=103 time=110.91
>
>Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan1.py dingo.dat
>Robin> len=139583265 w=103 time=140.53
>
>I'm not sure why the mmap() solution is so much slower for you.  Perhaps on
>some systems files opened for reading are mmap'd under the covers.  I'm sure
>it's highly platform-dependent.  (My results on MacOSX - see below - are
>somewhat better.)
>
>Let me return to your original problem though, doing regex operations on
>files.  I modified your two scripts slightly:
>
>tscan0.py:
>
>import sys, time, re
>fn = sys.argv[1]
>f=open(fn,'rb')
>n=0
>t0 = time.time()
>while 1:
> buf = f.read(4096)
> if not buf: break
> for i in re.split("X", buf):
To be fairer, I think you'd want to hoist the re compilation out of the loop.
But also to be fairer, maybe include the overhead of splitting correctly, at
least for the simple case regex in my example -- or is a you-goofed post
for me in the usenet forwarding queues somewhere still? ;-)

> n += 1
>t1 = time.time()
>
>print "n=%d time=%.2f" % (n, (t1-t0))
>
>tscan1.py:
>
>import sys, time, mmap, os, re
>fn = sys.argv[1]
>fh=os.open(fn,os.O_RDONLY)
>s=mmap.mmap(fh,0,access=mmap.ACCESS_READ)
>t0 = time.time()
>n = 0
>for mat in re.split("X", s):
>n += 1
>t1 = time.time()
>
>print "n=%d time=%.2f" % (n, (t1-t0))
>
>The mmap version is almost obviously correct, assuming what we want to do is
>split the file on "X".  The buffered read version is almost certainly
>incorrect, given our understanding that corner cases lurk at buffer
>boundaries.
>I took the file from Bengt Richter's example and replicated it a bunch of
>times to get a 122MB file.  I then ran the above two programs against it:
>
>% python tscan1.py splitX
>n=2112001 time=8.88
>% python tscan0.py splitX
>n=2139845 time=10.26
>
>So the mmap'd version is within 15% of the performance of the buffered read
with regex recompilation in loop ;-)
>version and we don't have to solve the problem of any corner cases (note the
>different values of n).  I'm happy to take the extra runtime in exchange for
>simpler code.
>
Agree. Hm, I wonder if the OS notices sequential page faults and schedules 
speculative
read-ahead. Hm2, I wonder if you can just touch bytes from another coordinated 
thread
to cause that, if it isn't happening ;-) Not for 15% though ;-)

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


Re: (PHP or Python) Developing something like www.tribe.net

2005-04-27 Thread Michele Simionato
Mir Nazim:
> Can you please brief me a bit about your decision to CherryPy

Decision? I made no decision about CherryPy, I am actually a Quixote
user. I evalued CherryPy six months ago and I did not like it, since
they were using custom classes and a strange compilation procedure.

However, from the presentation I saw at the ACCU conference, it looks
like now CherryPy is much more pythonic than before (use the definition
you like for pythonic). If I was shopping for a web framework today, I
would
certainly consider CherryPy.

CherryPy and Quixote are in the same league, Zope and Twisted and PEAK
are in an enterely different league. They are meant for programming in
the large
and do not scale well for small size applications. CherryPy and Quixote
are for
programming in the small, I have not idea how they scale in the large.
Is your application going to be large (many developers, hundred of
components, hundreds of thousand of lines of code) or small?

   Michele Simionato

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


Re: python equivalent of php implode

2005-04-27 Thread Dave Cook
On 2005-04-27, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> On Wed, 27 Apr 2005 08:44:36 +0200, Ola Natvig <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:

>> sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()), 
>> ','.join(param.values()))

>   That also violates the DB-API recommendations that the
> .execute() method should be used to do parameter substitution -- to
> ensure proper quoting of odd data...

I would think this would be OK:

keys = params.keys()
columnList = ", ".join(keys)
valueList = ["%%(%s)s" % key for keys]
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, columnList, valueList)
cursor.execute(sql, params)

Though you would probably want to go further and filter out keys that don't
belong in the table, something like:

keys = [key for key in tableColumns if key in params]

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


Re: creating very small types

2005-04-27 Thread Bengt Richter
On Wed, 27 Apr 2005 15:54:54 -0700, Michael Spencer <[EMAIL PROTECTED]> wrote:

>andrea wrote:
I was thinking to code the huffman algorithm and trying to compress
something with it, but I've got a problem.
How can I represent for example a char with only 3 bits??
>
I had a look to the compression modules but I can't understand them much...
>...
>> I understand I can't do it easily in python, but maybe I could define a
>> new type in C and use it to do those dirty works, what do you think?
>
>Why do you need to create 'very small types'?
>
>You only need actual bit-twiddling when you do the encoding/de-coding right?
>If you create an encoding map 'codes' as a dict of strings of '1' and '0', 
>encoding might look like (untested):
>
>
> def encode(stream):
> outchar = count = 0
> for char in stream:
> for bit in codes[char]:
> (outchar << 1) | (bit == "1")
> count +=1
> if count ==8:
> yield chr(outchar)
> outchar = count = 0
> if count:
  outchar <<= 8-count  # make last bit field big-endian like others?
> yield chr(outchar)
>
>
I think I prefer little-endian bit streams though, e.g. (just hacked, not 
tested beyond
what you see and not recommended as efficient either way, esp the decode, but 
it might
be illustrative of something for Andrea ;-)

< trivcodec.py >
#trivcodec.py
def encode(stream):
outchar = count = 0
for char in stream:
#print '%r code: %r'%(char, codes[char])
bits, width = codes[char]
outchar |= (bits<= 8:
yield chr(outchar%0xff)
outchar >>= 8
count -= 8
if count:
yield chr(outchar)

def decode(stream):
codebuf = count = 0
width = 1
for codebyte in stream:
codebyte = ord(codebyte)
codebuf |= (codebyte= width
count -= width
width = 1
width = 1 

#trivial encoding dict: a=0 b=01 C=0011 D=0111 E=1011 F=
codes = {'a':(0x00,1), 'b':(0x01,2), 
 'C':(0x3+0x4*0,4), 'D':(0x3+0x4*1,4),
 'E':(0x3+0x4*2,4), 'F':(0x3+0x4*3,4)}
chars = dict([(v,k) for k,v in codes.items()]) # reverse

def test(*tests):
if not tests: tests = ['abaFECbaabbDF']
for charstream in tests:
print
codestream = ''.join(list(encode(charstream)))
print '%r [%s] -(encode)-> %r [%s]' % (
charstream, len(charstream), codestream, len(codestream))
recovered = ''.join(list(decode(codestream)))
print '%r [%s] -(decode)-> %r [%s]' % (
codestream, len(codestream), charstream, len(charstream))
 
if __name__ == '__main__':
import sys
test(*sys.argv[1:])


Result:

[22:02] C:\pywk\clp>py24 trivcodec.py

'abaFECbaabbDF' [13] -(encode)-> '\xf2;Q\xf7' [4]
'\xf2;Q\xf7' [4] -(decode)-> 'abaFECbaabbDF' [13]

[22:02] C:\pywk\clp>py24 trivcodec.py  a b C D E F

'a' [1] -(encode)-> '\x00' [1]
'\x00' [1] -(decode)-> 'a' [1]

'b' [1] -(encode)-> '\x01' [1]
'\x01' [1] -(decode)-> 'b' [1]

'C' [1] -(encode)-> '\x03' [1]
'\x03' [1] -(decode)-> 'C' [1]

'D' [1] -(encode)-> '\x07' [1]
'\x07' [1] -(decode)-> 'D' [1]

'E' [1] -(encode)-> '\x0b' [1]
'\x0b' [1] -(decode)-> 'E' [1]

'F' [1] -(encode)-> '\x0f' [1]
'\x0f' [1] -(decode)-> 'F' [1]

[22:02] C:\pywk\clp>py24 trivcodec.py

'abaFECbaabbDF' [13] -(encode)-> '\xf2;Q\xf7' [4]
'\xf2;Q\xf7' [4] -(decode)-> 'abaFECbaabbDF' [13]

[22:02] C:\pywk\clp>py24 trivcodec.py    CC DD EE FF

'' [8] -(encode)-> '\x00' [1]
'\x00' [1] -(decode)-> '' [8]

'' [4] -(encode)-> 'U' [1]
'U' [1] -(decode)-> '' [4]

'CC' [2] -(encode)-> '3' [1]
'3' [1] -(decode)-> 'CC' [2]

'DD' [2] -(encode)-> 'w' [1]
'w' [1] -(decode)-> 'DD' [2]

'EE' [2] -(encode)-> '\xbb' [1]
'\xbb' [1] -(decode)-> 'EE' [2]

'FF' [2] -(encode)-> '\x00' [1]
'\x00' [1] -(decode)-> 'FF' [2]

[22:03] C:\pywk\clp>py24 trivcodec.py  CCDDEEFF

'CCDDEEFF' [20] -(encode)-> '\x00U3w\xbb\x00' [6]
'\x00U3w\xbb\x00' [6] -(decode)-> 'CCDDEEFF' [20]


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


Re: How do I parse this ? regexp ?

2005-04-27 Thread Paul McGuire
Jake -

If regexp's give you pause, here is a pyparsing version that, while
verbose, is fairly straightforward.  I made some guesses at what some
of the data fields might be, but that doesn't matter much.

Note the use of setResultsName() to give different parse fragments
names so that they are directly addressable in the results, instead of
having to count out "the 0'th group is the date, the 1'st group is the
time...".  Also, there is a commented-out conversion action, to
automatically convert strings to floats during parsing.

Download pyparsing at http://pyparsing.sourceforge.net.

Good luck,
-- Paul


data = """04242005 18:20:42-0.02, 271.1748608, [-4.119873046875,
3.4332275390625, 105.062255859375], [0.093780517578125, 0.041015625,
-0.960662841796875], [0.01556396484375, 0.01220703125,
0.01068115234375]"""

from pyparsing import *

COMMA = Literal(",").suppress()
LBRACK = Literal("[").suppress()
RBRACK = Literal("]").suppress()

# define a two-digit integer, we'll need a lot of them
int2 = Word(nums,exact=2)
month = int2
day = int2
yr = Combine("20" + int2)
date = Combine(month + day + yr)

hr = int2
min = int2
sec = int2
tz = oneOf("+ -") + Word(nums) + "." + Word(nums)
time = Combine( hr + ":" + min + ":" + sec + tz )

realNum = Combine( Optional("-") + Word(nums) + "." + Word(nums) )
# uncomment the next line and reals will be converted from strings to
floats during parsing
#realNum.setParseAction( lambda s,l,t: float(t[0]) )

triplet = Group( LBRACK + realNum + COMMA + realNum + COMMA + realNum +
RBRACK )
entry = Group( date.setResultsName("date") +
  time.setResultsName("time") + COMMA +
  realNum.setResultsName("temp") + COMMA +
  Group( triplet + COMMA + triplet + COMMA + triplet
).setResultsName("coords") )

dataFormat = OneOrMore(entry)
results = dataFormat.parseString(data)

for d in results:
print d.date
print d.time
print d.temp
print d.coords[0].asList()
print d.coords[1].asList()
print d.coords[2].asList()

returns:

04242005
18:20:42-0.02
271.1748608
['-4.119873046875', '3.4332275390625', '105.062255859375']
['0.093780517578125', '0.041015625', '-0.960662841796875']
['0.01556396484375', '0.01220703125', '0.01068115234375']

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


Re: Fast plotting?

2005-04-27 Thread William Park
Russell E. Owen <[EMAIL PROTECTED]> wrote:
> Can anyone recommend a fast cross-platform plotting package for 2-D 
> plots?
> 
> Our situation:
> We are driving an instrument that outputs data at 20Hz. Control is via 
> an existing Tkinter application (which is being extended for this new 
> instrument) that runs on unix, mac and windows. We wish to update 5-10 
> summary plots at approximately 2 Hz and will be offering controls to 
> control the instrument and the plots, preferably (but not necessarily) 
> mixed in with the plots.

That's 10-20 plots per second.  The only GUI plotter that I know is
'gnuplot', and I don't know if it will spit out anything at 10-20Hz.
For character plots (like old days terminal), it has speed but ugly to
look at.

> 
> Ideally the package would create plots in the Tkinter application. But 
> we realize we're unlikely to get the speed we need that way. So we are 
> willing to have the Tkinter app send data to the plotting package  (e.g. 
> via a socket) and have it display the plots in a separate process.
> 
> We started out with matplotlib, which is a wonderful package (and well 
> integrated with most or all GUI toolkits). Unfortunately it is just too 
> slow -- at least when driving plots integrated with the Tkinter app. (It  
> is getting faster and so are computers, so at some point this will be a 
> great way to go. But for now...)
> 
> Any suggestions?
> 
> -- Russell

-- 
William Park <[EMAIL PROTECTED]>, Toronto, Canada
Slackware Linux -- because it works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (PHP or Python) Developing something like www.tribe.net

2005-04-27 Thread Mir Nazim
Can you please brief me a bit about your decision to CherryPy

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


Re: bytecode non-backcompatibility

2005-04-27 Thread "Martin v. Löwis"
Maurice LING wrote:
> I've emailed to catelog-sig mailing list and is still waiting to hear
> something. Currently, I have no idea of the structure of PyPI. I hope I
> can hear from them soon and generate some starting points...

Posting questions is not the only way to find answers. The source code
of PyPI is available: sf.net/projects/pypi.

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


Re: bytecode non-backcompatibility

2005-04-27 Thread "Martin v. Löwis"
Maurice LING wrote:
>> I doubt anyone disputes that upgrades are more hassle than we would
>> like. My main point was that freezing CPython's technology is not the
>> solution. Any other upgrade helper that you can contribute will be
>> welcome.
> 
> So there is no way of releasing a close-source application written in
> Python?

I fail to see the relationship between the statement and your question.

Again, whether or not the C API is frozen has nothing to do with
whether or not the bytecode format is frozen. So any implication
from not freezing the C API to not being able to ship byte-code
only is invalid.

As for only shipping byte code: sure, that is certainly possible,
and people do that all the time.

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


Re: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?)

2005-04-27 Thread MsKitty
Neil -
Interesting theory, but I installed brand new versions of Python
(2.4.1) and the win32 extensions on a machine that had no Python and
got the the same 4 minute response time, so that does not seem a likely
explanation, although its possible.
  - Kitty

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


Re: Can .py be complied?

2005-04-27 Thread steve.leach
Harlin Seritt wrote:
Hi monkey,
Not a stupid question especially if you're trying to create commercial
software and don't want to reveal your source. At any rate, you can use
py2exe to create a .exe file. It does have some cons to it since you
Some very severe cons considering that would mean his code would only 
run on a certain infamous legacy operating system that will remain 
unnamed.  The last I checked, ".exe" files were rather useless on most 
operating systems.
--
http://mail.python.org/mailman/listinfo/python-list


TKinter and Python Sync. Problems

2005-04-27 Thread Brian Kazian
I am currently having trouble running a piece of code I have written.  My 
main code is called new.py, and when I run it, it pops up the TKinter root 
window as specified.  However, if I try perform a function that uses an 
imported module, the code crashes, giving me this error:


Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
  File "C:\jython\new.py", line 38, in save_var
var = expression.Variable(name, description)
AttributeError: 'module' object has no attribute 'Variable'

Now, when I close the TKinter window that popped up when the code was 
compiled, an identical one is opened in its place.  If I perform the same 
action as before, the program works flawlessly.  Also worth noting is that 
when this same file is run from SPE, this problem does not ocur.

Does anyone have any idea why this would happen?   I do not understand why a 
new Window is created when I try to close it if run from the command line. 
Also, I don't understand why it can't find the proper module the on the 
first run, but can on the second.  It seems weird that it doesn't also 
happen from the IDE.

Another interesting thing to note is that if I run the module that it chokes 
on intially, ie. 'python expr.py', it brings up the GUI associated with the 
main code.  The problem is, there is no TKinter related code in the expr 
module!

If any additional info or clarification would be helpful, please let me 
know.  Thanks in advance for the help, as I am truly perplexed as to what is 
going on!! 


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


Re: PyGTK vs. wxPython

2005-04-27 Thread dcrespo
> Really though, these questions are more suited for the wxPython
mailing list.

Thank you very much for this acclaration :)

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


urllib2 file upload error

2005-04-27 Thread Thomas








 

 

import urllib2

URL = ''

FILE= 'c:/Documents and
Settings/Administrator/Desktop/Vousleve 1 .pps';

d = [ ('cmd', 'add-item'),

  ('protocol_version', '2.1'),

  ('userfile', open(FILE)),

    ]

req = urllib2.Request(URL, d)

try:

    u = urllib2.urlopen(req)

except urllib2.HTTPError, errobj:

    print "HTTPError:", errobj.code

else:

 buf = u.read()

 print "OK"

 

 

 

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32

Type "help", "copyright",
"credits" or "license" for more information.

>>> ## working on region in file
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1396n5Q.py...

Traceback (most recent call last):

  File "", line 1, in ?

  File
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1396n5Q.py", line 11, in ?

    u = urllib2.urlopen(req)

  File "c:\Python23\lib\urllib2.py", line
129, in urlopen

    return _opener.open(url, data)

  File "c:\Python23\lib\urllib2.py", line
326, in open

    '_open', req)

  File "c:\Python23\lib\urllib2.py", line
306, in _call_chain

    result = func(*args)

  File "c:\Python23\lib\urllib2.py", line
901, in http_open

    return self.do_open(httplib.HTTP, req)

  File "c:\Python23\lib\urllib2.py", line
888, in do_open

    h.send(data)

  File "C:\Python23\lib\httplib.py", line
576, in send

    self.sock.sendall(str)

  File "", line 1, in sendall

TypeError: sendall() argument 1 must be string or read-only
buffer, not list

 

 

 

 

Tried the script from http://fabien.seisen.org/python/urllib2_multipart.html
 also

 

Getting similar error..

 

Cheers

Thomas

 






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

Question about python code distribution...

2005-04-27 Thread [EMAIL PROTECTED]
Hi,

I am sure that this question might have come up repeatedly. Companies
may not want to distribute their python code in source form. Even
though pyc files are one option, it gets inconvenient to distribute
bunch of them . If there is some way to bundle pyc files (akin to
.jar), it would be really nice. I understand that pyc files are not
hard to decompile (from my reading of previous posts) and module
startup times may be longer if they have to be read from an archive.
Neverthless, an option to distribute in the form of an archive is
attractive. Has this ever been considered for Python? If one were to
consider it, what would be pros and cons of such approach?

Any comments are appreciated.

Thanks,
Raghu.

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


Re: PyGTK vs. wxPython

2005-04-27 Thread Jaime Wyant
On 27 Apr 2005 11:31:00 -0700, dcrespo <[EMAIL PROTECTED]> wrote:
> Correct me if I'm wrong: XRCed doesn't allow to do MDI Parent and Child
> frames, but simple apps only.
> For what you wouldn't use it? And instead, what would you use instead?
> GUI Hand coding?
> 
> Daniel
> 

Looking at the docs, both wx.MDIChildFrame and wx.MDIParentFrame are
derived from wx.Frame.  So, you *ought* to be able to create a
wx.Panel with one of the aforementioned windows as its parent.  When
wx.Frame is given a single child window, it expands that window to use
all of the available client space.

Really though, these questions are more suited for the wxPython mailing list.

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


Re: regex over files

2005-04-27 Thread Skip Montanaro

Robin> I implemented a simple scanning algorithm in two ways. First 
buffered scan 
Robin> tscan0.py; second mmapped scan tscan1.py.

...

Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan0.py dingo.dat
Robin> len=139583265 w=103 time=110.91

Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan1.py dingo.dat
Robin> len=139583265 w=103 time=140.53

I'm not sure why the mmap() solution is so much slower for you.  Perhaps on
some systems files opened for reading are mmap'd under the covers.  I'm sure
it's highly platform-dependent.  (My results on MacOSX - see below - are
somewhat better.)

Let me return to your original problem though, doing regex operations on
files.  I modified your two scripts slightly:

tscan0.py:

import sys, time, re
fn = sys.argv[1]
f=open(fn,'rb')
n=0
t0 = time.time()
while 1:
 buf = f.read(4096)
 if not buf: break
 for i in re.split("X", buf):
 n += 1
t1 = time.time()

print "n=%d time=%.2f" % (n, (t1-t0))

tscan1.py:

import sys, time, mmap, os, re
fn = sys.argv[1]
fh=os.open(fn,os.O_RDONLY)
s=mmap.mmap(fh,0,access=mmap.ACCESS_READ)
t0 = time.time()
n = 0
for mat in re.split("X", s):
n += 1
t1 = time.time()

print "n=%d time=%.2f" % (n, (t1-t0))

The mmap version is almost obviously correct, assuming what we want to do is
split the file on "X".  The buffered read version is almost certainly
incorrect, given our understanding that corner cases lurk at buffer
boundaries.

I took the file from Bengt Richter's example and replicated it a bunch of
times to get a 122MB file.  I then ran the above two programs against it:

% python tscan1.py splitX
n=2112001 time=8.88
% python tscan0.py splitX
n=2139845 time=10.26

So the mmap'd version is within 15% of the performance of the buffered read
version and we don't have to solve the problem of any corner cases (note the
different values of n).  I'm happy to take the extra runtime in exchange for
simpler code.

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


Re: pyqt and Eric 3

2005-04-27 Thread ChrisH
In article <[EMAIL PROTECTED]>, 
[EMAIL PROTECTED] says...
> Are there any Eric 3 users out there?
> 
> I've been thinking about trying it.
> 
> Also, if I write scripts for internal use only at my company, do I have 
> to purchase a Qt or pyqt license?
> 
> Thanks for the info!
> Chris
> 

Oops.. I forgot to say I'm writing code for Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


pyqt and Eric 3

2005-04-27 Thread ChrisH
Are there any Eric 3 users out there?

I've been thinking about trying it.

Also, if I write scripts for internal use only at my company, do I have 
to purchase a Qt or pyqt license?

Thanks for the info!
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with sending a variable(python) while using html

2005-04-27 Thread Hal Rosser
append "&eventid=str(variable_name)"  to the url in the link
The hidden field is not sent unless the form is submitted.
If you use the link - you send the data appended to the url

"Hansan"  wrote in message
news:[EMAIL PROTECTED]
> Hi.
>
> Sorry forgot to post a "non-working" example
>
> That could be
> print "", "some text"   type=hidden name="eventid" value='''+str(variable_name)+'''>'''"
>
> I know that it isnt very creative, but I am having a hard time getting
html
> to work together with python.
>
> When the link "some text" is clicked I want to send both the first
variable
> called variable and the second one(variable_name) to the script
(script.py)


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


Re: PyGTK vs. wxPython

2005-04-27 Thread dcrespo
Ok, I get the point. So, when a dynamic component comes up, It can be
handled importing from an XRC file?
I have to develop a complete MDI app, so I'm realizing that I will get
ride of hand-coding it.

Daniel

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


Re: Is there a better interactive plotter then pylab?

2005-04-27 Thread Charles Krug
On Wed, 27 Apr 2005 20:56:07 -0500, John Hunter
<[EMAIL PROTECTED]> wrote:
>> "Charles" == Charles Krug <[EMAIL PROTECTED]> writes:
> 
>Charles> List: I'm trying to us pylab to see what I'm doing with
>Charles> some DSP algorithms, in case my posts about convolution
>Charles> and ffts weren't giving it away.
> 
>Charles> I've been using pylab's plot function, but I'm finding it
>Charles> a bit cumbersome.
> 
>Charles> It works, but if I switch from the interactive window to
>Charles> the plot window and back, the plot window gets trashed.
> 
>Charles> Is there a better alternative for interactive use?
> 
> You are probably not using pylab interactive mode properly.
> matplotlib has several GUI backends (gtk, tk, qt, etc...).  Most GUIs
> take control with their mainloop and prevent further interaction.
>>From what you describe, I'm pretty sure you haven't setup your
> configuration properly for interactive use.  Fortunately, there are a
> couple of solutions.
> 
> For the standard python shell, you need to use the TkAgg backend.
> Tkinter is the only python GUI that plays nicely with the standard
> python shell.  You will need to set "backend : TkAgg" and 
> "interactive : True" in the matplotlib rc file.  See
> http://matplotlib.sf.net/interactive.html for details and
> http://matplotlib.sf.net/.matplotlibrc for information on the
> configuration file.
> 

Those are already set.  I'm taking a look at ipython now.

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


Re: Problem with sending a variable(python) while using html

2005-04-27 Thread Jaime Wyant
On 4/27/05, Hansan <[EMAIL PROTECTED]> wrote:
> Hi.
> 
> Sorry forgot to post a "non-working" example
> 
> That could be
> print "", "some text"   type=hidden name="eventid" value='''+str(variable_name)+'''>'''"
> 
> I know that it isnt very creative, but I am having a hard time getting html
> to work together with python.
> 
> When the link "some text" is clicked I want to send both the first variable
> called variable and the second one(variable_name) to the script (script.py)
> 
> Hope that makes some sense :)

Got it - I think :)

# Create a link that passes the value of `variable' to script.py via 
# the id parameter.  You may want to escape `variable' somehow
# in case it contains spaces or something else that isn't valid.
print ' some text '  % variable

# Create a hidden input variable named `eventid' that contains a value of
# `variable_name'
print '' % variable_name

hth,
jw
--
http://mail.python.org/mailman/listinfo/python-list


converting binary data

2005-04-27 Thread Dan Stromberg

I've written up a page about how to convert native binary data to
another platform's native binary data, as I did some fortran data
conversions for a client.

The programs and documentation are at: 
http://dcs.nac.uci.edu/~strombrg/converting-binary.html

So far, the page includes a variety of programs written in C or python to
do:

1) A program for determining if your machine is big endian, little endian,
or something else

2) A program for swapping big endian to little endian, or vice versa, on
words of an arbitrary number of bytes, assuming a homogeneous size for all
items in the file

3) A pair of programs for converting a series of reals/floats to ascii and
back again (to be used in combination with ssh, rsh, &c)

4) An example program that converts binary data with variable length
records

5) A program that removes fortran record framing for big endian or little
endian, with arbitrary word size (must bew a multiple of 8 bits)


The documentation includes:

1) A taxonomy of three different kinds of conversions

2) Tips for determining record lengths

3) An admonition to reject these methods, and instead convert to a
platform-independent representation.  A list of common
platform-independent representations is given.


I hope someone will find this useful.

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


Re: Ron Grossi: God is not a man

2005-04-27 Thread Matt Hayden

Johnny Gentile wrote:
> C'mon. Everyone knows God plays a Martin.

I dunno.  I think God has a honkin' big collection so he won't offend
ANY luthiers when they come to visit.  SOMEONE has to set up his
guitars...

mh

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


Re: kdialog and unicode

2005-04-27 Thread dmbkiwi

John Ridley wrote:
> dmbkiwi wrote:
>
> > I'm trying to get python, unicode and kdialog to play nicely
> together.
> > This is a linux machine, and kdialog is a way to generate dialog
> boxes in
> > kde with which users can interact (for example input text), and you
> can
> > use the outputted text in your script.
> >
> > Anyway, what I'm doing is reading from a utf-8 encoded text file
> using the
> > codecs module, and using the following:
> >
> > data = codecs.open('file', 'r', 'utf-8')
> >
> > I then manipulate the data to break it down into text snippets.
> >
> > Then I run this command:
> >
>  test = os.popen('kdialog --inputbox %s' %(data))
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\u017a'
in
> > position 272: ordinal not in range(128)
> >
> > I would really like kdialog display the text as utf-8.  However, it
> seems
> > that python is trying to pass the utf-8 encoded data as ascii,
which
> > obviously fails because it can't deal with the utf-8 encoded text.
> Is it
> > possible to pass the text out to kdialog as utf-8, rather than
ascii?
>
> kdialog will accept a limited form of markup as text, including xml
> character escapes. so you should be able to display polish text
> correctly using this method:
>
> >>> import os
> >>> s = """Wszyscy ludzie rodz\xc4\x85 si\xc4\x99
> ...  wolni i r\xc3\xb3wni pod wzgl\xc4\x99dem
> ...  swej godno\xc5\x9bci i swych praw. S\xc4\x85
> ...  oni obdarzeni rozumem i sumieniem i powinni
> ...  post\xc4\x99powa\xc4\x87 wobec innych w duchu
> ...  braterstwa."""
> >>> s = s.decode('utf-8').encode('ascii','xmlcharrefreplace')
> >>> k = os.popen('kdialog --inputbox "%s"' % s)
>
>
> John Ridley
>
> Send instant messages to your online friends
http://uk.messenger.yahoo.com

Interesting - this displays correctly when I run the above code from a
python shell.  However, when I run it as a superkaramba theme (which is
a wrapper interface to some kde functions, but allegedly passes
straight python functions direct to the python interpreter), it shows
up as letters, with &nnn (where nnn is a number) instead of the \xc4
etc.  I need to do some more investigating of this with the
superkaramba developers, and my own machine to see where the problem
lies - clearly it's not in the code I'm using - there's either
something wrong on my machine, or wrong with the way superkaramba
passes this code to the python interpreter.

Thanks for your help.

Matt

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


Re: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?)

2005-04-27 Thread Neil Hodgson
Kitty:

> Now it can take up to 4 minutes for the file dialog box to appear. No
> problems with speed in PythonWin, of course, but she is not used to
> doing that. Any suggestions? Anyone know why it is so slow?

   I have seen similar issues in the past but mainly on Windows 9x with 
particular start directories for the dialog. Windows tries to remember 
which directory was most recently chosen by each application. Possibly 
it has associated python.exe with a directory on a removed drive, 
network share, or virtual location (like "My Network Places") and takes 
a while to fail over to a working place. 

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


Re: Is there a better interactive plotter then pylab?

2005-04-27 Thread John Hunter
> "Charles" == Charles Krug <[EMAIL PROTECTED]> writes:

Charles> List: I'm trying to us pylab to see what I'm doing with
Charles> some DSP algorithms, in case my posts about convolution
Charles> and ffts weren't giving it away.

Charles> I've been using pylab's plot function, but I'm finding it
Charles> a bit cumbersome.

Charles> It works, but if I switch from the interactive window to
Charles> the plot window and back, the plot window gets trashed.

Charles> Is there a better alternative for interactive use?

You are probably not using pylab interactive mode properly.
matplotlib has several GUI backends (gtk, tk, qt, etc...).  Most GUIs
take control with their mainloop and prevent further interaction.
>From what you describe, I'm pretty sure you haven't setup your
configuration properly for interactive use.  Fortunately, there are a
couple of solutions.

For the standard python shell, you need to use the TkAgg backend.
Tkinter is the only python GUI that plays nicely with the standard
python shell.  You will need to set "backend : TkAgg" and 
"interactive : True" in the matplotlib rc file.  See
http://matplotlib.sf.net/interactive.html for details and
http://matplotlib.sf.net/.matplotlibrc for information on the
configuration file.

If you want to use another GUI backend, eg GTKAgg (the default on
linux and also the fastest backend), you need to use a custom python
interpreter which runs the GUI in a thread.  The best choice here is
to use ipython (http://ipython.scipy.org) with the -pylab option.
ipython is aware of matplotlib and its rc file, and will read the rc
file, set the interactive mode, detect the GUI backend, and make the
proper threading calls.  Basically it *just works*.  If you are on
linux, it's an easy install (sudo python setup.py install).  On
windows it's a bit harder, and you may want to look at the 1069
release candidate of enthought python at
http://www.enthought.com/downloads/downloads.htm#download, which comes
with ipython and matplotlib and lots of other goodies.  Again, you'll
need to start ipythhon with

  > ipython -pylab

In addition to the links above, see also
http://matplotlib.sf.net/faq.html#SHOW.

Hope this helps,
JDH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suggestions on how to do this

2005-04-27 Thread bwaha
Hi bgs

Many thanks. This generates the correct coefficients. I am studying
your implementation now. I've  not used a dictionary of dictionaries
before so there's a bit of a learning curve going on right now. However
I can see that b[k] holds the relevant info (coefficients and powers)
so I can easily modify it to collect terms with like powers. As for
speed, its not a concern. Thanks again.

bwaha Chris

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


Re: Trigraph Idiom - Original?

2005-04-27 Thread Shane Hathaway
Jeff Winkler wrote:
> I've come up with a trigraph idiom, am curious if it's been done before
> (probably). I like to use trigraphs occasionally.
> 
> Scenario: I'm doing an RSS->Javascript conversion for our intranet. I'd
> like to use different CSS class if a post is new. Code:
> 
> hoursOld=abs(time.time()-time.mktime(i.modified_parsed))/3600
> cssClass=['rssLink','rssLinkNew'][hoursOld<12]
> entry='%s' %
> (cssClass,i['link'],i['title'])
> 
> So, ['rssLink','rssLinkNew'] is index by boolean value- False:0, or
> True:1.
> 
> I realize many will find this hideous, but 3 lines of code to do
> something simple seems equally bad. Thoughts? Is there a better way?

The need for ternary expressions seems to center around presentation to
humans.  I find myself using such expressions frequently in presentation
templates or in code that prepares information for templates.  You're
using it the same way.

I always write it this way:

condition and truecase or falsecase

This works as long as truecase evaluates as a true value.  (If it
doesn't, the result of the expression is falsecase.)  So I would write
the cssClass assignment like this:

cssClass = (hoursOld < 12) and 'rssLinkNew' or 'rssLink'

The C equivalent is more readable, but this is close enough.  It's the
same trick people use in shell scripts.

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


Re: Shutting down twisted reacotr

2005-04-27 Thread Jason Mobarak
Why do you want to do this in a thread? What's wrong with
reactor.callLater?

import time
from twisted.internet import reactor

def shutdown():

time.sleep(3)
print "stopping"
reactor.callFromThread(reactor.stop)

reactor.callInThread(shutdown)
reactor.run()

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


Re: Trigraph Idiom - Original?

2005-04-27 Thread Michael Spencer
Jeff Winkler wrote:
I've come up with...

cssClass=['rssLink','rssLinkNew'][hoursOld<12]
Not hideous, but:
 >>> cssClass=('rssLink','rssLinkNew')[hoursOld<12]
is IMO, slightly less surprising,
and in this context:
 >>> cssClass = hoursOld<12 and 'rssLinkNew' or 'rssLink'
 >>>
reads better too
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Is there a better interactive plotter then pylab?

2005-04-27 Thread Charles Krug
List:

I'm trying to us pylab to see what I'm doing with some DSP algorithms,
in case my posts about convolution and ffts weren't giving it away.

I've been using pylab's plot function, but I'm finding it a bit
cumbersome.

It works, but if I switch from the interactive window to the plot window
and back, the plot window gets trashed.

Is there a better alternative for interactive use?

Thanks


Charles

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


Re: suggestions on how to do this

2005-04-27 Thread bgs
You could probably use scipy.base.polynomial, but it's easy enough to
implement a polynomial yourself.  Just use a dict-- each key represents
the power and each value the coefficient of the polynomial.

You didn't say exactly how efficient you need this.  It takes only a
couple seconds to sum 100 of the b(k)'s using the implementation below.
  This gets you roots out to about A=500.

Perhaps there are bugs in the below implementation.  Either way, you
can compare your results and its results and if they're not the same,
well then there's a problem.


--
from rational import rational #get from bitconjurer.org/rational.py

def add(a, b, s=1):
c = {}
for k, v in b.items():
if not a.has_key(k):
c[k] = s*v
for k, v in a.items():
vb = b.get(k, 0)
c[k] = a[k] + s*vb
return c

def raise1(a):
b = {}
for k, v in a.items():
b[k+1] = v
return b

def scale(a, s):
b = {}
for k, v in a.items():
b[k] = v*s
return b

def eval(x, p):
s = 0.0
for k, v in p.items():
s = s + float(v.num)/float(v.den)*x**k
return s

b = {-3 : {}, -2 : {}, -1 : {}, 0 : {0:rational(1,1)}, 1 : {}}

N = 100
for k in range(2,N):
b[k] = scale(raise1(add(b[k-5],b[k-2],-1)),rational(1,k**2))
o = [b[0]]
for k in range(1, N):
o.append(add(o[-1], b[k]))

for x in range(0,800):
print x, eval(x, o[-3]), eval(x, o[-2]), eval(x, o[-1])
# o[-1],o[-2], and o[-3] start to split around x = 500

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


Re: Which IDE is recommended?

2005-04-27 Thread Dave Cook
On 2005-04-27, monkey <[EMAIL PROTECTED]> wrote:

> Read through python site for programming tool, really plenty of choices :-)
> (For c++, I just can't breath with very very limited choices)
>
> Tried Spe, it come with wxGlade built-in very nice(is Spe still actively
> develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse)
> also worth looking. Actually which one are you guys using? and why? I think
> it is also valuable for those who are new to python as me.

Pydev has some compelling features, but I wish I didn't have to run eclipse
to get them.  I use XEmacs.  Once upon a time emacs was considered bloated,
but it's tiny compared to eclipse.

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


Re: creating very small types

2005-04-27 Thread Dan Bishop
Michael Spencer wrote:
> andrea wrote:
> >>>I was thinking to code the huffman algorithm and trying to
compress
> >>>something with it, but I've got a problem.
> >>>How can I represent for example a char with only 3 bits??
>
> >>>I had a look to the compression modules but I can't understand
them much...
> ...
> > I understand I can't do it easily in python, but maybe I could
define a
> > new type in C and use it to do those dirty works, what do you
think?
>
> Why do you need to create 'very small types'?
>
> You only need actual bit-twiddling when you do the encoding/de-coding
right?
> If you create an encoding map 'codes' as a dict of strings of '1' and
'0',
> encoding might look like (untested):
>
>  def encode(stream):
>  outchar = count = 0
>  for char in stream:
>  for bit in codes[char]:
>  (outchar << 1) | (bit == "1")
>  count +=1
>  if count ==8:
>  yield chr(outchar)
>  outchar = count = 0
>  if count:
>  yield chr(outchar)

I wrote some Huffman compression code a few years ago, with

class BitWriter(object):
   # writes individual bits to an output stream
   def __init__(self, outputStream):
  self.__out = outputStream
  self.__bitCount = 0  # number of unwritten bits
  self.__currentByte = 0   # buffer for unwritten bits
   def write(self, bit):
  self.__currentByte = self.__currentByte << 1 | bit
  self.__bitCount += 1
  if self.__bitCount == BYTE_SIZE:
 self.__out.write(chr(self.__currentByte))
 self.__bitCount = 0
 self.__currentByte = 0
   def flush(self):
  while self.__bitCount > 0:
 self.write(0)

class BitReader(object):
   # reads individual bits from an input stream
   def __init__(self, inputStream):
  self.__in = inputStream
  self.__bits = []  # buffer to hold incoming bits
   def readBit(self):
  if len(self.__bits) == 0:
 # read the next byte
 b = ord(self.__in.read(1))
 # unpack the bits
 self.__bits = [(b & (1

Re: Trigraph Idiom - Original?

2005-04-27 Thread John Machin
On 27 Apr 2005 16:26:02 -0700, "Jeff  Winkler" <[EMAIL PROTECTED]>
wrote:

>I've come up with a trigraph idiom, am curious if it's been done before
>(probably). I like to use trigraphs occasionally.
>
>Scenario: I'm doing an RSS->Javascript conversion for our intranet. I'd
>like to use different CSS class if a post is new. Code:
>
>hoursOld=abs(time.time()-time.mktime(i.modified_parsed))/3600
>cssClass=['rssLink','rssLinkNew'][hoursOld<12]
>entry='%s' %
>(cssClass,i['link'],i['title'])
>
>So, ['rssLink','rssLinkNew'] is index by boolean value- False:0, or
>True:1.
>
>I realize many will find this hideous, but 3 lines of code to do
>something simple seems equally bad. Thoughts? Is there a better way?

1. You appear to be conflating "trigraph" [a truly hideous
little-known lexical feature of C] and "ternary operator".

2. No, it's not original; the idea of using a boolean value as index
to an array of 2 elements probably occurred to somebody at about the
time that subroutines were invented. Look at the threads that break
out periodically in this newsgroup: "why doesn't python have a ternary
operator", "why doesn't 'foo and bar or zot' work sometimes" etc etc
-- it usually gets a mention.

3. Some might say it is hideous, but perhaps less hideous than (a)
using "i" as a reference to data other than a loop index (b) being so
worried about the longevity of your keyboard and/or thumb(s) that you
hit the spacebar only once or twice (other than inside string
literals) in three statements.

4. In the 3rd statement, you appear at best to have gravely misleading
variable names -- cssClass is shoved into the href="%s" but i['link']
is shoved into the class="%s" -- or worse, a stuffup.



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


Re: kdialog and unicode

2005-04-27 Thread John Ridley
dmbkiwi wrote:

> I'm trying to get python, unicode and kdialog to play nicely
together.
> This is a linux machine, and kdialog is a way to generate dialog
boxes in
> kde with which users can interact (for example input text), and you
can
> use the outputted text in your script.
> 
> Anyway, what I'm doing is reading from a utf-8 encoded text file
using the
> codecs module, and using the following:
> 
> data = codecs.open('file', 'r', 'utf-8')
> 
> I then manipulate the data to break it down into text snippets.
> 
> Then I run this command:
> 
 test = os.popen('kdialog --inputbox %s' %(data))
> Traceback (most recent call last):
>   File "", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\u017a' in
> position 272: ordinal not in range(128)
> 
> I would really like kdialog display the text as utf-8.  However, it
seems
> that python is trying to pass the utf-8 encoded data as ascii, which
> obviously fails because it can't deal with the utf-8 encoded text. 
Is it
> possible to pass the text out to kdialog as utf-8, rather than ascii?

kdialog will accept a limited form of markup as text, including xml
character escapes. so you should be able to display polish text
correctly using this method:

>>> import os
>>> s = """Wszyscy ludzie rodz\xc4\x85 si\xc4\x99
...  wolni i r\xc3\xb3wni pod wzgl\xc4\x99dem
...  swej godno\xc5\x9bci i swych praw. S\xc4\x85
...  oni obdarzeni rozumem i sumieniem i powinni
...  post\xc4\x99powa\xc4\x87 wobec innych w duchu
...  braterstwa."""
>>> s = s.decode('utf-8').encode('ascii','xmlcharrefreplace')
>>> k = os.popen('kdialog --inputbox "%s"' % s)


John Ridley

Send instant messages to your online friends http://uk.messenger.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good morning or good evening depending upon your location. I want to ask you the most important question of your life. Your joy or sorrow for all eternity depends upon your answer. The question is: Are you saved? It is not a question of how good you are, nor if you are a church member, but are you saved? Are you sure you will go to Heaven when you die? GOOGLE·NEWSGROUP·POST·151

2005-04-27 Thread George Sakkis
 wrote in message
news:[EMAIL PROTECTED]
> Reports to [EMAIL PROTECTED], [EMAIL PROTECTED], [EMAIL PROTECTED],
> [EMAIL PROTECTED], [EMAIL PROTECTED]
>
> And do not feed the troll!

I'm afraid he's not a troll. He's just a lame spammer, doesn't need
feeding to survive...

In any case, the hell with :-/

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


Re: suggestions on how to do this

2005-04-27 Thread cfriedl
Hi Bengt

OK, that's right. So I'm curious how you did this. And any comments on
how to collect coefficients of like powers in your result.

Be Well and Happy Always

Chris

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


Re: suggestions on how to do this

2005-04-27 Thread cfriedl
Hi Terry

I apprecaite the advice. Briefly I'm familiar with the math (its an
eigenvalue problem in fluid flow) but not so much with python (3 months
on and off), hence my post here. I'm looking for python advice on how
to implement this effectively. I love python and would like to use it
well.

As for vague subject, I've not found a strong correlation between
subject line and number or depth of responses. Perhaps today the
curious looked at it. But at other times, even with a quite specific
subject, no replies come. Such is life.

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


Re: Lexicographical sort for numarray

2005-04-27 Thread Jason Mobarak
Ah, okay, I didn't remember correctly what arr.tolist did. My mistake.

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


Re: Good morning or good evening depending upon your location. I want to ask you the most important question of your life. Your joy or sorrow for all eternity depends upon your answer. The question is: Are you saved? It is not a question of how good you are, nor if you are a church member, but are you saved? Are you sure you will go to Heaven when you die? GOOGLE·NEWSGROUP·POST·151

2005-04-27 Thread Please
Reports to [EMAIL PROTECTED], [EMAIL PROTECTED], [EMAIL PROTECTED],
[EMAIL PROTECTED], [EMAIL PROTECTED]

And do not feed the troll!
-- 
http://mail.python.org/mailman/listinfo/python-list


win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?)

2005-04-27 Thread MsKitty
My client is used to clicking on the script name on her PC and getting
a windows command line box which it runs in. Not fancy but did the job
until recently...

Now it can take up to 4 minutes for the file dialog box to appear. No
problems with speed in PythonWin, of course, but she is not used to
doing that. Any suggestions? Anyone know why it is so slow?

Here is the code snippet to open her input file (output goes in the
same directory so we have to get the directory path for that)

try:
d=win32ui.CreateFileDialog(1)
d.DoModal()
inputpath=d.GetPathName()
inputsplit=string.split(inputpath,"\\")
inputdir = string.join(inputsplit[:-1],"\\")
inputname=d.GetFileName()
if printit:
print "input file is ",inputname
try:
input = open(inputname,"r") # expects text to mark up
except:
print "Error opening input file",inputname
if inputname:
print "Invalid Input File ",inputname
line = raw_input()
sys.exit(2)

(there's another except later in the code ...)

Kitty
OpenSkyWebDesign.com

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


Re: Which IDE is recommended?

2005-04-27 Thread runes
I used Boa for a Win32 project. It helped me enormously. It's very easy
to design windows etc. But the generated python code is not beautiful.

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


Trigraph Idiom - Original?

2005-04-27 Thread Jeff Winkler
I've come up with a trigraph idiom, am curious if it's been done before
(probably). I like to use trigraphs occasionally.

Scenario: I'm doing an RSS->Javascript conversion for our intranet. I'd
like to use different CSS class if a post is new. Code:

hoursOld=abs(time.time()-time.mktime(i.modified_parsed))/3600
cssClass=['rssLink','rssLinkNew'][hoursOld<12]
entry='%s' %
(cssClass,i['link'],i['title'])

So, ['rssLink','rssLinkNew'] is index by boolean value- False:0, or
True:1.

I realize many will find this hideous, but 3 lines of code to do
something simple seems equally bad. Thoughts? Is there a better way?

- Jeff

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


Re: Python, Perl & PDF files

2005-04-27 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
rbt  <[EMAIL PROTECTED]> wrote:
>Cameron Laird wrote:
>> In article <[EMAIL PROTECTED]>,
>> rbt  <[EMAIL PROTECTED]> wrote:
>>  .
>>  .
>>  .
>> 
>>>Read and search them for strings. If I could do that on windows, linux 
>>>and mac with the *same* bit of Python code, I'd be very happy ;)
>> 
>> 
>> Textual content, right?  Without regard to font funniness, or
>> whether the string is in or out of a table, and so on?
>
>That's right. More specifically, I've written a script that uses a RE to 
>search 
>through documents for social security numbers. You can see it here:
>
>http://filebox.vt.edu/users/rtilley/public/find_ssns/find_ssns.html
>
>This works on Word, Excel, html, rtf or any ANSI based text. I need the
>ability to 
>read and make sense of PDF files as well so I can apply the RE to their
>content. It's 
>been frustrating to say the least. Nothing at all against Python...
>mostly just sick 
>of hearing about the 'Portable' document format that isn't string or RE
>searchable... 
>at least not easily anyway.
.
.
.
PDF is NOT easy to search.  'Fact, many times it's not even feasible,
in any automated sense.  

When I can make time, I want to look into your Word and Excel searching;
there are several tricks for doing these in full generality.

Unless I've missed late-breaking news, Perl does NOT help, despite the
flashy appearance of the CPAN search page you referenced.  None of that
stuff gets at content in a sense that'll serve you well.

Neither does anything open-sourced in Python.  The best I know is what
I'm slowly documenting at http://phaseit.net/claird/comp.text.pdf/PDF_converters.html#pdf2txt >,
as David mentioned earlier.
-- 
http://mail.python.org/mailman/listinfo/python-list


mbx repair script

2005-04-27 Thread David Isaac
I'm looking for a Python script to repair the mbx header
for a mail file where only the header is corrupted.

Thanks,
Alan Isaac


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


Re: creating very small types

2005-04-27 Thread Michael Spencer
andrea wrote:
I was thinking to code the huffman algorithm and trying to compress
something with it, but I've got a problem.
How can I represent for example a char with only 3 bits??

I had a look to the compression modules but I can't understand them much...
...
I understand I can't do it easily in python, but maybe I could define a
new type in C and use it to do those dirty works, what do you think?
Why do you need to create 'very small types'?
You only need actual bit-twiddling when you do the encoding/de-coding right?
If you create an encoding map 'codes' as a dict of strings of '1' and '0', 
encoding might look like (untested):

def encode(stream):
outchar = count = 0
for char in stream:
for bit in codes[char]:
(outchar << 1) | (bit == "1")
count +=1
if count ==8:
yield chr(outchar)
outchar = count = 0
if count:
yield chr(outchar)
HTH
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: bytecode non-backcompatibility

2005-04-27 Thread Maurice LING
Martin v. Löwis wrote:
[automatically install a set of packages]
What do you think?

That would certainly be possible. Contributions are welcome.
Regards,
Martin
I've emailed to catelog-sig mailing list and is still waiting to hear 
something. Currently, I have no idea of the structure of PyPI. I hope I 
can hear from them soon and generate some starting points...

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


Descriptor Transparency

2005-04-27 Thread Eric Huss
I'm trying to write a descriptor (similar to the EiffelDescriptor example
in the Demo directory).  However, I noticed an odd behavior that
descriptors written in pure Python mask the underlying object they are
wrapping, whereas the descriptors written in C do not.

For example, taking the code from
http://users.rcn.com/python/download/Descriptor.htm which implements what
one would think is a straightforward implementation:

class ClassMethod(object):
 "Emulate PyClassMethod_Type() in Objects/funcobject.c"

 def __init__(self, f):
  self.f = f

 def __get__(self, obj, klass=None):
  if klass is None:
   klass = type(obj)
  def newfunc(*args):
   return self.f(klass, *args)
  return newfunc

class MyClass(object):

def c_method_1(k, foo):
"some docstring"
print 'c_method_1: %r %r' % (k, foo)
c_method_1 = ClassMethod(c_method_1)

def c_method_2(k, foo):
"some docstring"
print 'c_method_2: %r %r' % (k, foo)
c_method_2 = classmethod(c_method_2)

You can see that the Python version does not behave the same as the C
version:

>>> print MyClass.c_method_1.__doc__
None
>>> print MyClass.c_method_2.__doc__
some docstring

I have seen some people manually assign the __doc__ attribute to match the
method they are wrapping (above in the __get__ method it would be
newfunc.__doc__ = self.f.__doc__ before the return).  However, this
extends further into introspection:

>>> import inspect
>>> print inspect.getargspec(MyClass.c_method_1)
([], 'args', None, None)
>>> print inspect.getargspec(MyClass.c_method_2)
(['k', 'foo'], None, None, None)

SO, my question is, is it possible to make a simple descriptor in Python
that has the same behavior as one implemented in C?  Or, at least a way
that does not require a very large amount of emulation code. ;)

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


Re: bytecode non-backcompatibility

2005-04-27 Thread Maurice LING
Terry Reedy wrote:
I doubt anyone disputes that upgrades are more hassle than we would like. 
My main point was that freezing CPython's technology is not the solution. 
Any other upgrade helper that you can contribute will be welcome.

Terry J. Reedy

So there is no way of releasing a close-source application written in 
Python?

Forget about reverse engineering or decompiling, things like EU Council 
Directive, Berne Convention , and legislation of individual countries 
are to be used and argued for handling what decompilation is allowed or 
not allowed. It does make a difference between  looking at the codes 
when it is given and performing an act of decompilation to look at the 
codes. As mentioned in one of my postings, it may be analogous to the 
difference between you dropping some cash on the ground and I take it, 
and I performing the act of pickpocketing and take your money.

I am not advocating close source in any sense and I believe the choice 
of open or close source distribution is individual's and corporate's rights.

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


Re: creating very small types

2005-04-27 Thread andrea
Jeremy Bowers wrote:

>On Wed, 27 Apr 2005 22:17:07 +0200, andrea wrote:
>
>  
>
>>I was thinking to code the huffman algorithm and trying to compress
>>something with it, but I've got a problem.
>>How can I represent for example a char with only 3 bits??
>>I had a look to the compression modules but I can't understand them much...
>>
>>Thank you very much
>>Any good link would be appreciated of course :)
>>
>>
>
>I think the answer to this question very much depends on why you want to
>do this. Easy and fast are pretty opposed in this particular domain in
>Python (IMHO anyways, it's an easy bit-bashing language but it's slow
>for that), and you're in one of the rare domains where it matters.
>
>The answers strongly vary if you're trying to create something performant,
>or just for your learning purposes. Or homework purposes... ;-)
>
>  
>
No it's not for homework but for learning purposes...
I understand I can't do it easily in python, but maybe I could define a
new type in C and use it to do those dirty works, what do you think?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [pygame] Very simple program fails. Why?

2005-04-27 Thread Sizer
"Brent W. Hughes" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> I'm just starting to learn pygame.  I write what I think is just about
> the simplest program that should display a window and then quit.
> #---
> import sys
> import time
> import pygame
> 
> pygame.init()
> screen = pygame.display.set_mode((640,480))
> pygame.display.set_caption("A Bug's Life")
> time.sleep(4)
> #---

Two problems here - first is that you should always call 
pygame.display.quit() when done. The second is that if you sleep(4) 
you've effectively blocked off the event loop for that process, which 
makes Windows unhappy. Even clicking 'close' to close the window won't 
work. Your very dumbest pygame program should have a loop like:

while pygame.event.poll().type != KEYDOWN:
pygame.time.delay(10)

Which just does nothing (but pumps the event loop) until a key is 
pressed, then exits.

Or you could add up the spent time and bail when it hits four seconds, or 
whatever you want, but you should be doing something with the 
pygame.event loop. And then call the pygame.display.quit() when done of 
course.


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


Re: creating very small types

2005-04-27 Thread Jeremy Bowers
On Wed, 27 Apr 2005 22:17:07 +0200, andrea wrote:

> I was thinking to code the huffman algorithm and trying to compress
> something with it, but I've got a problem.
> How can I represent for example a char with only 3 bits??
> I had a look to the compression modules but I can't understand them much...
> 
> Thank you very much
> Any good link would be appreciated of course :)

I think the answer to this question very much depends on why you want to
do this. Easy and fast are pretty opposed in this particular domain in
Python (IMHO anyways, it's an easy bit-bashing language but it's slow
for that), and you're in one of the rare domains where it matters.

The answers strongly vary if you're trying to create something performant,
or just for your learning purposes. Or homework purposes... ;-)

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


Re: tkinter text width

2005-04-27 Thread Jeremy Bowers
On Wed, 27 Apr 2005 12:52:21 -0700, James Stroud wrote:

> Thank you to everybody helping me. I think I am almost there...
> 
> On Wednesday 27 April 2005 12:10 pm, so sayeth Jeremy Bowers:
>> 2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
>> can ask the font for how wide any char is and do the math from there.)
> 
> How might I query the size of a fixed-width font in pixles? It appears that 
> the width of the font in points does not correlate with its width in pixels 
> based on some simple expriments I have done. Using cget("font") on the Text 
> gives back a string with the point size.

Ah, in that case you want the measure attribute of the font object.

http://www.pythonware.com/library/tkinter/introduction/x4671-methods.htm

> 
>> [snip some things to worry about]
>> Basically, I'm pretty sure you can't do this.
> 
> My setup is not very complicated, so I don't think I have to worry about 
> kerning, unicode, etc.. I am using a fixed width font (courier) only, and 
> only one size and am also quite comfortable with giving away several pixels 
> at the end of a line for "rounding errors" and will filter for a limited 
> alphabet consisting only of the numbers, the captial letters, and the space.
> 
> I think I can do this given these limitations.

Sounds like it.

What I did was set up unit test that threw random snippets at the text
widget, and compared how many lines my code thought the widget should
have, vs. what the widget claimed to have. This is how I discovered that
some unicode was wrapped incorrectly. You can get what the widget claims
to have by asking it for the geometric position of the last character with
the bbox method of the Text widget.

This is, however, probably not the answer you are looking for, because you
only get a bounding box if the text is currently visible on the screen.
This makes it fairly difficult to use to ask the widget *how far* off the
screen the text is. If it were that easy I would have said so earlier
:-) But you may find that useful too, as you cobble together a solution.

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


Re: Lexicographical sort for numarray

2005-04-27 Thread Robert Kern
Jason Mobarak wrote:
It does what the OPs example does, but with numeric types.
It certainly does not.
In [15]:arr = na.arange(100)
In [16]:random.shuffle(arr)
In [17]:arr.shape = (10,10)
In [18]:arr2 = na.array(arr)
In [19]:L = arr.tolist()
In [20]:L.sort()
In [21]:na.array(L)
Out[21]:
array([[ 8, 22, 40, 85, 64, 20, 91, 76, 19, 56],
   [11, 83, 86, 51, 72, 17, 80, 35,  1, 18],
   [13, 62,  0, 95, 25, 28,  5, 78, 54, 55],
   [41, 44, 15, 24, 27, 97, 31, 75, 65, 29],
   [45, 57, 16, 89, 87, 90, 42, 50, 93,  9],
   [53, 21, 47, 69,  2, 12, 92, 98, 66, 48],
   [70, 79, 36, 88, 10, 39, 81, 61, 43,  3],
   [74, 37, 49, 14, 33, 34, 52, 23, 96, 71],
   [82, 67, 30, 60,  6, 73, 99, 94,  7, 58],
   [84, 63,  4, 46, 26, 32, 59, 38, 68, 77]])
In [22]:arr2.flat.sort()
In [23]:arr2
Out[23]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
   [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
   [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
   [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
   [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
   [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
   [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
   [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
   [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
   [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: interactive web graphics

2005-04-27 Thread Diez B. Roggisch
> I would like a form with progress bars, but I guess
> that would have to be implemented in some special way.
> Sorry if these questions are ill-posed; I am just
> getting my feet wet with python.

Larry already said some true things about this. Let me just add that what
you are after _might_ be done using macromedia flash - as that is a
wide-spread browser plugin with interactive and multimedia capabilities.
But how to do it in flash I've no idea - after all I'm a pythoneer.

Alternatively, SVG might be an option - but I'm not sure if its mature and
powerful enough.

-- 
Regards,

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


Re: PyGTK vs. wxPython

2005-04-27 Thread Szabolcs Nagy
I forgot to mention in my previous post that the best thing in wxPython
is the wxPython demo. It helped me a lot. Browsing through the examples
usually faster than browsing through the api doc.

About XRCed:
I put every static components of the window layout in an xml file with
XRCed
(not static components: buttons moving around, changing labels ...)

Generally my code looks like:

import wx
import wx.xrc

class Frame(wx.Frame):
def __init__(self, parent, resource):
w = resource.LoadFrame(parent, 'FrameName')
self.PostCreate(w)
self.SetIcon(wx.Icon('myapp.ico', wx.BITMAP_TYPE_ICO))

...
#lots of init code here

...
#event handlers here


class App(wx.App):
def OnInit(self):
resource = wx.xrc.XmlResource('myapp.xrc')
self.f = Frame(None, resource)
self.f.Show()
return True

if __name__ == '__main__':
app = App()
app.MainLoop()

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


Re: Lexicographical sort for numarray

2005-04-27 Thread Jason Mobarak
It does what the OPs example does, but with numeric types.

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


Re: interactive web graphics

2005-04-27 Thread Larry Bates
Web application are different than local or client
server applications.  Web browser can connect to a
server and make a request, but the program that
satisfies the request runs to completion and disconnects
from the client.  You cannot easily do interactive-type
applications.  Things like progress bars can't really
even be done.  You can have your applications create
graphs, charts, etc. and deliver them back to the user
either as web pages or as PDF files.  There is a python
toolkit called ReportLab that provides a framework to
do this from python programs that run on the server.
The ReportLab graphics can do barcharts, line charts,
scatter plots, etc. and you can either save as .JPG
files that can be delivered on a web page or as a .PDF
file that the user can download.  Hard to say which
would work best for you.

Hope information helps a little.

-Larry Bates

Eckhoff, Michael A wrote:
> Hello,
> 
> I failed to locate a list for pygtk, so I thought I'd
> ask my question here. Is it possible to write CGI
> scripts that bring up a GUI (as in GTK+, QT, Tk, ...)
> or an openGL display that is windowed inside a web
> browser?
> 
> The answer would seem to me to be no, since the
> client could be Windows or Linux. I'd like to
> display some pretty graphics (scientific visualisation),
> but web applications are not my background.
> 
> I would like a form with progress bars, but I guess
> that would have to be implemented in some special way.
> Sorry if these questions are ill-posed; I am just
> getting my feet wet with python.
> 
> Thanks,
> Michael E
> 
> PS Congratulations for having such wonderful documentation
> on all things python. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lexicographical sort for numarray

2005-04-27 Thread Robert Kern
Jason Mobarak wrote:
import numarray as na
import random
# example array
arr = range(100)
random.shuffle(arr)
arr = na.array(arr)
arr = na.reshape(arr, (10,10))
print arr # not rowsort'ed
arr.flat.sort() # key line
print arr # rowsort'ed
That's definitely not a lexicographic sort.
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which IDE is recommended?

2005-04-27 Thread Bruno Desthuilliers
monkey a écrit :
Read through python site for programming tool, really plenty of choices :-)
(For c++, I just can't breath with very very limited choices)
Tried Spe, it come with wxGlade built-in very nice(is Spe still actively
develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse)
also worth looking. Actually which one are you guys using? and why? I think
it is also valuable for those who are new to python as me.
emacs + ECB + python-mode.
--
http://mail.python.org/mailman/listinfo/python-list


Re: kdialog and unicode

2005-04-27 Thread dmbkiwi

John Machin wrote:
> On 26 Apr 2005 19:16:25 -0700, [EMAIL PROTECTED] wrote:
>
> >
> >John Machin wrote:
> >> On 26 Apr 2005 13:39:26 -0700, [EMAIL PROTECTED] (dumbkiwi) wrote:
> >>
> >> >Peter Otten <[EMAIL PROTECTED]> wrote in message
> >news:<[EMAIL PROTECTED]>...
> >> >> Dumbkiwi wrote:
> >> >>
> >> >> >> Just encode the data in the target encoding before passing
it
> >to
> >> >> >> os.popen():
> >>
> >> >
> >> >Anyway, from your post, I've done some more digging, and found
the
> >> >command:
> >> >
> >> >sys.setappdefaultencoding()
> >> >
> >> >which I've used, and it's fixed the problem (I think).
> >> >
> >>
> >> Dumb Kiwi, eh? Maybe not so dumb -- where'd you find
> >> sys.setappdefaultencoding()? I'm just a dumb Aussie [1]; I looked
in
> >> the 2.4.1 docs and also did import sys; dir(sys) and I can't spot
it.
> >
> >Hmmm. See post above, seems to be something generated by eric3.  So
> >this may not be the fix I'm looking for.
> >
> >>
> >> In any case, how could the magical sys.setappdefaultencoding() fix
> >> your problem? From your description, your problem appeared to be
that
> >> you didn't know what encoding to use.
> >
> >I knew what encoding to use,
>
> Would you mind telling us (a) what that encoding is (b) how you came
> to that knowledge (c) why you just didn't do

(a)  utf-8
(b)  I asked the author of the text, and it displays properly in other
parts of the script when not using kdialog.  Is there a way to test it
otherwise - I presume that there is.

>
> test = os.popen('kdialog --inputbox %s'
> %(data.encode('that_encoding')))
>
> instead of
>
> test = os.popen('kdialog --inputbox %s' %(data.encode('utf-8')))

Because, "that_encoding" == "utf-8" (as far as I was aware).

>
> > the problem was that the text was being
> >passed to kdialog as ascii.
>
> It wasn't being passed to kdialog; there was an attempt which failed.

Quite right.

>
> >  The .encode('utf-8') at least allows
> >kdialog to run, but the text still looks like crap.  Using
> >sys.setappdefaultencoding() seemed to help.  The text looked a bit
> >better - although not entirely perfect - but I think that's because
the
> >font I was using didn't have the correct characters (they came up as
> >square boxes).
>
> And the font you *were* using is what? And the font you are now using
> is what? What facilities do you have to use different fonts?

The font I was using was bitstream vera sans.  The font I'm now using
is verdana.

>
> >>
> >> What is the essential difference between
> >>
> >>send(u_data.encode('polish'))
> >>
> >> and
> >>
> >>sys.setappdefaultencoding('polish')
> >>...
> >>send(u_data)
> >
> >Not sure - I'm new to character encoding, and most of this seems
like
> >black magic to me.
>
> The essential difference is that setting a default encoding is a daft
> idea.
>
Because it acheives nothing more than what I can do with
.encode('that_encoding')?

>
> >
> >>
> >> [1]: Now that's *TWO* contenders for TautologyOTW :-)
> >>
>
> Before I retract that back to one contender, I'll give it one more
> shot:
>
Aaah, there's nothing better than a bit of cheerful snarkiness on a
newsgroup.

> 1. Your data: you say it is Polish text, and is utf-8. This implies
> that it is in Unicode, encoded as utf-8. What evidence do you have?

See above.

> Have you been able to display it anywhere so that it "looks good"?

Yes.  What I am doing here is a theme for a superkaramba widget (see
http://netdragon.sourceforge.net).  It displays fine everywhere else on
the widget, it's just in the kdialog boxes that it doesn't display
correctly.

> If it's not confidential, can you show us a dump of the first say 100
> bytes of text, in an unambiguous form, like this:

Can't do it now, because I'm at work.  I can do it when I get home
tonight.

>
> print repr(open('polish.text', 'rb').read(100))
>
> 2. Your script: You say "I then manipulate the data to break it down
> into text snippets" - uh-huh ... *what* manipulations? Care to tell
> us? Care to show us the code?

Manipulation is simply breaking the text down into dictionary pairs.
It is basically a translation file for my widget, with English text,
and a corresponding Posish text.  I use the re module to parse the
file, and create dictionary pairs between the English text, and the
corresponding Polish text.

>
> 3. kdialog: I know nothing of KDE and its toolkit. I would expect
> either (a) it should take utf-8 and be able to display *any* of the
> first 64K (nominal) Unicode characters, given a Unicode font or (b)
> you can encode your data in a legacy charset, *AND* tell it what that
> charset is, and have a corresponding font or (c) you have both
> options. Which is correct, and what are the details of how you can
> tell kdialog what to do -- configuration? command-line arguments?

That's what I was hoping someone here might be able to tell me.  Having
searched on line, I cannot find any information about kdialog and
encoding.  I have left a message on the relevant kde mai

Re: Secure FTP

2005-04-27 Thread Steve Horsley
Daniel Bowett wrote:
I need to download files over a secure channel.
I have been looking into Paramiko which seems to have the functonality I 
need. The problem is I need a FTP server which supports key based 
encryption to install on my windows server.

Has anyone succeeded in doing this? If so - what FTP server did you use?
Dan.
OpenSSH (www.openssh.com) supports SFTP which can use a shared 
key or certificates for its encryption. It includes both client 
and server programs.

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


interactive web graphics

2005-04-27 Thread Eckhoff, Michael A
Hello,

I failed to locate a list for pygtk, so I thought I'd
ask my question here. Is it possible to write CGI
scripts that bring up a GUI (as in GTK+, QT, Tk, ...)
or an openGL display that is windowed inside a web
browser?

The answer would seem to me to be no, since the
client could be Windows or Linux. I'd like to
display some pretty graphics (scientific visualisation),
but web applications are not my background.

I would like a form with progress bars, but I guess
that would have to be implemented in some special way.
Sorry if these questions are ill-posed; I am just
getting my feet wet with python.

Thanks,
Michael E

PS Congratulations for having such wonderful documentation
on all things python. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lexicographical sort for numarray

2005-04-27 Thread Jason Mobarak
import numarray as na
import random

# example array
arr = range(100)
random.shuffle(arr)
arr = na.array(arr)
arr = na.reshape(arr, (10,10))

print arr # not rowsort'ed

arr.flat.sort() # key line

print arr # rowsort'ed

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


Re: compile shebang into pyc file

2005-04-27 Thread rbt
Fredrik Lundh wrote:
Joerg Schuster wrote:
> #!/usr/bin/env python
> import app
Yes, of course this is a possibility. But it implies having (or giving
away) two files.

yeah, think of all the disk space you'll waste!
Because if you have two files, you need a third one: a README
that tells you what to do with the two files

so you're saying that the set of people that can deal with no more than one
file at a time but knows how to install and configure Python (which in 
itself
comes with a few thousand files) is larger than zero?
On Windows, installing Python takes only a few clicks. No brain cycles 
needed ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread Steven Bethard
Lonnie Princehouse wrote:
Might as well make a class for Book instead of dealing with buckets of
lists...
class Book(object):
def __init__(self, title, author, publisher, isbn, date):# add
more fields according to CSV
self.__dict__.update(locals())  # lazy!
Just for any newbies not paying attention, a slightly less lazy approach 
that doesn't leave the Book instance referencing itself would do 
something like:

params = locals()
del params['self']
self.__dict__.update(params)
or just write it out:
self.title = title
self.author = author
self.publisher = publisher
self.isbn = isbn
self.date = date
=)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with sending a variable(python) while using html

2005-04-27 Thread Hansan
Hi.

Sorry forgot to post a "non-working" example

That could be
print "", "some text"  '''"

I know that it isnt very creative, but I am having a hard time getting html 
to work together with python.

When the link "some text" is clicked I want to send both the first variable 
called variable and the second one(variable_name) to the script (script.py)

Hope that makes some sense :)


"Jaime Wyant" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On 4/27/05, Hansan <[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I am working on a webpage where I use python and html.
>
> When I want to send one variable to a new script/page I use the following
> code:
> 0) print ''' value='''+str(variable_name)+'''>'''
>
> This works fine, the problem occurs when I want to send a variable to a 
> page
> while using a 1)meta refresh or a 2)Href.
> 1) and 2) works fine as they are but not when I try to send the variable
> with them.
>
> The working version of 1) and 2) could look like
> 1) print '
> 2) print "", "some text", ""
>

What exactly does the "non-working" version look like?  Perhaps a
snippet of broken code would be helpful here?

jw 


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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread Lonnie Princehouse
Might as well make a class for Book instead of dealing with buckets of
lists...

class Book(object):
def __init__(self, title, author, publisher, isbn, date):# add
more fields according to CSV
self.__dict__.update(locals())  # lazy!
def __repr__(self):
return '<"%s" by %s>' % (self.title, self.author)

def read_books(filename):
import csv   #   (this battery is included)
csv_file = open(filename, "rb")
reader = csv.reader(csv_file)
books = [Book(*[field.strip() for field in row]) for row in reader]
csv_file.close()
return books

if __name__ == '__main__':
books = read_books("my_csv_file.csv")
import operator

# example - Sort by author
books.sort(key = operator.attrgetter("author"))

for book in books:
print book

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


Inheriting socket handles on Windows

2005-04-27 Thread Iker Arizmendi
Hello all.
I'm trying to get a server process to do the following
on both Linux and Windows:
   1) Create a socket and bind it to some port number.
   2) Use spawnl to create other processes that will
  then listen and accept on that socket.
On Linux I've managed to do that by using command line
args to pass the FD number of the listening socket to
the spawned processes. Eg:
# SERVER
#
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', ))
s.listen(5)
exe = "childscript"
fds = str(s.fileno())
pid = os.spawnl(os.P_NOWAIT, exe, exe, fds))
print "process spawned"
time.sleep(5)
# CLIENT
# where fds was received from the parent
#
fds = int(sys.argv[1])
s = socket.fromfd(fds, socket.AF_INET, socket.SOCK_STREAM)
s.listen(5)
print "child listening..."
However, this fails on Windows as it doesn't have the fromfd
function. Aren't WinSock handles inherited by default? And if
so, is there some other way to perform a listen()/accept() in
this case?
Regards,
Iker Arizmendi

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


creating very small types

2005-04-27 Thread andrea
I was thinking to code the huffman algorithm and trying to compress
something with it, but I've got a problem.
How can I represent for example a char with only 3 bits??
I had a look to the compression modules but I can't understand them much...

Thank you very much
Any good link would be appreciated of course :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Shutting down twisted reacotr

2005-04-27 Thread Operation Latte Thunder
I have a simple ( I hope ) problem that I have been baning my head against
all day.  I have isolated it down to a very small demo script, which I
will include below.

Basically, I want to have twisted run until an event makes it stop. My
problem is that my reactor.stop() doesn't seem to do anything if its not
called via a calllater or an equivilent.  Unfortunately, my google-fu
seems weak today, as I have not been able to discern its solution.
Without further adieu:

from thread import start_new_thread
import time
from twisted.internet import reactor

def shutdown():
time.sleep( 1 )
print "Stopping"
reactor.stop()

start_new_thread ( shutdown, () )

reactor.run()
print "done"

This will continue to run even after printing "Stopping"

any ideas?

-- 
[EMAIL PROTECTED]   | Roma Invicta!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suggestions on how to do this

2005-04-27 Thread Kay Schluehr
Seems You are looking for a generating function of a recurrence
relation. There is a standard text about this topic written by Herbert
S. Wilf downloadable from his homapage:

http://www.cis.upenn.edu/~wilf/

Regards,
Kay

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


Re: tkinter text width

2005-04-27 Thread James Stroud
Thank you to everybody helping me. I think I am almost there...

On Wednesday 27 April 2005 12:10 pm, so sayeth Jeremy Bowers:
> 2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
> can ask the font for how wide any char is and do the math from there.)

How might I query the size of a fixed-width font in pixles? It appears that 
the width of the font in points does not correlate with its width in pixels 
based on some simple expriments I have done. Using cget("font") on the Text 
gives back a string with the point size.

> [snip some things to worry about]
> Basically, I'm pretty sure you can't do this.

My setup is not very complicated, so I don't think I have to worry about 
kerning, unicode, etc.. I am using a fixed width font (courier) only, and 
only one size and am also quite comfortable with giving away several pixels 
at the end of a line for "rounding errors" and will filter for a limited 
alphabet consisting only of the numbers, the captial letters, and the space.

I think I can do this given these limitations.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: odeint function in SciPy

2005-04-27 Thread Robert Kern
FLChamp wrote:
I was wondering what numerical method the odeint function is based on.
I have checked the documentation but couldnt find anything. I would be
very grateful if someone could answer this question for me, I'm not
looking for a heavy mathematical answer!
You could also check the source or ask on the appropriate mailing list.
But since if you do the latter, you'll still get me, odeint uses ODEPACK.
http://www.netlib.org/odepack/opkd-sum
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


odeint function in SciPy

2005-04-27 Thread FLChamp
I was wondering what numerical method the odeint function is based on.
I have checked the documentation but couldnt find anything. I would be
very grateful if someone could answer this question for me, I'm not
looking for a heavy mathematical answer!

Cheers!

Ben

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


Re: Problem with sending a variable(python) while using html

2005-04-27 Thread Jaime Wyant
On 4/27/05, Hansan <[EMAIL PROTECTED]> wrote:
> Hi all.
> 
> I am working on a webpage where I use python and html.
> 
> When I want to send one variable to a new script/page I use the following
> code:
> 0) print ''' value='''+str(variable_name)+'''>'''
> 
> This works fine, the problem occurs when I want to send a variable to a page
> while using a 1)meta refresh or a 2)Href.
> 1) and 2) works fine as they are but not when I try to send the variable
> with them.
> 
> The working version of 1) and 2) could look like
> 1) print '
> 2) print "", "some text", ""
> 

What exactly does the "non-working" version look like?  Perhaps a
snippet of broken code would be helpful here?

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


Re: Design advice for unit test asserters

2005-04-27 Thread Gary
First, thanks to both Kent and Edvard for useful comments.  I certainly
need to consider whether it make sense to switch to py.test at this
time; its simplicity is attractive.

In response to Edvards question:

Edvard Majakari wrote:
> "Gary" <[EMAIL PROTECTED]> writes:
...
> >  self.AssertAllFilesExist(fileList)
...
> >
> >  def test_SomeTest(...):
> >  ...
> >  [ self.AssertFileExists(f) for f in fileList ]
>
> I prefer the latter, because then you'd get error for the missing
file -
> otherwise you'd just know a file didn't exist (but not which, unless
you
> explicitly coded that in, no?)

Yes, my intent is that AssertAllFilesExist(fileList) would be something
like the following, more or less:

def AssertAllFilesExist(fileList):
for f in fileList:
self.assert_(os.path.isfile(f) and not os.path.islink(f),
 "File %s is missing" % f)

It's the smarts in these that caused me to instantly see applicability
of the Template Pattern - which became quite a distraction to me,
because after doing it, I think it was obviously unnecessary overkill.

Gary

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


How to launch an application on a remote computer using Python

2005-04-27 Thread Milon
I have 2 computers hooked to the same network.  One of the computer has
Python installed, and I want to write a python script to launch
"c:\notepad.exe" on the second computer, how do I do this?  (Note:
Python is not installed on the second computer)

Thanks.

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


Re: tkinter text width

2005-04-27 Thread Jeremy Bowers
On Wed, 27 Apr 2005 10:52:14 -0700, James Stroud wrote:
> This is more or less what I would like, but I would also like to probe the 
> Text to see how many characters it thinks it can display within the container 
> window. I am formatting text dynamically and so I rely on the width. I am not 
> after the built in "wrap" option, it does not do what I want. But, say if 
> wrap were turned on, it would be good to know how many characters the Text 
> would wrap at.

I have extensive experience with trying to get text containers to do this.
It is not easy. You have two choices:

1. Give up. You can't tell anyhow if you're using a proportional font.

2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
can ask the font for how wide any char is and do the math from there.)

I have 70 line function that tries to replicate the Tk wrapping algorithm
in the proportional text case, and it *still* doesn't work. For one thing,
I actually found some bugs in the wrapping code (if a Unicode character
gets into just the right position, it can actually run off the right end
of the text widget, even if the widget is being wrapped), so completely
matching the layout seems infeasible.

I would strongly, strongly suggest finding another way to do what you are
trying to do. I have blown many, many hours on this problem, and I found
no simple logic. The edge cases kill you; while Tk is consistent (same
text, same wrap every time), sometimes it wraps a word if it goes up to
the edge, sometimes if it's one pixel off, damned if I can find a pattern
(probably has something to do with trying to space the letters out,
kerning or one of its simpler friends), and it probably changes
periodically anyhow... and note based on this I can't even guarantee #2
above, if you get unlucky.

Basically, I'm pretty sure you can't do this.

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


Problem with sending a variable(python) while using html

2005-04-27 Thread Hansan
Hi all.

I am working on a webpage where I use python and html.

When I want to send one variable to a new script/page I use the following 
code:
0) print ''

This works fine, the problem occurs when I want to send a variable to a page 
while using a 1)meta refresh or a 2)Href.
1) and 2) works fine as they are but not when I try to send the variable 
with them.

The working version of 1) and 2) could look like
1) print '
2) print "", "some text", ""

What I have to do is to combine 0) with 1) so that I can send the variable 
while using a meta refresh
and 0) and 2)

But I no matter how hard I try I cant get it done.

Can any of you experienced users give me some guidance.

I would really appreciate it.

Thanks 


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


Re: bytecode non-backcompatibility

2005-04-27 Thread "Martin v. Löwis"
Maurice LING wrote:
> So if C extension API (or whatever that is really called) is stable, the
> system admin can just copy all of /sw/lib/python2.3/site-packages into
> /sw/lib/python2.4/site-packages and it should work. 

It would be counter-productive to make it stable, as this would render
certain desirable changes impossible. Backwards compatibility on C API
(source) level is a goal, binary compatibility within a 2.x release
is a goal, binary compatibility across 2.x releases is not.

[automatically install a set of packages]
> What do you think?

That would certainly be possible. Contributions are welcome.

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


Re: suggestions on how to do this

2005-04-27 Thread Bengt Richter
On Wed, 27 Apr 2005 11:34:53 GMT, "chris" <[EMAIL PROTECTED]> wrote:

>The problem I have is as follows:
>
>I have a recursive function b(k)
>
>b(k) = -(A/k**2)*(b(k-2) - b(k-5))
>k<0, b(k)=0
>k=0, b(k)=1
>k=1, b(k)=0
>
>eg. b(2) = -A/4
>  b(3) = 0
>  b(4) = A**2/64
>
>note that as k increases b(k) can itself be a sum of terms in powers of A
>rather than a single power of A in the examples above.
>
>Summing all terms and equating to zero gives:
>
>F= sum b(k) = 0 for all k = 0, infinity
>
>When this is expanded I get a polynomial F(A). I want to determine the
>coefficients of the polynomial so that I can find the roots of the function
>F up to a specified order of A.
>
>
>I have yet to code this but I was hoping for some ideas on how to do this
>reasonably.
>
>I figure I can compute each b(k) and store the numeric value(s) and
>associated powers of A. Then collect coefficients for like powers of A.
>Finally I have a set of polynomial coefficients in A which I can pass to
>scipy.base.roots()
>
>Any suggestions on how I might do this efficiently? I have no doubt I can
>get this done with brute force, but I would prefer to explore more elegant
>means which I look to the masters for.
>

Does this look right?

b(-5) -> 0
b(-4) -> 0
b(-3) -> 0
b(-2) -> 0
b(-1) -> 0
 b(0) -> 0
 b(1) -> 0
 b(2) -> -A/4
 b(3) -> 0
 b(4) -> A**2/64
 b(5) -> A/25
 b(6) -> -A**3/2304
 b(7) -> -29*A**2/4900
 b(8) -> A**4/147456
 b(9) -> 563*A**3/2116800
b(10) -> A**2/2500 -A**5/14745600
b(11) -> -5927*A**4/1024531200
b(12) -> -43*A**3/98 +A**6/2123366400
b(13) -> 824003*A**5/11081329459200
b(14) -> 16397*A**4/1037232 -A**7/416179814400
b(15) -> A**3/562500 -1260403*A**6/1994639302656000

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread Steven Bethard
James Stroud wrote:
Oops, last one had a typo:
a = ['bob', 'greg', 'cindy', 'alice']
b = ['fred','barney','betty','wilma','pebbles','bambam']
c = ['jed', 'granny', 'jethro', 'ellie-mae']
d = ['bob','carol','ted','alice']
e = [a,b,c,d]
for ary in e:
  print ary
e.sort(lambda x,y:cmp(x[1],y[1]))
for ary in e:
  print ary
e.sort(lambda x,y:cmp(x[0],y[0]))
for ary in e:
  print ary
I would probably use the key= argument instead of the cmp= argument. 
Not only is it easier, but it'll probably be faster too:

py> lst = [['bob', 'greg', 'cindy', 'alice'],
...['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'],
...['jed', 'granny', 'jethro', 'ellie-mae'],
...['bob', 'carol', 'ted', 'alice']]
py> import operator
py> lst.sort(key=operator.itemgetter(3))
py> lst
[['bob', 'greg', 'cindy', 'alice'], ['bob', 'carol', 'ted', 'alice'], 
['jed', 'granny', 'jethro', 'ellie-mae'], ['fred', 'barney', 'betty', 
'wilma', 'pebbles', 'bambam']]
py> lst.sort(key=operator.itemgetter(0))
py> lst
[['bob', 'greg', 'cindy', 'alice'], ['bob', 'carol', 'ted', 'alice'], 
['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'], ['jed', 
'granny', 'jethro', 'ellie-mae']]
py> lst.sort(key=operator.itemgetter(slice(2)))
py> lst
[['bob', 'carol', 'ted', 'alice'], ['bob', 'greg', 'cindy', 'alice'], 
['fred', 'barney', 'betty', 'wilma', 'pebbles', 'bambam'], ['jed', 
'granny', 'jethro', 'ellie-mae']]

Note that you can pass slice objects to operator.itemgetter, so the last 
example is like "key=lambda x: x[:2]".

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


Re: PyGTK vs. wxPython

2005-04-27 Thread dcrespo
Correct me if I'm wrong: XRCed doesn't allow to do MDI Parent and Child
frames, but simple apps only.
For what you wouldn't use it? And instead, what would you use instead?
GUI Hand coding?

Daniel

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


Re: List comprehension and FieldStorage

2005-04-27 Thread Derek Basch
Sorry Peter. I will refrain from nudging in the future. I did spend
time at the interactive prompt and got nothing. Maybe I will have
better luck next time.

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


Re: List comprehension and FieldStorage

2005-04-27 Thread Peter Hansen
Derek Basch wrote:
bump
If "bump" is supposed to be some kind of nudge to get people to reply, 
please have more patience.  You posted only sometime late yesterday, and 
many people take up to a few days to receive the posts from this 
newsgroup, and even those who don't shouldn't be expected to reply the 
same instant they read your question.  Also, it's quite possible you 
won't get any reply (though this is pretty rare) in which case "bump" is 
going to be seen as nothing more than rudeness, given that if an answer 
was forthcoming it would probably already have been posted.  In such a 
case, you're better off rereading your request and considering whether 
you phrased it adequately or can supply additional information to help 
potential responders.

(In this case, your question looks fairly clear, though it doesn't look 
like you've spent much time at the interactive prompt experimenting and 
trying to find an answer on your own.)

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread [EMAIL PROTECTED]
What you want I guess is to read first all lines of the file into a
string as you did, and then let the split method split it based on
newlines only - see example below.

Then you use split again to put all elements of one line into another
list - split it on commas.

Now you can define sortfunctions for all columns you want to sort, e.g.
like below - and use those to compare elements. You get a script like:
-#!/usr/bin/env python
-
-def cmp_index(a, b, ndx):
-   if a[ndx] < b[ndx]:
-return -1
-elif a[ndx] > b[ndx]:
-   return 1
-else:
-return 0
-
-def cmp_0(a, b):
-return cmp_index(a, b, 0)
-
-def cmp_1(a, b):
-return cmp_index(a, b, 1)
-
-s = 'Kikker en Eend,Max Veldhuis\nDikkie Dik,Jet Boeke\nRuminations on
C++,Andrew Koenig & Barbara Moo'
-s = s.split('\n')
-l = []
-for i in s:
-l.append(i.split(','))
-
-l.sort(cmp_0)
-print l
-l.sort(cmp_1)
-print l

with output like:
[EMAIL PROTECTED]:~ $ ./test.py
[['Dikkie Dik', 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis'],
['Ruminations on C++', 'Andrew Koenig & Barbara Moo']]
[['Ruminations on C++', 'Andrew Koenig & Barbara Moo'], ['Dikkie Dik',
'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis']]
[EMAIL PROTECTED]:~ $

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread James Stroud
Oops, last one had a typo:


a = ['bob', 'greg', 'cindy', 'alice']
b = ['fred','barney','betty','wilma','pebbles','bambam']
c = ['jed', 'granny', 'jethro', 'ellie-mae']
d = ['bob','carol','ted','alice']

e = [a,b,c,d]

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[1],y[1]))

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[0],y[0]))

for ary in e:
  print ary

James

On Wednesday 27 April 2005 10:34 am, so sayeth googleboy:
> I didn't think this would be as difficult as it now seems to me.
>
> I am reading in a csv file that documents a bunch of different info on
> about 200 books, such as title, author, publisher, isbn, date and
> several other bits of info too.
>
> I can do a simple sort over the first field (title as it turns out),
> and that is fine as far as it gets:
>
>
> import string
>
> bookData = open(r'D:\path\to\books.csv', 'r')
> sBookData = bookData.read()
> lBooks = string.split(sBookData, '\n')
>
> lBooks.sort()
> sorted = string.join(lBooks, '\n')
> output = open(r'D:\path\to\output.csv', 'w')
> output.close()
>
>
> I really want to be able to sort the list of books based on other
> criterium, and even multiple criteria (such as by author, and then by
> date.)
>
> I am using python 2.4 and have found this site:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305304
>
> and so I tried doing things like
>
> >>>lBooks.sort(cmp=cmp5)
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'cmp5' is not defined
>
> (I was hoping that cmp5 meant it would use the 5th item in the lists to
> sort across)
>
> >>> lBooks.sort(key=lambda i:i[4])
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1, in 
> IndexError: string index out of range
>
>
> (I was hoping for similar things)
>
>
> would you be so kind as to point me in the right direction?
>
> THanks!
>
> googleboy

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: names of methods, exported functions

2005-04-27 Thread M.E.Farmer
Appears that most of the relevant code is in the Helper and TextDoc
classes of pydoc also might need the doc() function.
My head hurts every time I stare at the internals of pydoc ;)
I guess it is time for a lunch break.
M.E.Farmer

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread James Stroud
I think if you work backwards, it comes out:

a = ['bob', 'greg', 'cindy', 'alice']
b = ['fred',barney','betty','wilma','pebbles','bambam']
c = ['jed', 'granny', 'jethro', 'ellie-mae']
d = ['bob','carol','ted','alice']

e = [a,b,c,d]

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[1],y[1]))

for ary in e:
  print ary

e.sort(lambda x,y:cmp(x[0],y[0]))

for ary in e:
  print ary

James

On Wednesday 27 April 2005 10:34 am, so sayeth googleboy:
> I didn't think this would be as difficult as it now seems to me.
>
> I am reading in a csv file that documents a bunch of different info on
> about 200 books, such as title, author, publisher, isbn, date and
> several other bits of info too.
>
> I can do a simple sort over the first field (title as it turns out),
> and that is fine as far as it gets:
>
>
> import string
>
> bookData = open(r'D:\path\to\books.csv', 'r')
> sBookData = bookData.read()
> lBooks = string.split(sBookData, '\n')
>
> lBooks.sort()
> sorted = string.join(lBooks, '\n')
> output = open(r'D:\path\to\output.csv', 'w')
> output.close()
>
>
> I really want to be able to sort the list of books based on other
> criterium, and even multiple criteria (such as by author, and then by
> date.)
>
> I am using python 2.4 and have found this site:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305304
>
> and so I tried doing things like
>
> >>>lBooks.sort(cmp=cmp5)
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'cmp5' is not defined
>
> (I was hoping that cmp5 meant it would use the 5th item in the lists to
> sort across)
>
> >>> lBooks.sort(key=lambda i:i[4])
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1, in 
> IndexError: string index out of range
>
>
> (I was hoping for similar things)
>
>
> would you be so kind as to point me in the right direction?
>
> THanks!
>
> googleboy

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: List comprehension and FieldStorage

2005-04-27 Thread Derek Basch
bump

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


Re: tkinter text width

2005-04-27 Thread James Stroud
On Wednesday 27 April 2005 02:31 am, so sayeth Eric Brunel:
> The "trick" is to create the Text as small as possible (width=1, height=1),
> make it fill its whole container (pack(fill=BOTH, expand=1)), then set the
> dimensions for the container window (geometry('500x200')). You'll get a
> Text that will shrink and expand as much as you like.
>
> Is it what you were after?

This is more or less what I would like, but I would also like to probe the 
Text to see how many characters it thinks it can display within the container 
window. I am formatting text dynamically and so I rely on the width. I am not 
after the built in "wrap" option, it does not do what I want. But, say if 
wrap were turned on, it would be good to know how many characters the Text 
would wrap at.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


  1   2   >